VirtualBox

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

Last change on this file since 94319 was 93905, checked in by vboxsync, 3 years ago

VMM: More arm tweaks. bugref:9898

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

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