VirtualBox

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

Last change on this file since 94866 was 94800, checked in by vboxsync, 3 years ago

VMM/IEM,PGM: TLB work, esp. on the data one. bugref:9898

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 224.5 KB
Line 
1/* $Id: PGMPhys.cpp 94800 2022-05-03 21:49:43Z 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(cPages, pVM->pgm.s.fUseLargePages ? SUP_PAGE_ALLOC_F_LARGE_PAGES : 0, &pNew->pvR3);
1632 if (RT_FAILURE(rc))
1633 return rc;
1634
1635 RTGCPHYS iPage = cPages;
1636 while (iPage-- > 0)
1637 PGM_PAGE_INIT(&pNew->aPages[iPage], UINT64_C(0x0000fffffffff000), NIL_GMM_PAGEID,
1638 PGMPAGETYPE_RAM, PGM_PAGE_STATE_ALLOCATED);
1639
1640 /* Update the page count stats. */
1641 pVM->pgm.s.cPrivatePages += cPages;
1642 pVM->pgm.s.cAllPages += cPages;
1643 }
1644#endif
1645
1646 /*
1647 * Link it.
1648 */
1649 pgmR3PhysLinkRamRange(pVM, pNew, pPrev);
1650
1651#ifdef VBOX_WITH_NATIVE_NEM
1652 /*
1653 * Notify NEM now that it has been linked.
1654 */
1655 if (VM_IS_NEM_ENABLED(pVM))
1656 {
1657 uint8_t u2State = UINT8_MAX;
1658 int rc = NEMR3NotifyPhysRamRegister(pVM, GCPhys, pNew->cb, pNew->pvR3, &u2State, &pNew->uNemRange);
1659 if (RT_SUCCESS(rc))
1660 {
1661 if (u2State != UINT8_MAX)
1662 pgmPhysSetNemStateForPages(&pNew->aPages[0], cPages, u2State);
1663 }
1664 else
1665 pgmR3PhysUnlinkRamRange2(pVM, pNew, pPrev);
1666 return rc;
1667 }
1668#endif
1669 return VINF_SUCCESS;
1670}
1671
1672
1673/**
1674 * PGMR3PhysRegisterRam worker that registers a high chunk.
1675 *
1676 * @returns VBox status code.
1677 * @param pVM The cross context VM structure.
1678 * @param GCPhys The address of the RAM.
1679 * @param cRamPages The number of RAM pages to register.
1680 * @param iChunk The chunk number.
1681 * @param pszDesc The RAM range description.
1682 * @param ppPrev Previous RAM range pointer. In/Out.
1683 */
1684static int pgmR3PhysRegisterHighRamChunk(PVM pVM, RTGCPHYS GCPhys, uint32_t cRamPages, uint32_t iChunk,
1685 const char *pszDesc, PPGMRAMRANGE *ppPrev)
1686{
1687 const char *pszDescChunk = iChunk == 0
1688 ? pszDesc
1689 : MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s (#%u)", pszDesc, iChunk + 1);
1690 AssertReturn(pszDescChunk, VERR_NO_MEMORY);
1691
1692 /*
1693 * Allocate memory for the new chunk.
1694 */
1695 size_t const cChunkPages = RT_ALIGN_Z(RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cRamPages]), HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
1696 PSUPPAGE paChunkPages = (PSUPPAGE)RTMemTmpAllocZ(sizeof(SUPPAGE) * cChunkPages);
1697 AssertReturn(paChunkPages, VERR_NO_TMP_MEMORY);
1698 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
1699 void *pvChunk = NULL;
1700 int rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk, &R0PtrChunk, paChunkPages);
1701 if (RT_SUCCESS(rc))
1702 {
1703 Assert(R0PtrChunk != NIL_RTR0PTR || PGM_IS_IN_NEM_MODE(pVM));
1704 memset(pvChunk, 0, cChunkPages << HOST_PAGE_SHIFT);
1705
1706 PPGMRAMRANGE pNew = (PPGMRAMRANGE)pvChunk;
1707
1708 /*
1709 * Ok, init and link the range.
1710 */
1711 rc = pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhys + ((RTGCPHYS)cRamPages << GUEST_PAGE_SHIFT) - 1,
1712 R0PtrChunk, PGM_RAM_RANGE_FLAGS_FLOATING, pszDescChunk, *ppPrev);
1713 if (RT_SUCCESS(rc))
1714 *ppPrev = pNew;
1715
1716 if (RT_FAILURE(rc))
1717 SUPR3PageFreeEx(pvChunk, cChunkPages);
1718 }
1719
1720 RTMemTmpFree(paChunkPages);
1721 return rc;
1722}
1723
1724
1725/**
1726 * Sets up a range RAM.
1727 *
1728 * This will check for conflicting registrations, make a resource
1729 * reservation for the memory (with GMM), and setup the per-page
1730 * tracking structures (PGMPAGE).
1731 *
1732 * @returns VBox status code.
1733 * @param pVM The cross context VM structure.
1734 * @param GCPhys The physical address of the RAM.
1735 * @param cb The size of the RAM.
1736 * @param pszDesc The description - not copied, so, don't free or change it.
1737 */
1738VMMR3DECL(int) PGMR3PhysRegisterRam(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, const char *pszDesc)
1739{
1740 /*
1741 * Validate input.
1742 */
1743 Log(("PGMR3PhysRegisterRam: GCPhys=%RGp cb=%RGp pszDesc=%s\n", GCPhys, cb, pszDesc));
1744 AssertReturn(RT_ALIGN_T(GCPhys, GUEST_PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
1745 AssertReturn(RT_ALIGN_T(cb, GUEST_PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
1746 AssertReturn(cb > 0, VERR_INVALID_PARAMETER);
1747 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1748 AssertMsgReturn(GCPhysLast > GCPhys, ("The range wraps! GCPhys=%RGp cb=%RGp\n", GCPhys, cb), VERR_INVALID_PARAMETER);
1749 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1750 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1751
1752 PGM_LOCK_VOID(pVM);
1753
1754 /*
1755 * Find range location and check for conflicts.
1756 */
1757 PPGMRAMRANGE pPrev = NULL;
1758 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
1759 while (pRam && GCPhysLast >= pRam->GCPhys)
1760 {
1761 AssertLogRelMsgReturnStmt( GCPhysLast < pRam->GCPhys
1762 || GCPhys > pRam->GCPhysLast,
1763 ("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
1764 GCPhys, GCPhysLast, pszDesc, pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1765 PGM_UNLOCK(pVM), VERR_PGM_RAM_CONFLICT);
1766
1767 /* next */
1768 pPrev = pRam;
1769 pRam = pRam->pNextR3;
1770 }
1771
1772 /*
1773 * Register it with GMM (the API bitches).
1774 */
1775 const RTGCPHYS cPages = cb >> GUEST_PAGE_SHIFT;
1776 int rc = MMR3IncreaseBaseReservation(pVM, cPages);
1777 if (RT_FAILURE(rc))
1778 {
1779 PGM_UNLOCK(pVM);
1780 return rc;
1781 }
1782
1783 if ( GCPhys >= _4G
1784 && cPages > 256)
1785 {
1786 /*
1787 * The PGMRAMRANGE structures for the high memory can get very big.
1788 * There used to be some limitations on SUPR3PageAllocEx allocation
1789 * sizes, so traditionally we limited this to 16MB chunks. These days
1790 * we do ~64 MB chunks each covering 16GB of guest RAM, making sure
1791 * each range is a multiple of 1GB to enable eager hosts to use 1GB
1792 * pages in NEM mode.
1793 *
1794 * See also pgmR3PhysMmio2CalcChunkCount.
1795 */
1796 uint32_t const cPagesPerChunk = _4M;
1797 Assert(RT_ALIGN_32(cPagesPerChunk, X86_PD_PAE_SHIFT - X86_PAGE_SHIFT)); /* NEM large page requirement: 1GB pages. */
1798
1799 RTGCPHYS cPagesLeft = cPages;
1800 RTGCPHYS GCPhysChunk = GCPhys;
1801 uint32_t iChunk = 0;
1802 while (cPagesLeft > 0)
1803 {
1804 uint32_t cPagesInChunk = cPagesLeft;
1805 if (cPagesInChunk > cPagesPerChunk)
1806 cPagesInChunk = cPagesPerChunk;
1807
1808 rc = pgmR3PhysRegisterHighRamChunk(pVM, GCPhysChunk, cPagesInChunk, iChunk, pszDesc, &pPrev);
1809 AssertRCReturn(rc, rc);
1810
1811 /* advance */
1812 GCPhysChunk += (RTGCPHYS)cPagesInChunk << GUEST_PAGE_SHIFT;
1813 cPagesLeft -= cPagesInChunk;
1814 iChunk++;
1815 }
1816 }
1817 else
1818 {
1819 /*
1820 * Allocate, initialize and link the new RAM range.
1821 */
1822 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
1823 PPGMRAMRANGE pNew = NULL;
1824 RTR0PTR pNewR0 = NIL_RTR0PTR;
1825 rc = SUPR3PageAllocEx(RT_ALIGN_Z(cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT, 0 /*fFlags*/,
1826 (void **)&pNew, &pNewR0, NULL /*paPages*/);
1827 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc cbRamRange=%zu\n", rc, cbRamRange), rc);
1828
1829 rc = pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhysLast, pNewR0, 0 /*fFlags*/, pszDesc, pPrev);
1830 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc cbRamRange=%zu\n", rc, cbRamRange), rc);
1831 }
1832 pgmPhysInvalidatePageMapTLB(pVM);
1833
1834 PGM_UNLOCK(pVM);
1835 return rc;
1836}
1837
1838
1839/**
1840 * Worker called by PGMR3InitFinalize if we're configured to pre-allocate RAM.
1841 *
1842 * We do this late in the init process so that all the ROM and MMIO ranges have
1843 * been registered already and we don't go wasting memory on them.
1844 *
1845 * @returns VBox status code.
1846 *
1847 * @param pVM The cross context VM structure.
1848 */
1849int pgmR3PhysRamPreAllocate(PVM pVM)
1850{
1851 Assert(pVM->pgm.s.fRamPreAlloc);
1852 Log(("pgmR3PhysRamPreAllocate: enter\n"));
1853#ifdef VBOX_WITH_PGM_NEM_MODE
1854 AssertLogRelReturn(!pVM->pgm.s.fNemMode, VERR_PGM_NOT_SUPPORTED_FOR_NEM_MODE);
1855#endif
1856
1857 /*
1858 * Walk the RAM ranges and allocate all RAM pages, halt at
1859 * the first allocation error.
1860 */
1861 uint64_t cPages = 0;
1862 uint64_t NanoTS = RTTimeNanoTS();
1863 PGM_LOCK_VOID(pVM);
1864 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1865 {
1866 PPGMPAGE pPage = &pRam->aPages[0];
1867 RTGCPHYS GCPhys = pRam->GCPhys;
1868 uint32_t cLeft = pRam->cb >> GUEST_PAGE_SHIFT;
1869 while (cLeft-- > 0)
1870 {
1871 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM)
1872 {
1873 switch (PGM_PAGE_GET_STATE(pPage))
1874 {
1875 case PGM_PAGE_STATE_ZERO:
1876 {
1877 int rc = pgmPhysAllocPage(pVM, pPage, GCPhys);
1878 if (RT_FAILURE(rc))
1879 {
1880 LogRel(("PGM: RAM Pre-allocation failed at %RGp (in %s) with rc=%Rrc\n", GCPhys, pRam->pszDesc, rc));
1881 PGM_UNLOCK(pVM);
1882 return rc;
1883 }
1884 cPages++;
1885 break;
1886 }
1887
1888 case PGM_PAGE_STATE_BALLOONED:
1889 case PGM_PAGE_STATE_ALLOCATED:
1890 case PGM_PAGE_STATE_WRITE_MONITORED:
1891 case PGM_PAGE_STATE_SHARED:
1892 /* nothing to do here. */
1893 break;
1894 }
1895 }
1896
1897 /* next */
1898 pPage++;
1899 GCPhys += GUEST_PAGE_SIZE;
1900 }
1901 }
1902 PGM_UNLOCK(pVM);
1903 NanoTS = RTTimeNanoTS() - NanoTS;
1904
1905 LogRel(("PGM: Pre-allocated %llu pages in %llu ms\n", cPages, NanoTS / 1000000));
1906 Log(("pgmR3PhysRamPreAllocate: returns VINF_SUCCESS\n"));
1907 return VINF_SUCCESS;
1908}
1909
1910
1911/**
1912 * Checks shared page checksums.
1913 *
1914 * @param pVM The cross context VM structure.
1915 */
1916void pgmR3PhysAssertSharedPageChecksums(PVM pVM)
1917{
1918#ifdef VBOX_STRICT
1919 PGM_LOCK_VOID(pVM);
1920
1921 if (pVM->pgm.s.cSharedPages > 0)
1922 {
1923 /*
1924 * Walk the ram ranges.
1925 */
1926 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1927 {
1928 uint32_t iPage = pRam->cb >> GUEST_PAGE_SHIFT;
1929 AssertMsg(((RTGCPHYS)iPage << GUEST_PAGE_SHIFT) == pRam->cb,
1930 ("%RGp %RGp\n", (RTGCPHYS)iPage << GUEST_PAGE_SHIFT, pRam->cb));
1931
1932 while (iPage-- > 0)
1933 {
1934 PPGMPAGE pPage = &pRam->aPages[iPage];
1935 if (PGM_PAGE_IS_SHARED(pPage))
1936 {
1937 uint32_t u32Checksum = pPage->s.u2Unused0/* | ((uint32_t)pPage->s.u2Unused1 << 8)*/;
1938 if (!u32Checksum)
1939 {
1940 RTGCPHYS GCPhysPage = pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT);
1941 void const *pvPage;
1942 int rc = pgmPhysPageMapReadOnly(pVM, pPage, GCPhysPage, &pvPage);
1943 if (RT_SUCCESS(rc))
1944 {
1945 uint32_t u32Checksum2 = RTCrc32(pvPage, GUEST_PAGE_SIZE);
1946# if 0
1947 AssertMsg((u32Checksum2 & /*UINT32_C(0x00000303)*/ 0x3) == u32Checksum, ("GCPhysPage=%RGp\n", GCPhysPage));
1948# else
1949 if ((u32Checksum2 & /*UINT32_C(0x00000303)*/ 0x3) == u32Checksum)
1950 LogFlow(("shpg %#x @ %RGp %#x [OK]\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
1951 else
1952 AssertMsgFailed(("shpg %#x @ %RGp %#x\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
1953# endif
1954 }
1955 else
1956 AssertRC(rc);
1957 }
1958 }
1959
1960 } /* for each page */
1961
1962 } /* for each ram range */
1963 }
1964
1965 PGM_UNLOCK(pVM);
1966#endif /* VBOX_STRICT */
1967 NOREF(pVM);
1968}
1969
1970
1971/**
1972 * Resets the physical memory state.
1973 *
1974 * ASSUMES that the caller owns the PGM lock.
1975 *
1976 * @returns VBox status code.
1977 * @param pVM The cross context VM structure.
1978 */
1979int pgmR3PhysRamReset(PVM pVM)
1980{
1981 PGM_LOCK_ASSERT_OWNER(pVM);
1982
1983 /* Reset the memory balloon. */
1984 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
1985 AssertRC(rc);
1986
1987#ifdef VBOX_WITH_PAGE_SHARING
1988 /* Clear all registered shared modules. */
1989 pgmR3PhysAssertSharedPageChecksums(pVM);
1990 rc = GMMR3ResetSharedModules(pVM);
1991 AssertRC(rc);
1992#endif
1993 /* Reset counters. */
1994 pVM->pgm.s.cReusedSharedPages = 0;
1995 pVM->pgm.s.cBalloonedPages = 0;
1996
1997 return VINF_SUCCESS;
1998}
1999
2000
2001/**
2002 * Resets (zeros) the RAM after all devices and components have been reset.
2003 *
2004 * ASSUMES that the caller owns the PGM lock.
2005 *
2006 * @returns VBox status code.
2007 * @param pVM The cross context VM structure.
2008 */
2009int pgmR3PhysRamZeroAll(PVM pVM)
2010{
2011 PGM_LOCK_ASSERT_OWNER(pVM);
2012
2013 /*
2014 * We batch up pages that should be freed instead of calling GMM for
2015 * each and every one of them.
2016 */
2017 uint32_t cPendingPages = 0;
2018 PGMMFREEPAGESREQ pReq;
2019 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2020 AssertLogRelRCReturn(rc, rc);
2021
2022 /*
2023 * Walk the ram ranges.
2024 */
2025 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2026 {
2027 uint32_t iPage = pRam->cb >> GUEST_PAGE_SHIFT;
2028 AssertMsg(((RTGCPHYS)iPage << GUEST_PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << GUEST_PAGE_SHIFT, pRam->cb));
2029
2030 if ( !pVM->pgm.s.fRamPreAlloc
2031#ifdef VBOX_WITH_PGM_NEM_MODE
2032 && !pVM->pgm.s.fNemMode
2033#endif
2034 && pVM->pgm.s.fZeroRamPagesOnReset)
2035 {
2036 /* Replace all RAM pages by ZERO pages. */
2037 while (iPage-- > 0)
2038 {
2039 PPGMPAGE pPage = &pRam->aPages[iPage];
2040 switch (PGM_PAGE_GET_TYPE(pPage))
2041 {
2042 case PGMPAGETYPE_RAM:
2043 /* Do not replace pages part of a 2 MB continuous range
2044 with zero pages, but zero them instead. */
2045 if ( PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE
2046 || PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE_DISABLED)
2047 {
2048 void *pvPage;
2049 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), &pvPage);
2050 AssertLogRelRCReturn(rc, rc);
2051 RT_BZERO(pvPage, GUEST_PAGE_SIZE);
2052 }
2053 else if (PGM_PAGE_IS_BALLOONED(pPage))
2054 {
2055 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
2056 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
2057 }
2058 else if (!PGM_PAGE_IS_ZERO(pPage))
2059 {
2060 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage,
2061 pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), PGMPAGETYPE_RAM);
2062 AssertLogRelRCReturn(rc, rc);
2063 }
2064 break;
2065
2066 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2067 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
2068 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT),
2069 pRam, true /*fDoAccounting*/);
2070 break;
2071
2072 case PGMPAGETYPE_MMIO2:
2073 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
2074 case PGMPAGETYPE_ROM:
2075 case PGMPAGETYPE_MMIO:
2076 break;
2077 default:
2078 AssertFailed();
2079 }
2080 } /* for each page */
2081 }
2082 else
2083 {
2084 /* Zero the memory. */
2085 while (iPage-- > 0)
2086 {
2087 PPGMPAGE pPage = &pRam->aPages[iPage];
2088 switch (PGM_PAGE_GET_TYPE(pPage))
2089 {
2090 case PGMPAGETYPE_RAM:
2091 switch (PGM_PAGE_GET_STATE(pPage))
2092 {
2093 case PGM_PAGE_STATE_ZERO:
2094 break;
2095
2096 case PGM_PAGE_STATE_BALLOONED:
2097 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
2098 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
2099 break;
2100
2101 case PGM_PAGE_STATE_SHARED:
2102 case PGM_PAGE_STATE_WRITE_MONITORED:
2103 rc = pgmPhysPageMakeWritable(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT));
2104 AssertLogRelRCReturn(rc, rc);
2105 RT_FALL_THRU();
2106
2107 case PGM_PAGE_STATE_ALLOCATED:
2108 if (pVM->pgm.s.fZeroRamPagesOnReset)
2109 {
2110 void *pvPage;
2111 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), &pvPage);
2112 AssertLogRelRCReturn(rc, rc);
2113 RT_BZERO(pvPage, GUEST_PAGE_SIZE);
2114 }
2115 break;
2116 }
2117 break;
2118
2119 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2120 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
2121 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT),
2122 pRam, true /*fDoAccounting*/);
2123 break;
2124
2125 case PGMPAGETYPE_MMIO2:
2126 case PGMPAGETYPE_ROM_SHADOW:
2127 case PGMPAGETYPE_ROM:
2128 case PGMPAGETYPE_MMIO:
2129 break;
2130 default:
2131 AssertFailed();
2132
2133 }
2134 } /* for each page */
2135 }
2136
2137 }
2138
2139 /*
2140 * Finish off any pages pending freeing.
2141 */
2142 if (cPendingPages)
2143 {
2144 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2145 AssertLogRelRCReturn(rc, rc);
2146 }
2147 GMMR3FreePagesCleanup(pReq);
2148 return VINF_SUCCESS;
2149}
2150
2151
2152/**
2153 * Frees all RAM during VM termination
2154 *
2155 * ASSUMES that the caller owns the PGM lock.
2156 *
2157 * @returns VBox status code.
2158 * @param pVM The cross context VM structure.
2159 */
2160int pgmR3PhysRamTerm(PVM pVM)
2161{
2162 PGM_LOCK_ASSERT_OWNER(pVM);
2163
2164 /* Reset the memory balloon. */
2165 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
2166 AssertRC(rc);
2167
2168#ifdef VBOX_WITH_PAGE_SHARING
2169 /*
2170 * Clear all registered shared modules.
2171 */
2172 pgmR3PhysAssertSharedPageChecksums(pVM);
2173 rc = GMMR3ResetSharedModules(pVM);
2174 AssertRC(rc);
2175
2176 /*
2177 * Flush the handy pages updates to make sure no shared pages are hiding
2178 * in there. (Not unlikely if the VM shuts down, apparently.)
2179 */
2180# ifdef VBOX_WITH_PGM_NEM_MODE
2181 if (!pVM->pgm.s.fNemMode)
2182# endif
2183 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_FLUSH_HANDY_PAGES, 0, NULL);
2184#endif
2185
2186 /*
2187 * We batch up pages that should be freed instead of calling GMM for
2188 * each and every one of them.
2189 */
2190 uint32_t cPendingPages = 0;
2191 PGMMFREEPAGESREQ pReq;
2192 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2193 AssertLogRelRCReturn(rc, rc);
2194
2195 /*
2196 * Walk the ram ranges.
2197 */
2198 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2199 {
2200 uint32_t iPage = pRam->cb >> GUEST_PAGE_SHIFT;
2201 AssertMsg(((RTGCPHYS)iPage << GUEST_PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << GUEST_PAGE_SHIFT, pRam->cb));
2202
2203 while (iPage-- > 0)
2204 {
2205 PPGMPAGE pPage = &pRam->aPages[iPage];
2206 switch (PGM_PAGE_GET_TYPE(pPage))
2207 {
2208 case PGMPAGETYPE_RAM:
2209 /* Free all shared pages. Private pages are automatically freed during GMM VM cleanup. */
2210 /** @todo change this to explicitly free private pages here. */
2211 if (PGM_PAGE_IS_SHARED(pPage))
2212 {
2213 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage,
2214 pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), PGMPAGETYPE_RAM);
2215 AssertLogRelRCReturn(rc, rc);
2216 }
2217 break;
2218
2219 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2220 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO:
2221 case PGMPAGETYPE_MMIO2:
2222 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
2223 case PGMPAGETYPE_ROM:
2224 case PGMPAGETYPE_MMIO:
2225 break;
2226 default:
2227 AssertFailed();
2228 }
2229 } /* for each page */
2230 }
2231
2232 /*
2233 * Finish off any pages pending freeing.
2234 */
2235 if (cPendingPages)
2236 {
2237 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2238 AssertLogRelRCReturn(rc, rc);
2239 }
2240 GMMR3FreePagesCleanup(pReq);
2241 return VINF_SUCCESS;
2242}
2243
2244
2245
2246/*********************************************************************************************************************************
2247* MMIO *
2248*********************************************************************************************************************************/
2249
2250/**
2251 * This is the interface IOM is using to register an MMIO region.
2252 *
2253 * It will check for conflicts and ensure that a RAM range structure
2254 * is present before calling the PGMR3HandlerPhysicalRegister API to
2255 * register the callbacks.
2256 *
2257 * @returns VBox status code.
2258 *
2259 * @param pVM The cross context VM structure.
2260 * @param GCPhys The start of the MMIO region.
2261 * @param cb The size of the MMIO region.
2262 * @param hType The physical access handler type registration.
2263 * @param uUser The user argument.
2264 * @param pszDesc The description of the MMIO region.
2265 */
2266VMMR3DECL(int) PGMR3PhysMMIORegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMPHYSHANDLERTYPE hType,
2267 uint64_t uUser, const char *pszDesc)
2268{
2269 /*
2270 * Assert on some assumption.
2271 */
2272 VM_ASSERT_EMT(pVM);
2273 AssertReturn(!(cb & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2274 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2275 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2276 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
2277#ifdef VBOX_STRICT
2278 PCPGMPHYSHANDLERTYPEINT pType = pgmHandlerPhysicalTypeHandleToPtr(pVM, hType);
2279 Assert(pType);
2280 Assert(pType->enmKind == PGMPHYSHANDLERKIND_MMIO);
2281#endif
2282
2283 int rc = PGM_LOCK(pVM);
2284 AssertRCReturn(rc, rc);
2285
2286 /*
2287 * Make sure there's a RAM range structure for the region.
2288 */
2289 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2290 bool fRamExists = false;
2291 PPGMRAMRANGE pRamPrev = NULL;
2292 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2293 while (pRam && GCPhysLast >= pRam->GCPhys)
2294 {
2295 if ( GCPhysLast >= pRam->GCPhys
2296 && GCPhys <= pRam->GCPhysLast)
2297 {
2298 /* Simplification: all within the same range. */
2299 AssertLogRelMsgReturnStmt( GCPhys >= pRam->GCPhys
2300 && GCPhysLast <= pRam->GCPhysLast,
2301 ("%RGp-%RGp (MMIO/%s) falls partly outside %RGp-%RGp (%s)\n",
2302 GCPhys, GCPhysLast, pszDesc,
2303 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2304 PGM_UNLOCK(pVM),
2305 VERR_PGM_RAM_CONFLICT);
2306
2307 /* Check that it's all RAM or MMIO pages. */
2308 PCPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
2309 uint32_t cLeft = cb >> GUEST_PAGE_SHIFT;
2310 while (cLeft-- > 0)
2311 {
2312 AssertLogRelMsgReturnStmt( PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM
2313 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO,
2314 ("%RGp-%RGp (MMIO/%s): %RGp is not a RAM or MMIO page - type=%d desc=%s\n",
2315 GCPhys, GCPhysLast, pszDesc, pRam->GCPhys, PGM_PAGE_GET_TYPE(pPage), pRam->pszDesc),
2316 PGM_UNLOCK(pVM),
2317 VERR_PGM_RAM_CONFLICT);
2318 pPage++;
2319 }
2320
2321 /* Looks good. */
2322 fRamExists = true;
2323 break;
2324 }
2325
2326 /* next */
2327 pRamPrev = pRam;
2328 pRam = pRam->pNextR3;
2329 }
2330 PPGMRAMRANGE pNew;
2331 if (fRamExists)
2332 {
2333 pNew = NULL;
2334
2335 /*
2336 * Make all the pages in the range MMIO/ZERO pages, freeing any
2337 * RAM pages currently mapped here. This might not be 100% correct
2338 * for PCI memory, but we're doing the same thing for MMIO2 pages.
2339 */
2340 rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, NULL);
2341 AssertRCReturnStmt(rc, PGM_UNLOCK(pVM), rc);
2342
2343 /* Force a PGM pool flush as guest ram references have been changed. */
2344 /** @todo not entirely SMP safe; assuming for now the guest takes
2345 * care of this internally (not touch mapped mmio while changing the
2346 * mapping). */
2347 PVMCPU pVCpu = VMMGetCpu(pVM);
2348 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2349 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2350 }
2351 else
2352 {
2353 /*
2354 * No RAM range, insert an ad hoc one.
2355 *
2356 * Note that we don't have to tell REM about this range because
2357 * PGMHandlerPhysicalRegisterEx will do that for us.
2358 */
2359 Log(("PGMR3PhysMMIORegister: Adding ad hoc MMIO range for %RGp-%RGp %s\n", GCPhys, GCPhysLast, pszDesc));
2360
2361 /* Alloc. */
2362 const uint32_t cPages = cb >> GUEST_PAGE_SHIFT;
2363 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
2364 const size_t cRangePages = RT_ALIGN_Z(cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
2365 RTR0PTR pNewR0 = NIL_RTR0PTR;
2366 rc = SUPR3PageAllocEx(cRangePages, 0 /*fFlags*/, (void **)&pNew, &pNewR0, NULL /*paPages*/);
2367 AssertLogRelMsgRCReturnStmt(rc, ("cbRamRange=%zu\n", cbRamRange), PGM_UNLOCK(pVM), rc);
2368
2369#ifdef VBOX_WITH_NATIVE_NEM
2370 /* Notify NEM. */
2371 uint8_t u2State = 0; /* (must have valid state as there can't be anything to preserve) */
2372 if (VM_IS_NEM_ENABLED(pVM))
2373 {
2374 rc = NEMR3NotifyPhysMmioExMapEarly(pVM, GCPhys, cPages << GUEST_PAGE_SHIFT, 0 /*fFlags*/, NULL, NULL,
2375 &u2State, &pNew->uNemRange);
2376 AssertLogRelRCReturnStmt(rc, SUPR3PageFreeEx(pNew, cRangePages), rc);
2377 }
2378#endif
2379
2380 /* Initialize the range. */
2381 pNew->pSelfR0 = pNewR0;
2382 pNew->GCPhys = GCPhys;
2383 pNew->GCPhysLast = GCPhysLast;
2384 pNew->cb = cb;
2385 pNew->pszDesc = pszDesc;
2386 pNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO;
2387 pNew->pvR3 = NULL;
2388 pNew->paLSPages = NULL;
2389
2390 uint32_t iPage = cPages;
2391 while (iPage-- > 0)
2392 {
2393 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_MMIO);
2394#ifdef VBOX_WITH_NATIVE_NEM
2395 PGM_PAGE_SET_NEM_STATE(&pNew->aPages[iPage], u2State);
2396#endif
2397 }
2398 Assert(PGM_PAGE_GET_TYPE(&pNew->aPages[0]) == PGMPAGETYPE_MMIO);
2399
2400 /* update the page count stats. */
2401 pVM->pgm.s.cPureMmioPages += cPages;
2402 pVM->pgm.s.cAllPages += cPages;
2403
2404 /* link it */
2405 pgmR3PhysLinkRamRange(pVM, pNew, pRamPrev);
2406 }
2407
2408 /*
2409 * Register the access handler.
2410 */
2411 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, hType, uUser, pszDesc);
2412 if (RT_SUCCESS(rc))
2413 {
2414#ifdef VBOX_WITH_NATIVE_NEM
2415 /* Late NEM notification. */
2416 if (VM_IS_NEM_ENABLED(pVM))
2417 {
2418 uint32_t const fNemNotify = (fRamExists ? NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE : 0);
2419 rc = NEMR3NotifyPhysMmioExMapLate(pVM, GCPhys, GCPhysLast - GCPhys + 1, fNemNotify,
2420 fRamExists ? (uint8_t *)pRam->pvR3 + (uintptr_t)(GCPhys - pRam->GCPhys) : NULL,
2421 NULL, !fRamExists ? &pRam->uNemRange : NULL);
2422 AssertLogRelRCReturn(rc, rc);
2423 }
2424#endif
2425 }
2426 /** @todo the phys handler failure handling isn't complete, esp. wrt NEM. */
2427 else if (!fRamExists)
2428 {
2429 pVM->pgm.s.cPureMmioPages -= cb >> GUEST_PAGE_SHIFT;
2430 pVM->pgm.s.cAllPages -= cb >> GUEST_PAGE_SHIFT;
2431
2432 /* remove the ad hoc range. */
2433 pgmR3PhysUnlinkRamRange2(pVM, pNew, pRamPrev);
2434 pNew->cb = pNew->GCPhys = pNew->GCPhysLast = NIL_RTGCPHYS;
2435 SUPR3PageFreeEx(pRam, RT_ALIGN_Z(RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cb >> GUEST_PAGE_SHIFT]),
2436 HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT);
2437 }
2438 pgmPhysInvalidatePageMapTLB(pVM);
2439
2440 PGM_UNLOCK(pVM);
2441 return rc;
2442}
2443
2444
2445/**
2446 * This is the interface IOM is using to register an MMIO region.
2447 *
2448 * It will take care of calling PGMHandlerPhysicalDeregister and clean up
2449 * any ad hoc PGMRAMRANGE left behind.
2450 *
2451 * @returns VBox status code.
2452 * @param pVM The cross context VM structure.
2453 * @param GCPhys The start of the MMIO region.
2454 * @param cb The size of the MMIO region.
2455 */
2456VMMR3DECL(int) PGMR3PhysMMIODeregister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb)
2457{
2458 VM_ASSERT_EMT(pVM);
2459
2460 int rc = PGM_LOCK(pVM);
2461 AssertRCReturn(rc, rc);
2462
2463 /*
2464 * First deregister the handler, then check if we should remove the ram range.
2465 */
2466 rc = PGMHandlerPhysicalDeregister(pVM, GCPhys);
2467 if (RT_SUCCESS(rc))
2468 {
2469 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2470 PPGMRAMRANGE pRamPrev = NULL;
2471 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2472 while (pRam && GCPhysLast >= pRam->GCPhys)
2473 {
2474 /** @todo We're being a bit too careful here. rewrite. */
2475 if ( GCPhysLast == pRam->GCPhysLast
2476 && GCPhys == pRam->GCPhys)
2477 {
2478 Assert(pRam->cb == cb);
2479
2480 /*
2481 * See if all the pages are dead MMIO pages.
2482 */
2483 uint32_t const cGuestPages = cb >> GUEST_PAGE_SHIFT;
2484 bool fAllMMIO = true;
2485 uint32_t iPage = 0;
2486 uint32_t cLeft = cGuestPages;
2487 while (cLeft-- > 0)
2488 {
2489 PPGMPAGE pPage = &pRam->aPages[iPage];
2490 if ( !PGM_PAGE_IS_MMIO_OR_ALIAS(pPage)
2491 /*|| not-out-of-action later */)
2492 {
2493 fAllMMIO = false;
2494 AssertMsgFailed(("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), pPage));
2495 break;
2496 }
2497 Assert( PGM_PAGE_IS_ZERO(pPage)
2498 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2_ALIAS_MMIO
2499 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_SPECIAL_ALIAS_MMIO);
2500 pPage++;
2501 }
2502 if (fAllMMIO)
2503 {
2504 /*
2505 * Ad-hoc range, unlink and free it.
2506 */
2507 Log(("PGMR3PhysMMIODeregister: Freeing ad hoc MMIO range for %RGp-%RGp %s\n",
2508 GCPhys, GCPhysLast, pRam->pszDesc));
2509 /** @todo check the ad-hoc flags? */
2510
2511#ifdef VBOX_WITH_NATIVE_NEM
2512 if (VM_IS_NEM_ENABLED(pVM)) /* Notify REM before we unlink the range. */
2513 {
2514 rc = NEMR3NotifyPhysMmioExUnmap(pVM, GCPhys, GCPhysLast - GCPhys + 1, 0 /*fFlags*/,
2515 NULL, NULL, NULL, &pRam->uNemRange);
2516 AssertLogRelRCReturn(rc, rc);
2517 }
2518#endif
2519
2520 pVM->pgm.s.cAllPages -= cGuestPages;
2521 pVM->pgm.s.cPureMmioPages -= cGuestPages;
2522
2523 pgmR3PhysUnlinkRamRange2(pVM, pRam, pRamPrev);
2524 const uint32_t cPages = pRam->cb >> GUEST_PAGE_SHIFT;
2525 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
2526 pRam->cb = pRam->GCPhys = pRam->GCPhysLast = NIL_RTGCPHYS;
2527 SUPR3PageFreeEx(pRam, RT_ALIGN_Z(cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT);
2528 break;
2529 }
2530 }
2531
2532 /*
2533 * Range match? It will all be within one range (see PGMAllHandler.cpp).
2534 */
2535 if ( GCPhysLast >= pRam->GCPhys
2536 && GCPhys <= pRam->GCPhysLast)
2537 {
2538 Assert(GCPhys >= pRam->GCPhys);
2539 Assert(GCPhysLast <= pRam->GCPhysLast);
2540
2541 /*
2542 * Turn the pages back into RAM pages.
2543 */
2544 uint32_t iPage = (GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT;
2545 uint32_t cLeft = cb >> GUEST_PAGE_SHIFT;
2546 while (cLeft--)
2547 {
2548 PPGMPAGE pPage = &pRam->aPages[iPage];
2549 AssertMsg( (PGM_PAGE_IS_MMIO(pPage) && PGM_PAGE_IS_ZERO(pPage))
2550 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2_ALIAS_MMIO
2551 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_SPECIAL_ALIAS_MMIO,
2552 ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), pPage));
2553 if (PGM_PAGE_IS_MMIO_OR_ALIAS(pPage))
2554 PGM_PAGE_SET_TYPE(pVM, pPage, PGMPAGETYPE_RAM);
2555 iPage++;
2556 }
2557
2558#ifdef VBOX_WITH_NATIVE_NEM
2559 /* Notify REM (failure will probably leave things in a non-working state). */
2560 if (VM_IS_NEM_ENABLED(pVM))
2561 {
2562 uint8_t u2State = UINT8_MAX;
2563 rc = NEMR3NotifyPhysMmioExUnmap(pVM, GCPhys, GCPhysLast - GCPhys + 1, NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE,
2564 pRam->pvR3 ? (uint8_t *)pRam->pvR3 + GCPhys - pRam->GCPhys : NULL,
2565 NULL, &u2State, &pRam->uNemRange);
2566 AssertLogRelRCReturn(rc, rc);
2567 if (u2State != UINT8_MAX)
2568 pgmPhysSetNemStateForPages(&pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT],
2569 cb >> GUEST_PAGE_SHIFT, u2State);
2570 }
2571#endif
2572 break;
2573 }
2574
2575 /* next */
2576 pRamPrev = pRam;
2577 pRam = pRam->pNextR3;
2578 }
2579 }
2580
2581 /* Force a PGM pool flush as guest ram references have been changed. */
2582 /** @todo Not entirely SMP safe; assuming for now the guest takes care of
2583 * this internally (not touch mapped mmio while changing the mapping). */
2584 PVMCPU pVCpu = VMMGetCpu(pVM);
2585 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2586 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2587
2588 pgmPhysInvalidatePageMapTLB(pVM);
2589 pgmPhysInvalidRamRangeTlbs(pVM);
2590 PGM_UNLOCK(pVM);
2591 return rc;
2592}
2593
2594
2595
2596/*********************************************************************************************************************************
2597* MMIO2 *
2598*********************************************************************************************************************************/
2599
2600/**
2601 * Locate a MMIO2 range.
2602 *
2603 * @returns Pointer to the MMIO2 range.
2604 * @param pVM The cross context VM structure.
2605 * @param pDevIns The device instance owning the region.
2606 * @param iSubDev The sub-device number.
2607 * @param iRegion The region.
2608 * @param hMmio2 Handle to look up. If NIL, use the @a iSubDev and
2609 * @a iRegion.
2610 */
2611DECLINLINE(PPGMREGMMIO2RANGE) pgmR3PhysMmio2Find(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev,
2612 uint32_t iRegion, PGMMMIO2HANDLE hMmio2)
2613{
2614 if (hMmio2 != NIL_PGMMMIO2HANDLE)
2615 {
2616 if (hMmio2 <= RT_ELEMENTS(pVM->pgm.s.apMmio2RangesR3) && hMmio2 != 0)
2617 {
2618 PPGMREGMMIO2RANGE pCur = pVM->pgm.s.apMmio2RangesR3[hMmio2 - 1];
2619 if (pCur && pCur->pDevInsR3 == pDevIns)
2620 {
2621 Assert(pCur->idMmio2 == hMmio2);
2622 AssertReturn(pCur->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK, NULL);
2623 return pCur;
2624 }
2625 Assert(!pCur);
2626 }
2627 for (PPGMREGMMIO2RANGE pCur = pVM->pgm.s.pRegMmioRangesR3; pCur; pCur = pCur->pNextR3)
2628 if (pCur->idMmio2 == hMmio2)
2629 {
2630 AssertBreak(pCur->pDevInsR3 == pDevIns);
2631 AssertReturn(pCur->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK, NULL);
2632 return pCur;
2633 }
2634 }
2635 else
2636 {
2637 /*
2638 * Search the list. There shouldn't be many entries.
2639 */
2640 /** @todo Optimize this lookup! There may now be many entries and it'll
2641 * become really slow when doing MMR3HyperMapMMIO2 and similar. */
2642 for (PPGMREGMMIO2RANGE pCur = pVM->pgm.s.pRegMmioRangesR3; pCur; pCur = pCur->pNextR3)
2643 if ( pCur->pDevInsR3 == pDevIns
2644 && pCur->iRegion == iRegion
2645 && pCur->iSubDev == iSubDev)
2646 return pCur;
2647 }
2648 return NULL;
2649}
2650
2651
2652/**
2653 * Worker for PGMR3PhysMmio2ControlDirtyPageTracking and PGMR3PhysMmio2Map.
2654 */
2655static int pgmR3PhysMmio2EnableDirtyPageTracing(PVM pVM, PPGMREGMMIO2RANGE pFirstMmio2)
2656{
2657 int rc = VINF_SUCCESS;
2658 for (PPGMREGMMIO2RANGE pCurMmio2 = pFirstMmio2; pCurMmio2; pCurMmio2 = pCurMmio2->pNextR3)
2659 {
2660 Assert(!(pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_IS_TRACKING));
2661 int rc2 = pgmHandlerPhysicalExRegister(pVM, pCurMmio2->pPhysHandlerR3, pCurMmio2->RamRange.GCPhys,
2662 pCurMmio2->RamRange.GCPhysLast);
2663 AssertLogRelMsgRC(rc2, ("%#RGp-%#RGp %s failed -> %Rrc\n", pCurMmio2->RamRange.GCPhys, pCurMmio2->RamRange.GCPhysLast,
2664 pCurMmio2->RamRange.pszDesc, rc2));
2665 if (RT_SUCCESS(rc2))
2666 pCurMmio2->fFlags |= PGMREGMMIO2RANGE_F_IS_TRACKING;
2667 else if (RT_SUCCESS(rc))
2668 rc = rc2;
2669 if (pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2670 return rc;
2671 }
2672 AssertFailed();
2673 return rc;
2674}
2675
2676
2677/**
2678 * Worker for PGMR3PhysMmio2ControlDirtyPageTracking and PGMR3PhysMmio2Unmap.
2679 */
2680static int pgmR3PhysMmio2DisableDirtyPageTracing(PVM pVM, PPGMREGMMIO2RANGE pFirstMmio2)
2681{
2682 for (PPGMREGMMIO2RANGE pCurMmio2 = pFirstMmio2; pCurMmio2; pCurMmio2 = pCurMmio2->pNextR3)
2683 {
2684 if (pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_IS_TRACKING)
2685 {
2686 int rc2 = pgmHandlerPhysicalExDeregister(pVM, pCurMmio2->pPhysHandlerR3);
2687 AssertLogRelMsgRC(rc2, ("%#RGp-%#RGp %s failed -> %Rrc\n", pCurMmio2->RamRange.GCPhys, pCurMmio2->RamRange.GCPhysLast,
2688 pCurMmio2->RamRange.pszDesc, rc2));
2689 pCurMmio2->fFlags &= ~PGMREGMMIO2RANGE_F_IS_TRACKING;
2690 }
2691 if (pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2692 return VINF_SUCCESS;
2693 }
2694 AssertFailed();
2695 return VINF_SUCCESS;
2696
2697}
2698
2699
2700/**
2701 * Calculates the number of chunks
2702 *
2703 * @returns Number of registration chunk needed.
2704 * @param pVM The cross context VM structure.
2705 * @param cb The size of the MMIO/MMIO2 range.
2706 * @param pcPagesPerChunk Where to return the number of pages tracked by each
2707 * chunk. Optional.
2708 * @param pcbChunk Where to return the guest mapping size for a chunk.
2709 */
2710static uint16_t pgmR3PhysMmio2CalcChunkCount(PVM pVM, RTGCPHYS cb, uint32_t *pcPagesPerChunk, uint32_t *pcbChunk)
2711{
2712 RT_NOREF_PV(pVM); /* without raw mode */
2713
2714 /*
2715 * This is the same calculation as PGMR3PhysRegisterRam does, except we'll be
2716 * needing a few bytes extra the PGMREGMMIO2RANGE structure.
2717 *
2718 * Note! In additions, we've got a 24 bit sub-page range for MMIO2 ranges, leaving
2719 * us with an absolute maximum of 16777215 pages per chunk (close to 64 GB).
2720 */
2721 uint32_t const cPagesPerChunk = _4M;
2722 Assert(RT_ALIGN_32(cPagesPerChunk, X86_PD_PAE_SHIFT - X86_PAGE_SHIFT)); /* NEM large page requirement: 1GB pages. */
2723 uint32_t const cbChunk = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE, RamRange.aPages[cPagesPerChunk]);
2724 AssertRelease(cPagesPerChunk < _16M);
2725
2726 if (pcbChunk)
2727 *pcbChunk = cbChunk;
2728 if (pcPagesPerChunk)
2729 *pcPagesPerChunk = cPagesPerChunk;
2730
2731 /* Calc the number of chunks we need. */
2732 RTGCPHYS const cGuestPages = cb >> GUEST_PAGE_SHIFT;
2733 uint16_t cChunks = (uint16_t)((cGuestPages + cPagesPerChunk - 1) / cPagesPerChunk);
2734 AssertRelease((RTGCPHYS)cChunks * cPagesPerChunk >= cGuestPages);
2735 return cChunks;
2736}
2737
2738
2739/**
2740 * Worker for PGMR3PhysMMIO2Register that allocates and the PGMREGMMIO2RANGE
2741 * structures and does basic initialization.
2742 *
2743 * Caller must set type specfic members and initialize the PGMPAGE structures.
2744 *
2745 * This was previously also used by PGMR3PhysMmio2PreRegister, a function for
2746 * pre-registering MMIO that was later (6.1) replaced by a new handle based IOM
2747 * interface. The reference to caller and type above is purely historical.
2748 *
2749 * @returns VBox status code.
2750 * @param pVM The cross context VM structure.
2751 * @param pDevIns The device instance owning the region.
2752 * @param iSubDev The sub-device number (internal PCI config number).
2753 * @param iRegion The region number. If the MMIO2 memory is a PCI
2754 * I/O region this number has to be the number of that
2755 * region. Otherwise it can be any number safe
2756 * UINT8_MAX.
2757 * @param cb The size of the region. Must be page aligned.
2758 * @param fFlags PGMPHYS_MMIO2_FLAGS_XXX.
2759 * @param idMmio2 The MMIO2 ID for the first chunk.
2760 * @param pszDesc The description.
2761 * @param ppHeadRet Where to return the pointer to the first
2762 * registration chunk.
2763 *
2764 * @thread EMT
2765 */
2766static int pgmR3PhysMmio2Create(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags,
2767 uint8_t idMmio2, const char *pszDesc, PPGMREGMMIO2RANGE *ppHeadRet)
2768{
2769 /*
2770 * Figure out how many chunks we need and of which size.
2771 */
2772 uint32_t cPagesPerChunk;
2773 uint16_t cChunks = pgmR3PhysMmio2CalcChunkCount(pVM, cb, &cPagesPerChunk, NULL);
2774 AssertReturn(cChunks, VERR_PGM_PHYS_MMIO_EX_IPE);
2775
2776 /*
2777 * Allocate the chunks.
2778 */
2779 PPGMREGMMIO2RANGE *ppNext = ppHeadRet;
2780 *ppNext = NULL;
2781
2782 int rc = VINF_SUCCESS;
2783 uint32_t cPagesLeft = cb >> GUEST_PAGE_SHIFT;
2784 for (uint16_t iChunk = 0; iChunk < cChunks && RT_SUCCESS(rc); iChunk++, idMmio2++)
2785 {
2786 /*
2787 * We currently do a single RAM range for the whole thing. This will
2788 * probably have to change once someone needs really large MMIO regions,
2789 * as we will be running into SUPR3PageAllocEx limitations and such.
2790 */
2791 const uint32_t cPagesTrackedByChunk = RT_MIN(cPagesLeft, cPagesPerChunk);
2792 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE, RamRange.aPages[cPagesTrackedByChunk]);
2793 PPGMREGMMIO2RANGE pNew = NULL;
2794
2795 /*
2796 * Allocate memory for the registration structure.
2797 */
2798 size_t const cChunkPages = RT_ALIGN_Z(cbRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
2799 size_t const cbChunk = (1 + cChunkPages + 1) << HOST_PAGE_SHIFT;
2800 AssertLogRelBreakStmt(cbChunk == (uint32_t)cbChunk, rc = VERR_OUT_OF_RANGE);
2801 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
2802 void *pvChunk = NULL;
2803 rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk, &R0PtrChunk, NULL /*paPages*/);
2804 AssertLogRelMsgRCBreak(rc, ("rc=%Rrc, cChunkPages=%#zx\n", rc, cChunkPages));
2805
2806 Assert(R0PtrChunk != NIL_RTR0PTR || PGM_IS_IN_NEM_MODE(pVM));
2807 RT_BZERO(pvChunk, cChunkPages << HOST_PAGE_SHIFT);
2808
2809 pNew = (PPGMREGMMIO2RANGE)pvChunk;
2810 pNew->RamRange.fFlags = PGM_RAM_RANGE_FLAGS_FLOATING;
2811 pNew->RamRange.pSelfR0 = R0PtrChunk + RT_UOFFSETOF(PGMREGMMIO2RANGE, RamRange);
2812
2813 /*
2814 * Initialize the registration structure (caller does specific bits).
2815 */
2816 pNew->pDevInsR3 = pDevIns;
2817 //pNew->pvR3 = NULL;
2818 //pNew->pNext = NULL;
2819 if (iChunk == 0)
2820 pNew->fFlags |= PGMREGMMIO2RANGE_F_FIRST_CHUNK;
2821 if (iChunk + 1 == cChunks)
2822 pNew->fFlags |= PGMREGMMIO2RANGE_F_LAST_CHUNK;
2823 if (fFlags & PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES)
2824 pNew->fFlags |= PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES;
2825 pNew->iSubDev = iSubDev;
2826 pNew->iRegion = iRegion;
2827 pNew->idSavedState = UINT8_MAX;
2828 pNew->idMmio2 = idMmio2;
2829 //pNew->pPhysHandlerR3 = NULL;
2830 //pNew->paLSPages = NULL;
2831 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
2832 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
2833 pNew->RamRange.pszDesc = pszDesc;
2834 pNew->RamRange.cb = pNew->cbReal = (RTGCPHYS)cPagesTrackedByChunk << X86_PAGE_SHIFT;
2835 pNew->RamRange.fFlags |= PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO_EX;
2836 pNew->RamRange.uNemRange = UINT32_MAX;
2837 //pNew->RamRange.pvR3 = NULL;
2838 //pNew->RamRange.paLSPages = NULL;
2839
2840 *ppNext = pNew;
2841 ASMCompilerBarrier();
2842 cPagesLeft -= cPagesTrackedByChunk;
2843 ppNext = &pNew->pNextR3;
2844
2845 /*
2846 * Pre-allocate a handler if we're tracking dirty pages, unless NEM takes care of this.
2847 */
2848 if ( (fFlags & PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES)
2849#ifdef VBOX_WITH_PGM_NEM_MODE
2850 && (!VM_IS_NEM_ENABLED(pVM) || !NEMR3IsMmio2DirtyPageTrackingSupported(pVM))
2851#endif
2852 )
2853
2854 {
2855 rc = pgmHandlerPhysicalExCreate(pVM, pVM->pgm.s.hMmio2DirtyPhysHandlerType, idMmio2, pszDesc, &pNew->pPhysHandlerR3);
2856 AssertLogRelMsgRCBreak(rc, ("idMmio2=%zu\n", idMmio2));
2857 }
2858 }
2859 Assert(cPagesLeft == 0);
2860
2861 if (RT_SUCCESS(rc))
2862 {
2863 Assert((*ppHeadRet)->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
2864 return VINF_SUCCESS;
2865 }
2866
2867 /*
2868 * Free floating ranges.
2869 */
2870 while (*ppHeadRet)
2871 {
2872 PPGMREGMMIO2RANGE pFree = *ppHeadRet;
2873 *ppHeadRet = pFree->pNextR3;
2874
2875 if (pFree->pPhysHandlerR3)
2876 {
2877 pgmHandlerPhysicalExDestroy(pVM, pFree->pPhysHandlerR3);
2878 pFree->pPhysHandlerR3 = NULL;
2879 }
2880
2881 if (pFree->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
2882 {
2883 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE,
2884 RamRange.aPages[pFree->RamRange.cb >> X86_PAGE_SHIFT]);
2885 size_t const cChunkPages = RT_ALIGN_Z(cbRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
2886 SUPR3PageFreeEx(pFree, cChunkPages);
2887 }
2888 }
2889
2890 return rc;
2891}
2892
2893
2894/**
2895 * Common worker PGMR3PhysMmio2PreRegister & PGMR3PhysMMIO2Register that links a
2896 * complete registration entry into the lists and lookup tables.
2897 *
2898 * @param pVM The cross context VM structure.
2899 * @param pNew The new MMIO / MMIO2 registration to link.
2900 */
2901static void pgmR3PhysMmio2Link(PVM pVM, PPGMREGMMIO2RANGE pNew)
2902{
2903 Assert(pNew->idMmio2 != UINT8_MAX);
2904
2905 /*
2906 * Link it into the list (order doesn't matter, so insert it at the head).
2907 *
2908 * Note! The range we're linking may consist of multiple chunks, so we
2909 * have to find the last one.
2910 */
2911 PPGMREGMMIO2RANGE pLast = pNew;
2912 for (pLast = pNew; ; pLast = pLast->pNextR3)
2913 {
2914 if (pLast->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2915 break;
2916 Assert(pLast->pNextR3);
2917 Assert(pLast->pNextR3->pDevInsR3 == pNew->pDevInsR3);
2918 Assert(pLast->pNextR3->iSubDev == pNew->iSubDev);
2919 Assert(pLast->pNextR3->iRegion == pNew->iRegion);
2920 Assert(pLast->pNextR3->idMmio2 == pLast->idMmio2 + 1);
2921 }
2922
2923 PGM_LOCK_VOID(pVM);
2924
2925 /* Link in the chain of ranges at the head of the list. */
2926 pLast->pNextR3 = pVM->pgm.s.pRegMmioRangesR3;
2927 pVM->pgm.s.pRegMmioRangesR3 = pNew;
2928
2929 /* Insert the MMIO2 range/page IDs. */
2930 uint8_t idMmio2 = pNew->idMmio2;
2931 for (;;)
2932 {
2933 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == NULL);
2934 Assert(pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] == NIL_RTR0PTR);
2935 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = pNew;
2936 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = pNew->RamRange.pSelfR0 - RT_UOFFSETOF(PGMREGMMIO2RANGE, RamRange);
2937 if (pNew->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2938 break;
2939 pNew = pNew->pNextR3;
2940 idMmio2++;
2941 }
2942
2943 pgmPhysInvalidatePageMapTLB(pVM);
2944 PGM_UNLOCK(pVM);
2945}
2946
2947
2948/**
2949 * Allocate and register an MMIO2 region.
2950 *
2951 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's RAM
2952 * associated with a device. It is also non-shared memory with a permanent
2953 * ring-3 mapping and page backing (presently).
2954 *
2955 * A MMIO2 range may overlap with base memory if a lot of RAM is configured for
2956 * the VM, in which case we'll drop the base memory pages. Presently we will
2957 * make no attempt to preserve anything that happens to be present in the base
2958 * memory that is replaced, this is of course incorrect but it's too much
2959 * effort.
2960 *
2961 * @returns VBox status code.
2962 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
2963 * memory.
2964 * @retval VERR_ALREADY_EXISTS if the region already exists.
2965 *
2966 * @param pVM The cross context VM structure.
2967 * @param pDevIns The device instance owning the region.
2968 * @param iSubDev The sub-device number.
2969 * @param iRegion The region number. If the MMIO2 memory is a PCI
2970 * I/O region this number has to be the number of that
2971 * region. Otherwise it can be any number save
2972 * UINT8_MAX.
2973 * @param cb The size of the region. Must be page aligned.
2974 * @param fFlags Reserved for future use, must be zero.
2975 * @param pszDesc The description.
2976 * @param ppv Where to store the pointer to the ring-3 mapping of
2977 * the memory.
2978 * @param phRegion Where to return the MMIO2 region handle. Optional.
2979 * @thread EMT
2980 */
2981VMMR3_INT_DECL(int) PGMR3PhysMmio2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cb,
2982 uint32_t fFlags, const char *pszDesc, void **ppv, PGMMMIO2HANDLE *phRegion)
2983{
2984 /*
2985 * Validate input.
2986 */
2987 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
2988 *ppv = NULL;
2989 if (phRegion)
2990 {
2991 AssertPtrReturn(phRegion, VERR_INVALID_POINTER);
2992 *phRegion = NIL_PGMMMIO2HANDLE;
2993 }
2994 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2995 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2996 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
2997 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2998 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2999 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
3000 AssertReturn(pgmR3PhysMmio2Find(pVM, pDevIns, iSubDev, iRegion, NIL_PGMMMIO2HANDLE) == NULL, VERR_ALREADY_EXISTS);
3001 AssertReturn(!(cb & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3002 AssertReturn(cb, VERR_INVALID_PARAMETER);
3003 AssertReturn(!(fFlags & ~PGMPHYS_MMIO2_FLAGS_VALID_MASK), VERR_INVALID_FLAGS);
3004
3005 const uint32_t cGuestPages = cb >> GUEST_PAGE_SHIFT;
3006 AssertLogRelReturn(((RTGCPHYS)cGuestPages << GUEST_PAGE_SHIFT) == cb, VERR_INVALID_PARAMETER);
3007 AssertLogRelReturn(cGuestPages <= (MM_MMIO_64_MAX >> X86_PAGE_SHIFT), VERR_OUT_OF_RANGE);
3008 AssertLogRelReturn(cGuestPages <= PGM_MMIO2_MAX_PAGE_COUNT, VERR_OUT_OF_RANGE);
3009
3010 /*
3011 * For the 2nd+ instance, mangle the description string so it's unique.
3012 */
3013 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
3014 {
3015 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
3016 if (!pszDesc)
3017 return VERR_NO_MEMORY;
3018 }
3019
3020 /*
3021 * Allocate an MMIO2 range ID (not freed on failure).
3022 *
3023 * The zero ID is not used as it could be confused with NIL_GMM_PAGEID, so
3024 * the IDs goes from 1 thru PGM_MMIO2_MAX_RANGES.
3025 */
3026 unsigned cChunks = pgmR3PhysMmio2CalcChunkCount(pVM, cb, NULL, NULL);
3027
3028 PGM_LOCK_VOID(pVM);
3029 AssertCompile(PGM_MMIO2_MAX_RANGES < 255);
3030 uint8_t const idMmio2 = pVM->pgm.s.cMmio2Regions + 1;
3031 unsigned const cNewMmio2Regions = pVM->pgm.s.cMmio2Regions + cChunks;
3032 if (cNewMmio2Regions > PGM_MMIO2_MAX_RANGES)
3033 {
3034 PGM_UNLOCK(pVM);
3035 AssertLogRelFailedReturn(VERR_PGM_TOO_MANY_MMIO2_RANGES);
3036 }
3037 pVM->pgm.s.cMmio2Regions = cNewMmio2Regions;
3038 PGM_UNLOCK(pVM);
3039
3040 /*
3041 * Try reserve and allocate the backing memory first as this is what is
3042 * most likely to fail.
3043 */
3044 int rc = MMR3AdjustFixedReservation(pVM, cGuestPages, pszDesc);
3045 if (RT_SUCCESS(rc))
3046 {
3047 const uint32_t cHostPages = RT_ALIGN_T(cb, HOST_PAGE_SIZE, RTGCPHYS) >> HOST_PAGE_SHIFT;
3048 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cHostPages * sizeof(SUPPAGE));
3049 if (RT_SUCCESS(rc))
3050 {
3051 void *pvPages = NULL;
3052#ifndef VBOX_WITH_LINEAR_HOST_PHYS_MEM
3053 RTR0PTR pvPagesR0 = NIL_RTR0PTR;
3054#endif
3055#ifdef VBOX_WITH_PGM_NEM_MODE
3056 if (PGM_IS_IN_NEM_MODE(pVM))
3057 rc = SUPR3PageAlloc(cHostPages, pVM->pgm.s.fUseLargePages ? SUP_PAGE_ALLOC_F_LARGE_PAGES : 0, &pvPages);
3058 else
3059#endif
3060 {
3061#ifndef VBOX_WITH_LINEAR_HOST_PHYS_MEM
3062 rc = SUPR3PageAllocEx(cHostPages, 0 /*fFlags*/, &pvPages, &pvPagesR0, paPages);
3063#else
3064 rc = SUPR3PageAllocEx(cHostPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
3065#endif
3066 }
3067 if (RT_SUCCESS(rc))
3068 {
3069 memset(pvPages, 0, cGuestPages * GUEST_PAGE_SIZE);
3070
3071 /*
3072 * Create the registered MMIO range record for it.
3073 */
3074 PPGMREGMMIO2RANGE pNew;
3075 rc = pgmR3PhysMmio2Create(pVM, pDevIns, iSubDev, iRegion, cb, fFlags, idMmio2, pszDesc, &pNew);
3076 if (RT_SUCCESS(rc))
3077 {
3078 if (phRegion)
3079 *phRegion = idMmio2; /* The ID of the first chunk. */
3080
3081 uint32_t iSrcPage = 0;
3082 uint8_t *pbCurPages = (uint8_t *)pvPages;
3083 for (PPGMREGMMIO2RANGE pCur = pNew; pCur; pCur = pCur->pNextR3)
3084 {
3085 pCur->pvR3 = pbCurPages;
3086#ifndef VBOX_WITH_LINEAR_HOST_PHYS_MEM
3087 pCur->pvR0 = pvPagesR0 + (iSrcPage << GUEST_PAGE_SHIFT);
3088#endif
3089 pCur->RamRange.pvR3 = pbCurPages;
3090
3091 uint32_t iDstPage = pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3092#ifdef VBOX_WITH_PGM_NEM_MODE
3093 if (PGM_IS_IN_NEM_MODE(pVM))
3094 while (iDstPage-- > 0)
3095 PGM_PAGE_INIT(&pNew->RamRange.aPages[iDstPage], UINT64_C(0x0000ffffffff0000),
3096 PGM_MMIO2_PAGEID_MAKE(idMmio2, iDstPage),
3097 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
3098 else
3099#endif
3100 {
3101 AssertRelease(HOST_PAGE_SHIFT == GUEST_PAGE_SHIFT);
3102 while (iDstPage-- > 0)
3103 PGM_PAGE_INIT(&pNew->RamRange.aPages[iDstPage], paPages[iDstPage + iSrcPage].Phys,
3104 PGM_MMIO2_PAGEID_MAKE(idMmio2, iDstPage),
3105 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
3106 }
3107
3108 /* advance. */
3109 iSrcPage += pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3110 pbCurPages += pCur->RamRange.cb;
3111 }
3112
3113 RTMemTmpFree(paPages);
3114
3115 /*
3116 * Update the page count stats, link the registration and we're done.
3117 */
3118 pVM->pgm.s.cAllPages += cGuestPages;
3119 pVM->pgm.s.cPrivatePages += cGuestPages;
3120
3121 pgmR3PhysMmio2Link(pVM, pNew);
3122
3123 *ppv = pvPages;
3124 return VINF_SUCCESS;
3125 }
3126
3127 SUPR3PageFreeEx(pvPages, cHostPages);
3128 }
3129 }
3130 RTMemTmpFree(paPages);
3131 MMR3AdjustFixedReservation(pVM, -(int32_t)cGuestPages, pszDesc);
3132 }
3133 if (pDevIns->iInstance > 0)
3134 MMR3HeapFree((void *)pszDesc);
3135 return rc;
3136}
3137
3138
3139/**
3140 * Deregisters and frees an MMIO2 region.
3141 *
3142 * Any physical access handlers registered for the region must be deregistered
3143 * before calling this function.
3144 *
3145 * @returns VBox status code.
3146 * @param pVM The cross context VM structure.
3147 * @param pDevIns The device instance owning the region.
3148 * @param hMmio2 The MMIO2 handle to deregister, or NIL if all
3149 * regions for the given device is to be deregistered.
3150 */
3151VMMR3_INT_DECL(int) PGMR3PhysMmio2Deregister(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2)
3152{
3153 /*
3154 * Validate input.
3155 */
3156 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3157 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3158
3159 /*
3160 * The loop here scanning all registrations will make sure that multi-chunk ranges
3161 * get properly deregistered, though it's original purpose was the wildcard iRegion.
3162 */
3163 PGM_LOCK_VOID(pVM);
3164 int rc = VINF_SUCCESS;
3165 unsigned cFound = 0;
3166 PPGMREGMMIO2RANGE pPrev = NULL;
3167 PPGMREGMMIO2RANGE pCur = pVM->pgm.s.pRegMmioRangesR3;
3168 while (pCur)
3169 {
3170 uint32_t const fFlags = pCur->fFlags;
3171 if ( pCur->pDevInsR3 == pDevIns
3172 && ( hMmio2 == NIL_PGMMMIO2HANDLE
3173 || pCur->idMmio2 == hMmio2))
3174 {
3175 cFound++;
3176
3177 /*
3178 * Unmap it if it's mapped.
3179 */
3180 if (fFlags & PGMREGMMIO2RANGE_F_MAPPED)
3181 {
3182 int rc2 = PGMR3PhysMmio2Unmap(pVM, pCur->pDevInsR3, pCur->idMmio2, pCur->RamRange.GCPhys);
3183 AssertRC(rc2);
3184 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3185 rc = rc2;
3186 }
3187
3188 /*
3189 * Unlink it
3190 */
3191 PPGMREGMMIO2RANGE pNext = pCur->pNextR3;
3192 if (pPrev)
3193 pPrev->pNextR3 = pNext;
3194 else
3195 pVM->pgm.s.pRegMmioRangesR3 = pNext;
3196 pCur->pNextR3 = NULL;
3197
3198 uint8_t idMmio2 = pCur->idMmio2;
3199 Assert(idMmio2 <= RT_ELEMENTS(pVM->pgm.s.apMmio2RangesR3));
3200 if (idMmio2 <= RT_ELEMENTS(pVM->pgm.s.apMmio2RangesR3))
3201 {
3202 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == pCur);
3203 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = NULL;
3204 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = NIL_RTR0PTR;
3205 }
3206
3207 /*
3208 * Free the memory.
3209 */
3210 uint32_t const cGuestPages = pCur->cbReal >> GUEST_PAGE_SHIFT;
3211 uint32_t const cHostPages = RT_ALIGN_T(pCur->cbReal, HOST_PAGE_SIZE, RTGCPHYS) >> HOST_PAGE_SHIFT;
3212#ifdef VBOX_WITH_PGM_NEM_MODE
3213 if (!pVM->pgm.s.fNemMode)
3214#endif
3215 {
3216 int rc2 = SUPR3PageFreeEx(pCur->pvR3, cHostPages);
3217 AssertRC(rc2);
3218 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3219 rc = rc2;
3220
3221 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cGuestPages, pCur->RamRange.pszDesc);
3222 AssertRC(rc2);
3223 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3224 rc = rc2;
3225 }
3226#ifdef VBOX_WITH_PGM_NEM_MODE
3227 else
3228 {
3229 int rc2 = SUPR3PageFreeEx(pCur->pvR3, cHostPages);
3230 AssertRC(rc2);
3231 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3232 rc = rc2;
3233 }
3234#endif
3235
3236 if (pCur->pPhysHandlerR3)
3237 {
3238 pgmHandlerPhysicalExDestroy(pVM, pCur->pPhysHandlerR3);
3239 pCur->pPhysHandlerR3 = NULL;
3240 }
3241
3242 /* we're leaking hyper memory here if done at runtime. */
3243#ifdef VBOX_STRICT
3244 VMSTATE const enmState = VMR3GetState(pVM);
3245 AssertMsg( enmState == VMSTATE_POWERING_OFF
3246 || enmState == VMSTATE_POWERING_OFF_LS
3247 || enmState == VMSTATE_OFF
3248 || enmState == VMSTATE_OFF_LS
3249 || enmState == VMSTATE_DESTROYING
3250 || enmState == VMSTATE_TERMINATED
3251 || enmState == VMSTATE_CREATING
3252 , ("%s\n", VMR3GetStateName(enmState)));
3253#endif
3254
3255 if (pCur->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
3256 {
3257 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE, RamRange.aPages[cGuestPages]);
3258 size_t const cChunkPages = RT_ALIGN_Z(cbRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
3259 SUPR3PageFreeEx(pCur, cChunkPages);
3260 }
3261 /*else
3262 {
3263 rc = MMHyperFree(pVM, pCur); - does not work, see the alloc call.
3264 AssertRCReturn(rc, rc);
3265 } */
3266
3267
3268 /* update page count stats */
3269 pVM->pgm.s.cAllPages -= cGuestPages;
3270 pVM->pgm.s.cPrivatePages -= cGuestPages;
3271
3272 /* next */
3273 pCur = pNext;
3274 if (hMmio2 != NIL_PGMMMIO2HANDLE)
3275 {
3276 if (fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3277 break;
3278 hMmio2++;
3279 Assert(pCur->idMmio2 == hMmio2);
3280 Assert(pCur->pDevInsR3 == pDevIns);
3281 Assert(!(pCur->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK));
3282 }
3283 }
3284 else
3285 {
3286 pPrev = pCur;
3287 pCur = pCur->pNextR3;
3288 }
3289 }
3290 pgmPhysInvalidatePageMapTLB(pVM);
3291 PGM_UNLOCK(pVM);
3292 return !cFound && hMmio2 != NIL_PGMMMIO2HANDLE ? VERR_NOT_FOUND : rc;
3293}
3294
3295
3296/**
3297 * Maps a MMIO2 region.
3298 *
3299 * This is typically done when a guest / the bios / state loading changes the
3300 * PCI config. The replacing of base memory has the same restrictions as during
3301 * registration, of course.
3302 *
3303 * @returns VBox status code.
3304 *
3305 * @param pVM The cross context VM structure.
3306 * @param pDevIns The device instance owning the region.
3307 * @param hMmio2 The handle of the region to map.
3308 * @param GCPhys The guest-physical address to be remapped.
3309 */
3310VMMR3_INT_DECL(int) PGMR3PhysMmio2Map(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, RTGCPHYS GCPhys)
3311{
3312 /*
3313 * Validate input.
3314 *
3315 * Note! It's safe to walk the MMIO/MMIO2 list since registrations only
3316 * happens during VM construction.
3317 */
3318 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3319 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3320 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
3321 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
3322 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3323 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
3324
3325 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3326 AssertReturn(pFirstMmio, VERR_NOT_FOUND);
3327 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
3328
3329 PPGMREGMMIO2RANGE pLastMmio = pFirstMmio;
3330 RTGCPHYS cbRange = 0;
3331 for (;;)
3332 {
3333 AssertReturn(!(pLastMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED), VERR_WRONG_ORDER);
3334 Assert(pLastMmio->RamRange.GCPhys == NIL_RTGCPHYS);
3335 Assert(pLastMmio->RamRange.GCPhysLast == NIL_RTGCPHYS);
3336 Assert(pLastMmio->pDevInsR3 == pFirstMmio->pDevInsR3);
3337 Assert(pLastMmio->iSubDev == pFirstMmio->iSubDev);
3338 Assert(pLastMmio->iRegion == pFirstMmio->iRegion);
3339 cbRange += pLastMmio->RamRange.cb;
3340 if (pLastMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3341 break;
3342 pLastMmio = pLastMmio->pNextR3;
3343 }
3344
3345 RTGCPHYS GCPhysLast = GCPhys + cbRange - 1;
3346 AssertLogRelReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3347
3348 /*
3349 * Find our location in the ram range list, checking for restriction
3350 * we don't bother implementing yet (partially overlapping, multiple
3351 * ram ranges).
3352 */
3353 PGM_LOCK_VOID(pVM);
3354
3355 AssertReturnStmt(!(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED), PGM_UNLOCK(pVM), VERR_WRONG_ORDER);
3356
3357 bool fRamExists = false;
3358 PPGMRAMRANGE pRamPrev = NULL;
3359 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3360 while (pRam && GCPhysLast >= pRam->GCPhys)
3361 {
3362 if ( GCPhys <= pRam->GCPhysLast
3363 && GCPhysLast >= pRam->GCPhys)
3364 {
3365 /* Completely within? */
3366 AssertLogRelMsgReturnStmt( GCPhys >= pRam->GCPhys
3367 && GCPhysLast <= pRam->GCPhysLast,
3368 ("%RGp-%RGp (MMIOEx/%s) falls partly outside %RGp-%RGp (%s)\n",
3369 GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc,
3370 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
3371 PGM_UNLOCK(pVM),
3372 VERR_PGM_RAM_CONFLICT);
3373
3374 /* Check that all the pages are RAM pages. */
3375 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
3376 uint32_t cPagesLeft = cbRange >> GUEST_PAGE_SHIFT;
3377 while (cPagesLeft-- > 0)
3378 {
3379 AssertLogRelMsgReturnStmt(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
3380 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
3381 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc),
3382 PGM_UNLOCK(pVM),
3383 VERR_PGM_RAM_CONFLICT);
3384 pPage++;
3385 }
3386
3387 /* There can only be one MMIO/MMIO2 chunk matching here! */
3388 AssertLogRelMsgReturnStmt(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK,
3389 ("%RGp-%RGp (MMIOEx/%s, flags %#X) consists of multiple chunks whereas the RAM somehow doesn't!\n",
3390 GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc, pFirstMmio->fFlags),
3391 PGM_UNLOCK(pVM),
3392 VERR_PGM_PHYS_MMIO_EX_IPE);
3393
3394 fRamExists = true;
3395 break;
3396 }
3397
3398 /* next */
3399 pRamPrev = pRam;
3400 pRam = pRam->pNextR3;
3401 }
3402 Log(("PGMR3PhysMmio2Map: %RGp-%RGp fRamExists=%RTbool %s\n", GCPhys, GCPhysLast, fRamExists, pFirstMmio->RamRange.pszDesc));
3403
3404
3405 /*
3406 * Make the changes.
3407 */
3408 RTGCPHYS GCPhysCur = GCPhys;
3409 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3410 {
3411 pCurMmio->RamRange.GCPhys = GCPhysCur;
3412 pCurMmio->RamRange.GCPhysLast = GCPhysCur + pCurMmio->RamRange.cb - 1;
3413 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3414 {
3415 Assert(pCurMmio->RamRange.GCPhysLast == GCPhysLast);
3416 break;
3417 }
3418 GCPhysCur += pCurMmio->RamRange.cb;
3419 }
3420
3421 if (fRamExists)
3422 {
3423 /*
3424 * Make all the pages in the range MMIO/ZERO pages, freeing any
3425 * RAM pages currently mapped here. This might not be 100% correct
3426 * for PCI memory, but we're doing the same thing for MMIO2 pages.
3427 *
3428 * We replace these MMIO/ZERO pages with real pages in the MMIO2 case.
3429 */
3430 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK); /* Only one chunk */
3431 Assert(pFirstMmio->pvR3 == pFirstMmio->RamRange.pvR3);
3432 Assert(pFirstMmio->RamRange.pvR3 != NULL);
3433
3434#ifdef VBOX_WITH_PGM_NEM_MODE
3435 /* We cannot mix MMIO2 into a RAM range in simplified memory mode because pRam->pvR3 can't point
3436 both at the RAM and MMIO2, so we won't ever write & read from the actual MMIO2 memory if we try. */
3437 AssertLogRelMsgReturn(!pVM->pgm.s.fNemMode, ("%s at %RGp-%RGp\n", pFirstMmio->RamRange.pszDesc, GCPhys, GCPhysLast),
3438 VERR_PGM_NOT_SUPPORTED_FOR_NEM_MODE);
3439#endif
3440
3441 int rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, pFirstMmio->RamRange.pvR3);
3442 AssertRCReturnStmt(rc, PGM_UNLOCK(pVM), rc);
3443
3444 /* Replace the pages, freeing all present RAM pages. */
3445 PPGMPAGE pPageSrc = &pFirstMmio->RamRange.aPages[0];
3446 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
3447 uint32_t cPagesLeft = pFirstMmio->RamRange.cb >> GUEST_PAGE_SHIFT;
3448 while (cPagesLeft-- > 0)
3449 {
3450 Assert(PGM_PAGE_IS_MMIO(pPageDst));
3451
3452 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
3453 uint32_t const idPage = PGM_PAGE_GET_PAGEID(pPageSrc);
3454 PGM_PAGE_SET_PAGEID(pVM, pPageDst, idPage);
3455 PGM_PAGE_SET_HCPHYS(pVM, pPageDst, HCPhys);
3456 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO2);
3457 PGM_PAGE_SET_STATE(pVM, pPageDst, PGM_PAGE_STATE_ALLOCATED);
3458 PGM_PAGE_SET_PDE_TYPE(pVM, pPageDst, PGM_PAGE_PDE_TYPE_DONTCARE);
3459 PGM_PAGE_SET_PTE_INDEX(pVM, pPageDst, 0);
3460 PGM_PAGE_SET_TRACKING(pVM, pPageDst, 0);
3461 /* NEM state is set by pgmR3PhysFreePageRange. */
3462
3463 pVM->pgm.s.cZeroPages--;
3464 GCPhys += GUEST_PAGE_SIZE;
3465 pPageSrc++;
3466 pPageDst++;
3467 }
3468
3469 /* Flush physical page map TLB. */
3470 pgmPhysInvalidatePageMapTLB(pVM);
3471
3472 /* Force a PGM pool flush as guest ram references have been changed. */
3473 /** @todo not entirely SMP safe; assuming for now the guest takes care of
3474 * this internally (not touch mapped mmio while changing the mapping). */
3475 PVMCPU pVCpu = VMMGetCpu(pVM);
3476 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
3477 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3478 }
3479 else
3480 {
3481 /*
3482 * No RAM range, insert the ones prepared during registration.
3483 */
3484 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3485 {
3486#ifdef VBOX_WITH_NATIVE_NEM
3487 /* Tell NEM and get the new NEM state for the pages. */
3488 uint8_t u2NemState = 0;
3489 if (VM_IS_NEM_ENABLED(pVM))
3490 {
3491 int rc = NEMR3NotifyPhysMmioExMapEarly(pVM, pCurMmio->RamRange.GCPhys,
3492 pCurMmio->RamRange.GCPhysLast - pCurMmio->RamRange.GCPhys + 1,
3493 NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2
3494 | (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES
3495 ? NEM_NOTIFY_PHYS_MMIO_EX_F_TRACK_DIRTY_PAGES : 0),
3496 NULL /*pvRam*/, pCurMmio->RamRange.pvR3,
3497 &u2NemState, &pCurMmio->RamRange.uNemRange);
3498 AssertLogRelRCReturnStmt(rc, PGM_UNLOCK(pVM), rc);
3499 }
3500#endif
3501
3502 /* Clear the tracking data of pages we're going to reactivate. */
3503 PPGMPAGE pPageSrc = &pCurMmio->RamRange.aPages[0];
3504 uint32_t cPagesLeft = pCurMmio->RamRange.cb >> GUEST_PAGE_SHIFT;
3505 while (cPagesLeft-- > 0)
3506 {
3507 PGM_PAGE_SET_TRACKING(pVM, pPageSrc, 0);
3508 PGM_PAGE_SET_PTE_INDEX(pVM, pPageSrc, 0);
3509#ifdef VBOX_WITH_NATIVE_NEM
3510 PGM_PAGE_SET_NEM_STATE(pPageSrc, u2NemState);
3511#endif
3512 pPageSrc++;
3513 }
3514
3515 /* link in the ram range */
3516 pgmR3PhysLinkRamRange(pVM, &pCurMmio->RamRange, pRamPrev);
3517
3518 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3519 {
3520 Assert(pCurMmio->RamRange.GCPhysLast == GCPhysLast);
3521 break;
3522 }
3523 pRamPrev = &pCurMmio->RamRange;
3524 }
3525 }
3526
3527 /*
3528 * If the range have dirty page monitoring enabled, enable that.
3529 *
3530 * We ignore failures here for now because if we fail, the whole mapping
3531 * will have to be reversed and we'll end up with nothing at all on the
3532 * screen and a grumpy guest, whereas if we just go on, we'll only have
3533 * visual distortions to gripe about. There will be something in the
3534 * release log.
3535 */
3536 if ( pFirstMmio->pPhysHandlerR3
3537 && (pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3538 pgmR3PhysMmio2EnableDirtyPageTracing(pVM, pFirstMmio);
3539
3540 /*
3541 * We're good, set the flags and invalid the mapping TLB.
3542 */
3543 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3544 {
3545 pCurMmio->fFlags |= PGMREGMMIO2RANGE_F_MAPPED;
3546 if (fRamExists)
3547 pCurMmio->fFlags |= PGMREGMMIO2RANGE_F_OVERLAPPING;
3548 else
3549 pCurMmio->fFlags &= ~PGMREGMMIO2RANGE_F_OVERLAPPING;
3550 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3551 break;
3552 }
3553 pgmPhysInvalidatePageMapTLB(pVM);
3554
3555#ifdef VBOX_WITH_NATIVE_NEM
3556 /*
3557 * Late NEM notification.
3558 */
3559 if (VM_IS_NEM_ENABLED(pVM))
3560 {
3561 int rc;
3562 uint32_t fNemFlags = NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2;
3563 if (pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES)
3564 fNemFlags |= NEM_NOTIFY_PHYS_MMIO_EX_F_TRACK_DIRTY_PAGES;
3565 if (fRamExists)
3566 rc = NEMR3NotifyPhysMmioExMapLate(pVM, GCPhys, GCPhysLast - GCPhys + 1, fNemFlags | NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE,
3567 pRam->pvR3 ? (uint8_t *)pRam->pvR3 + GCPhys - pRam->GCPhys : NULL, pFirstMmio->pvR3,
3568 NULL /*puNemRange*/);
3569 else
3570 {
3571 rc = VINF_SUCCESS;
3572 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3573 {
3574 rc = NEMR3NotifyPhysMmioExMapLate(pVM, pCurMmio->RamRange.GCPhys, pCurMmio->RamRange.cb, fNemFlags,
3575 NULL, pCurMmio->RamRange.pvR3, &pCurMmio->RamRange.uNemRange);
3576 if ((pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK) || RT_FAILURE(rc))
3577 break;
3578 }
3579 }
3580 AssertLogRelRCReturnStmt(rc, PGMR3PhysMmio2Unmap(pVM, pDevIns, hMmio2, GCPhys); PGM_UNLOCK(pVM), rc);
3581 }
3582#endif
3583
3584 PGM_UNLOCK(pVM);
3585
3586 return VINF_SUCCESS;
3587}
3588
3589
3590/**
3591 * Unmaps an MMIO2 region.
3592 *
3593 * This is typically done when a guest / the bios / state loading changes the
3594 * PCI config. The replacing of base memory has the same restrictions as during
3595 * registration, of course.
3596 */
3597VMMR3_INT_DECL(int) PGMR3PhysMmio2Unmap(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, RTGCPHYS GCPhys)
3598{
3599 /*
3600 * Validate input
3601 */
3602 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3603 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3604 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
3605 if (GCPhys != NIL_RTGCPHYS)
3606 {
3607 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
3608 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3609 }
3610
3611 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3612 AssertReturn(pFirstMmio, VERR_NOT_FOUND);
3613 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
3614
3615 int rc = PGM_LOCK(pVM);
3616 AssertRCReturn(rc, rc);
3617
3618 PPGMREGMMIO2RANGE pLastMmio = pFirstMmio;
3619 RTGCPHYS cbRange = 0;
3620 for (;;)
3621 {
3622 AssertReturnStmt(pLastMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED, PGM_UNLOCK(pVM), VERR_WRONG_ORDER);
3623 AssertReturnStmt(pLastMmio->RamRange.GCPhys == GCPhys + cbRange || GCPhys == NIL_RTGCPHYS, PGM_UNLOCK(pVM), VERR_INVALID_PARAMETER);
3624 Assert(pLastMmio->pDevInsR3 == pFirstMmio->pDevInsR3);
3625 Assert(pLastMmio->iSubDev == pFirstMmio->iSubDev);
3626 Assert(pLastMmio->iRegion == pFirstMmio->iRegion);
3627 cbRange += pLastMmio->RamRange.cb;
3628 if (pLastMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3629 break;
3630 pLastMmio = pLastMmio->pNextR3;
3631 }
3632
3633 Log(("PGMR3PhysMmio2Unmap: %RGp-%RGp %s\n",
3634 pFirstMmio->RamRange.GCPhys, pLastMmio->RamRange.GCPhysLast, pFirstMmio->RamRange.pszDesc));
3635
3636 uint16_t const fOldFlags = pFirstMmio->fFlags;
3637 AssertReturnStmt(fOldFlags & PGMREGMMIO2RANGE_F_MAPPED, PGM_UNLOCK(pVM), VERR_WRONG_ORDER);
3638
3639 /*
3640 * If monitoring dirty pages, we must deregister the handlers first.
3641 */
3642 if ( pFirstMmio->pPhysHandlerR3
3643 && (fOldFlags & PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3644 pgmR3PhysMmio2DisableDirtyPageTracing(pVM, pFirstMmio);
3645
3646 /*
3647 * Unmap it.
3648 */
3649 int rcRet = VINF_SUCCESS;
3650#ifdef VBOX_WITH_NATIVE_NEM
3651 uint32_t const fNemFlags = NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2
3652 | (fOldFlags & PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES
3653 ? NEM_NOTIFY_PHYS_MMIO_EX_F_TRACK_DIRTY_PAGES : 0);
3654#endif
3655 if (fOldFlags & PGMREGMMIO2RANGE_F_OVERLAPPING)
3656 {
3657 /*
3658 * We've replaced RAM, replace with zero pages.
3659 *
3660 * Note! This is where we might differ a little from a real system, because
3661 * it's likely to just show the RAM pages as they were before the
3662 * MMIO/MMIO2 region was mapped here.
3663 */
3664 /* Only one chunk allowed when overlapping! */
3665 Assert(fOldFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK);
3666
3667 /* Restore the RAM pages we've replaced. */
3668 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3669 while (pRam->GCPhys > pFirstMmio->RamRange.GCPhysLast)
3670 pRam = pRam->pNextR3;
3671
3672 PPGMPAGE pPageDst = &pRam->aPages[(pFirstMmio->RamRange.GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
3673 uint32_t cPagesLeft = pFirstMmio->RamRange.cb >> GUEST_PAGE_SHIFT;
3674 pVM->pgm.s.cZeroPages += cPagesLeft; /** @todo not correct for NEM mode */
3675
3676#ifdef VBOX_WITH_NATIVE_NEM
3677 if (VM_IS_NEM_ENABLED(pVM)) /* Notify NEM. Note! we cannot be here in simple memory mode, see mapping function. */
3678 {
3679 uint8_t u2State = UINT8_MAX;
3680 rc = NEMR3NotifyPhysMmioExUnmap(pVM, pFirstMmio->RamRange.GCPhys, pFirstMmio->RamRange.cb,
3681 fNemFlags | NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE,
3682 pRam->pvR3
3683 ? (uint8_t *)pRam->pvR3 + pFirstMmio->RamRange.GCPhys - pRam->GCPhys : NULL,
3684 pFirstMmio->pvR3, &u2State, &pRam->uNemRange);
3685 AssertRCStmt(rc, rcRet = rc);
3686 if (u2State != UINT8_MAX)
3687 pgmPhysSetNemStateForPages(pPageDst, cPagesLeft, u2State);
3688 }
3689#endif
3690
3691 while (cPagesLeft-- > 0)
3692 {
3693 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
3694 pPageDst++;
3695 }
3696
3697 /* Flush physical page map TLB. */
3698 pgmPhysInvalidatePageMapTLB(pVM);
3699
3700 /* Update range state. */
3701 pFirstMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3702 pFirstMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3703 pFirstMmio->fFlags &= ~(PGMREGMMIO2RANGE_F_OVERLAPPING | PGMREGMMIO2RANGE_F_MAPPED);
3704 }
3705 else
3706 {
3707 /*
3708 * Unlink the chunks related to the MMIO/MMIO2 region.
3709 */
3710 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3711 {
3712#ifdef VBOX_WITH_NATIVE_NEM
3713 if (VM_IS_NEM_ENABLED(pVM)) /* Notify NEM. */
3714 {
3715 uint8_t u2State = UINT8_MAX;
3716 rc = NEMR3NotifyPhysMmioExUnmap(pVM, pCurMmio->RamRange.GCPhys, pCurMmio->RamRange.cb, fNemFlags,
3717 NULL, pCurMmio->pvR3, &u2State, &pCurMmio->RamRange.uNemRange);
3718 AssertRCStmt(rc, rcRet = rc);
3719 if (u2State != UINT8_MAX)
3720 pgmPhysSetNemStateForPages(pCurMmio->RamRange.aPages, pCurMmio->RamRange.cb >> GUEST_PAGE_SHIFT, u2State);
3721 }
3722#endif
3723 pgmR3PhysUnlinkRamRange(pVM, &pCurMmio->RamRange);
3724 pCurMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3725 pCurMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3726 pCurMmio->fFlags &= ~(PGMREGMMIO2RANGE_F_OVERLAPPING | PGMREGMMIO2RANGE_F_MAPPED);
3727 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3728 break;
3729 }
3730 }
3731
3732 /* Force a PGM pool flush as guest ram references have been changed. */
3733 /** @todo not entirely SMP safe; assuming for now the guest takes care
3734 * of this internally (not touch mapped mmio while changing the
3735 * mapping). */
3736 PVMCPU pVCpu = VMMGetCpu(pVM);
3737 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
3738 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3739
3740 pgmPhysInvalidatePageMapTLB(pVM);
3741 pgmPhysInvalidRamRangeTlbs(pVM);
3742
3743 PGM_UNLOCK(pVM);
3744 return rcRet;
3745}
3746
3747
3748/**
3749 * Reduces the mapping size of a MMIO2 region.
3750 *
3751 * This is mainly for dealing with old saved states after changing the default
3752 * size of a mapping region. See PGMDevHlpMMIOExReduce and
3753 * PDMPCIDEV::pfnRegionLoadChangeHookR3.
3754 *
3755 * The region must not currently be mapped when making this call. The VM state
3756 * must be state restore or VM construction.
3757 *
3758 * @returns VBox status code.
3759 * @param pVM The cross context VM structure.
3760 * @param pDevIns The device instance owning the region.
3761 * @param hMmio2 The handle of the region to reduce.
3762 * @param cbRegion The new mapping size.
3763 */
3764VMMR3_INT_DECL(int) PGMR3PhysMmio2Reduce(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, RTGCPHYS cbRegion)
3765{
3766 /*
3767 * Validate input
3768 */
3769 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3770 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3771 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
3772 AssertReturn(cbRegion >= X86_PAGE_SIZE, VERR_INVALID_PARAMETER);
3773 AssertReturn(!(cbRegion & X86_PAGE_OFFSET_MASK), VERR_UNSUPPORTED_ALIGNMENT);
3774 VMSTATE enmVmState = VMR3GetState(pVM);
3775 AssertLogRelMsgReturn( enmVmState == VMSTATE_CREATING
3776 || enmVmState == VMSTATE_LOADING,
3777 ("enmVmState=%d (%s)\n", enmVmState, VMR3GetStateName(enmVmState)),
3778 VERR_VM_INVALID_VM_STATE);
3779
3780 int rc = PGM_LOCK(pVM);
3781 AssertRCReturn(rc, rc);
3782
3783 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3784 if (pFirstMmio)
3785 {
3786 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
3787 if (!(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED))
3788 {
3789 /*
3790 * NOTE! Current implementation does not support multiple ranges.
3791 * Implement when there is a real world need and thus a testcase.
3792 */
3793 AssertLogRelMsgStmt(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK,
3794 ("%s: %#x\n", pFirstMmio->RamRange.pszDesc, pFirstMmio->fFlags),
3795 rc = VERR_NOT_SUPPORTED);
3796 if (RT_SUCCESS(rc))
3797 {
3798 /*
3799 * Make the change.
3800 */
3801 Log(("PGMR3PhysMmio2Reduce: %s changes from %RGp bytes (%RGp) to %RGp bytes.\n",
3802 pFirstMmio->RamRange.pszDesc, pFirstMmio->RamRange.cb, pFirstMmio->cbReal, cbRegion));
3803
3804 AssertLogRelMsgStmt(cbRegion <= pFirstMmio->cbReal,
3805 ("%s: cbRegion=%#RGp cbReal=%#RGp\n", pFirstMmio->RamRange.pszDesc, cbRegion, pFirstMmio->cbReal),
3806 rc = VERR_OUT_OF_RANGE);
3807 if (RT_SUCCESS(rc))
3808 {
3809 pFirstMmio->RamRange.cb = cbRegion;
3810 }
3811 }
3812 }
3813 else
3814 rc = VERR_WRONG_ORDER;
3815 }
3816 else
3817 rc = VERR_NOT_FOUND;
3818
3819 PGM_UNLOCK(pVM);
3820 return rc;
3821}
3822
3823
3824/**
3825 * Validates @a hMmio2, making sure it belongs to @a pDevIns.
3826 *
3827 * @returns VBox status code.
3828 * @param pVM The cross context VM structure.
3829 * @param pDevIns The device which allegedly owns @a hMmio2.
3830 * @param hMmio2 The handle to validate.
3831 */
3832VMMR3_INT_DECL(int) PGMR3PhysMmio2ValidateHandle(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2)
3833{
3834 /*
3835 * Validate input
3836 */
3837 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3838 AssertPtrReturn(pDevIns, VERR_INVALID_POINTER);
3839
3840 /*
3841 * Just do this the simple way. No need for locking as this is only taken at
3842 */
3843 PGM_LOCK_VOID(pVM);
3844 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3845 PGM_UNLOCK(pVM);
3846 AssertReturn(pFirstMmio, VERR_INVALID_HANDLE);
3847 AssertReturn(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK, VERR_INVALID_HANDLE);
3848 return VINF_SUCCESS;
3849}
3850
3851
3852/**
3853 * Gets the mapping address of an MMIO2 region.
3854 *
3855 * @returns Mapping address, NIL_RTGCPHYS if not mapped or invalid handle.
3856 *
3857 * @param pVM The cross context VM structure.
3858 * @param pDevIns The device owning the MMIO2 handle.
3859 * @param hMmio2 The region handle.
3860 */
3861VMMR3_INT_DECL(RTGCPHYS) PGMR3PhysMmio2GetMappingAddress(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2)
3862{
3863 AssertPtrReturn(pDevIns, NIL_RTGCPHYS);
3864
3865 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3866 AssertReturn(pFirstRegMmio, NIL_RTGCPHYS);
3867
3868 if (pFirstRegMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED)
3869 return pFirstRegMmio->RamRange.GCPhys;
3870 return NIL_RTGCPHYS;
3871}
3872
3873
3874/**
3875 * Worker for PGMR3PhysMmio2QueryAndResetDirtyBitmap.
3876 *
3877 * Called holding the PGM lock.
3878 */
3879static int pgmR3PhysMmio2QueryAndResetDirtyBitmapLocked(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2,
3880 void *pvBitmap, size_t cbBitmap)
3881{
3882 /*
3883 * Continue validation.
3884 */
3885 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3886 AssertReturn(pFirstRegMmio, VERR_INVALID_HANDLE);
3887 AssertReturn( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
3888 == (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK),
3889 VERR_INVALID_FUNCTION);
3890 AssertReturn(pDevIns == pFirstRegMmio->pDevInsR3, VERR_NOT_OWNER);
3891
3892 RTGCPHYS cbTotal = 0;
3893 uint16_t fTotalDirty = 0;
3894 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio;;)
3895 {
3896 cbTotal += pCur->RamRange.cb; /* Not using cbReal here, because NEM is not in on the creating, only the mapping. */
3897 fTotalDirty |= pCur->fFlags;
3898 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3899 break;
3900 pCur = pCur->pNextR3;
3901 AssertPtrReturn(pCur, VERR_INTERNAL_ERROR_5);
3902 AssertReturn( (pCur->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
3903 == PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES,
3904 VERR_INTERNAL_ERROR_4);
3905 }
3906 size_t const cbTotalBitmap = RT_ALIGN_T(cbTotal, GUEST_PAGE_SIZE * 64, RTGCPHYS) / GUEST_PAGE_SIZE / 8;
3907
3908 if (cbBitmap)
3909 {
3910 AssertPtrReturn(pvBitmap, VERR_INVALID_POINTER);
3911 AssertReturn(RT_ALIGN_P(pvBitmap, sizeof(uint64_t)) == pvBitmap, VERR_INVALID_POINTER);
3912 AssertReturn(cbBitmap == cbTotalBitmap, VERR_INVALID_PARAMETER);
3913 }
3914
3915 /*
3916 * Do the work.
3917 */
3918 int rc = VINF_SUCCESS;
3919 if (pvBitmap)
3920 {
3921#ifdef VBOX_WITH_PGM_NEM_MODE
3922 if (pFirstRegMmio->pPhysHandlerR3 == NULL)
3923 {
3924/** @todo This does not integrate at all with --execute-all-in-iem, leaving the
3925 * screen blank when using it together with --driverless. Fixing this won't be
3926 * entirely easy as we take the PGM_PAGE_HNDL_PHYS_STATE_DISABLED page status to
3927 * mean a dirty page. */
3928 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_INTERNAL_ERROR_4);
3929 uint8_t *pbBitmap = (uint8_t *)pvBitmap;
3930 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
3931 {
3932 size_t const cbBitmapChunk = pCur->RamRange.cb / GUEST_PAGE_SIZE / 8;
3933 Assert((RTGCPHYS)cbBitmapChunk * GUEST_PAGE_SIZE * 8 == pCur->RamRange.cb);
3934 int rc2 = NEMR3PhysMmio2QueryAndResetDirtyBitmap(pVM, pCur->RamRange.GCPhys, pCur->RamRange.cb,
3935 pCur->RamRange.uNemRange, pbBitmap, cbBitmapChunk);
3936 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3937 rc = rc2;
3938 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3939 break;
3940 pbBitmap += pCur->RamRange.cb / GUEST_PAGE_SIZE / 8;
3941 }
3942 }
3943 else
3944#endif
3945 if (fTotalDirty & PGMREGMMIO2RANGE_F_IS_DIRTY)
3946 {
3947 if ( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3948 == (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3949 {
3950 /*
3951 * Reset each chunk, gathering dirty bits.
3952 */
3953 RT_BZERO(pvBitmap, cbBitmap); /* simpler for now. */
3954 uint32_t iPageNo = 0;
3955 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
3956 {
3957 if (pCur->fFlags & PGMREGMMIO2RANGE_F_IS_DIRTY)
3958 {
3959 int rc2 = pgmHandlerPhysicalResetMmio2WithBitmap(pVM, pCur->RamRange.GCPhys, pvBitmap, iPageNo);
3960 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3961 rc = rc2;
3962 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_IS_DIRTY;
3963 }
3964 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3965 break;
3966 iPageNo += pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3967 }
3968 }
3969 else
3970 {
3971 /*
3972 * If not mapped or tracking is disabled, we return the
3973 * PGMREGMMIO2RANGE_F_IS_DIRTY status for all pages. We cannot
3974 * get more accurate data than that after unmapping or disabling.
3975 */
3976 RT_BZERO(pvBitmap, cbBitmap);
3977 uint32_t iPageNo = 0;
3978 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
3979 {
3980 if (pCur->fFlags & PGMREGMMIO2RANGE_F_IS_DIRTY)
3981 {
3982 ASMBitSetRange(pvBitmap, iPageNo, iPageNo + (pCur->RamRange.cb >> GUEST_PAGE_SHIFT));
3983 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_IS_DIRTY;
3984 }
3985 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3986 break;
3987 iPageNo += pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3988 }
3989 }
3990 }
3991 /*
3992 * No dirty chunks.
3993 */
3994 else
3995 RT_BZERO(pvBitmap, cbBitmap);
3996 }
3997 /*
3998 * No bitmap. Reset the region if tracking is currently enabled.
3999 */
4000 else if ( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
4001 == (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
4002 {
4003#ifdef VBOX_WITH_PGM_NEM_MODE
4004 if (pFirstRegMmio->pPhysHandlerR3 == NULL)
4005 {
4006 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_INTERNAL_ERROR_4);
4007 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
4008 {
4009 int rc2 = NEMR3PhysMmio2QueryAndResetDirtyBitmap(pVM, pCur->RamRange.GCPhys, pCur->RamRange.cb,
4010 pCur->RamRange.uNemRange, NULL, 0);
4011 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
4012 rc = rc2;
4013 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
4014 break;
4015 }
4016 }
4017 else
4018#endif
4019 {
4020 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
4021 {
4022 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_IS_DIRTY;
4023 int rc2 = PGMHandlerPhysicalReset(pVM, pCur->RamRange.GCPhys);
4024 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
4025 rc = rc2;
4026 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
4027 break;
4028 }
4029 }
4030 }
4031
4032 return rc;
4033}
4034
4035
4036/**
4037 * Queries the dirty page bitmap and resets the monitoring.
4038 *
4039 * The PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES flag must be specified when
4040 * creating the range for this to work.
4041 *
4042 * @returns VBox status code.
4043 * @retval VERR_INVALID_FUNCTION if not created using
4044 * PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES.
4045 * @param pVM The cross context VM structure.
4046 * @param pDevIns The device owning the MMIO2 handle.
4047 * @param hMmio2 The region handle.
4048 * @param pvBitmap The output bitmap. Must be 8-byte aligned. Ignored
4049 * when @a cbBitmap is zero.
4050 * @param cbBitmap The size of the bitmap. Must be the size of the whole
4051 * MMIO2 range, rounded up to the nearest 8 bytes.
4052 * When zero only a reset is done.
4053 */
4054VMMR3_INT_DECL(int) PGMR3PhysMmio2QueryAndResetDirtyBitmap(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2,
4055 void *pvBitmap, size_t cbBitmap)
4056{
4057 /*
4058 * Do some basic validation before grapping the PGM lock and continuing.
4059 */
4060 AssertPtrReturn(pDevIns, VERR_INVALID_POINTER);
4061 AssertReturn(RT_ALIGN_Z(cbBitmap, sizeof(uint64_t)) == cbBitmap, VERR_INVALID_PARAMETER);
4062 int rc = PGM_LOCK(pVM);
4063 if (RT_SUCCESS(rc))
4064 {
4065 STAM_PROFILE_START(&pVM->pgm.s.StatMmio2QueryAndResetDirtyBitmap, a);
4066 rc = pgmR3PhysMmio2QueryAndResetDirtyBitmapLocked(pVM, pDevIns, hMmio2, pvBitmap, cbBitmap);
4067 STAM_PROFILE_STOP(&pVM->pgm.s.StatMmio2QueryAndResetDirtyBitmap, a);
4068 PGM_UNLOCK(pVM);
4069 }
4070 return rc;
4071}
4072
4073
4074/**
4075 * Worker for PGMR3PhysMmio2ControlDirtyPageTracking
4076 *
4077 * Called owning the PGM lock.
4078 */
4079static int pgmR3PhysMmio2ControlDirtyPageTrackingLocked(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, bool fEnabled)
4080{
4081 /*
4082 * Continue validation.
4083 */
4084 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
4085 AssertReturn(pFirstRegMmio, VERR_INVALID_HANDLE);
4086 AssertReturn( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
4087 == (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK)
4088 , VERR_INVALID_FUNCTION);
4089 AssertReturn(pDevIns == pFirstRegMmio->pDevInsR3, VERR_NOT_OWNER);
4090
4091#ifdef VBOX_WITH_PGM_NEM_MODE
4092 /*
4093 * This is a nop if NEM is responsible for doing the tracking, we simply
4094 * leave the tracking on all the time there.
4095 */
4096 if (pFirstRegMmio->pPhysHandlerR3 == NULL)
4097 {
4098 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_INTERNAL_ERROR_4);
4099 return VINF_SUCCESS;
4100 }
4101#endif
4102
4103 /*
4104 * Anyting needing doing?
4105 */
4106 if (fEnabled != RT_BOOL(pFirstRegMmio->fFlags & PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
4107 {
4108 LogFlowFunc(("fEnabled=%RTbool %s\n", fEnabled, pFirstRegMmio->RamRange.pszDesc));
4109
4110 /*
4111 * Update the PGMREGMMIO2RANGE_F_TRACKING_ENABLED flag.
4112 */
4113 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio;;)
4114 {
4115 if (fEnabled)
4116 pCur->fFlags |= PGMREGMMIO2RANGE_F_TRACKING_ENABLED;
4117 else
4118 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_TRACKING_ENABLED;
4119 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
4120 break;
4121 pCur = pCur->pNextR3;
4122 AssertPtrReturn(pCur, VERR_INTERNAL_ERROR_5);
4123 AssertReturn( (pCur->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
4124 == PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES
4125 , VERR_INTERNAL_ERROR_4);
4126 }
4127
4128 /*
4129 * Enable/disable handlers if currently mapped.
4130 *
4131 * We ignore status codes here as we've already changed the flags and
4132 * returning a failure status now would be confusing. Besides, the two
4133 * functions will continue past failures. As argued in the mapping code,
4134 * it's in the release log.
4135 */
4136 if (pFirstRegMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED)
4137 {
4138 if (fEnabled)
4139 pgmR3PhysMmio2EnableDirtyPageTracing(pVM, pFirstRegMmio);
4140 else
4141 pgmR3PhysMmio2DisableDirtyPageTracing(pVM, pFirstRegMmio);
4142 }
4143 }
4144 else
4145 LogFlowFunc(("fEnabled=%RTbool %s - no change\n", fEnabled, pFirstRegMmio->RamRange.pszDesc));
4146
4147 return VINF_SUCCESS;
4148}
4149
4150
4151/**
4152 * Controls the dirty page tracking for an MMIO2 range.
4153 *
4154 * @returns VBox status code.
4155 * @param pVM The cross context VM structure.
4156 * @param pDevIns The device owning the MMIO2 memory.
4157 * @param hMmio2 The handle of the region.
4158 * @param fEnabled The new tracking state.
4159 */
4160VMMR3_INT_DECL(int) PGMR3PhysMmio2ControlDirtyPageTracking(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, bool fEnabled)
4161{
4162 /*
4163 * Do some basic validation before grapping the PGM lock and continuing.
4164 */
4165 AssertPtrReturn(pDevIns, VERR_INVALID_POINTER);
4166 int rc = PGM_LOCK(pVM);
4167 if (RT_SUCCESS(rc))
4168 {
4169 rc = pgmR3PhysMmio2ControlDirtyPageTrackingLocked(pVM, pDevIns, hMmio2, fEnabled);
4170 PGM_UNLOCK(pVM);
4171 }
4172 return rc;
4173}
4174
4175
4176/**
4177 * Changes the region number of an MMIO2 region.
4178 *
4179 * This is only for dealing with save state issues, nothing else.
4180 *
4181 * @return VBox status code.
4182 *
4183 * @param pVM The cross context VM structure.
4184 * @param pDevIns The device owning the MMIO2 memory.
4185 * @param hMmio2 The handle of the region.
4186 * @param iNewRegion The new region index.
4187 *
4188 * @thread EMT(0)
4189 * @sa @bugref{9359}
4190 */
4191VMMR3_INT_DECL(int) PGMR3PhysMmio2ChangeRegionNo(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, uint32_t iNewRegion)
4192{
4193 /*
4194 * Validate input.
4195 */
4196 VM_ASSERT_EMT0_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
4197 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_LOADING, VERR_VM_INVALID_VM_STATE);
4198 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4199 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
4200 AssertReturn(iNewRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4201
4202 AssertReturn(pVM->enmVMState == VMSTATE_LOADING, VERR_INVALID_STATE);
4203
4204 int rc = PGM_LOCK(pVM);
4205 AssertRCReturn(rc, rc);
4206
4207 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
4208 AssertReturnStmt(pFirstRegMmio, PGM_UNLOCK(pVM), VERR_NOT_FOUND);
4209 AssertReturnStmt(pgmR3PhysMmio2Find(pVM, pDevIns, pFirstRegMmio->iSubDev, iNewRegion, NIL_PGMMMIO2HANDLE) == NULL,
4210 PGM_UNLOCK(pVM), VERR_RESOURCE_IN_USE);
4211
4212 /*
4213 * Make the change.
4214 */
4215 pFirstRegMmio->iRegion = (uint8_t)iNewRegion;
4216
4217 PGM_UNLOCK(pVM);
4218 return VINF_SUCCESS;
4219}
4220
4221
4222
4223/*********************************************************************************************************************************
4224* ROM *
4225*********************************************************************************************************************************/
4226
4227/**
4228 * Worker for PGMR3PhysRomRegister.
4229 *
4230 * This is here to simplify lock management, i.e. the caller does all the
4231 * locking and we can simply return without needing to remember to unlock
4232 * anything first.
4233 *
4234 * @returns VBox status code.
4235 * @param pVM The cross context VM structure.
4236 * @param pDevIns The device instance owning the ROM.
4237 * @param GCPhys First physical address in the range.
4238 * Must be page aligned!
4239 * @param cb The size of the range (in bytes).
4240 * Must be page aligned!
4241 * @param pvBinary Pointer to the binary data backing the ROM image.
4242 * @param cbBinary The size of the binary data pvBinary points to.
4243 * This must be less or equal to @a cb.
4244 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
4245 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
4246 * @param pszDesc Pointer to description string. This must not be freed.
4247 */
4248static int pgmR3PhysRomRegisterLocked(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
4249 const void *pvBinary, uint32_t cbBinary, uint8_t fFlags, const char *pszDesc)
4250{
4251 /*
4252 * Validate input.
4253 */
4254 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4255 AssertReturn(RT_ALIGN_T(GCPhys, GUEST_PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
4256 AssertReturn(RT_ALIGN_T(cb, GUEST_PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
4257 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
4258 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
4259 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
4260 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
4261 AssertReturn(!(fFlags & ~PGMPHYS_ROM_FLAGS_VALID_MASK), VERR_INVALID_PARAMETER);
4262 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
4263
4264 const uint32_t cGuestPages = cb >> GUEST_PAGE_SHIFT;
4265#ifdef VBOX_WITH_PGM_NEM_MODE
4266 const uint32_t cHostPages = RT_ALIGN_T(cb, HOST_PAGE_SIZE, RTGCPHYS) >> HOST_PAGE_SHIFT;
4267#endif
4268
4269 /*
4270 * Find the ROM location in the ROM list first.
4271 */
4272 PPGMROMRANGE pRomPrev = NULL;
4273 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
4274 while (pRom && GCPhysLast >= pRom->GCPhys)
4275 {
4276 if ( GCPhys <= pRom->GCPhysLast
4277 && GCPhysLast >= pRom->GCPhys)
4278 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
4279 GCPhys, GCPhysLast, pszDesc,
4280 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
4281 VERR_PGM_RAM_CONFLICT);
4282 /* next */
4283 pRomPrev = pRom;
4284 pRom = pRom->pNextR3;
4285 }
4286
4287 /*
4288 * Find the RAM location and check for conflicts.
4289 *
4290 * Conflict detection is a bit different than for RAM registration since a
4291 * ROM can be located within a RAM range. So, what we have to check for is
4292 * other memory types (other than RAM that is) and that we don't span more
4293 * than one RAM range (lazy).
4294 */
4295 bool fRamExists = false;
4296 PPGMRAMRANGE pRamPrev = NULL;
4297 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
4298 while (pRam && GCPhysLast >= pRam->GCPhys)
4299 {
4300 if ( GCPhys <= pRam->GCPhysLast
4301 && GCPhysLast >= pRam->GCPhys)
4302 {
4303 /* completely within? */
4304 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
4305 && GCPhysLast <= pRam->GCPhysLast,
4306 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
4307 GCPhys, GCPhysLast, pszDesc,
4308 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
4309 VERR_PGM_RAM_CONFLICT);
4310 fRamExists = true;
4311 break;
4312 }
4313
4314 /* next */
4315 pRamPrev = pRam;
4316 pRam = pRam->pNextR3;
4317 }
4318 if (fRamExists)
4319 {
4320 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
4321 uint32_t cPagesLeft = cGuestPages;
4322 while (cPagesLeft-- > 0)
4323 {
4324 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
4325 ("%RGp (%R[pgmpage]) isn't a RAM page - registering %RGp-%RGp (%s).\n",
4326 pRam->GCPhys + ((RTGCPHYS)(uintptr_t)(pPage - &pRam->aPages[0]) << GUEST_PAGE_SHIFT),
4327 pPage, GCPhys, GCPhysLast, pszDesc), VERR_PGM_RAM_CONFLICT);
4328 Assert(PGM_PAGE_IS_ZERO(pPage) || PGM_IS_IN_NEM_MODE(pVM));
4329 pPage++;
4330 }
4331 }
4332
4333 /*
4334 * Update the base memory reservation if necessary.
4335 */
4336 uint32_t cExtraBaseCost = fRamExists ? 0 : cGuestPages;
4337 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4338 cExtraBaseCost += cGuestPages;
4339 if (cExtraBaseCost)
4340 {
4341 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
4342 if (RT_FAILURE(rc))
4343 return rc;
4344 }
4345
4346#ifdef VBOX_WITH_NATIVE_NEM
4347 /*
4348 * Early NEM notification before we've made any changes or anything.
4349 */
4350 uint32_t const fNemNotify = (fRamExists ? NEM_NOTIFY_PHYS_ROM_F_REPLACE : 0)
4351 | (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED ? NEM_NOTIFY_PHYS_ROM_F_SHADOW : 0);
4352 uint8_t u2NemState = UINT8_MAX;
4353 uint32_t uNemRange = 0;
4354 if (VM_IS_NEM_ENABLED(pVM))
4355 {
4356 int rc = NEMR3NotifyPhysRomRegisterEarly(pVM, GCPhys, cGuestPages << GUEST_PAGE_SHIFT,
4357 fRamExists ? PGM_RAMRANGE_CALC_PAGE_R3PTR(pRam, GCPhys) : NULL,
4358 fNemNotify, &u2NemState, fRamExists ? &pRam->uNemRange : &uNemRange);
4359 AssertLogRelRCReturn(rc, rc);
4360 }
4361#endif
4362
4363 /*
4364 * Allocate memory for the virgin copy of the RAM. In simplified memory mode,
4365 * we allocate memory for any ad-hoc RAM range and for shadow pages.
4366 */
4367 PGMMALLOCATEPAGESREQ pReq = NULL;
4368#ifdef VBOX_WITH_PGM_NEM_MODE
4369 void *pvRam = NULL;
4370 void *pvAlt = NULL;
4371 if (pVM->pgm.s.fNemMode)
4372 {
4373 if (!fRamExists)
4374 {
4375 int rc = SUPR3PageAlloc(cHostPages, 0, &pvRam);
4376 if (RT_FAILURE(rc))
4377 return rc;
4378 }
4379 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4380 {
4381 int rc = SUPR3PageAlloc(cHostPages, 0, &pvAlt);
4382 if (RT_FAILURE(rc))
4383 {
4384 if (pvRam)
4385 SUPR3PageFree(pvRam, cHostPages);
4386 return rc;
4387 }
4388 }
4389 }
4390 else
4391#endif
4392 {
4393 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cGuestPages, GMMACCOUNT_BASE);
4394 AssertRCReturn(rc, rc);
4395
4396 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++)
4397 {
4398 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << GUEST_PAGE_SHIFT);
4399 pReq->aPages[iPage].fZeroed = false;
4400 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
4401 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
4402 }
4403
4404 rc = GMMR3AllocatePagesPerform(pVM, pReq);
4405 if (RT_FAILURE(rc))
4406 {
4407 GMMR3AllocatePagesCleanup(pReq);
4408 return rc;
4409 }
4410 }
4411
4412 /*
4413 * Allocate the new ROM range and RAM range (if necessary).
4414 */
4415 PPGMROMRANGE pRomNew = NULL;
4416 RTR0PTR pRomNewR0 = NIL_RTR0PTR;
4417 size_t const cbRomRange = RT_ALIGN_Z(RT_UOFFSETOF_DYN(PGMROMRANGE, aPages[cGuestPages]), 128);
4418 size_t const cbRamRange = fRamExists ? 0 : RT_UOFFSETOF_DYN(PGMROMRANGE, aPages[cGuestPages]);
4419 size_t const cRangePages = RT_ALIGN_Z(cbRomRange + cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
4420 int rc = SUPR3PageAllocEx(cRangePages, 0 /*fFlags*/, (void **)&pRomNew, &pRomNewR0, NULL /*paPages*/);
4421 if (RT_SUCCESS(rc))
4422 {
4423
4424 /*
4425 * Initialize and insert the RAM range (if required).
4426 */
4427 PPGMRAMRANGE pRamNew;
4428 uint32_t const idxFirstRamPage = fRamExists ? (GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT : 0;
4429 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
4430 if (!fRamExists)
4431 {
4432 /* New RAM range. */
4433 pRamNew = (PPGMRAMRANGE)((uintptr_t)pRomNew + cbRomRange);
4434 pRamNew->pSelfR0 = !pRomNewR0 ? NIL_RTR0PTR : pRomNewR0 + cbRomRange;
4435 pRamNew->GCPhys = GCPhys;
4436 pRamNew->GCPhysLast = GCPhysLast;
4437 pRamNew->cb = cb;
4438 pRamNew->pszDesc = pszDesc;
4439 pRamNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_ROM;
4440 pRamNew->pvR3 = NULL;
4441 pRamNew->paLSPages = NULL;
4442#ifdef VBOX_WITH_NATIVE_NEM
4443 pRamNew->uNemRange = uNemRange;
4444#endif
4445
4446 PPGMPAGE pRamPage = &pRamNew->aPages[idxFirstRamPage];
4447#ifdef VBOX_WITH_PGM_NEM_MODE
4448 if (pVM->pgm.s.fNemMode)
4449 {
4450 AssertPtr(pvRam); Assert(pReq == NULL);
4451 pRamNew->pvR3 = pvRam;
4452 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4453 {
4454 PGM_PAGE_INIT(pRamPage, UINT64_C(0x0000fffffffff000), NIL_GMM_PAGEID,
4455 PGMPAGETYPE_ROM, PGM_PAGE_STATE_ALLOCATED);
4456 pRomPage->Virgin = *pRamPage;
4457 }
4458 }
4459 else
4460#endif
4461 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4462 {
4463 PGM_PAGE_INIT(pRamPage,
4464 pReq->aPages[iPage].HCPhysGCPhys,
4465 pReq->aPages[iPage].idPage,
4466 PGMPAGETYPE_ROM,
4467 PGM_PAGE_STATE_ALLOCATED);
4468
4469 pRomPage->Virgin = *pRamPage;
4470 }
4471
4472 pVM->pgm.s.cAllPages += cGuestPages;
4473 pVM->pgm.s.cPrivatePages += cGuestPages;
4474 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
4475 }
4476 else
4477 {
4478 /* Existing RAM range. */
4479 PPGMPAGE pRamPage = &pRam->aPages[idxFirstRamPage];
4480#ifdef VBOX_WITH_PGM_NEM_MODE
4481 if (pVM->pgm.s.fNemMode)
4482 {
4483 Assert(pvRam == NULL); Assert(pReq == NULL);
4484 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4485 {
4486 Assert(PGM_PAGE_GET_HCPHYS(pRamPage) == UINT64_C(0x0000fffffffff000));
4487 Assert(PGM_PAGE_GET_PAGEID(pRamPage) == NIL_GMM_PAGEID);
4488 Assert(PGM_PAGE_GET_STATE(pRamPage) == PGM_PAGE_STATE_ALLOCATED);
4489 PGM_PAGE_SET_TYPE(pVM, pRamPage, PGMPAGETYPE_ROM);
4490 PGM_PAGE_SET_STATE(pVM, pRamPage, PGM_PAGE_STATE_ALLOCATED);
4491 PGM_PAGE_SET_PDE_TYPE(pVM, pRamPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4492 PGM_PAGE_SET_PTE_INDEX(pVM, pRamPage, 0);
4493 PGM_PAGE_SET_TRACKING(pVM, pRamPage, 0);
4494
4495 pRomPage->Virgin = *pRamPage;
4496 }
4497 }
4498 else
4499#endif
4500 {
4501 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4502 {
4503 PGM_PAGE_SET_TYPE(pVM, pRamPage, PGMPAGETYPE_ROM);
4504 PGM_PAGE_SET_HCPHYS(pVM, pRamPage, pReq->aPages[iPage].HCPhysGCPhys);
4505 PGM_PAGE_SET_STATE(pVM, pRamPage, PGM_PAGE_STATE_ALLOCATED);
4506 PGM_PAGE_SET_PAGEID(pVM, pRamPage, pReq->aPages[iPage].idPage);
4507 PGM_PAGE_SET_PDE_TYPE(pVM, pRamPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4508 PGM_PAGE_SET_PTE_INDEX(pVM, pRamPage, 0);
4509 PGM_PAGE_SET_TRACKING(pVM, pRamPage, 0);
4510
4511 pRomPage->Virgin = *pRamPage;
4512 }
4513 pVM->pgm.s.cZeroPages -= cGuestPages;
4514 pVM->pgm.s.cPrivatePages += cGuestPages;
4515 }
4516 pRamNew = pRam;
4517 }
4518
4519#ifdef VBOX_WITH_NATIVE_NEM
4520 /* Set the NEM state of the pages if needed. */
4521 if (u2NemState != UINT8_MAX)
4522 pgmPhysSetNemStateForPages(&pRamNew->aPages[idxFirstRamPage], cGuestPages, u2NemState);
4523#endif
4524
4525 /* Flush physical page map TLB. */
4526 pgmPhysInvalidatePageMapTLB(pVM);
4527
4528 /*
4529 * Register the ROM access handler.
4530 */
4531 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, pVM->pgm.s.hRomPhysHandlerType, GCPhys, pszDesc);
4532 if (RT_SUCCESS(rc))
4533 {
4534 /*
4535 * Copy the image over to the virgin pages.
4536 * This must be done after linking in the RAM range.
4537 */
4538 size_t cbBinaryLeft = cbBinary;
4539 PPGMPAGE pRamPage = &pRamNew->aPages[idxFirstRamPage];
4540 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++)
4541 {
4542 void *pvDstPage;
4543 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << GUEST_PAGE_SHIFT), &pvDstPage);
4544 if (RT_FAILURE(rc))
4545 {
4546 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
4547 break;
4548 }
4549 if (cbBinaryLeft >= GUEST_PAGE_SIZE)
4550 {
4551 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << GUEST_PAGE_SHIFT), GUEST_PAGE_SIZE);
4552 cbBinaryLeft -= GUEST_PAGE_SIZE;
4553 }
4554 else
4555 {
4556 RT_BZERO(pvDstPage, GUEST_PAGE_SIZE); /* (shouldn't be necessary, but can't hurt either) */
4557 if (cbBinaryLeft > 0)
4558 {
4559 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << GUEST_PAGE_SHIFT), cbBinaryLeft);
4560 cbBinaryLeft = 0;
4561 }
4562 }
4563 }
4564 if (RT_SUCCESS(rc))
4565 {
4566 /*
4567 * Initialize the ROM range.
4568 * Note that the Virgin member of the pages has already been initialized above.
4569 */
4570 pRomNew->pSelfR0 = pRomNewR0;
4571 pRomNew->GCPhys = GCPhys;
4572 pRomNew->GCPhysLast = GCPhysLast;
4573 pRomNew->cb = cb;
4574 pRomNew->fFlags = fFlags;
4575 pRomNew->idSavedState = UINT8_MAX;
4576 pRomNew->cbOriginal = cbBinary;
4577 pRomNew->pszDesc = pszDesc;
4578#ifdef VBOX_WITH_PGM_NEM_MODE
4579 pRomNew->pbR3Alternate = (uint8_t *)pvAlt;
4580#endif
4581 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY
4582 ? pvBinary : RTMemDup(pvBinary, cbBinary);
4583 if (pRomNew->pvOriginal)
4584 {
4585 for (unsigned iPage = 0; iPage < cGuestPages; iPage++)
4586 {
4587 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
4588 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
4589#ifdef VBOX_WITH_PGM_NEM_MODE
4590 if (pVM->pgm.s.fNemMode)
4591 PGM_PAGE_INIT(&pPage->Shadow, UINT64_C(0x0000fffffffff000), NIL_GMM_PAGEID,
4592 PGMPAGETYPE_ROM_SHADOW, PGM_PAGE_STATE_ALLOCATED);
4593 else
4594#endif
4595 PGM_PAGE_INIT_ZERO(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
4596 }
4597
4598 /* update the page count stats for the shadow pages. */
4599 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4600 {
4601#ifdef VBOX_WITH_PGM_NEM_MODE
4602 if (pVM->pgm.s.fNemMode)
4603 pVM->pgm.s.cPrivatePages += cGuestPages;
4604 else
4605#endif
4606 pVM->pgm.s.cZeroPages += cGuestPages;
4607 pVM->pgm.s.cAllPages += cGuestPages;
4608 }
4609
4610 /*
4611 * Insert the ROM range, tell REM and return successfully.
4612 */
4613 pRomNew->pNextR3 = pRom;
4614 pRomNew->pNextR0 = pRom ? pRom->pSelfR0 : NIL_RTR0PTR;
4615
4616 if (pRomPrev)
4617 {
4618 pRomPrev->pNextR3 = pRomNew;
4619 pRomPrev->pNextR0 = pRomNew->pSelfR0;
4620 }
4621 else
4622 {
4623 pVM->pgm.s.pRomRangesR3 = pRomNew;
4624 pVM->pgm.s.pRomRangesR0 = pRomNew->pSelfR0;
4625 }
4626
4627 pgmPhysInvalidatePageMapTLB(pVM);
4628#ifdef VBOX_WITH_PGM_NEM_MODE
4629 if (!pVM->pgm.s.fNemMode)
4630#endif
4631 GMMR3AllocatePagesCleanup(pReq);
4632
4633#ifdef VBOX_WITH_NATIVE_NEM
4634 /*
4635 * Notify NEM again.
4636 */
4637 if (VM_IS_NEM_ENABLED(pVM))
4638 {
4639 u2NemState = UINT8_MAX;
4640 rc = NEMR3NotifyPhysRomRegisterLate(pVM, GCPhys, cb, PGM_RAMRANGE_CALC_PAGE_R3PTR(pRamNew, GCPhys),
4641 fNemNotify, &u2NemState,
4642 fRamExists ? &pRam->uNemRange : &pRamNew->uNemRange);
4643 if (u2NemState != UINT8_MAX)
4644 pgmPhysSetNemStateForPages(&pRamNew->aPages[idxFirstRamPage], cGuestPages, u2NemState);
4645 if (RT_SUCCESS(rc))
4646 return rc;
4647 }
4648 else
4649#endif
4650 return rc;
4651
4652 /*
4653 * bail out
4654 */
4655#ifdef VBOX_WITH_NATIVE_NEM
4656 /* unlink */
4657 if (pRomPrev)
4658 {
4659 pRomPrev->pNextR3 = pRom;
4660 pRomPrev->pNextR0 = pRom ? pRom->pSelfR0 : NIL_RTR0PTR;
4661 }
4662 else
4663 {
4664 pVM->pgm.s.pRomRangesR3 = pRom;
4665 pVM->pgm.s.pRomRangesR0 = pRom ? pRom->pSelfR0 : NIL_RTR0PTR;
4666 }
4667
4668 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4669 {
4670# ifdef VBOX_WITH_PGM_NEM_MODE
4671 if (pVM->pgm.s.fNemMode)
4672 pVM->pgm.s.cPrivatePages -= cGuestPages;
4673 else
4674# endif
4675 pVM->pgm.s.cZeroPages -= cGuestPages;
4676 pVM->pgm.s.cAllPages -= cGuestPages;
4677 }
4678#endif
4679 }
4680 else
4681 rc = VERR_NO_MEMORY;
4682 }
4683
4684 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
4685 AssertRC(rc2);
4686 }
4687
4688 if (!fRamExists)
4689 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
4690 else
4691 {
4692 PPGMPAGE pRamPage = &pRam->aPages[idxFirstRamPage];
4693#ifdef VBOX_WITH_PGM_NEM_MODE
4694 if (pVM->pgm.s.fNemMode)
4695 {
4696 Assert(pvRam == NULL); Assert(pReq == NULL);
4697 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4698 {
4699 Assert(PGM_PAGE_GET_HCPHYS(pRamPage) == UINT64_C(0x0000fffffffff000));
4700 Assert(PGM_PAGE_GET_PAGEID(pRamPage) == NIL_GMM_PAGEID);
4701 Assert(PGM_PAGE_GET_STATE(pRamPage) == PGM_PAGE_STATE_ALLOCATED);
4702 PGM_PAGE_SET_TYPE(pVM, pRamPage, PGMPAGETYPE_RAM);
4703 PGM_PAGE_SET_STATE(pVM, pRamPage, PGM_PAGE_STATE_ALLOCATED);
4704 }
4705 }
4706 else
4707#endif
4708 {
4709 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++)
4710 PGM_PAGE_INIT_ZERO(pRamPage, pVM, PGMPAGETYPE_RAM);
4711 pVM->pgm.s.cZeroPages += cGuestPages;
4712 pVM->pgm.s.cPrivatePages -= cGuestPages;
4713 }
4714 }
4715
4716 SUPR3PageFreeEx(pRomNew, cRangePages);
4717 }
4718
4719 /** @todo Purge the mapping cache or something... */
4720#ifdef VBOX_WITH_PGM_NEM_MODE
4721 if (pVM->pgm.s.fNemMode)
4722 {
4723 Assert(!pReq);
4724 if (pvRam)
4725 SUPR3PageFree(pvRam, cHostPages);
4726 if (pvAlt)
4727 SUPR3PageFree(pvAlt, cHostPages);
4728 }
4729 else
4730#endif
4731 {
4732 GMMR3FreeAllocatedPages(pVM, pReq);
4733 GMMR3AllocatePagesCleanup(pReq);
4734 }
4735 return rc;
4736}
4737
4738
4739/**
4740 * Registers a ROM image.
4741 *
4742 * Shadowed ROM images requires double the amount of backing memory, so,
4743 * don't use that unless you have to. Shadowing of ROM images is process
4744 * where we can select where the reads go and where the writes go. On real
4745 * hardware the chipset provides means to configure this. We provide
4746 * PGMR3PhysProtectROM() for this purpose.
4747 *
4748 * A read-only copy of the ROM image will always be kept around while we
4749 * will allocate RAM pages for the changes on demand (unless all memory
4750 * is configured to be preallocated).
4751 *
4752 * @returns VBox status code.
4753 * @param pVM The cross context VM structure.
4754 * @param pDevIns The device instance owning the ROM.
4755 * @param GCPhys First physical address in the range.
4756 * Must be page aligned!
4757 * @param cb The size of the range (in bytes).
4758 * Must be page aligned!
4759 * @param pvBinary Pointer to the binary data backing the ROM image.
4760 * @param cbBinary The size of the binary data pvBinary points to.
4761 * This must be less or equal to @a cb.
4762 * @param fFlags Mask of flags, PGMPHYS_ROM_FLAGS_XXX.
4763 * @param pszDesc Pointer to description string. This must not be freed.
4764 *
4765 * @remark There is no way to remove the rom, automatically on device cleanup or
4766 * manually from the device yet. This isn't difficult in any way, it's
4767 * just not something we expect to be necessary for a while.
4768 */
4769VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
4770 const void *pvBinary, uint32_t cbBinary, uint8_t fFlags, const char *pszDesc)
4771{
4772 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p cbBinary=%#x fFlags=%#x pszDesc=%s\n",
4773 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, cbBinary, fFlags, pszDesc));
4774 PGM_LOCK_VOID(pVM);
4775 int rc = pgmR3PhysRomRegisterLocked(pVM, pDevIns, GCPhys, cb, pvBinary, cbBinary, fFlags, pszDesc);
4776 PGM_UNLOCK(pVM);
4777 return rc;
4778}
4779
4780
4781/**
4782 * Called by PGMR3MemSetup to reset the shadow, switch to the virgin, and verify
4783 * that the virgin part is untouched.
4784 *
4785 * This is done after the normal memory has been cleared.
4786 *
4787 * ASSUMES that the caller owns the PGM lock.
4788 *
4789 * @param pVM The cross context VM structure.
4790 */
4791int pgmR3PhysRomReset(PVM pVM)
4792{
4793 PGM_LOCK_ASSERT_OWNER(pVM);
4794 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4795 {
4796 const uint32_t cGuestPages = pRom->cb >> GUEST_PAGE_SHIFT;
4797
4798 if (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4799 {
4800 /*
4801 * Reset the physical handler.
4802 */
4803 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
4804 AssertRCReturn(rc, rc);
4805
4806 /*
4807 * What we do with the shadow pages depends on the memory
4808 * preallocation option. If not enabled, we'll just throw
4809 * out all the dirty pages and replace them by the zero page.
4810 */
4811#ifdef VBOX_WITH_PGM_NEM_MODE
4812 if (pVM->pgm.s.fNemMode)
4813 {
4814 /* Clear all the shadow pages (currently using alternate backing). */
4815 RT_BZERO(pRom->pbR3Alternate, pRom->cb);
4816 }
4817 else
4818#endif
4819 if (!pVM->pgm.s.fRamPreAlloc)
4820 {
4821 /* Free the dirty pages. */
4822 uint32_t cPendingPages = 0;
4823 PGMMFREEPAGESREQ pReq;
4824 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
4825 AssertRCReturn(rc, rc);
4826
4827 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++)
4828 if ( !PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow)
4829 && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow))
4830 {
4831 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
4832 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, &pRom->aPages[iPage].Shadow,
4833 pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT),
4834 (PGMPAGETYPE)PGM_PAGE_GET_TYPE(&pRom->aPages[iPage].Shadow));
4835 AssertLogRelRCReturn(rc, rc);
4836 }
4837
4838 if (cPendingPages)
4839 {
4840 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
4841 AssertLogRelRCReturn(rc, rc);
4842 }
4843 GMMR3FreePagesCleanup(pReq);
4844 }
4845 else
4846 {
4847 /* clear all the shadow pages. */
4848 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++)
4849 {
4850 if (PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow))
4851 continue;
4852 Assert(!PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow));
4853 void *pvDstPage;
4854 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT);
4855 rc = pgmPhysPageMakeWritableAndMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pvDstPage);
4856 if (RT_FAILURE(rc))
4857 break;
4858 RT_BZERO(pvDstPage, GUEST_PAGE_SIZE);
4859 }
4860 AssertRCReturn(rc, rc);
4861 }
4862 }
4863
4864 /*
4865 * Restore the original ROM pages after a saved state load.
4866 * Also, in strict builds check that ROM pages remain unmodified.
4867 */
4868#ifndef VBOX_STRICT
4869 if (pVM->pgm.s.fRestoreRomPagesOnReset)
4870#endif
4871 {
4872 size_t cbSrcLeft = pRom->cbOriginal;
4873 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
4874 uint32_t cRestored = 0;
4875 for (uint32_t iPage = 0; iPage < cGuestPages && cbSrcLeft > 0; iPage++, pbSrcPage += GUEST_PAGE_SIZE)
4876 {
4877 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT);
4878 PPGMPAGE const pPage = pgmPhysGetPage(pVM, GCPhys);
4879 void const *pvDstPage = NULL;
4880 int rc = pgmPhysPageMapReadOnly(pVM, pPage, GCPhys, &pvDstPage);
4881 if (RT_FAILURE(rc))
4882 break;
4883
4884 if (memcmp(pvDstPage, pbSrcPage, RT_MIN(cbSrcLeft, GUEST_PAGE_SIZE)))
4885 {
4886 if (pVM->pgm.s.fRestoreRomPagesOnReset)
4887 {
4888 void *pvDstPageW = NULL;
4889 rc = pgmPhysPageMap(pVM, pPage, GCPhys, &pvDstPageW);
4890 AssertLogRelRCReturn(rc, rc);
4891 memcpy(pvDstPageW, pbSrcPage, RT_MIN(cbSrcLeft, GUEST_PAGE_SIZE));
4892 cRestored++;
4893 }
4894 else
4895 LogRel(("pgmR3PhysRomReset: %RGp: ROM page changed (%s)\n", GCPhys, pRom->pszDesc));
4896 }
4897 cbSrcLeft -= RT_MIN(cbSrcLeft, GUEST_PAGE_SIZE);
4898 }
4899 if (cRestored > 0)
4900 LogRel(("PGM: ROM \"%s\": Reloaded %u of %u pages.\n", pRom->pszDesc, cRestored, cGuestPages));
4901 }
4902 }
4903
4904 /* Clear the ROM restore flag now as we only need to do this once after
4905 loading saved state. */
4906 pVM->pgm.s.fRestoreRomPagesOnReset = false;
4907
4908 return VINF_SUCCESS;
4909}
4910
4911
4912/**
4913 * Called by PGMR3Term to free resources.
4914 *
4915 * ASSUMES that the caller owns the PGM lock.
4916 *
4917 * @param pVM The cross context VM structure.
4918 */
4919void pgmR3PhysRomTerm(PVM pVM)
4920{
4921 /*
4922 * Free the heap copy of the original bits.
4923 */
4924 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4925 {
4926 if ( pRom->pvOriginal
4927 && !(pRom->fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY))
4928 {
4929 RTMemFree((void *)pRom->pvOriginal);
4930 pRom->pvOriginal = NULL;
4931 }
4932 }
4933}
4934
4935
4936/**
4937 * Change the shadowing of a range of ROM pages.
4938 *
4939 * This is intended for implementing chipset specific memory registers
4940 * and will not be very strict about the input. It will silently ignore
4941 * any pages that are not the part of a shadowed ROM.
4942 *
4943 * @returns VBox status code.
4944 * @retval VINF_PGM_SYNC_CR3
4945 *
4946 * @param pVM The cross context VM structure.
4947 * @param GCPhys Where to start. Page aligned.
4948 * @param cb How much to change. Page aligned.
4949 * @param enmProt The new ROM protection.
4950 */
4951VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
4952{
4953 /*
4954 * Check input
4955 */
4956 if (!cb)
4957 return VINF_SUCCESS;
4958 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
4959 AssertReturn(!(cb & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
4960 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
4961 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
4962 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
4963
4964 /*
4965 * Process the request.
4966 */
4967 PGM_LOCK_VOID(pVM);
4968 int rc = VINF_SUCCESS;
4969 bool fFlushTLB = false;
4970 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4971 {
4972 if ( GCPhys <= pRom->GCPhysLast
4973 && GCPhysLast >= pRom->GCPhys
4974 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
4975 {
4976 /*
4977 * Iterate the relevant pages and make necessary the changes.
4978 */
4979#ifdef VBOX_WITH_NATIVE_NEM
4980 PPGMRAMRANGE const pRam = pgmPhysGetRange(pVM, GCPhys);
4981 AssertPtrReturn(pRam, VERR_INTERNAL_ERROR_3);
4982#endif
4983 bool fChanges = false;
4984 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
4985 ? pRom->cb >> GUEST_PAGE_SHIFT
4986 : (GCPhysLast - pRom->GCPhys + 1) >> GUEST_PAGE_SHIFT;
4987 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> GUEST_PAGE_SHIFT;
4988 iPage < cPages;
4989 iPage++)
4990 {
4991 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
4992 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
4993 {
4994 fChanges = true;
4995
4996 /* flush references to the page. */
4997 RTGCPHYS const GCPhysPage = pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT);
4998 PPGMPAGE pRamPage = pgmPhysGetPage(pVM, GCPhysPage);
4999 int rc2 = pgmPoolTrackUpdateGCPhys(pVM, GCPhysPage, pRamPage, true /*fFlushPTEs*/, &fFlushTLB);
5000 if (rc2 != VINF_SUCCESS && (rc == VINF_SUCCESS || RT_FAILURE(rc2)))
5001 rc = rc2;
5002#ifdef VBOX_WITH_NATIVE_NEM
5003 uint8_t u2State = PGM_PAGE_GET_NEM_STATE(pRamPage);
5004#endif
5005
5006 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
5007 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
5008
5009 *pOld = *pRamPage;
5010 *pRamPage = *pNew;
5011 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
5012
5013#ifdef VBOX_WITH_NATIVE_NEM
5014# ifdef VBOX_WITH_PGM_NEM_MODE
5015 /* In simplified mode we have to switch the page data around too. */
5016 if (pVM->pgm.s.fNemMode)
5017 {
5018 uint8_t abPage[GUEST_PAGE_SIZE];
5019 uint8_t * const pbRamPage = PGM_RAMRANGE_CALC_PAGE_R3PTR(pRam, GCPhysPage);
5020 memcpy(abPage, &pRom->pbR3Alternate[(size_t)iPage << GUEST_PAGE_SHIFT], sizeof(abPage));
5021 memcpy(&pRom->pbR3Alternate[(size_t)iPage << GUEST_PAGE_SHIFT], pbRamPage, sizeof(abPage));
5022 memcpy(pbRamPage, abPage, sizeof(abPage));
5023 }
5024# endif
5025 /* Tell NEM about the backing and protection change. */
5026 if (VM_IS_NEM_ENABLED(pVM))
5027 {
5028 PGMPAGETYPE enmType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pNew);
5029 NEMHCNotifyPhysPageChanged(pVM, GCPhys, PGM_PAGE_GET_HCPHYS(pOld), PGM_PAGE_GET_HCPHYS(pNew),
5030 PGM_RAMRANGE_CALC_PAGE_R3PTR(pRam, GCPhysPage),
5031 pgmPhysPageCalcNemProtection(pRamPage, enmType), enmType, &u2State);
5032 PGM_PAGE_SET_NEM_STATE(pRamPage, u2State);
5033 }
5034#endif
5035 }
5036 pRomPage->enmProt = enmProt;
5037 }
5038
5039 /*
5040 * Reset the access handler if we made changes, no need
5041 * to optimize this.
5042 */
5043 if (fChanges)
5044 {
5045 int rc2 = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
5046 if (RT_FAILURE(rc2))
5047 {
5048 PGM_UNLOCK(pVM);
5049 AssertRC(rc);
5050 return rc2;
5051 }
5052 }
5053
5054 /* Advance - cb isn't updated. */
5055 GCPhys = pRom->GCPhys + (cPages << GUEST_PAGE_SHIFT);
5056 }
5057 }
5058 PGM_UNLOCK(pVM);
5059 if (fFlushTLB)
5060 PGM_INVL_ALL_VCPU_TLBS(pVM);
5061
5062 return rc;
5063}
5064
5065
5066
5067/*********************************************************************************************************************************
5068* Ballooning *
5069*********************************************************************************************************************************/
5070
5071#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
5072
5073/**
5074 * Rendezvous callback used by PGMR3ChangeMemBalloon that changes the memory balloon size
5075 *
5076 * This is only called on one of the EMTs while the other ones are waiting for
5077 * it to complete this function.
5078 *
5079 * @returns VINF_SUCCESS (VBox strict status code).
5080 * @param pVM The cross context VM structure.
5081 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
5082 * @param pvUser User parameter
5083 */
5084static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysChangeMemBalloonRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
5085{
5086 uintptr_t *paUser = (uintptr_t *)pvUser;
5087 bool fInflate = !!paUser[0];
5088 unsigned cPages = paUser[1];
5089 RTGCPHYS *paPhysPage = (RTGCPHYS *)paUser[2];
5090 uint32_t cPendingPages = 0;
5091 PGMMFREEPAGESREQ pReq;
5092 int rc;
5093
5094 Log(("pgmR3PhysChangeMemBalloonRendezvous: %s %x pages\n", (fInflate) ? "inflate" : "deflate", cPages));
5095 PGM_LOCK_VOID(pVM);
5096
5097 if (fInflate)
5098 {
5099 /* Flush the PGM pool cache as we might have stale references to pages that we just freed. */
5100 pgmR3PoolClearAllRendezvous(pVM, pVCpu, NULL);
5101
5102 /* Replace pages with ZERO pages. */
5103 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
5104 if (RT_FAILURE(rc))
5105 {
5106 PGM_UNLOCK(pVM);
5107 AssertLogRelRC(rc);
5108 return rc;
5109 }
5110
5111 /* Iterate the pages. */
5112 for (unsigned i = 0; i < cPages; i++)
5113 {
5114 PPGMPAGE pPage = pgmPhysGetPage(pVM, paPhysPage[i]);
5115 if ( pPage == NULL
5116 || PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM)
5117 {
5118 Log(("pgmR3PhysChangeMemBalloonRendezvous: invalid physical page %RGp pPage->u3Type=%d\n", paPhysPage[i], pPage ? PGM_PAGE_GET_TYPE(pPage) : 0));
5119 break;
5120 }
5121
5122 LogFlow(("balloon page: %RGp\n", paPhysPage[i]));
5123
5124 /* Flush the shadow PT if this page was previously used as a guest page table. */
5125 pgmPoolFlushPageByGCPhys(pVM, paPhysPage[i]);
5126
5127 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, paPhysPage[i], (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage));
5128 if (RT_FAILURE(rc))
5129 {
5130 PGM_UNLOCK(pVM);
5131 AssertLogRelRC(rc);
5132 return rc;
5133 }
5134 Assert(PGM_PAGE_IS_ZERO(pPage));
5135 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_BALLOONED);
5136 }
5137
5138 if (cPendingPages)
5139 {
5140 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
5141 if (RT_FAILURE(rc))
5142 {
5143 PGM_UNLOCK(pVM);
5144 AssertLogRelRC(rc);
5145 return rc;
5146 }
5147 }
5148 GMMR3FreePagesCleanup(pReq);
5149 }
5150 else
5151 {
5152 /* Iterate the pages. */
5153 for (unsigned i = 0; i < cPages; i++)
5154 {
5155 PPGMPAGE pPage = pgmPhysGetPage(pVM, paPhysPage[i]);
5156 AssertBreak(pPage && PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM);
5157
5158 LogFlow(("Free ballooned page: %RGp\n", paPhysPage[i]));
5159
5160 Assert(PGM_PAGE_IS_BALLOONED(pPage));
5161
5162 /* Change back to zero page. (NEM does not need to be informed.) */
5163 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
5164 }
5165
5166 /* Note that we currently do not map any ballooned pages in our shadow page tables, so no need to flush the pgm pool. */
5167 }
5168
5169 /* Notify GMM about the balloon change. */
5170 rc = GMMR3BalloonedPages(pVM, (fInflate) ? GMMBALLOONACTION_INFLATE : GMMBALLOONACTION_DEFLATE, cPages);
5171 if (RT_SUCCESS(rc))
5172 {
5173 if (!fInflate)
5174 {
5175 Assert(pVM->pgm.s.cBalloonedPages >= cPages);
5176 pVM->pgm.s.cBalloonedPages -= cPages;
5177 }
5178 else
5179 pVM->pgm.s.cBalloonedPages += cPages;
5180 }
5181
5182 PGM_UNLOCK(pVM);
5183
5184 /* Flush the recompiler's TLB as well. */
5185 for (VMCPUID i = 0; i < pVM->cCpus; i++)
5186 CPUMSetChangedFlags(pVM->apCpusR3[i], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5187
5188 AssertLogRelRC(rc);
5189 return rc;
5190}
5191
5192
5193/**
5194 * Frees a range of ram pages, replacing them with ZERO pages; helper for PGMR3PhysFreeRamPages
5195 *
5196 * @returns VBox status code.
5197 * @param pVM The cross context VM structure.
5198 * @param fInflate Inflate or deflate memory balloon
5199 * @param cPages Number of pages to free
5200 * @param paPhysPage Array of guest physical addresses
5201 */
5202static DECLCALLBACK(void) pgmR3PhysChangeMemBalloonHelper(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
5203{
5204 uintptr_t paUser[3];
5205
5206 paUser[0] = fInflate;
5207 paUser[1] = cPages;
5208 paUser[2] = (uintptr_t)paPhysPage;
5209 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
5210 AssertRC(rc);
5211
5212 /* Made a copy in PGMR3PhysFreeRamPages; free it here. */
5213 RTMemFree(paPhysPage);
5214}
5215
5216#endif /* 64-bit host && (Windows || Solaris || Linux || FreeBSD) */
5217
5218/**
5219 * Inflate or deflate a memory balloon
5220 *
5221 * @returns VBox status code.
5222 * @param pVM The cross context VM structure.
5223 * @param fInflate Inflate or deflate memory balloon
5224 * @param cPages Number of pages to free
5225 * @param paPhysPage Array of guest physical addresses
5226 */
5227VMMR3DECL(int) PGMR3PhysChangeMemBalloon(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
5228{
5229 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
5230#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
5231 int rc;
5232
5233 /* Older additions (ancient non-functioning balloon code) pass wrong physical addresses. */
5234 AssertReturn(!(paPhysPage[0] & 0xfff), VERR_INVALID_PARAMETER);
5235
5236 /* We own the IOM lock here and could cause a deadlock by waiting for another VCPU that is blocking on the IOM lock.
5237 * In the SMP case we post a request packet to postpone the job.
5238 */
5239 if (pVM->cCpus > 1)
5240 {
5241 unsigned cbPhysPage = cPages * sizeof(paPhysPage[0]);
5242 RTGCPHYS *paPhysPageCopy = (RTGCPHYS *)RTMemAlloc(cbPhysPage);
5243 AssertReturn(paPhysPageCopy, VERR_NO_MEMORY);
5244
5245 memcpy(paPhysPageCopy, paPhysPage, cbPhysPage);
5246
5247 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysChangeMemBalloonHelper, 4, pVM, fInflate, cPages, paPhysPageCopy);
5248 AssertRC(rc);
5249 }
5250 else
5251 {
5252 uintptr_t paUser[3];
5253
5254 paUser[0] = fInflate;
5255 paUser[1] = cPages;
5256 paUser[2] = (uintptr_t)paPhysPage;
5257 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
5258 AssertRC(rc);
5259 }
5260 return rc;
5261
5262#else
5263 NOREF(pVM); NOREF(fInflate); NOREF(cPages); NOREF(paPhysPage);
5264 return VERR_NOT_IMPLEMENTED;
5265#endif
5266}
5267
5268
5269/*********************************************************************************************************************************
5270* Write Monitoring *
5271*********************************************************************************************************************************/
5272
5273/**
5274 * Rendezvous callback used by PGMR3WriteProtectRAM that write protects all
5275 * physical RAM.
5276 *
5277 * This is only called on one of the EMTs while the other ones are waiting for
5278 * it to complete this function.
5279 *
5280 * @returns VINF_SUCCESS (VBox strict status code).
5281 * @param pVM The cross context VM structure.
5282 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
5283 * @param pvUser User parameter, unused.
5284 */
5285static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysWriteProtectRAMRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
5286{
5287 int rc = VINF_SUCCESS;
5288 NOREF(pvUser); NOREF(pVCpu);
5289
5290 PGM_LOCK_VOID(pVM);
5291#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
5292 pgmPoolResetDirtyPages(pVM);
5293#endif
5294
5295 /** @todo pointless to write protect the physical page pointed to by RSP. */
5296
5297 for (PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRangesX);
5298 pRam;
5299 pRam = pRam->CTX_SUFF(pNext))
5300 {
5301 uint32_t cPages = pRam->cb >> GUEST_PAGE_SHIFT;
5302 for (uint32_t iPage = 0; iPage < cPages; iPage++)
5303 {
5304 PPGMPAGE pPage = &pRam->aPages[iPage];
5305 PGMPAGETYPE enmPageType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage);
5306
5307 if ( RT_LIKELY(enmPageType == PGMPAGETYPE_RAM)
5308 || enmPageType == PGMPAGETYPE_MMIO2)
5309 {
5310 /*
5311 * A RAM page.
5312 */
5313 switch (PGM_PAGE_GET_STATE(pPage))
5314 {
5315 case PGM_PAGE_STATE_ALLOCATED:
5316 /** @todo Optimize this: Don't always re-enable write
5317 * monitoring if the page is known to be very busy. */
5318 if (PGM_PAGE_IS_WRITTEN_TO(pPage))
5319 PGM_PAGE_CLEAR_WRITTEN_TO(pVM, pPage);
5320
5321 pgmPhysPageWriteMonitor(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT));
5322 break;
5323
5324 case PGM_PAGE_STATE_SHARED:
5325 AssertFailed();
5326 break;
5327
5328 case PGM_PAGE_STATE_WRITE_MONITORED: /* nothing to change. */
5329 default:
5330 break;
5331 }
5332 }
5333 }
5334 }
5335 pgmR3PoolWriteProtectPages(pVM);
5336 PGM_INVL_ALL_VCPU_TLBS(pVM);
5337 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
5338 CPUMSetChangedFlags(pVM->apCpusR3[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5339
5340 PGM_UNLOCK(pVM);
5341 return rc;
5342}
5343
5344/**
5345 * Protect all physical RAM to monitor writes
5346 *
5347 * @returns VBox status code.
5348 * @param pVM The cross context VM structure.
5349 */
5350VMMR3DECL(int) PGMR3PhysWriteProtectRAM(PVM pVM)
5351{
5352 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
5353
5354 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysWriteProtectRAMRendezvous, NULL);
5355 AssertRC(rc);
5356 return rc;
5357}
5358
5359
5360/*********************************************************************************************************************************
5361* Stats. *
5362*********************************************************************************************************************************/
5363
5364/**
5365 * Query the amount of free memory inside VMMR0
5366 *
5367 * @returns VBox status code.
5368 * @param pUVM The user mode VM handle.
5369 * @param pcbAllocMem Where to return the amount of memory allocated
5370 * by VMs.
5371 * @param pcbFreeMem Where to return the amount of memory that is
5372 * allocated from the host but not currently used
5373 * by any VMs.
5374 * @param pcbBallonedMem Where to return the sum of memory that is
5375 * currently ballooned by the VMs.
5376 * @param pcbSharedMem Where to return the amount of memory that is
5377 * currently shared.
5378 */
5379VMMR3DECL(int) PGMR3QueryGlobalMemoryStats(PUVM pUVM, uint64_t *pcbAllocMem, uint64_t *pcbFreeMem,
5380 uint64_t *pcbBallonedMem, uint64_t *pcbSharedMem)
5381{
5382 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
5383 VM_ASSERT_VALID_EXT_RETURN(pUVM->pVM, VERR_INVALID_VM_HANDLE);
5384
5385 uint64_t cAllocPages = 0;
5386 uint64_t cFreePages = 0;
5387 uint64_t cBalloonPages = 0;
5388 uint64_t cSharedPages = 0;
5389 if (!SUPR3IsDriverless())
5390 {
5391 int rc = GMMR3QueryHypervisorMemoryStats(pUVM->pVM, &cAllocPages, &cFreePages, &cBalloonPages, &cSharedPages);
5392 AssertRCReturn(rc, rc);
5393 }
5394
5395 if (pcbAllocMem)
5396 *pcbAllocMem = cAllocPages * _4K;
5397
5398 if (pcbFreeMem)
5399 *pcbFreeMem = cFreePages * _4K;
5400
5401 if (pcbBallonedMem)
5402 *pcbBallonedMem = cBalloonPages * _4K;
5403
5404 if (pcbSharedMem)
5405 *pcbSharedMem = cSharedPages * _4K;
5406
5407 Log(("PGMR3QueryVMMMemoryStats: all=%llx free=%llx ballooned=%llx shared=%llx\n",
5408 cAllocPages, cFreePages, cBalloonPages, cSharedPages));
5409 return VINF_SUCCESS;
5410}
5411
5412
5413/**
5414 * Query memory stats for the VM.
5415 *
5416 * @returns VBox status code.
5417 * @param pUVM The user mode VM handle.
5418 * @param pcbTotalMem Where to return total amount memory the VM may
5419 * possibly use.
5420 * @param pcbPrivateMem Where to return the amount of private memory
5421 * currently allocated.
5422 * @param pcbSharedMem Where to return the amount of actually shared
5423 * memory currently used by the VM.
5424 * @param pcbZeroMem Where to return the amount of memory backed by
5425 * zero pages.
5426 *
5427 * @remarks The total mem is normally larger than the sum of the three
5428 * components. There are two reasons for this, first the amount of
5429 * shared memory is what we're sure is shared instead of what could
5430 * possibly be shared with someone. Secondly, because the total may
5431 * include some pure MMIO pages that doesn't go into any of the three
5432 * sub-counts.
5433 *
5434 * @todo Why do we return reused shared pages instead of anything that could
5435 * potentially be shared? Doesn't this mean the first VM gets a much
5436 * lower number of shared pages?
5437 */
5438VMMR3DECL(int) PGMR3QueryMemoryStats(PUVM pUVM, uint64_t *pcbTotalMem, uint64_t *pcbPrivateMem,
5439 uint64_t *pcbSharedMem, uint64_t *pcbZeroMem)
5440{
5441 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
5442 PVM pVM = pUVM->pVM;
5443 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
5444
5445 if (pcbTotalMem)
5446 *pcbTotalMem = (uint64_t)pVM->pgm.s.cAllPages * GUEST_PAGE_SIZE;
5447
5448 if (pcbPrivateMem)
5449 *pcbPrivateMem = (uint64_t)pVM->pgm.s.cPrivatePages * GUEST_PAGE_SIZE;
5450
5451 if (pcbSharedMem)
5452 *pcbSharedMem = (uint64_t)pVM->pgm.s.cReusedSharedPages * GUEST_PAGE_SIZE;
5453
5454 if (pcbZeroMem)
5455 *pcbZeroMem = (uint64_t)pVM->pgm.s.cZeroPages * GUEST_PAGE_SIZE;
5456
5457 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));
5458 return VINF_SUCCESS;
5459}
5460
5461
5462
5463/*********************************************************************************************************************************
5464* Chunk Mappings and Page Allocation *
5465*********************************************************************************************************************************/
5466
5467/**
5468 * Tree enumeration callback for dealing with age rollover.
5469 * It will perform a simple compression of the current age.
5470 */
5471static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
5472{
5473 /* Age compression - ASSUMES iNow == 4. */
5474 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
5475 if (pChunk->iLastUsed >= UINT32_C(0xffffff00))
5476 pChunk->iLastUsed = 3;
5477 else if (pChunk->iLastUsed >= UINT32_C(0xfffff000))
5478 pChunk->iLastUsed = 2;
5479 else if (pChunk->iLastUsed)
5480 pChunk->iLastUsed = 1;
5481 else /* iLastUsed = 0 */
5482 pChunk->iLastUsed = 4;
5483
5484 NOREF(pvUser);
5485 return 0;
5486}
5487
5488
5489/**
5490 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
5491 */
5492typedef struct PGMR3PHYSCHUNKUNMAPCB
5493{
5494 PVM pVM; /**< Pointer to the VM. */
5495 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
5496} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
5497
5498
5499/**
5500 * Callback used to find the mapping that's been unused for
5501 * the longest time.
5502 */
5503static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLU32NODECORE pNode, void *pvUser)
5504{
5505 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
5506 PPGMR3PHYSCHUNKUNMAPCB pArg = (PPGMR3PHYSCHUNKUNMAPCB)pvUser;
5507
5508 /*
5509 * Check for locks and compare when last used.
5510 */
5511 if (pChunk->cRefs)
5512 return 0;
5513 if (pChunk->cPermRefs)
5514 return 0;
5515 if ( pArg->pChunk
5516 && pChunk->iLastUsed >= pArg->pChunk->iLastUsed)
5517 return 0;
5518
5519 /*
5520 * Check that it's not in any of the TLBs.
5521 */
5522 PVM pVM = pArg->pVM;
5523 if ( pVM->pgm.s.ChunkR3Map.Tlb.aEntries[PGM_CHUNKR3MAPTLB_IDX(pChunk->Core.Key)].idChunk
5524 == pChunk->Core.Key)
5525 {
5526 pChunk = NULL;
5527 return 0;
5528 }
5529#ifdef VBOX_STRICT
5530 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
5531 {
5532 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk != pChunk);
5533 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk != pChunk->Core.Key);
5534 }
5535#endif
5536
5537 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbR3.aEntries); i++)
5538 if (pVM->pgm.s.PhysTlbR3.aEntries[i].pMap == pChunk)
5539 return 0;
5540
5541 pArg->pChunk = pChunk;
5542 return 0;
5543}
5544
5545
5546/**
5547 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
5548 *
5549 * The candidate will not be part of any TLBs, so no need to flush
5550 * anything afterwards.
5551 *
5552 * @returns Chunk id.
5553 * @param pVM The cross context VM structure.
5554 */
5555static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
5556{
5557 PGM_LOCK_ASSERT_OWNER(pVM);
5558
5559 /*
5560 * Enumerate the age tree starting with the left most node.
5561 */
5562 STAM_PROFILE_START(&pVM->pgm.s.Stats.StatChunkFindCandidate, a);
5563 PGMR3PHYSCHUNKUNMAPCB Args;
5564 Args.pVM = pVM;
5565 Args.pChunk = NULL;
5566 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, &Args);
5567 Assert(Args.pChunk);
5568 if (Args.pChunk)
5569 {
5570 Assert(Args.pChunk->cRefs == 0);
5571 Assert(Args.pChunk->cPermRefs == 0);
5572 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkFindCandidate, a);
5573 return Args.pChunk->Core.Key;
5574 }
5575
5576 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkFindCandidate, a);
5577 return INT32_MAX;
5578}
5579
5580
5581/**
5582 * Rendezvous callback used by pgmR3PhysUnmapChunk that unmaps a chunk
5583 *
5584 * This is only called on one of the EMTs while the other ones are waiting for
5585 * it to complete this function.
5586 *
5587 * @returns VINF_SUCCESS (VBox strict status code).
5588 * @param pVM The cross context VM structure.
5589 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
5590 * @param pvUser User pointer. Unused
5591 *
5592 */
5593static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysUnmapChunkRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
5594{
5595 int rc = VINF_SUCCESS;
5596 PGM_LOCK_VOID(pVM);
5597 NOREF(pVCpu); NOREF(pvUser);
5598
5599 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
5600 {
5601 /* Flush the pgm pool cache; call the internal rendezvous handler as we're already in a rendezvous handler here. */
5602 /** @todo also not really efficient to unmap a chunk that contains PD
5603 * or PT pages. */
5604 pgmR3PoolClearAllRendezvous(pVM, pVM->apCpusR3[0], NULL /* no need to flush the REM TLB as we already did that above */);
5605
5606 /*
5607 * Request the ring-0 part to unmap a chunk to make space in the mapping cache.
5608 */
5609 GMMMAPUNMAPCHUNKREQ Req;
5610 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
5611 Req.Hdr.cbReq = sizeof(Req);
5612 Req.pvR3 = NULL;
5613 Req.idChunkMap = NIL_GMM_CHUNKID;
5614 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
5615 if (Req.idChunkUnmap != INT32_MAX)
5616 {
5617 STAM_PROFILE_START(&pVM->pgm.s.Stats.StatChunkUnmap, a);
5618 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
5619 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkUnmap, a);
5620 if (RT_SUCCESS(rc))
5621 {
5622 /*
5623 * Remove the unmapped one.
5624 */
5625 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
5626 AssertRelease(pUnmappedChunk);
5627 AssertRelease(!pUnmappedChunk->cRefs);
5628 AssertRelease(!pUnmappedChunk->cPermRefs);
5629 pUnmappedChunk->pv = NULL;
5630 pUnmappedChunk->Core.Key = UINT32_MAX;
5631 MMR3HeapFree(pUnmappedChunk);
5632 pVM->pgm.s.ChunkR3Map.c--;
5633 pVM->pgm.s.cUnmappedChunks++;
5634
5635 /*
5636 * Flush dangling PGM pointers (R3 & R0 ptrs to GC physical addresses).
5637 */
5638 /** @todo We should not flush chunks which include cr3 mappings. */
5639 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
5640 {
5641 PPGMCPU pPGM = &pVM->apCpusR3[idCpu]->pgm.s;
5642
5643 pPGM->pGst32BitPdR3 = NULL;
5644 pPGM->pGstPaePdptR3 = NULL;
5645 pPGM->pGstAmd64Pml4R3 = NULL;
5646 pPGM->pGstEptPml4R3 = NULL;
5647 pPGM->pGst32BitPdR0 = NIL_RTR0PTR;
5648 pPGM->pGstPaePdptR0 = NIL_RTR0PTR;
5649 pPGM->pGstAmd64Pml4R0 = NIL_RTR0PTR;
5650 pPGM->pGstEptPml4R0 = NIL_RTR0PTR;
5651 for (unsigned i = 0; i < RT_ELEMENTS(pPGM->apGstPaePDsR3); i++)
5652 {
5653 pPGM->apGstPaePDsR3[i] = NULL;
5654 pPGM->apGstPaePDsR0[i] = NIL_RTR0PTR;
5655 }
5656
5657 /* Flush REM TLBs. */
5658 CPUMSetChangedFlags(pVM->apCpusR3[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5659 }
5660 }
5661 }
5662 }
5663 PGM_UNLOCK(pVM);
5664 return rc;
5665}
5666
5667/**
5668 * Unmap a chunk to free up virtual address space (request packet handler for pgmR3PhysChunkMap)
5669 *
5670 * @returns VBox status code.
5671 * @param pVM The cross context VM structure.
5672 */
5673static DECLCALLBACK(void) pgmR3PhysUnmapChunk(PVM pVM)
5674{
5675 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysUnmapChunkRendezvous, NULL);
5676 AssertRC(rc);
5677}
5678
5679
5680/**
5681 * Maps the given chunk into the ring-3 mapping cache.
5682 *
5683 * This will call ring-0.
5684 *
5685 * @returns VBox status code.
5686 * @param pVM The cross context VM structure.
5687 * @param idChunk The chunk in question.
5688 * @param ppChunk Where to store the chunk tracking structure.
5689 *
5690 * @remarks Called from within the PGM critical section.
5691 * @remarks Can be called from any thread!
5692 */
5693int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
5694{
5695 int rc;
5696
5697 PGM_LOCK_ASSERT_OWNER(pVM);
5698
5699 /*
5700 * Move the chunk time forward.
5701 */
5702 pVM->pgm.s.ChunkR3Map.iNow++;
5703 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
5704 {
5705 pVM->pgm.s.ChunkR3Map.iNow = 4;
5706 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, NULL);
5707 }
5708
5709 /*
5710 * Allocate a new tracking structure first.
5711 */
5712 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
5713 AssertReturn(pChunk, VERR_NO_MEMORY);
5714 pChunk->Core.Key = idChunk;
5715 pChunk->iLastUsed = pVM->pgm.s.ChunkR3Map.iNow;
5716
5717 /*
5718 * Request the ring-0 part to map the chunk in question.
5719 */
5720 GMMMAPUNMAPCHUNKREQ Req;
5721 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
5722 Req.Hdr.cbReq = sizeof(Req);
5723 Req.pvR3 = NULL;
5724 Req.idChunkMap = idChunk;
5725 Req.idChunkUnmap = NIL_GMM_CHUNKID;
5726
5727 /* Must be callable from any thread, so can't use VMMR3CallR0. */
5728 STAM_PROFILE_START(&pVM->pgm.s.Stats.StatChunkMap, a);
5729 rc = SUPR3CallVMMR0Ex(VMCC_GET_VMR0_FOR_CALL(pVM), NIL_VMCPUID, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
5730 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkMap, a);
5731 if (RT_SUCCESS(rc))
5732 {
5733 pChunk->pv = Req.pvR3;
5734
5735 /*
5736 * If we're running out of virtual address space, then we should
5737 * unmap another chunk.
5738 *
5739 * Currently, an unmap operation requires that all other virtual CPUs
5740 * are idling and not by chance making use of the memory we're
5741 * unmapping. So, we create an async unmap operation here.
5742 *
5743 * Now, when creating or restoring a saved state this wont work very
5744 * well since we may want to restore all guest RAM + a little something.
5745 * So, we have to do the unmap synchronously. Fortunately for us
5746 * though, during these operations the other virtual CPUs are inactive
5747 * and it should be safe to do this.
5748 */
5749 /** @todo Eventually we should lock all memory when used and do
5750 * map+unmap as one kernel call without any rendezvous or
5751 * other precautions. */
5752 if (pVM->pgm.s.ChunkR3Map.c + 1 >= pVM->pgm.s.ChunkR3Map.cMax)
5753 {
5754 switch (VMR3GetState(pVM))
5755 {
5756 case VMSTATE_LOADING:
5757 case VMSTATE_SAVING:
5758 {
5759 PVMCPU pVCpu = VMMGetCpu(pVM);
5760 if ( pVCpu
5761 && pVM->pgm.s.cDeprecatedPageLocks == 0)
5762 {
5763 pgmR3PhysUnmapChunkRendezvous(pVM, pVCpu, NULL);
5764 break;
5765 }
5766 }
5767 RT_FALL_THRU();
5768 default:
5769 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysUnmapChunk, 1, pVM);
5770 AssertRC(rc);
5771 break;
5772 }
5773 }
5774
5775 /*
5776 * Update the tree. We must do this after any unmapping to make sure
5777 * the chunk we're going to return isn't unmapped by accident.
5778 */
5779 AssertPtr(Req.pvR3);
5780 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
5781 AssertRelease(fRc);
5782 pVM->pgm.s.ChunkR3Map.c++;
5783 pVM->pgm.s.cMappedChunks++;
5784 }
5785 else
5786 {
5787 /** @todo this may fail because of /proc/sys/vm/max_map_count, so we
5788 * should probably restrict ourselves on linux. */
5789 AssertRC(rc);
5790 MMR3HeapFree(pChunk);
5791 pChunk = NULL;
5792 }
5793
5794 *ppChunk = pChunk;
5795 return rc;
5796}
5797
5798
5799/**
5800 * Invalidates the TLB for the ring-3 mapping cache.
5801 *
5802 * @param pVM The cross context VM structure.
5803 */
5804VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
5805{
5806 PGM_LOCK_VOID(pVM);
5807 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
5808 {
5809 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
5810 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
5811 }
5812 /* The page map TLB references chunks, so invalidate that one too. */
5813 pgmPhysInvalidatePageMapTLB(pVM);
5814 PGM_UNLOCK(pVM);
5815}
5816
5817
5818/**
5819 * Response to VM_FF_PGM_NEED_HANDY_PAGES and helper for pgmPhysEnsureHandyPage.
5820 *
5821 * This function will also work the VM_FF_PGM_NO_MEMORY force action flag, to
5822 * signal and clear the out of memory condition. When called, this API is used
5823 * to try clear the condition when the user wants to resume.
5824 *
5825 * @returns The following VBox status codes.
5826 * @retval VINF_SUCCESS on success. FFs cleared.
5827 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in
5828 * this case and it gets accompanied by VM_FF_PGM_NO_MEMORY.
5829 *
5830 * @param pVM The cross context VM structure.
5831 *
5832 * @remarks The VINF_EM_NO_MEMORY status is for the benefit of the FF processing
5833 * in EM.cpp and shouldn't be propagated outside TRPM, HM, EM and
5834 * pgmPhysEnsureHandyPage. There is one exception to this in the \#PF
5835 * handler.
5836 */
5837VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
5838{
5839 PGM_LOCK_VOID(pVM);
5840
5841 /*
5842 * Allocate more pages, noting down the index of the first new page.
5843 */
5844 uint32_t iClear = pVM->pgm.s.cHandyPages;
5845 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_PGM_HANDY_PAGE_IPE);
5846 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
5847 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
5848 /** @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) */
5849 if ( rc == VERR_GMM_HIT_VM_ACCOUNT_LIMIT
5850 && pVM->pgm.s.cHandyPages > 0)
5851 {
5852 /* Still handy pages left, so don't panic. */
5853 rc = VINF_SUCCESS;
5854 }
5855
5856 if (RT_SUCCESS(rc))
5857 {
5858 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
5859 Assert(pVM->pgm.s.cHandyPages > 0);
5860#ifdef VBOX_STRICT
5861 uint32_t i;
5862 for (i = iClear; i < pVM->pgm.s.cHandyPages; i++)
5863 if ( pVM->pgm.s.aHandyPages[i].idPage == NIL_GMM_PAGEID
5864 || pVM->pgm.s.aHandyPages[i].idSharedPage != NIL_GMM_PAGEID
5865 || (pVM->pgm.s.aHandyPages[i].HCPhysGCPhys & GUEST_PAGE_OFFSET_MASK))
5866 break;
5867 if (i != pVM->pgm.s.cHandyPages)
5868 {
5869 RTAssertMsg1Weak(NULL, __LINE__, __FILE__, __FUNCTION__);
5870 RTAssertMsg2Weak("i=%d iClear=%d cHandyPages=%d\n", i, iClear, pVM->pgm.s.cHandyPages);
5871 for (uint32_t j = iClear; j < pVM->pgm.s.cHandyPages; j++)
5872 RTAssertMsg2Add("%03d: idPage=%d HCPhysGCPhys=%RHp idSharedPage=%d%s\n", j,
5873 pVM->pgm.s.aHandyPages[j].idPage,
5874 pVM->pgm.s.aHandyPages[j].HCPhysGCPhys,
5875 pVM->pgm.s.aHandyPages[j].idSharedPage,
5876 j == i ? " <---" : "");
5877 RTAssertPanic();
5878 }
5879#endif
5880 }
5881 else
5882 {
5883 /*
5884 * We should never get here unless there is a genuine shortage of
5885 * memory (or some internal error). Flag the error so the VM can be
5886 * suspended ASAP and the user informed. If we're totally out of
5887 * handy pages we will return failure.
5888 */
5889 /* Report the failure. */
5890 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc cHandyPages=%#x\n"
5891 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
5892 rc, pVM->pgm.s.cHandyPages,
5893 pVM->pgm.s.cAllPages, pVM->pgm.s.cPrivatePages, pVM->pgm.s.cSharedPages, pVM->pgm.s.cZeroPages));
5894
5895 if ( rc != VERR_NO_MEMORY
5896 && rc != VERR_NO_PHYS_MEMORY
5897 && rc != VERR_LOCK_FAILED)
5898 for (uint32_t i = 0; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
5899 {
5900 LogRel(("PGM: aHandyPages[#%#04x] = {.HCPhysGCPhys=%RHp, .idPage=%#08x, .idSharedPage=%#08x}\n",
5901 i, pVM->pgm.s.aHandyPages[i].HCPhysGCPhys, pVM->pgm.s.aHandyPages[i].idPage,
5902 pVM->pgm.s.aHandyPages[i].idSharedPage));
5903 uint32_t const idPage = pVM->pgm.s.aHandyPages[i].idPage;
5904 if (idPage != NIL_GMM_PAGEID)
5905 {
5906 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
5907 pRam;
5908 pRam = pRam->pNextR3)
5909 {
5910 uint32_t const cPages = pRam->cb >> GUEST_PAGE_SHIFT;
5911 for (uint32_t iPage = 0; iPage < cPages; iPage++)
5912 if (PGM_PAGE_GET_PAGEID(&pRam->aPages[iPage]) == idPage)
5913 LogRel(("PGM: Used by %RGp %R[pgmpage] (%s)\n",
5914 pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), &pRam->aPages[iPage], pRam->pszDesc));
5915 }
5916 }
5917 }
5918
5919 if (rc == VERR_NO_MEMORY)
5920 {
5921 uint64_t cbHostRamAvail = 0;
5922 int rc2 = RTSystemQueryAvailableRam(&cbHostRamAvail);
5923 if (RT_SUCCESS(rc2))
5924 LogRel(("Host RAM: %RU64MB available\n", cbHostRamAvail / _1M));
5925 else
5926 LogRel(("Cannot determine the amount of available host memory\n"));
5927 }
5928
5929 /* Set the FFs and adjust rc. */
5930 VM_FF_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
5931 VM_FF_SET(pVM, VM_FF_PGM_NO_MEMORY);
5932 if ( rc == VERR_NO_MEMORY
5933 || rc == VERR_NO_PHYS_MEMORY
5934 || rc == VERR_LOCK_FAILED)
5935 rc = VINF_EM_NO_MEMORY;
5936 }
5937
5938 PGM_UNLOCK(pVM);
5939 return rc;
5940}
5941
5942
5943/*********************************************************************************************************************************
5944* Other Stuff *
5945*********************************************************************************************************************************/
5946
5947/**
5948 * Sets the Address Gate 20 state.
5949 *
5950 * @param pVCpu The cross context virtual CPU structure.
5951 * @param fEnable True if the gate should be enabled.
5952 * False if the gate should be disabled.
5953 */
5954VMMDECL(void) PGMR3PhysSetA20(PVMCPU pVCpu, bool fEnable)
5955{
5956 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVCpu->pgm.s.fA20Enabled));
5957 if (pVCpu->pgm.s.fA20Enabled != fEnable)
5958 {
5959#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5960 PCCPUMCTX pCtx = CPUMQueryGuestCtxPtr(pVCpu);
5961 if ( CPUMIsGuestInVmxRootMode(pCtx)
5962 && !fEnable)
5963 {
5964 Log(("Cannot enter A20M mode while in VMX root mode\n"));
5965 return;
5966 }
5967#endif
5968 pVCpu->pgm.s.fA20Enabled = fEnable;
5969 pVCpu->pgm.s.GCPhysA20Mask = ~((RTGCPHYS)!fEnable << 20);
5970 if (VM_IS_NEM_ENABLED(pVCpu->CTX_SUFF(pVM)))
5971 NEMR3NotifySetA20(pVCpu, fEnable);
5972#ifdef PGM_WITH_A20
5973 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
5974 pgmR3RefreshShadowModeAfterA20Change(pVCpu);
5975 HMFlushTlb(pVCpu);
5976#endif
5977#if 0 /* PGMGetPage will apply the A20 mask to the GCPhys it returns, so we must invalid both sides of the TLB. */
5978 IEMTlbInvalidateAllPhysical(pVCpu);
5979#else
5980 IEMTlbInvalidateAll(pVCpu);
5981#endif
5982 STAM_REL_COUNTER_INC(&pVCpu->pgm.s.cA20Changes);
5983 }
5984}
5985
Note: See TracBrowser for help on using the repository browser.

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