VirtualBox

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

Last change on this file since 102557 was 100970, checked in by vboxsync, 16 months ago

VMM/IEM: Flush IEM physical page TLB info from PGMR3PhysRomProtect. bugref:10369

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