VirtualBox

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

Last change on this file since 92192 was 92177, checked in by vboxsync, 3 years ago

VMM/PGM,NEM: Moved the StatProfQueryGpaRangeDirtyBitmap NEM stat up to PGM. bugref:10122

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

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