VirtualBox

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

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

VMM: Removed PGM_WITHOUT_MAPPINGS and associated mapping code. bugref:9517

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