VirtualBox

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

Last change on this file since 99051 was 99051, checked in by vboxsync, 21 months ago

VMM: More ARMv8 x86/amd64 separation work, VBoxVMMArm compiles and links now, bugref:10385

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