VirtualBox

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

Last change on this file since 35346 was 35346, checked in by vboxsync, 14 years ago

VMM reorg: Moving the public include files from include/VBox to include/VBox/vmm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 154.3 KB
Line 
1/* $Id: PGMPhys.cpp 35346 2010-12-27 16:13:13Z vboxsync $ */
2/** @file
3 * PGM - Page Manager and Monitor, Physical Memory Addressing.
4 */
5
6/*
7 * Copyright (C) 2006-2007 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#include <VBox/vmm/pgm.h>
24#include <VBox/vmm/iom.h>
25#include <VBox/vmm/mm.h>
26#include <VBox/vmm/stam.h>
27#include <VBox/vmm/rem.h>
28#include <VBox/vmm/pdmdev.h>
29#include "PGMInternal.h"
30#include <VBox/vmm/vm.h>
31#include "PGMInline.h"
32#include <VBox/sup.h>
33#include <VBox/param.h>
34#include <VBox/err.h>
35#include <VBox/log.h>
36#include <iprt/assert.h>
37#include <iprt/alloc.h>
38#include <iprt/asm.h>
39#include <iprt/thread.h>
40#include <iprt/string.h>
41#include <iprt/system.h>
42
43
44/*******************************************************************************
45* Defined Constants And Macros *
46*******************************************************************************/
47/** The number of pages to free in one batch. */
48#define PGMPHYS_FREE_PAGE_BATCH_SIZE 128
49
50
51/*******************************************************************************
52* Internal Functions *
53*******************************************************************************/
54static DECLCALLBACK(int) pgmR3PhysRomWriteHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser);
55
56
57/*
58 * PGMR3PhysReadU8-64
59 * PGMR3PhysWriteU8-64
60 */
61#define PGMPHYSFN_READNAME PGMR3PhysReadU8
62#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU8
63#define PGMPHYS_DATASIZE 1
64#define PGMPHYS_DATATYPE uint8_t
65#include "PGMPhysRWTmpl.h"
66
67#define PGMPHYSFN_READNAME PGMR3PhysReadU16
68#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU16
69#define PGMPHYS_DATASIZE 2
70#define PGMPHYS_DATATYPE uint16_t
71#include "PGMPhysRWTmpl.h"
72
73#define PGMPHYSFN_READNAME PGMR3PhysReadU32
74#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU32
75#define PGMPHYS_DATASIZE 4
76#define PGMPHYS_DATATYPE uint32_t
77#include "PGMPhysRWTmpl.h"
78
79#define PGMPHYSFN_READNAME PGMR3PhysReadU64
80#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU64
81#define PGMPHYS_DATASIZE 8
82#define PGMPHYS_DATATYPE uint64_t
83#include "PGMPhysRWTmpl.h"
84
85
86/**
87 * EMT worker for PGMR3PhysReadExternal.
88 */
89static DECLCALLBACK(int) pgmR3PhysReadExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, void *pvBuf, size_t cbRead)
90{
91 PGMPhysRead(pVM, *pGCPhys, pvBuf, cbRead);
92 return VINF_SUCCESS;
93}
94
95
96/**
97 * Read from physical memory, external users.
98 *
99 * @returns VBox status code.
100 * @retval VINF_SUCCESS.
101 *
102 * @param pVM VM Handle.
103 * @param GCPhys Physical address to read from.
104 * @param pvBuf Where to read into.
105 * @param cbRead How many bytes to read.
106 *
107 * @thread Any but EMTs.
108 */
109VMMR3DECL(int) PGMR3PhysReadExternal(PVM pVM, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead)
110{
111 VM_ASSERT_OTHER_THREAD(pVM);
112
113 AssertMsgReturn(cbRead > 0, ("don't even think about reading zero bytes!\n"), VINF_SUCCESS);
114 LogFlow(("PGMR3PhysReadExternal: %RGp %d\n", GCPhys, cbRead));
115
116 pgmLock(pVM);
117
118 /*
119 * Copy loop on ram ranges.
120 */
121 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
122 for (;;)
123 {
124 /* Find range. */
125 while (pRam && GCPhys > pRam->GCPhysLast)
126 pRam = pRam->CTX_SUFF(pNext);
127 /* Inside range or not? */
128 if (pRam && GCPhys >= pRam->GCPhys)
129 {
130 /*
131 * Must work our way thru this page by page.
132 */
133 RTGCPHYS off = GCPhys - pRam->GCPhys;
134 while (off < pRam->cb)
135 {
136 unsigned iPage = off >> PAGE_SHIFT;
137 PPGMPAGE pPage = &pRam->aPages[iPage];
138
139 /*
140 * If the page has an ALL access handler, we'll have to
141 * delegate the job to EMT.
142 */
143 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
144 {
145 pgmUnlock(pVM);
146
147 return VMR3ReqCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysReadExternalEMT, 4,
148 pVM, &GCPhys, pvBuf, cbRead);
149 }
150 Assert(!PGM_PAGE_IS_MMIO(pPage));
151
152 /*
153 * Simple stuff, go ahead.
154 */
155 size_t cb = PAGE_SIZE - (off & PAGE_OFFSET_MASK);
156 if (cb > cbRead)
157 cb = cbRead;
158 const void *pvSrc;
159 int rc = pgmPhysGCPhys2CCPtrInternalReadOnly(pVM, pPage, pRam->GCPhys + off, &pvSrc);
160 if (RT_SUCCESS(rc))
161 memcpy(pvBuf, pvSrc, cb);
162 else
163 {
164 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternalReadOnly failed on %RGp / %R[pgmpage] -> %Rrc\n",
165 pRam->GCPhys + off, pPage, rc));
166 memset(pvBuf, 0xff, cb);
167 }
168
169 /* next page */
170 if (cb >= cbRead)
171 {
172 pgmUnlock(pVM);
173 return VINF_SUCCESS;
174 }
175 cbRead -= cb;
176 off += cb;
177 GCPhys += cb;
178 pvBuf = (char *)pvBuf + cb;
179 } /* walk pages in ram range. */
180 }
181 else
182 {
183 LogFlow(("PGMPhysRead: Unassigned %RGp size=%u\n", GCPhys, cbRead));
184
185 /*
186 * Unassigned address space.
187 */
188 if (!pRam)
189 break;
190 size_t cb = pRam->GCPhys - GCPhys;
191 if (cb >= cbRead)
192 {
193 memset(pvBuf, 0xff, cbRead);
194 break;
195 }
196 memset(pvBuf, 0xff, cb);
197
198 cbRead -= cb;
199 pvBuf = (char *)pvBuf + cb;
200 GCPhys += cb;
201 }
202 } /* Ram range walk */
203
204 pgmUnlock(pVM);
205
206 return VINF_SUCCESS;
207}
208
209
210/**
211 * EMT worker for PGMR3PhysWriteExternal.
212 */
213static DECLCALLBACK(int) pgmR3PhysWriteExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, const void *pvBuf, size_t cbWrite)
214{
215 /** @todo VERR_EM_NO_MEMORY */
216 PGMPhysWrite(pVM, *pGCPhys, pvBuf, cbWrite);
217 return VINF_SUCCESS;
218}
219
220
221/**
222 * Write to physical memory, external users.
223 *
224 * @returns VBox status code.
225 * @retval VINF_SUCCESS.
226 * @retval VERR_EM_NO_MEMORY.
227 *
228 * @param pVM VM Handle.
229 * @param GCPhys Physical address to write to.
230 * @param pvBuf What to write.
231 * @param cbWrite How many bytes to write.
232 * @param pszWho Who is writing. For tracking down who is writing
233 * after we've saved the state.
234 *
235 * @thread Any but EMTs.
236 */
237VMMDECL(int) PGMR3PhysWriteExternal(PVM pVM, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite, const char *pszWho)
238{
239 VM_ASSERT_OTHER_THREAD(pVM);
240
241 AssertMsg(!pVM->pgm.s.fNoMorePhysWrites,
242 ("Calling PGMR3PhysWriteExternal after pgmR3Save()! GCPhys=%RGp cbWrite=%#x pszWho=%s\n",
243 GCPhys, cbWrite, pszWho));
244 AssertMsgReturn(cbWrite > 0, ("don't even think about writing zero bytes!\n"), VINF_SUCCESS);
245 LogFlow(("PGMR3PhysWriteExternal: %RGp %d\n", GCPhys, cbWrite));
246
247 pgmLock(pVM);
248
249 /*
250 * Copy loop on ram ranges, stop when we hit something difficult.
251 */
252 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
253 for (;;)
254 {
255 /* Find range. */
256 while (pRam && GCPhys > pRam->GCPhysLast)
257 pRam = pRam->CTX_SUFF(pNext);
258 /* Inside range or not? */
259 if (pRam && GCPhys >= pRam->GCPhys)
260 {
261 /*
262 * Must work our way thru this page by page.
263 */
264 RTGCPTR off = GCPhys - pRam->GCPhys;
265 while (off < pRam->cb)
266 {
267 RTGCPTR iPage = off >> PAGE_SHIFT;
268 PPGMPAGE pPage = &pRam->aPages[iPage];
269
270 /*
271 * Is the page problematic, we have to do the work on the EMT.
272 *
273 * Allocating writable pages and access handlers are
274 * problematic, write monitored pages are simple and can be
275 * dealt with here.
276 */
277 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
278 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED)
279 {
280 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
281 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
282 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage);
283 else
284 {
285 pgmUnlock(pVM);
286
287 return VMR3ReqCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysWriteExternalEMT, 4,
288 pVM, &GCPhys, pvBuf, cbWrite);
289 }
290 }
291 Assert(!PGM_PAGE_IS_MMIO(pPage));
292
293 /*
294 * Simple stuff, go ahead.
295 */
296 size_t cb = PAGE_SIZE - (off & PAGE_OFFSET_MASK);
297 if (cb > cbWrite)
298 cb = cbWrite;
299 void *pvDst;
300 int rc = pgmPhysGCPhys2CCPtrInternal(pVM, pPage, pRam->GCPhys + off, &pvDst);
301 if (RT_SUCCESS(rc))
302 memcpy(pvDst, pvBuf, cb);
303 else
304 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternal failed on %RGp / %R[pgmpage] -> %Rrc\n",
305 pRam->GCPhys + off, pPage, rc));
306
307 /* next page */
308 if (cb >= cbWrite)
309 {
310 pgmUnlock(pVM);
311 return VINF_SUCCESS;
312 }
313
314 cbWrite -= cb;
315 off += cb;
316 GCPhys += cb;
317 pvBuf = (const char *)pvBuf + cb;
318 } /* walk pages in ram range */
319 }
320 else
321 {
322 /*
323 * Unassigned address space, skip it.
324 */
325 if (!pRam)
326 break;
327 size_t cb = pRam->GCPhys - GCPhys;
328 if (cb >= cbWrite)
329 break;
330 cbWrite -= cb;
331 pvBuf = (const char *)pvBuf + cb;
332 GCPhys += cb;
333 }
334 } /* Ram range walk */
335
336 pgmUnlock(pVM);
337 return VINF_SUCCESS;
338}
339
340
341/**
342 * VMR3ReqCall worker for PGMR3PhysGCPhys2CCPtrExternal to make pages writable.
343 *
344 * @returns see PGMR3PhysGCPhys2CCPtrExternal
345 * @param pVM The VM handle.
346 * @param pGCPhys Pointer to the guest physical address.
347 * @param ppv Where to store the mapping address.
348 * @param pLock Where to store the lock.
349 */
350static DECLCALLBACK(int) pgmR3PhysGCPhys2CCPtrDelegated(PVM pVM, PRTGCPHYS pGCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
351{
352 /*
353 * Just hand it to PGMPhysGCPhys2CCPtr and check that it's not a page with
354 * an access handler after it succeeds.
355 */
356 int rc = pgmLock(pVM);
357 AssertRCReturn(rc, rc);
358
359 rc = PGMPhysGCPhys2CCPtr(pVM, *pGCPhys, ppv, pLock);
360 if (RT_SUCCESS(rc))
361 {
362 PPGMPAGEMAPTLBE pTlbe;
363 int rc2 = pgmPhysPageQueryTlbe(&pVM->pgm.s, *pGCPhys, &pTlbe);
364 AssertFatalRC(rc2);
365 PPGMPAGE pPage = pTlbe->pPage;
366 if (PGM_PAGE_IS_MMIO(pPage))
367 {
368 PGMPhysReleasePageMappingLock(pVM, pLock);
369 rc = VERR_PGM_PHYS_PAGE_RESERVED;
370 }
371 else if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
372#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
373 || pgmPoolIsDirtyPage(pVM, *pGCPhys)
374#endif
375 )
376 {
377 /* We *must* flush any corresponding pgm pool page here, otherwise we'll
378 * not be informed about writes and keep bogus gst->shw mappings around.
379 */
380 pgmPoolFlushPageByGCPhys(pVM, *pGCPhys);
381 Assert(!PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage));
382 /** @todo r=bird: return VERR_PGM_PHYS_PAGE_RESERVED here if it still has
383 * active handlers, see the PGMR3PhysGCPhys2CCPtrExternal docs. */
384 }
385 }
386
387 pgmUnlock(pVM);
388 return rc;
389}
390
391
392/**
393 * Requests the mapping of a guest page into ring-3, external threads.
394 *
395 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
396 * release it.
397 *
398 * This API will assume your intention is to write to the page, and will
399 * therefore replace shared and zero pages. If you do not intend to modify the
400 * page, use the PGMR3PhysGCPhys2CCPtrReadOnlyExternal() API.
401 *
402 * @returns VBox status code.
403 * @retval VINF_SUCCESS on success.
404 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
405 * backing or if the page has any active access handlers. The caller
406 * must fall back on using PGMR3PhysWriteExternal.
407 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
408 *
409 * @param pVM The VM handle.
410 * @param GCPhys The guest physical address of the page that should be mapped.
411 * @param ppv Where to store the address corresponding to GCPhys.
412 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
413 *
414 * @remark Avoid calling this API from within critical sections (other than the
415 * PGM one) because of the deadlock risk when we have to delegating the
416 * task to an EMT.
417 * @thread Any.
418 */
419VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrExternal(PVM pVM, RTGCPHYS GCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
420{
421 AssertPtr(ppv);
422 AssertPtr(pLock);
423
424 Assert(VM_IS_EMT(pVM) || !PGMIsLockOwner(pVM));
425
426 int rc = pgmLock(pVM);
427 AssertRCReturn(rc, rc);
428
429 /*
430 * Query the Physical TLB entry for the page (may fail).
431 */
432 PPGMPAGEMAPTLBE pTlbe;
433 rc = pgmPhysPageQueryTlbe(&pVM->pgm.s, GCPhys, &pTlbe);
434 if (RT_SUCCESS(rc))
435 {
436 PPGMPAGE pPage = pTlbe->pPage;
437 if (PGM_PAGE_IS_MMIO(pPage))
438 rc = VERR_PGM_PHYS_PAGE_RESERVED;
439 else
440 {
441 /*
442 * If the page is shared, the zero page, or being write monitored
443 * it must be converted to an page that's writable if possible.
444 * We can only deal with write monitored pages here, the rest have
445 * to be on an EMT.
446 */
447 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
448 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED
449#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
450 || pgmPoolIsDirtyPage(pVM, GCPhys)
451#endif
452 )
453 {
454 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
455 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
456#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
457 && !pgmPoolIsDirtyPage(pVM, GCPhys)
458#endif
459 )
460 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage);
461 else
462 {
463 pgmUnlock(pVM);
464
465 return VMR3ReqCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysGCPhys2CCPtrDelegated, 4,
466 pVM, &GCPhys, ppv, pLock);
467 }
468 }
469
470 /*
471 * Now, just perform the locking and calculate the return address.
472 */
473 PPGMPAGEMAP pMap = pTlbe->pMap;
474 if (pMap)
475 pMap->cRefs++;
476
477 unsigned cLocks = PGM_PAGE_GET_WRITE_LOCKS(pPage);
478 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
479 {
480 if (cLocks == 0)
481 pVM->pgm.s.cWriteLockedPages++;
482 PGM_PAGE_INC_WRITE_LOCKS(pPage);
483 }
484 else if (cLocks != PGM_PAGE_GET_WRITE_LOCKS(pPage))
485 {
486 PGM_PAGE_INC_WRITE_LOCKS(pPage);
487 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent write locked state!\n", GCPhys, pPage));
488 if (pMap)
489 pMap->cRefs++; /* Extra ref to prevent it from going away. */
490 }
491
492 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
493 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_WRITE;
494 pLock->pvMap = pMap;
495 }
496 }
497
498 pgmUnlock(pVM);
499 return rc;
500}
501
502
503/**
504 * Requests the mapping of a guest page into ring-3, external threads.
505 *
506 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
507 * release it.
508 *
509 * @returns VBox status code.
510 * @retval VINF_SUCCESS on success.
511 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
512 * backing or if the page as an active ALL access handler. The caller
513 * must fall back on using PGMPhysRead.
514 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
515 *
516 * @param pVM The VM handle.
517 * @param GCPhys The guest physical address of the page that should be mapped.
518 * @param ppv Where to store the address corresponding to GCPhys.
519 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
520 *
521 * @remark Avoid calling this API from within critical sections (other than
522 * the PGM one) because of the deadlock risk.
523 * @thread Any.
524 */
525VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrReadOnlyExternal(PVM pVM, RTGCPHYS GCPhys, void const **ppv, PPGMPAGEMAPLOCK pLock)
526{
527 int rc = pgmLock(pVM);
528 AssertRCReturn(rc, rc);
529
530 /*
531 * Query the Physical TLB entry for the page (may fail).
532 */
533 PPGMPAGEMAPTLBE pTlbe;
534 rc = pgmPhysPageQueryTlbe(&pVM->pgm.s, GCPhys, &pTlbe);
535 if (RT_SUCCESS(rc))
536 {
537 PPGMPAGE pPage = pTlbe->pPage;
538#if 1
539 /* MMIO pages doesn't have any readable backing. */
540 if (PGM_PAGE_IS_MMIO(pPage))
541 rc = VERR_PGM_PHYS_PAGE_RESERVED;
542#else
543 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
544 rc = VERR_PGM_PHYS_PAGE_RESERVED;
545#endif
546 else
547 {
548 /*
549 * Now, just perform the locking and calculate the return address.
550 */
551 PPGMPAGEMAP pMap = pTlbe->pMap;
552 if (pMap)
553 pMap->cRefs++;
554
555 unsigned cLocks = PGM_PAGE_GET_READ_LOCKS(pPage);
556 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
557 {
558 if (cLocks == 0)
559 pVM->pgm.s.cReadLockedPages++;
560 PGM_PAGE_INC_READ_LOCKS(pPage);
561 }
562 else if (cLocks != PGM_PAGE_GET_READ_LOCKS(pPage))
563 {
564 PGM_PAGE_INC_READ_LOCKS(pPage);
565 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent readonly locked state!\n", GCPhys, pPage));
566 if (pMap)
567 pMap->cRefs++; /* Extra ref to prevent it from going away. */
568 }
569
570 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
571 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_READ;
572 pLock->pvMap = pMap;
573 }
574 }
575
576 pgmUnlock(pVM);
577 return rc;
578}
579
580
581/**
582 * Relinks the RAM ranges using the pSelfRC and pSelfR0 pointers.
583 *
584 * Called when anything was relocated.
585 *
586 * @param pVM Pointer to the shared VM structure.
587 */
588void pgmR3PhysRelinkRamRanges(PVM pVM)
589{
590 PPGMRAMRANGE pCur;
591
592#ifdef VBOX_STRICT
593 for (pCur = pVM->pgm.s.pRamRangesR3; pCur; pCur = pCur->pNextR3)
594 {
595 Assert((pCur->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pCur->pSelfR0 == MMHyperCCToR0(pVM, pCur));
596 Assert((pCur->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pCur->pSelfRC == MMHyperCCToRC(pVM, pCur));
597 Assert((pCur->GCPhys & PAGE_OFFSET_MASK) == 0);
598 Assert((pCur->GCPhysLast & PAGE_OFFSET_MASK) == PAGE_OFFSET_MASK);
599 Assert((pCur->cb & PAGE_OFFSET_MASK) == 0);
600 Assert(pCur->cb == pCur->GCPhysLast - pCur->GCPhys + 1);
601 for (PPGMRAMRANGE pCur2 = pVM->pgm.s.pRamRangesR3; pCur2; pCur2 = pCur2->pNextR3)
602 Assert( pCur2 == pCur
603 || strcmp(pCur2->pszDesc, pCur->pszDesc)); /** @todo fix MMIO ranges!! */
604 }
605#endif
606
607 pCur = pVM->pgm.s.pRamRangesR3;
608 if (pCur)
609 {
610 pVM->pgm.s.pRamRangesR0 = pCur->pSelfR0;
611 pVM->pgm.s.pRamRangesRC = pCur->pSelfRC;
612
613 for (; pCur->pNextR3; pCur = pCur->pNextR3)
614 {
615 pCur->pNextR0 = pCur->pNextR3->pSelfR0;
616 pCur->pNextRC = pCur->pNextR3->pSelfRC;
617 }
618
619 Assert(pCur->pNextR0 == NIL_RTR0PTR);
620 Assert(pCur->pNextRC == NIL_RTRCPTR);
621 }
622 else
623 {
624 Assert(pVM->pgm.s.pRamRangesR0 == NIL_RTR0PTR);
625 Assert(pVM->pgm.s.pRamRangesRC == NIL_RTRCPTR);
626 }
627 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
628}
629
630
631/**
632 * Links a new RAM range into the list.
633 *
634 * @param pVM Pointer to the shared VM structure.
635 * @param pNew Pointer to the new list entry.
636 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
637 */
638static void pgmR3PhysLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, PPGMRAMRANGE pPrev)
639{
640 AssertMsg(pNew->pszDesc, ("%RGp-%RGp\n", pNew->GCPhys, pNew->GCPhysLast));
641 Assert((pNew->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pNew->pSelfR0 == MMHyperCCToR0(pVM, pNew));
642 Assert((pNew->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pNew->pSelfRC == MMHyperCCToRC(pVM, pNew));
643
644 pgmLock(pVM);
645
646 PPGMRAMRANGE pRam = pPrev ? pPrev->pNextR3 : pVM->pgm.s.pRamRangesR3;
647 pNew->pNextR3 = pRam;
648 pNew->pNextR0 = pRam ? pRam->pSelfR0 : NIL_RTR0PTR;
649 pNew->pNextRC = pRam ? pRam->pSelfRC : NIL_RTRCPTR;
650
651 if (pPrev)
652 {
653 pPrev->pNextR3 = pNew;
654 pPrev->pNextR0 = pNew->pSelfR0;
655 pPrev->pNextRC = pNew->pSelfRC;
656 }
657 else
658 {
659 pVM->pgm.s.pRamRangesR3 = pNew;
660 pVM->pgm.s.pRamRangesR0 = pNew->pSelfR0;
661 pVM->pgm.s.pRamRangesRC = pNew->pSelfRC;
662 }
663 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
664 pgmUnlock(pVM);
665}
666
667
668/**
669 * Unlink an existing RAM range from the list.
670 *
671 * @param pVM Pointer to the shared VM structure.
672 * @param pRam Pointer to the new list entry.
673 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
674 */
675static void pgmR3PhysUnlinkRamRange2(PVM pVM, PPGMRAMRANGE pRam, PPGMRAMRANGE pPrev)
676{
677 Assert(pPrev ? pPrev->pNextR3 == pRam : pVM->pgm.s.pRamRangesR3 == pRam);
678 Assert((pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pRam->pSelfR0 == MMHyperCCToR0(pVM, pRam));
679 Assert((pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pRam->pSelfRC == MMHyperCCToRC(pVM, pRam));
680
681 pgmLock(pVM);
682
683 PPGMRAMRANGE pNext = pRam->pNextR3;
684 if (pPrev)
685 {
686 pPrev->pNextR3 = pNext;
687 pPrev->pNextR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
688 pPrev->pNextRC = pNext ? pNext->pSelfRC : NIL_RTRCPTR;
689 }
690 else
691 {
692 Assert(pVM->pgm.s.pRamRangesR3 == pRam);
693 pVM->pgm.s.pRamRangesR3 = pNext;
694 pVM->pgm.s.pRamRangesR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
695 pVM->pgm.s.pRamRangesRC = pNext ? pNext->pSelfRC : NIL_RTRCPTR;
696 }
697 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
698 pgmUnlock(pVM);
699}
700
701
702/**
703 * Unlink an existing RAM range from the list.
704 *
705 * @param pVM Pointer to the shared VM structure.
706 * @param pRam Pointer to the new list entry.
707 */
708static void pgmR3PhysUnlinkRamRange(PVM pVM, PPGMRAMRANGE pRam)
709{
710 pgmLock(pVM);
711
712 /* find prev. */
713 PPGMRAMRANGE pPrev = NULL;
714 PPGMRAMRANGE pCur = pVM->pgm.s.pRamRangesR3;
715 while (pCur != pRam)
716 {
717 pPrev = pCur;
718 pCur = pCur->pNextR3;
719 }
720 AssertFatal(pCur);
721
722 pgmR3PhysUnlinkRamRange2(pVM, pRam, pPrev);
723 pgmUnlock(pVM);
724}
725
726
727/**
728 * Frees a range of pages, replacing them with ZERO pages of the specified type.
729 *
730 * @returns VBox status code.
731 * @param pVM The VM handle.
732 * @param pRam The RAM range in which the pages resides.
733 * @param GCPhys The address of the first page.
734 * @param GCPhysLast The address of the last page.
735 * @param uType The page type to replace then with.
736 */
737static int pgmR3PhysFreePageRange(PVM pVM, PPGMRAMRANGE pRam, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast, uint8_t uType)
738{
739 Assert(PGMIsLockOwner(pVM));
740 uint32_t cPendingPages = 0;
741 PGMMFREEPAGESREQ pReq;
742 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
743 AssertLogRelRCReturn(rc, rc);
744
745 /* Iterate the pages. */
746 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
747 uint32_t cPagesLeft = ((GCPhysLast - GCPhys) >> PAGE_SHIFT) + 1;
748 while (cPagesLeft-- > 0)
749 {
750 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys);
751 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
752
753 PGM_PAGE_SET_TYPE(pPageDst, uType);
754
755 GCPhys += PAGE_SIZE;
756 pPageDst++;
757 }
758
759 if (cPendingPages)
760 {
761 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
762 AssertLogRelRCReturn(rc, rc);
763 }
764 GMMR3FreePagesCleanup(pReq);
765
766 return rc;
767}
768
769#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
770/**
771 * Rendezvous callback used by PGMR3ChangeMemBalloon that changes the memory balloon size
772 *
773 * This is only called on one of the EMTs while the other ones are waiting for
774 * it to complete this function.
775 *
776 * @returns VINF_SUCCESS (VBox strict status code).
777 * @param pVM The VM handle.
778 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
779 * @param pvUser User parameter
780 */
781static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysChangeMemBalloonRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
782{
783 uintptr_t *paUser = (uintptr_t *)pvUser;
784 bool fInflate = !!paUser[0];
785 unsigned cPages = paUser[1];
786 RTGCPHYS *paPhysPage = (RTGCPHYS *)paUser[2];
787 uint32_t cPendingPages = 0;
788 PGMMFREEPAGESREQ pReq;
789 int rc;
790
791 Log(("pgmR3PhysChangeMemBalloonRendezvous: %s %x pages\n", (fInflate) ? "inflate" : "deflate", cPages));
792 pgmLock(pVM);
793
794 if (fInflate)
795 {
796 /* Flush the PGM pool cache as we might have stale references to pages that we just freed. */
797 pgmR3PoolClearAllRendezvous(pVM, pVCpu, NULL);
798
799 /* Replace pages with ZERO pages. */
800 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
801 if (RT_FAILURE(rc))
802 {
803 pgmUnlock(pVM);
804 AssertLogRelRC(rc);
805 return rc;
806 }
807
808 /* Iterate the pages. */
809 for (unsigned i = 0; i < cPages; i++)
810 {
811 PPGMPAGE pPage = pgmPhysGetPage(&pVM->pgm.s, paPhysPage[i]);
812 if ( pPage == NULL
813 || pPage->uTypeY != PGMPAGETYPE_RAM)
814 {
815 Log(("pgmR3PhysChangeMemBalloonRendezvous: invalid physical page %RGp pPage->u3Type=%d\n", paPhysPage[i], (pPage) ? pPage->uTypeY : 0));
816 break;
817 }
818
819 LogFlow(("balloon page: %RGp\n", paPhysPage[i]));
820
821 /* Flush the shadow PT if this page was previously used as a guest page table. */
822 pgmPoolFlushPageByGCPhys(pVM, paPhysPage[i]);
823
824 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, paPhysPage[i]);
825 if (RT_FAILURE(rc))
826 {
827 pgmUnlock(pVM);
828 AssertLogRelRC(rc);
829 return rc;
830 }
831 Assert(PGM_PAGE_IS_ZERO(pPage));
832 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_BALLOONED);
833 }
834
835 if (cPendingPages)
836 {
837 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
838 if (RT_FAILURE(rc))
839 {
840 pgmUnlock(pVM);
841 AssertLogRelRC(rc);
842 return rc;
843 }
844 }
845 GMMR3FreePagesCleanup(pReq);
846 }
847 else
848 {
849 /* Iterate the pages. */
850 for (unsigned i = 0; i < cPages; i++)
851 {
852 PPGMPAGE pPage = pgmPhysGetPage(&pVM->pgm.s, paPhysPage[i]);
853 AssertBreak(pPage && pPage->uTypeY == PGMPAGETYPE_RAM);
854
855 LogFlow(("Free ballooned page: %RGp\n", paPhysPage[i]));
856
857 Assert(PGM_PAGE_IS_BALLOONED(pPage));
858
859 /* Change back to zero page. */
860 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
861 }
862
863 /* Note that we currently do not map any ballooned pages in our shadow page tables, so no need to flush the pgm pool. */
864 }
865
866 /* Notify GMM about the balloon change. */
867 rc = GMMR3BalloonedPages(pVM, (fInflate) ? GMMBALLOONACTION_INFLATE : GMMBALLOONACTION_DEFLATE, cPages);
868 if (RT_SUCCESS(rc))
869 {
870 if (!fInflate)
871 {
872 Assert(pVM->pgm.s.cBalloonedPages >= cPages);
873 pVM->pgm.s.cBalloonedPages -= cPages;
874 }
875 else
876 pVM->pgm.s.cBalloonedPages += cPages;
877 }
878
879 pgmUnlock(pVM);
880
881 /* Flush the recompiler's TLB as well. */
882 for (VMCPUID i = 0; i < pVM->cCpus; i++)
883 CPUMSetChangedFlags(&pVM->aCpus[i], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
884
885 AssertLogRelRC(rc);
886 return rc;
887}
888
889/**
890 * Frees a range of ram pages, replacing them with ZERO pages; helper for PGMR3PhysFreeRamPages
891 *
892 * @returns VBox status code.
893 * @param pVM The VM handle.
894 * @param fInflate Inflate or deflate memory balloon
895 * @param cPages Number of pages to free
896 * @param paPhysPage Array of guest physical addresses
897 */
898static DECLCALLBACK(void) pgmR3PhysChangeMemBalloonHelper(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
899{
900 uintptr_t paUser[3];
901
902 paUser[0] = fInflate;
903 paUser[1] = cPages;
904 paUser[2] = (uintptr_t)paPhysPage;
905 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
906 AssertRC(rc);
907
908 /* Made a copy in PGMR3PhysFreeRamPages; free it here. */
909 RTMemFree(paPhysPage);
910}
911#endif
912
913/**
914 * Inflate or deflate a memory balloon
915 *
916 * @returns VBox status code.
917 * @param pVM The VM handle.
918 * @param fInflate Inflate or deflate memory balloon
919 * @param cPages Number of pages to free
920 * @param paPhysPage Array of guest physical addresses
921 */
922VMMR3DECL(int) PGMR3PhysChangeMemBalloon(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
923{
924 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
925#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
926 int rc;
927
928 /* Older additions (ancient non-functioning balloon code) pass wrong physical addresses. */
929 AssertReturn(!(paPhysPage[0] & 0xfff), VERR_INVALID_PARAMETER);
930
931 /* We own the IOM lock here and could cause a deadlock by waiting for another VCPU that is blocking on the IOM lock.
932 * In the SMP case we post a request packet to postpone the job.
933 */
934 if (pVM->cCpus > 1)
935 {
936 unsigned cbPhysPage = cPages * sizeof(paPhysPage[0]);
937 RTGCPHYS *paPhysPageCopy = (RTGCPHYS *)RTMemAlloc(cbPhysPage);
938 AssertReturn(paPhysPageCopy, VERR_NO_MEMORY);
939
940 memcpy(paPhysPageCopy, paPhysPage, cbPhysPage);
941
942 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysChangeMemBalloonHelper, 4, pVM, fInflate, cPages, paPhysPageCopy);
943 AssertRC(rc);
944 }
945 else
946 {
947 uintptr_t paUser[3];
948
949 paUser[0] = fInflate;
950 paUser[1] = cPages;
951 paUser[2] = (uintptr_t)paPhysPage;
952 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
953 AssertRC(rc);
954 }
955 return rc;
956#else
957 return VERR_NOT_IMPLEMENTED;
958#endif
959}
960
961/**
962 * Rendezvous callback used by PGMR3WriteProtectRAM that write protects all physical RAM
963 *
964 * This is only called on one of the EMTs while the other ones are waiting for
965 * it to complete this function.
966 *
967 * @returns VINF_SUCCESS (VBox strict status code).
968 * @param pVM The VM handle.
969 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
970 * @param pvUser User parameter
971 */
972static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysWriteProtectRAMRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
973{
974 int rc = VINF_SUCCESS;
975
976 pgmLock(pVM);
977#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
978 pgmPoolResetDirtyPages(pVM);
979#endif
980
981 /** @todo pointless to write protect the physical page pointed to by RSP. */
982
983 for (PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
984 pRam;
985 pRam = pRam->CTX_SUFF(pNext))
986 {
987 unsigned cPages = pRam->cb >> PAGE_SHIFT;
988 for (unsigned iPage = 0; iPage < cPages; iPage++)
989 {
990 PPGMPAGE pPage = &pRam->aPages[iPage];
991 PGMPAGETYPE enmPageType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage);
992
993 if ( RT_LIKELY(enmPageType == PGMPAGETYPE_RAM)
994 || enmPageType == PGMPAGETYPE_MMIO2)
995 {
996 /*
997 * A RAM page.
998 */
999 switch (PGM_PAGE_GET_STATE(pPage))
1000 {
1001 case PGM_PAGE_STATE_ALLOCATED:
1002 /** @todo Optimize this: Don't always re-enable write
1003 * monitoring if the page is known to be very busy. */
1004 if (PGM_PAGE_IS_WRITTEN_TO(pPage))
1005 {
1006 PGM_PAGE_CLEAR_WRITTEN_TO(pPage);
1007 /* Remember this dirty page for the next (memory) sync. */
1008 PGM_PAGE_SET_FT_DIRTY(pPage);
1009 }
1010
1011 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_WRITE_MONITORED);
1012 pVM->pgm.s.cMonitoredPages++;
1013 break;
1014
1015 case PGM_PAGE_STATE_SHARED:
1016 AssertFailed();
1017 break;
1018
1019 case PGM_PAGE_STATE_WRITE_MONITORED: /* nothing to change. */
1020 default:
1021 break;
1022 }
1023 }
1024 }
1025 }
1026 pgmR3PoolWriteProtectPages(pVM);
1027 PGM_INVL_ALL_VCPU_TLBS(pVM);
1028 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1029 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
1030
1031 pgmUnlock(pVM);
1032 return rc;
1033}
1034
1035/**
1036 * Protect all physical RAM to monitor writes
1037 *
1038 * @returns VBox status code.
1039 * @param pVM The VM handle.
1040 */
1041VMMR3DECL(int) PGMR3PhysWriteProtectRAM(PVM pVM)
1042{
1043 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1044
1045 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysWriteProtectRAMRendezvous, NULL);
1046 AssertRC(rc);
1047 return rc;
1048}
1049
1050/**
1051 * Enumerate all dirty FT pages
1052 *
1053 * @returns VBox status code.
1054 * @param pVM The VM handle.
1055 * @param pfnEnum Enumerate callback handler
1056 * @param pvUser Enumerate callback handler parameter
1057 */
1058VMMR3DECL(int) PGMR3PhysEnumDirtyFTPages(PVM pVM, PFNPGMENUMDIRTYFTPAGES pfnEnum, void *pvUser)
1059{
1060 int rc = VINF_SUCCESS;
1061
1062 pgmLock(pVM);
1063 for (PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
1064 pRam;
1065 pRam = pRam->CTX_SUFF(pNext))
1066 {
1067 unsigned cPages = pRam->cb >> PAGE_SHIFT;
1068 for (unsigned iPage = 0; iPage < cPages; iPage++)
1069 {
1070 PPGMPAGE pPage = &pRam->aPages[iPage];
1071 PGMPAGETYPE enmPageType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage);
1072
1073 if ( RT_LIKELY(enmPageType == PGMPAGETYPE_RAM)
1074 || enmPageType == PGMPAGETYPE_MMIO2)
1075 {
1076 /*
1077 * A RAM page.
1078 */
1079 switch (PGM_PAGE_GET_STATE(pPage))
1080 {
1081 case PGM_PAGE_STATE_ALLOCATED:
1082 case PGM_PAGE_STATE_WRITE_MONITORED:
1083 if ( !PGM_PAGE_IS_WRITTEN_TO(pPage) /* not very recently updated? */
1084 && PGM_PAGE_IS_FT_DIRTY(pPage))
1085 {
1086 unsigned cbPageRange = PAGE_SIZE;
1087 unsigned iPageClean = iPage + 1;
1088 RTGCPHYS GCPhysPage = pRam->GCPhys + iPage * PAGE_SIZE;
1089 uint8_t *pu8Page = NULL;
1090 PGMPAGEMAPLOCK Lock;
1091
1092 /* Find the next clean page, so we can merge adjacent dirty pages. */
1093 for (; iPageClean < cPages; iPageClean++)
1094 {
1095 PPGMPAGE pPageNext = &pRam->aPages[iPageClean];
1096 if ( RT_UNLIKELY(PGM_PAGE_GET_TYPE(pPageNext) != PGMPAGETYPE_RAM)
1097 || PGM_PAGE_GET_STATE(pPageNext) != PGM_PAGE_STATE_ALLOCATED
1098 || PGM_PAGE_IS_WRITTEN_TO(pPageNext)
1099 || !PGM_PAGE_IS_FT_DIRTY(pPageNext)
1100 /* Crossing a chunk boundary? */
1101 || (GCPhysPage & GMM_PAGEID_IDX_MASK) != ((GCPhysPage + cbPageRange) & GMM_PAGEID_IDX_MASK)
1102 )
1103 break;
1104
1105 cbPageRange += PAGE_SIZE;
1106 }
1107
1108 rc = PGMPhysGCPhys2CCPtrReadOnly(pVM, GCPhysPage, (const void **)&pu8Page, &Lock);
1109 if (RT_SUCCESS(rc))
1110 {
1111 /** @todo this is risky; the range might be changed, but little choice as the sync costs a lot of time */
1112 pgmUnlock(pVM);
1113 pfnEnum(pVM, GCPhysPage, pu8Page, cbPageRange, pvUser);
1114 pgmLock(pVM);
1115 PGMPhysReleasePageMappingLock(pVM, &Lock);
1116 }
1117
1118 for (iPage; iPage < iPageClean; iPage++)
1119 PGM_PAGE_CLEAR_FT_DIRTY(&pRam->aPages[iPage]);
1120
1121 iPage = iPageClean - 1;
1122 }
1123 break;
1124 }
1125 }
1126 }
1127 }
1128 pgmUnlock(pVM);
1129 return rc;
1130}
1131
1132
1133/**
1134 * Gets the number of ram ranges.
1135 *
1136 * @returns Number of ram ranges. Returns UINT32_MAX if @a pVM is invalid.
1137 * @param pVM The VM handle.
1138 */
1139VMMR3DECL(uint32_t) PGMR3PhysGetRamRangeCount(PVM pVM)
1140{
1141 VM_ASSERT_VALID_EXT_RETURN(pVM, UINT32_MAX);
1142
1143 pgmLock(pVM);
1144 uint32_t cRamRanges = 0;
1145 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRanges); pCur; pCur = pCur->CTX_SUFF(pNext))
1146 cRamRanges++;
1147 pgmUnlock(pVM);
1148 return cRamRanges;
1149}
1150
1151
1152/**
1153 * Get information about a range.
1154 *
1155 * @returns VINF_SUCCESS or VERR_OUT_OF_RANGE.
1156 * @param pVM The VM handle
1157 * @param iRange The ordinal of the range.
1158 * @param pGCPhysStart Where to return the start of the range. Optional.
1159 * @param pGCPhysLast Where to return the address of the last byte in the
1160 * range. Optional.
1161 * @param pfIsMmio Where to indicate that this is a pure MMIO range.
1162 * Optional.
1163 */
1164VMMR3DECL(int) PGMR3PhysGetRange(PVM pVM, uint32_t iRange, PRTGCPHYS pGCPhysStart, PRTGCPHYS pGCPhysLast,
1165 const char **ppszDesc, bool *pfIsMmio)
1166{
1167 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1168
1169 pgmLock(pVM);
1170 uint32_t iCurRange = 0;
1171 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRanges); pCur; pCur = pCur->CTX_SUFF(pNext), iCurRange++)
1172 if (iCurRange == iRange)
1173 {
1174 if (pGCPhysStart)
1175 *pGCPhysStart = pCur->GCPhys;
1176 if (pGCPhysLast)
1177 *pGCPhysLast = pCur->GCPhysLast;
1178 if (pfIsMmio)
1179 *pfIsMmio = !!(pCur->fFlags & PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO);
1180
1181 pgmUnlock(pVM);
1182 return VINF_SUCCESS;
1183 }
1184 pgmUnlock(pVM);
1185 return VERR_OUT_OF_RANGE;
1186}
1187
1188
1189/**
1190 * Query the amount of free memory inside VMMR0
1191 *
1192 * @returns VBox status code.
1193 * @param pVM The VM handle.
1194 * @param puTotalAllocSize Pointer to total allocated memory inside VMMR0 (in bytes)
1195 * @param puTotalFreeSize Pointer to total free (allocated but not used yet) memory inside VMMR0 (in bytes)
1196 * @param puTotalBalloonSize Pointer to total ballooned memory inside VMMR0 (in bytes)
1197 * @param puTotalSharedSize Pointer to total shared memory inside VMMR0 (in bytes)
1198 */
1199VMMR3DECL(int) PGMR3QueryVMMMemoryStats(PVM pVM, uint64_t *puTotalAllocSize, uint64_t *puTotalFreeSize, uint64_t *puTotalBalloonSize, uint64_t *puTotalSharedSize)
1200{
1201 int rc;
1202
1203 uint64_t cAllocPages = 0, cFreePages = 0, cBalloonPages = 0, cSharedPages = 0;
1204 rc = GMMR3QueryHypervisorMemoryStats(pVM, &cAllocPages, &cFreePages, &cBalloonPages, &cSharedPages);
1205 AssertRCReturn(rc, rc);
1206
1207 if (puTotalAllocSize)
1208 *puTotalAllocSize = cAllocPages * _4K;
1209
1210 if (puTotalFreeSize)
1211 *puTotalFreeSize = cFreePages * _4K;
1212
1213 if (puTotalBalloonSize)
1214 *puTotalBalloonSize = cBalloonPages * _4K;
1215
1216 if (puTotalSharedSize)
1217 *puTotalSharedSize = cSharedPages * _4K;
1218
1219 Log(("PGMR3QueryVMMMemoryStats: all=%x free=%x ballooned=%x shared=%x\n", cAllocPages, cFreePages, cBalloonPages, cSharedPages));
1220 return VINF_SUCCESS;
1221}
1222
1223/**
1224 * Query memory stats for the VM
1225 *
1226 * @returns VBox status code.
1227 * @param pVM The VM handle.
1228 * @param puTotalAllocSize Pointer to total allocated memory inside the VM (in bytes)
1229 * @param puTotalFreeSize Pointer to total free (allocated but not used yet) memory inside the VM (in bytes)
1230 * @param puTotalBalloonSize Pointer to total ballooned memory inside the VM (in bytes)
1231 * @param puTotalSharedSize Pointer to total shared memory inside the VM (in bytes)
1232 */
1233VMMR3DECL(int) PGMR3QueryMemoryStats(PVM pVM, uint64_t *pulTotalMem, uint64_t *pulPrivateMem, uint64_t *puTotalSharedMem, uint64_t *puTotalZeroMem)
1234{
1235 if (pulTotalMem)
1236 *pulTotalMem = (uint64_t)pVM->pgm.s.cAllPages * _4K;
1237
1238 if (pulPrivateMem)
1239 *pulPrivateMem = (uint64_t)pVM->pgm.s.cPrivatePages * _4K;
1240
1241 if (puTotalSharedMem)
1242 *puTotalSharedMem = (uint64_t)pVM->pgm.s.cReusedSharedPages * _4K;
1243
1244 if (puTotalZeroMem)
1245 *puTotalZeroMem = (uint64_t)pVM->pgm.s.cZeroPages * _4K;
1246
1247 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));
1248 return VINF_SUCCESS;
1249}
1250
1251/**
1252 * PGMR3PhysRegisterRam worker that initializes and links a RAM range.
1253 *
1254 * @param pVM The VM handle.
1255 * @param pNew The new RAM range.
1256 * @param GCPhys The address of the RAM range.
1257 * @param GCPhysLast The last address of the RAM range.
1258 * @param RCPtrNew The RC address if the range is floating. NIL_RTRCPTR
1259 * if in HMA.
1260 * @param R0PtrNew Ditto for R0.
1261 * @param pszDesc The description.
1262 * @param pPrev The previous RAM range (for linking).
1263 */
1264static void pgmR3PhysInitAndLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast,
1265 RTRCPTR RCPtrNew, RTR0PTR R0PtrNew, const char *pszDesc, PPGMRAMRANGE pPrev)
1266{
1267 /*
1268 * Initialize the range.
1269 */
1270 pNew->pSelfR0 = R0PtrNew != NIL_RTR0PTR ? R0PtrNew : MMHyperCCToR0(pVM, pNew);
1271 pNew->pSelfRC = RCPtrNew != NIL_RTRCPTR ? RCPtrNew : MMHyperCCToRC(pVM, pNew);
1272 pNew->GCPhys = GCPhys;
1273 pNew->GCPhysLast = GCPhysLast;
1274 pNew->cb = GCPhysLast - GCPhys + 1;
1275 pNew->pszDesc = pszDesc;
1276 pNew->fFlags = RCPtrNew != NIL_RTRCPTR ? PGM_RAM_RANGE_FLAGS_FLOATING : 0;
1277 pNew->pvR3 = NULL;
1278 pNew->paLSPages = NULL;
1279
1280 uint32_t const cPages = pNew->cb >> PAGE_SHIFT;
1281 RTGCPHYS iPage = cPages;
1282 while (iPage-- > 0)
1283 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_RAM);
1284
1285 /* Update the page count stats. */
1286 pVM->pgm.s.cZeroPages += cPages;
1287 pVM->pgm.s.cAllPages += cPages;
1288
1289 /*
1290 * Link it.
1291 */
1292 pgmR3PhysLinkRamRange(pVM, pNew, pPrev);
1293}
1294
1295
1296/**
1297 * Relocate a floating RAM range.
1298 *
1299 * @copydoc FNPGMRELOCATE.
1300 */
1301static DECLCALLBACK(bool) pgmR3PhysRamRangeRelocate(PVM pVM, RTGCPTR GCPtrOld, RTGCPTR GCPtrNew, PGMRELOCATECALL enmMode, void *pvUser)
1302{
1303 PPGMRAMRANGE pRam = (PPGMRAMRANGE)pvUser;
1304 Assert(pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING);
1305 Assert(pRam->pSelfRC == GCPtrOld + PAGE_SIZE);
1306
1307 switch (enmMode)
1308 {
1309 case PGMRELOCATECALL_SUGGEST:
1310 return true;
1311 case PGMRELOCATECALL_RELOCATE:
1312 {
1313 /* Update myself and then relink all the ranges. */
1314 pgmLock(pVM);
1315 pRam->pSelfRC = (RTRCPTR)(GCPtrNew + PAGE_SIZE);
1316 pgmR3PhysRelinkRamRanges(pVM);
1317 pgmUnlock(pVM);
1318 return true;
1319 }
1320
1321 default:
1322 AssertFailedReturn(false);
1323 }
1324}
1325
1326
1327/**
1328 * PGMR3PhysRegisterRam worker that registers a high chunk.
1329 *
1330 * @returns VBox status code.
1331 * @param pVM The VM handle.
1332 * @param GCPhys The address of the RAM.
1333 * @param cRamPages The number of RAM pages to register.
1334 * @param cbChunk The size of the PGMRAMRANGE guest mapping.
1335 * @param iChunk The chunk number.
1336 * @param pszDesc The RAM range description.
1337 * @param ppPrev Previous RAM range pointer. In/Out.
1338 */
1339static int pgmR3PhysRegisterHighRamChunk(PVM pVM, RTGCPHYS GCPhys, uint32_t cRamPages,
1340 uint32_t cbChunk, uint32_t iChunk, const char *pszDesc,
1341 PPGMRAMRANGE *ppPrev)
1342{
1343 const char *pszDescChunk = iChunk == 0
1344 ? pszDesc
1345 : MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s (#%u)", pszDesc, iChunk + 1);
1346 AssertReturn(pszDescChunk, VERR_NO_MEMORY);
1347
1348 /*
1349 * Allocate memory for the new chunk.
1350 */
1351 size_t const cChunkPages = RT_ALIGN_Z(RT_UOFFSETOF(PGMRAMRANGE, aPages[cRamPages]), PAGE_SIZE) >> PAGE_SHIFT;
1352 PSUPPAGE paChunkPages = (PSUPPAGE)RTMemTmpAllocZ(sizeof(SUPPAGE) * cChunkPages);
1353 AssertReturn(paChunkPages, VERR_NO_TMP_MEMORY);
1354 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
1355 void *pvChunk = NULL;
1356 int rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk,
1357#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1358 VMMIsHwVirtExtForced(pVM) ? &R0PtrChunk : NULL,
1359#else
1360 NULL,
1361#endif
1362 paChunkPages);
1363 if (RT_SUCCESS(rc))
1364 {
1365#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1366 if (!VMMIsHwVirtExtForced(pVM))
1367 R0PtrChunk = NIL_RTR0PTR;
1368#else
1369 R0PtrChunk = (uintptr_t)pvChunk;
1370#endif
1371 memset(pvChunk, 0, cChunkPages << PAGE_SHIFT);
1372
1373 PPGMRAMRANGE pNew = (PPGMRAMRANGE)pvChunk;
1374
1375 /*
1376 * Create a mapping and map the pages into it.
1377 * We push these in below the HMA.
1378 */
1379 RTGCPTR GCPtrChunkMap = pVM->pgm.s.GCPtrPrevRamRangeMapping - cbChunk;
1380 rc = PGMR3MapPT(pVM, GCPtrChunkMap, cbChunk, 0 /*fFlags*/, pgmR3PhysRamRangeRelocate, pNew, pszDescChunk);
1381 if (RT_SUCCESS(rc))
1382 {
1383 pVM->pgm.s.GCPtrPrevRamRangeMapping = GCPtrChunkMap;
1384
1385 RTGCPTR const GCPtrChunk = GCPtrChunkMap + PAGE_SIZE;
1386 RTGCPTR GCPtrPage = GCPtrChunk;
1387 for (uint32_t iPage = 0; iPage < cChunkPages && RT_SUCCESS(rc); iPage++, GCPtrPage += PAGE_SIZE)
1388 rc = PGMMap(pVM, GCPtrPage, paChunkPages[iPage].Phys, PAGE_SIZE, 0);
1389 if (RT_SUCCESS(rc))
1390 {
1391 /*
1392 * Ok, init and link the range.
1393 */
1394 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhys + ((RTGCPHYS)cRamPages << PAGE_SHIFT) - 1,
1395 (RTRCPTR)GCPtrChunk, R0PtrChunk, pszDescChunk, *ppPrev);
1396 *ppPrev = pNew;
1397 }
1398 }
1399
1400 if (RT_FAILURE(rc))
1401 SUPR3PageFreeEx(pvChunk, cChunkPages);
1402 }
1403
1404 RTMemTmpFree(paChunkPages);
1405 return rc;
1406}
1407
1408
1409/**
1410 * Sets up a range RAM.
1411 *
1412 * This will check for conflicting registrations, make a resource
1413 * reservation for the memory (with GMM), and setup the per-page
1414 * tracking structures (PGMPAGE).
1415 *
1416 * @returns VBox status code.
1417 * @param pVM Pointer to the shared VM structure.
1418 * @param GCPhys The physical address of the RAM.
1419 * @param cb The size of the RAM.
1420 * @param pszDesc The description - not copied, so, don't free or change it.
1421 */
1422VMMR3DECL(int) PGMR3PhysRegisterRam(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, const char *pszDesc)
1423{
1424 /*
1425 * Validate input.
1426 */
1427 Log(("PGMR3PhysRegisterRam: GCPhys=%RGp cb=%RGp pszDesc=%s\n", GCPhys, cb, pszDesc));
1428 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
1429 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
1430 AssertReturn(cb > 0, VERR_INVALID_PARAMETER);
1431 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1432 AssertMsgReturn(GCPhysLast > GCPhys, ("The range wraps! GCPhys=%RGp cb=%RGp\n", GCPhys, cb), VERR_INVALID_PARAMETER);
1433 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1434 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1435
1436 pgmLock(pVM);
1437
1438 /*
1439 * Find range location and check for conflicts.
1440 * (We don't lock here because the locking by EMT is only required on update.)
1441 */
1442 PPGMRAMRANGE pPrev = NULL;
1443 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
1444 while (pRam && GCPhysLast >= pRam->GCPhys)
1445 {
1446 if ( GCPhysLast >= pRam->GCPhys
1447 && GCPhys <= pRam->GCPhysLast)
1448 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
1449 GCPhys, GCPhysLast, pszDesc,
1450 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1451 VERR_PGM_RAM_CONFLICT);
1452
1453 /* next */
1454 pPrev = pRam;
1455 pRam = pRam->pNextR3;
1456 }
1457
1458 /*
1459 * Register it with GMM (the API bitches).
1460 */
1461 const RTGCPHYS cPages = cb >> PAGE_SHIFT;
1462 int rc = MMR3IncreaseBaseReservation(pVM, cPages);
1463 if (RT_FAILURE(rc))
1464 {
1465 pgmUnlock(pVM);
1466 return rc;
1467 }
1468
1469 if ( GCPhys >= _4G
1470 && cPages > 256)
1471 {
1472 /*
1473 * The PGMRAMRANGE structures for the high memory can get very big.
1474 * In order to avoid SUPR3PageAllocEx allocation failures due to the
1475 * allocation size limit there and also to avoid being unable to find
1476 * guest mapping space for them, we split this memory up into 4MB in
1477 * (potential) raw-mode configs and 16MB chunks in forced AMD-V/VT-x
1478 * mode.
1479 *
1480 * The first and last page of each mapping are guard pages and marked
1481 * not-present. So, we've got 4186112 and 16769024 bytes available for
1482 * the PGMRAMRANGE structure.
1483 *
1484 * Note! The sizes used here will influence the saved state.
1485 */
1486 uint32_t cbChunk;
1487 uint32_t cPagesPerChunk;
1488 if (VMMIsHwVirtExtForced(pVM))
1489 {
1490 cbChunk = 16U*_1M;
1491 cPagesPerChunk = 1048048; /* max ~1048059 */
1492 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 1048048 < 16U*_1M - PAGE_SIZE * 2);
1493 }
1494 else
1495 {
1496 cbChunk = 4U*_1M;
1497 cPagesPerChunk = 261616; /* max ~261627 */
1498 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 261616 < 4U*_1M - PAGE_SIZE * 2);
1499 }
1500 AssertRelease(RT_UOFFSETOF(PGMRAMRANGE, aPages[cPagesPerChunk]) + PAGE_SIZE * 2 <= cbChunk);
1501
1502 RTGCPHYS cPagesLeft = cPages;
1503 RTGCPHYS GCPhysChunk = GCPhys;
1504 uint32_t iChunk = 0;
1505 while (cPagesLeft > 0)
1506 {
1507 uint32_t cPagesInChunk = cPagesLeft;
1508 if (cPagesInChunk > cPagesPerChunk)
1509 cPagesInChunk = cPagesPerChunk;
1510
1511 rc = pgmR3PhysRegisterHighRamChunk(pVM, GCPhysChunk, cPagesInChunk, cbChunk, iChunk, pszDesc, &pPrev);
1512 AssertRCReturn(rc, rc);
1513
1514 /* advance */
1515 GCPhysChunk += (RTGCPHYS)cPagesInChunk << PAGE_SHIFT;
1516 cPagesLeft -= cPagesInChunk;
1517 iChunk++;
1518 }
1519 }
1520 else
1521 {
1522 /*
1523 * Allocate, initialize and link the new RAM range.
1524 */
1525 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
1526 PPGMRAMRANGE pNew;
1527 rc = MMR3HyperAllocOnceNoRel(pVM, cbRamRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
1528 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
1529
1530 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhysLast, NIL_RTRCPTR, NIL_RTR0PTR, pszDesc, pPrev);
1531 }
1532 PGMPhysInvalidatePageMapTLB(pVM);
1533 pgmUnlock(pVM);
1534
1535 /*
1536 * Notify REM.
1537 */
1538 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_RAM);
1539
1540 return VINF_SUCCESS;
1541}
1542
1543
1544/**
1545 * Worker called by PGMR3InitFinalize if we're configured to pre-allocate RAM.
1546 *
1547 * We do this late in the init process so that all the ROM and MMIO ranges have
1548 * been registered already and we don't go wasting memory on them.
1549 *
1550 * @returns VBox status code.
1551 *
1552 * @param pVM Pointer to the shared VM structure.
1553 */
1554int pgmR3PhysRamPreAllocate(PVM pVM)
1555{
1556 Assert(pVM->pgm.s.fRamPreAlloc);
1557 Log(("pgmR3PhysRamPreAllocate: enter\n"));
1558
1559 /*
1560 * Walk the RAM ranges and allocate all RAM pages, halt at
1561 * the first allocation error.
1562 */
1563 uint64_t cPages = 0;
1564 uint64_t NanoTS = RTTimeNanoTS();
1565 pgmLock(pVM);
1566 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3; pRam; pRam = pRam->pNextR3)
1567 {
1568 PPGMPAGE pPage = &pRam->aPages[0];
1569 RTGCPHYS GCPhys = pRam->GCPhys;
1570 uint32_t cLeft = pRam->cb >> PAGE_SHIFT;
1571 while (cLeft-- > 0)
1572 {
1573 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM)
1574 {
1575 switch (PGM_PAGE_GET_STATE(pPage))
1576 {
1577 case PGM_PAGE_STATE_ZERO:
1578 {
1579 int rc = pgmPhysAllocPage(pVM, pPage, GCPhys);
1580 if (RT_FAILURE(rc))
1581 {
1582 LogRel(("PGM: RAM Pre-allocation failed at %RGp (in %s) with rc=%Rrc\n", GCPhys, pRam->pszDesc, rc));
1583 pgmUnlock(pVM);
1584 return rc;
1585 }
1586 cPages++;
1587 break;
1588 }
1589
1590 case PGM_PAGE_STATE_BALLOONED:
1591 case PGM_PAGE_STATE_ALLOCATED:
1592 case PGM_PAGE_STATE_WRITE_MONITORED:
1593 case PGM_PAGE_STATE_SHARED:
1594 /* nothing to do here. */
1595 break;
1596 }
1597 }
1598
1599 /* next */
1600 pPage++;
1601 GCPhys += PAGE_SIZE;
1602 }
1603 }
1604 pgmUnlock(pVM);
1605 NanoTS = RTTimeNanoTS() - NanoTS;
1606
1607 LogRel(("PGM: Pre-allocated %llu pages in %llu ms\n", cPages, NanoTS / 1000000));
1608 Log(("pgmR3PhysRamPreAllocate: returns VINF_SUCCESS\n"));
1609 return VINF_SUCCESS;
1610}
1611
1612
1613/**
1614 * Resets (zeros) the RAM.
1615 *
1616 * ASSUMES that the caller owns the PGM lock.
1617 *
1618 * @returns VBox status code.
1619 * @param pVM Pointer to the shared VM structure.
1620 */
1621int pgmR3PhysRamReset(PVM pVM)
1622{
1623 Assert(PGMIsLockOwner(pVM));
1624
1625 /* Reset the memory balloon. */
1626 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
1627 AssertRC(rc);
1628
1629#ifdef VBOX_WITH_PAGE_SHARING
1630 /* Clear all registered shared modules. */
1631 rc = GMMR3ResetSharedModules(pVM);
1632 AssertRC(rc);
1633#endif
1634 /* Reset counters. */
1635 pVM->pgm.s.cReusedSharedPages = 0;
1636 pVM->pgm.s.cBalloonedPages = 0;
1637
1638 /*
1639 * We batch up pages that should be freed instead of calling GMM for
1640 * each and every one of them.
1641 */
1642 uint32_t cPendingPages = 0;
1643 PGMMFREEPAGESREQ pReq;
1644 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1645 AssertLogRelRCReturn(rc, rc);
1646
1647 /*
1648 * Walk the ram ranges.
1649 */
1650 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3; pRam; pRam = pRam->pNextR3)
1651 {
1652 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
1653 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
1654
1655 if (!pVM->pgm.s.fRamPreAlloc)
1656 {
1657 /* Replace all RAM pages by ZERO pages. */
1658 while (iPage-- > 0)
1659 {
1660 PPGMPAGE pPage = &pRam->aPages[iPage];
1661 switch (PGM_PAGE_GET_TYPE(pPage))
1662 {
1663 case PGMPAGETYPE_RAM:
1664 /* Do not replace pages part of a 2 MB continuous range with zero pages, but zero them instead. */
1665 if (PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE)
1666 {
1667 void *pvPage;
1668 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
1669 AssertLogRelRCReturn(rc, rc);
1670 ASMMemZeroPage(pvPage);
1671 }
1672 else
1673 if (PGM_PAGE_IS_BALLOONED(pPage))
1674 {
1675 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
1676 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
1677 }
1678 else
1679 if (!PGM_PAGE_IS_ZERO(pPage))
1680 {
1681 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1682 AssertLogRelRCReturn(rc, rc);
1683 }
1684 break;
1685
1686 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
1687 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
1688 true /*fDoAccounting*/);
1689 break;
1690
1691 case PGMPAGETYPE_MMIO2:
1692 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
1693 case PGMPAGETYPE_ROM:
1694 case PGMPAGETYPE_MMIO:
1695 break;
1696 default:
1697 AssertFailed();
1698 }
1699 } /* for each page */
1700 }
1701 else
1702 {
1703 /* Zero the memory. */
1704 while (iPage-- > 0)
1705 {
1706 PPGMPAGE pPage = &pRam->aPages[iPage];
1707 switch (PGM_PAGE_GET_TYPE(pPage))
1708 {
1709 case PGMPAGETYPE_RAM:
1710 switch (PGM_PAGE_GET_STATE(pPage))
1711 {
1712 case PGM_PAGE_STATE_ZERO:
1713 break;
1714
1715 case PGM_PAGE_STATE_BALLOONED:
1716 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
1717 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
1718 break;
1719
1720 case PGM_PAGE_STATE_SHARED:
1721 case PGM_PAGE_STATE_WRITE_MONITORED:
1722 rc = pgmPhysPageMakeWritable(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1723 AssertLogRelRCReturn(rc, rc);
1724 /* no break */
1725
1726 case PGM_PAGE_STATE_ALLOCATED:
1727 {
1728 void *pvPage;
1729 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
1730 AssertLogRelRCReturn(rc, rc);
1731 ASMMemZeroPage(pvPage);
1732 break;
1733 }
1734 }
1735 break;
1736
1737 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
1738 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
1739 true /*fDoAccounting*/);
1740 break;
1741
1742 case PGMPAGETYPE_MMIO2:
1743 case PGMPAGETYPE_ROM_SHADOW:
1744 case PGMPAGETYPE_ROM:
1745 case PGMPAGETYPE_MMIO:
1746 break;
1747 default:
1748 AssertFailed();
1749
1750 }
1751 } /* for each page */
1752 }
1753
1754 }
1755
1756 /*
1757 * Finish off any pages pending freeing.
1758 */
1759 if (cPendingPages)
1760 {
1761 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
1762 AssertLogRelRCReturn(rc, rc);
1763 }
1764 GMMR3FreePagesCleanup(pReq);
1765
1766 return VINF_SUCCESS;
1767}
1768
1769/**
1770 * Frees all RAM during VM termination
1771 *
1772 * ASSUMES that the caller owns the PGM lock.
1773 *
1774 * @returns VBox status code.
1775 * @param pVM Pointer to the shared VM structure.
1776 */
1777int pgmR3PhysRamTerm(PVM pVM)
1778{
1779 Assert(PGMIsLockOwner(pVM));
1780
1781 /* Reset the memory balloon. */
1782 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
1783 AssertRC(rc);
1784
1785#ifdef VBOX_WITH_PAGE_SHARING
1786 /* Clear all registered shared modules. */
1787 rc = GMMR3ResetSharedModules(pVM);
1788 AssertRC(rc);
1789#endif
1790
1791 /*
1792 * We batch up pages that should be freed instead of calling GMM for
1793 * each and every one of them.
1794 */
1795 uint32_t cPendingPages = 0;
1796 PGMMFREEPAGESREQ pReq;
1797 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1798 AssertLogRelRCReturn(rc, rc);
1799
1800 /*
1801 * Walk the ram ranges.
1802 */
1803 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3; pRam; pRam = pRam->pNextR3)
1804 {
1805 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
1806 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
1807
1808 /* Replace all RAM pages by ZERO pages. */
1809 while (iPage-- > 0)
1810 {
1811 PPGMPAGE pPage = &pRam->aPages[iPage];
1812 switch (PGM_PAGE_GET_TYPE(pPage))
1813 {
1814 case PGMPAGETYPE_RAM:
1815 /* Free all shared pages. Private pages are automatically freed during GMM VM cleanup. */
1816 if (PGM_PAGE_IS_SHARED(pPage))
1817 {
1818 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1819 AssertLogRelRCReturn(rc, rc);
1820 }
1821 break;
1822
1823 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
1824 case PGMPAGETYPE_MMIO2:
1825 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
1826 case PGMPAGETYPE_ROM:
1827 case PGMPAGETYPE_MMIO:
1828 break;
1829 default:
1830 AssertFailed();
1831 }
1832 } /* for each page */
1833 }
1834
1835 /*
1836 * Finish off any pages pending freeing.
1837 */
1838 if (cPendingPages)
1839 {
1840 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
1841 AssertLogRelRCReturn(rc, rc);
1842 }
1843 GMMR3FreePagesCleanup(pReq);
1844 return VINF_SUCCESS;
1845}
1846
1847/**
1848 * This is the interface IOM is using to register an MMIO region.
1849 *
1850 * It will check for conflicts and ensure that a RAM range structure
1851 * is present before calling the PGMR3HandlerPhysicalRegister API to
1852 * register the callbacks.
1853 *
1854 * @returns VBox status code.
1855 *
1856 * @param pVM Pointer to the shared VM structure.
1857 * @param GCPhys The start of the MMIO region.
1858 * @param cb The size of the MMIO region.
1859 * @param pfnHandlerR3 The address of the ring-3 handler. (IOMR3MMIOHandler)
1860 * @param pvUserR3 The user argument for R3.
1861 * @param pfnHandlerR0 The address of the ring-0 handler. (IOMMMIOHandler)
1862 * @param pvUserR0 The user argument for R0.
1863 * @param pfnHandlerRC The address of the RC handler. (IOMMMIOHandler)
1864 * @param pvUserRC The user argument for RC.
1865 * @param pszDesc The description of the MMIO region.
1866 */
1867VMMR3DECL(int) PGMR3PhysMMIORegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb,
1868 R3PTRTYPE(PFNPGMR3PHYSHANDLER) pfnHandlerR3, RTR3PTR pvUserR3,
1869 R0PTRTYPE(PFNPGMR0PHYSHANDLER) pfnHandlerR0, RTR0PTR pvUserR0,
1870 RCPTRTYPE(PFNPGMRCPHYSHANDLER) pfnHandlerRC, RTRCPTR pvUserRC,
1871 R3PTRTYPE(const char *) pszDesc)
1872{
1873 /*
1874 * Assert on some assumption.
1875 */
1876 VM_ASSERT_EMT(pVM);
1877 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
1878 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
1879 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1880 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
1881
1882 /*
1883 * Make sure there's a RAM range structure for the region.
1884 */
1885 int rc;
1886 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1887 bool fRamExists = false;
1888 PPGMRAMRANGE pRamPrev = NULL;
1889 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
1890 while (pRam && GCPhysLast >= pRam->GCPhys)
1891 {
1892 if ( GCPhysLast >= pRam->GCPhys
1893 && GCPhys <= pRam->GCPhysLast)
1894 {
1895 /* Simplification: all within the same range. */
1896 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
1897 && GCPhysLast <= pRam->GCPhysLast,
1898 ("%RGp-%RGp (MMIO/%s) falls partly outside %RGp-%RGp (%s)\n",
1899 GCPhys, GCPhysLast, pszDesc,
1900 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1901 VERR_PGM_RAM_CONFLICT);
1902
1903 /* Check that it's all RAM or MMIO pages. */
1904 PCPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
1905 uint32_t cLeft = cb >> PAGE_SHIFT;
1906 while (cLeft-- > 0)
1907 {
1908 AssertLogRelMsgReturn( PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM
1909 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO,
1910 ("%RGp-%RGp (MMIO/%s): %RGp is not a RAM or MMIO page - type=%d desc=%s\n",
1911 GCPhys, GCPhysLast, pszDesc, PGM_PAGE_GET_TYPE(pPage), pRam->pszDesc),
1912 VERR_PGM_RAM_CONFLICT);
1913 pPage++;
1914 }
1915
1916 /* Looks good. */
1917 fRamExists = true;
1918 break;
1919 }
1920
1921 /* next */
1922 pRamPrev = pRam;
1923 pRam = pRam->pNextR3;
1924 }
1925 PPGMRAMRANGE pNew;
1926 if (fRamExists)
1927 {
1928 pNew = NULL;
1929
1930 /*
1931 * Make all the pages in the range MMIO/ZERO pages, freeing any
1932 * RAM pages currently mapped here. This might not be 100% correct
1933 * for PCI memory, but we're doing the same thing for MMIO2 pages.
1934 */
1935 rc = pgmLock(pVM);
1936 if (RT_SUCCESS(rc))
1937 {
1938 rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, PGMPAGETYPE_MMIO);
1939 pgmUnlock(pVM);
1940 }
1941 AssertRCReturn(rc, rc);
1942
1943 /* Force a PGM pool flush as guest ram references have been changed. */
1944 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
1945 PVMCPU pVCpu = VMMGetCpu(pVM);
1946 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
1947 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
1948 }
1949 else
1950 {
1951 pgmLock(pVM);
1952
1953 /*
1954 * No RAM range, insert an ad hoc one.
1955 *
1956 * Note that we don't have to tell REM about this range because
1957 * PGMHandlerPhysicalRegisterEx will do that for us.
1958 */
1959 Log(("PGMR3PhysMMIORegister: Adding ad hoc MMIO range for %RGp-%RGp %s\n", GCPhys, GCPhysLast, pszDesc));
1960
1961 const uint32_t cPages = cb >> PAGE_SHIFT;
1962 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
1963 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), 16, MM_TAG_PGM_PHYS, (void **)&pNew);
1964 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
1965
1966 /* Initialize the range. */
1967 pNew->pSelfR0 = MMHyperCCToR0(pVM, pNew);
1968 pNew->pSelfRC = MMHyperCCToRC(pVM, pNew);
1969 pNew->GCPhys = GCPhys;
1970 pNew->GCPhysLast = GCPhysLast;
1971 pNew->cb = cb;
1972 pNew->pszDesc = pszDesc;
1973 pNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO;
1974 pNew->pvR3 = NULL;
1975 pNew->paLSPages = NULL;
1976
1977 uint32_t iPage = cPages;
1978 while (iPage-- > 0)
1979 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_MMIO);
1980 Assert(PGM_PAGE_GET_TYPE(&pNew->aPages[0]) == PGMPAGETYPE_MMIO);
1981
1982 /* update the page count stats. */
1983 pVM->pgm.s.cPureMmioPages += cPages;
1984 pVM->pgm.s.cAllPages += cPages;
1985
1986 /* link it */
1987 pgmR3PhysLinkRamRange(pVM, pNew, pRamPrev);
1988
1989 pgmUnlock(pVM);
1990 }
1991
1992 /*
1993 * Register the access handler.
1994 */
1995 rc = PGMHandlerPhysicalRegisterEx(pVM, PGMPHYSHANDLERTYPE_MMIO, GCPhys, GCPhysLast,
1996 pfnHandlerR3, pvUserR3,
1997 pfnHandlerR0, pvUserR0,
1998 pfnHandlerRC, pvUserRC, pszDesc);
1999 if ( RT_FAILURE(rc)
2000 && !fRamExists)
2001 {
2002 pVM->pgm.s.cPureMmioPages -= cb >> PAGE_SHIFT;
2003 pVM->pgm.s.cAllPages -= cb >> PAGE_SHIFT;
2004
2005 /* remove the ad hoc range. */
2006 pgmR3PhysUnlinkRamRange2(pVM, pNew, pRamPrev);
2007 pNew->cb = pNew->GCPhys = pNew->GCPhysLast = NIL_RTGCPHYS;
2008 MMHyperFree(pVM, pRam);
2009 }
2010 PGMPhysInvalidatePageMapTLB(pVM);
2011
2012 return rc;
2013}
2014
2015
2016/**
2017 * This is the interface IOM is using to register an MMIO region.
2018 *
2019 * It will take care of calling PGMHandlerPhysicalDeregister and clean up
2020 * any ad hoc PGMRAMRANGE left behind.
2021 *
2022 * @returns VBox status code.
2023 * @param pVM Pointer to the shared VM structure.
2024 * @param GCPhys The start of the MMIO region.
2025 * @param cb The size of the MMIO region.
2026 */
2027VMMR3DECL(int) PGMR3PhysMMIODeregister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb)
2028{
2029 VM_ASSERT_EMT(pVM);
2030
2031 /*
2032 * First deregister the handler, then check if we should remove the ram range.
2033 */
2034 int rc = PGMHandlerPhysicalDeregister(pVM, GCPhys);
2035 if (RT_SUCCESS(rc))
2036 {
2037 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2038 PPGMRAMRANGE pRamPrev = NULL;
2039 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2040 while (pRam && GCPhysLast >= pRam->GCPhys)
2041 {
2042 /** @todo We're being a bit too careful here. rewrite. */
2043 if ( GCPhysLast == pRam->GCPhysLast
2044 && GCPhys == pRam->GCPhys)
2045 {
2046 Assert(pRam->cb == cb);
2047
2048 /*
2049 * See if all the pages are dead MMIO pages.
2050 */
2051 uint32_t const cPages = cb >> PAGE_SHIFT;
2052 bool fAllMMIO = true;
2053 uint32_t iPage = 0;
2054 uint32_t cLeft = cPages;
2055 while (cLeft-- > 0)
2056 {
2057 PPGMPAGE pPage = &pRam->aPages[iPage];
2058 if ( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_MMIO
2059 /*|| not-out-of-action later */)
2060 {
2061 fAllMMIO = false;
2062 Assert(PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_MMIO2_ALIAS_MMIO);
2063 AssertMsgFailed(("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
2064 break;
2065 }
2066 Assert(PGM_PAGE_IS_ZERO(pPage));
2067 pPage++;
2068 }
2069 if (fAllMMIO)
2070 {
2071 /*
2072 * Ad-hoc range, unlink and free it.
2073 */
2074 Log(("PGMR3PhysMMIODeregister: Freeing ad hoc MMIO range for %RGp-%RGp %s\n",
2075 GCPhys, GCPhysLast, pRam->pszDesc));
2076
2077 pVM->pgm.s.cAllPages -= cPages;
2078 pVM->pgm.s.cPureMmioPages -= cPages;
2079
2080 pgmR3PhysUnlinkRamRange2(pVM, pRam, pRamPrev);
2081 pRam->cb = pRam->GCPhys = pRam->GCPhysLast = NIL_RTGCPHYS;
2082 MMHyperFree(pVM, pRam);
2083 break;
2084 }
2085 }
2086
2087 /*
2088 * Range match? It will all be within one range (see PGMAllHandler.cpp).
2089 */
2090 if ( GCPhysLast >= pRam->GCPhys
2091 && GCPhys <= pRam->GCPhysLast)
2092 {
2093 Assert(GCPhys >= pRam->GCPhys);
2094 Assert(GCPhysLast <= pRam->GCPhysLast);
2095
2096 /*
2097 * Turn the pages back into RAM pages.
2098 */
2099 uint32_t iPage = (GCPhys - pRam->GCPhys) >> PAGE_SHIFT;
2100 uint32_t cLeft = cb >> PAGE_SHIFT;
2101 while (cLeft--)
2102 {
2103 PPGMPAGE pPage = &pRam->aPages[iPage];
2104 AssertMsg(PGM_PAGE_IS_MMIO(pPage), ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
2105 AssertMsg(PGM_PAGE_IS_ZERO(pPage), ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
2106 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO)
2107 PGM_PAGE_SET_TYPE(pPage, PGMPAGETYPE_RAM);
2108 }
2109 break;
2110 }
2111
2112 /* next */
2113 pRamPrev = pRam;
2114 pRam = pRam->pNextR3;
2115 }
2116 }
2117
2118 /* Force a PGM pool flush as guest ram references have been changed. */
2119 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
2120 PVMCPU pVCpu = VMMGetCpu(pVM);
2121 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2122 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2123
2124 PGMPhysInvalidatePageMapTLB(pVM);
2125 return rc;
2126}
2127
2128
2129/**
2130 * Locate a MMIO2 range.
2131 *
2132 * @returns Pointer to the MMIO2 range.
2133 * @param pVM Pointer to the shared VM structure.
2134 * @param pDevIns The device instance owning the region.
2135 * @param iRegion The region.
2136 */
2137DECLINLINE(PPGMMMIO2RANGE) pgmR3PhysMMIO2Find(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
2138{
2139 /*
2140 * Search the list.
2141 */
2142 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
2143 if ( pCur->pDevInsR3 == pDevIns
2144 && pCur->iRegion == iRegion)
2145 return pCur;
2146 return NULL;
2147}
2148
2149
2150/**
2151 * Allocate and register an MMIO2 region.
2152 *
2153 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's RAM
2154 * associated with a device. It is also non-shared memory with a permanent
2155 * ring-3 mapping and page backing (presently).
2156 *
2157 * A MMIO2 range may overlap with base memory if a lot of RAM is configured for
2158 * the VM, in which case we'll drop the base memory pages. Presently we will
2159 * make no attempt to preserve anything that happens to be present in the base
2160 * memory that is replaced, this is of course incorrectly but it's too much
2161 * effort.
2162 *
2163 * @returns VBox status code.
2164 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
2165 * memory.
2166 * @retval VERR_ALREADY_EXISTS if the region already exists.
2167 *
2168 * @param pVM Pointer to the shared VM structure.
2169 * @param pDevIns The device instance owning the region.
2170 * @param iRegion The region number. If the MMIO2 memory is a PCI
2171 * I/O region this number has to be the number of that
2172 * region. Otherwise it can be any number safe
2173 * UINT8_MAX.
2174 * @param cb The size of the region. Must be page aligned.
2175 * @param fFlags Reserved for future use, must be zero.
2176 * @param ppv Where to store the pointer to the ring-3 mapping of
2177 * the memory.
2178 * @param pszDesc The description.
2179 */
2180VMMR3DECL(int) PGMR3PhysMMIO2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags, void **ppv, const char *pszDesc)
2181{
2182 /*
2183 * Validate input.
2184 */
2185 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2186 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2187 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2188 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
2189 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2190 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
2191 AssertReturn(pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion) == NULL, VERR_ALREADY_EXISTS);
2192 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2193 AssertReturn(cb, VERR_INVALID_PARAMETER);
2194 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
2195
2196 const uint32_t cPages = cb >> PAGE_SHIFT;
2197 AssertLogRelReturn(((RTGCPHYS)cPages << PAGE_SHIFT) == cb, VERR_INVALID_PARAMETER);
2198 AssertLogRelReturn(cPages <= INT32_MAX / 2, VERR_NO_MEMORY);
2199
2200 /*
2201 * For the 2nd+ instance, mangle the description string so it's unique.
2202 */
2203 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
2204 {
2205 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
2206 if (!pszDesc)
2207 return VERR_NO_MEMORY;
2208 }
2209
2210 /*
2211 * Try reserve and allocate the backing memory first as this is what is
2212 * most likely to fail.
2213 */
2214 int rc = MMR3AdjustFixedReservation(pVM, cPages, pszDesc);
2215 if (RT_SUCCESS(rc))
2216 {
2217 void *pvPages;
2218 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cPages * sizeof(SUPPAGE));
2219 if (RT_SUCCESS(rc))
2220 rc = SUPR3PageAllocEx(cPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
2221 if (RT_SUCCESS(rc))
2222 {
2223 memset(pvPages, 0, cPages * PAGE_SIZE);
2224
2225 /*
2226 * Create the MMIO2 range record for it.
2227 */
2228 const size_t cbRange = RT_OFFSETOF(PGMMMIO2RANGE, RamRange.aPages[cPages]);
2229 PPGMMMIO2RANGE pNew;
2230 rc = MMR3HyperAllocOnceNoRel(pVM, cbRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
2231 AssertLogRelMsgRC(rc, ("cbRamRange=%zu\n", cbRange));
2232 if (RT_SUCCESS(rc))
2233 {
2234 pNew->pDevInsR3 = pDevIns;
2235 pNew->pvR3 = pvPages;
2236 //pNew->pNext = NULL;
2237 //pNew->fMapped = false;
2238 //pNew->fOverlapping = false;
2239 pNew->iRegion = iRegion;
2240 pNew->idSavedState = UINT8_MAX;
2241 pNew->RamRange.pSelfR0 = MMHyperCCToR0(pVM, &pNew->RamRange);
2242 pNew->RamRange.pSelfRC = MMHyperCCToRC(pVM, &pNew->RamRange);
2243 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
2244 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
2245 pNew->RamRange.pszDesc = pszDesc;
2246 pNew->RamRange.cb = cb;
2247 pNew->RamRange.fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO2;
2248 pNew->RamRange.pvR3 = pvPages;
2249 //pNew->RamRange.paLSPages = NULL;
2250
2251 uint32_t iPage = cPages;
2252 while (iPage-- > 0)
2253 {
2254 PGM_PAGE_INIT(&pNew->RamRange.aPages[iPage],
2255 paPages[iPage].Phys, NIL_GMM_PAGEID,
2256 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
2257 }
2258
2259 /* update page count stats */
2260 pVM->pgm.s.cAllPages += cPages;
2261 pVM->pgm.s.cPrivatePages += cPages;
2262
2263 /*
2264 * Link it into the list.
2265 * Since there is no particular order, just push it.
2266 */
2267 pgmLock(pVM);
2268 pNew->pNextR3 = pVM->pgm.s.pMmio2RangesR3;
2269 pVM->pgm.s.pMmio2RangesR3 = pNew;
2270 pgmUnlock(pVM);
2271
2272 *ppv = pvPages;
2273 RTMemTmpFree(paPages);
2274 PGMPhysInvalidatePageMapTLB(pVM);
2275 return VINF_SUCCESS;
2276 }
2277
2278 SUPR3PageFreeEx(pvPages, cPages);
2279 }
2280 RTMemTmpFree(paPages);
2281 MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pszDesc);
2282 }
2283 if (pDevIns->iInstance > 0)
2284 MMR3HeapFree((void *)pszDesc);
2285 return rc;
2286}
2287
2288
2289/**
2290 * Deregisters and frees an MMIO2 region.
2291 *
2292 * Any physical (and virtual) access handlers registered for the region must
2293 * be deregistered before calling this function.
2294 *
2295 * @returns VBox status code.
2296 * @param pVM Pointer to the shared VM structure.
2297 * @param pDevIns The device instance owning the region.
2298 * @param iRegion The region. If it's UINT32_MAX it'll be a wildcard match.
2299 */
2300VMMR3DECL(int) PGMR3PhysMMIO2Deregister(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
2301{
2302 /*
2303 * Validate input.
2304 */
2305 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2306 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2307 AssertReturn(iRegion <= UINT8_MAX || iRegion == UINT32_MAX, VERR_INVALID_PARAMETER);
2308
2309 pgmLock(pVM);
2310 int rc = VINF_SUCCESS;
2311 unsigned cFound = 0;
2312 PPGMMMIO2RANGE pPrev = NULL;
2313 PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3;
2314 while (pCur)
2315 {
2316 if ( pCur->pDevInsR3 == pDevIns
2317 && ( iRegion == UINT32_MAX
2318 || pCur->iRegion == iRegion))
2319 {
2320 cFound++;
2321
2322 /*
2323 * Unmap it if it's mapped.
2324 */
2325 if (pCur->fMapped)
2326 {
2327 int rc2 = PGMR3PhysMMIO2Unmap(pVM, pCur->pDevInsR3, pCur->iRegion, pCur->RamRange.GCPhys);
2328 AssertRC(rc2);
2329 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2330 rc = rc2;
2331 }
2332
2333 /*
2334 * Unlink it
2335 */
2336 PPGMMMIO2RANGE pNext = pCur->pNextR3;
2337 if (pPrev)
2338 pPrev->pNextR3 = pNext;
2339 else
2340 pVM->pgm.s.pMmio2RangesR3 = pNext;
2341 pCur->pNextR3 = NULL;
2342
2343 /*
2344 * Free the memory.
2345 */
2346 int rc2 = SUPR3PageFreeEx(pCur->pvR3, pCur->RamRange.cb >> PAGE_SHIFT);
2347 AssertRC(rc2);
2348 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2349 rc = rc2;
2350
2351 uint32_t const cPages = pCur->RamRange.cb >> PAGE_SHIFT;
2352 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pCur->RamRange.pszDesc);
2353 AssertRC(rc2);
2354 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2355 rc = rc2;
2356
2357 /* we're leaking hyper memory here if done at runtime. */
2358#ifdef VBOX_STRICT
2359 VMSTATE const enmState = VMR3GetState(pVM);
2360 AssertMsg( enmState == VMSTATE_POWERING_OFF
2361 || enmState == VMSTATE_POWERING_OFF_LS
2362 || enmState == VMSTATE_OFF
2363 || enmState == VMSTATE_OFF_LS
2364 || enmState == VMSTATE_DESTROYING
2365 || enmState == VMSTATE_TERMINATED
2366 || enmState == VMSTATE_CREATING
2367 , ("%s\n", VMR3GetStateName(enmState)));
2368#endif
2369 /*rc = MMHyperFree(pVM, pCur);
2370 AssertRCReturn(rc, rc); - not safe, see the alloc call. */
2371
2372
2373 /* update page count stats */
2374 pVM->pgm.s.cAllPages -= cPages;
2375 pVM->pgm.s.cPrivatePages -= cPages;
2376
2377 /* next */
2378 pCur = pNext;
2379 }
2380 else
2381 {
2382 pPrev = pCur;
2383 pCur = pCur->pNextR3;
2384 }
2385 }
2386 PGMPhysInvalidatePageMapTLB(pVM);
2387 pgmUnlock(pVM);
2388 return !cFound && iRegion != UINT32_MAX ? VERR_NOT_FOUND : rc;
2389}
2390
2391
2392/**
2393 * Maps a MMIO2 region.
2394 *
2395 * This is done when a guest / the bios / state loading changes the
2396 * PCI config. The replacing of base memory has the same restrictions
2397 * as during registration, of course.
2398 *
2399 * @returns VBox status code.
2400 *
2401 * @param pVM Pointer to the shared VM structure.
2402 * @param pDevIns The
2403 */
2404VMMR3DECL(int) PGMR3PhysMMIO2Map(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
2405{
2406 /*
2407 * Validate input
2408 */
2409 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2410 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2411 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2412 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
2413 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
2414 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2415
2416 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2417 AssertReturn(pCur, VERR_NOT_FOUND);
2418 AssertReturn(!pCur->fMapped, VERR_WRONG_ORDER);
2419 Assert(pCur->RamRange.GCPhys == NIL_RTGCPHYS);
2420 Assert(pCur->RamRange.GCPhysLast == NIL_RTGCPHYS);
2421
2422 const RTGCPHYS GCPhysLast = GCPhys + pCur->RamRange.cb - 1;
2423 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2424
2425 /*
2426 * Find our location in the ram range list, checking for
2427 * restriction we don't bother implementing yet (partially overlapping).
2428 */
2429 bool fRamExists = false;
2430 PPGMRAMRANGE pRamPrev = NULL;
2431 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2432 while (pRam && GCPhysLast >= pRam->GCPhys)
2433 {
2434 if ( GCPhys <= pRam->GCPhysLast
2435 && GCPhysLast >= pRam->GCPhys)
2436 {
2437 /* completely within? */
2438 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
2439 && GCPhysLast <= pRam->GCPhysLast,
2440 ("%RGp-%RGp (MMIO2/%s) falls partly outside %RGp-%RGp (%s)\n",
2441 GCPhys, GCPhysLast, pCur->RamRange.pszDesc,
2442 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2443 VERR_PGM_RAM_CONFLICT);
2444 fRamExists = true;
2445 break;
2446 }
2447
2448 /* next */
2449 pRamPrev = pRam;
2450 pRam = pRam->pNextR3;
2451 }
2452 if (fRamExists)
2453 {
2454 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2455 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2456 while (cPagesLeft-- > 0)
2457 {
2458 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
2459 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
2460 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pCur->RamRange.pszDesc),
2461 VERR_PGM_RAM_CONFLICT);
2462 pPage++;
2463 }
2464 }
2465 Log(("PGMR3PhysMMIO2Map: %RGp-%RGp fRamExists=%RTbool %s\n",
2466 GCPhys, GCPhysLast, fRamExists, pCur->RamRange.pszDesc));
2467
2468 /*
2469 * Make the changes.
2470 */
2471 pgmLock(pVM);
2472
2473 pCur->RamRange.GCPhys = GCPhys;
2474 pCur->RamRange.GCPhysLast = GCPhysLast;
2475 pCur->fMapped = true;
2476 pCur->fOverlapping = fRamExists;
2477
2478 if (fRamExists)
2479 {
2480/** @todo use pgmR3PhysFreePageRange here. */
2481 uint32_t cPendingPages = 0;
2482 PGMMFREEPAGESREQ pReq;
2483 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2484 AssertLogRelRCReturn(rc, rc);
2485
2486 /* replace the pages, freeing all present RAM pages. */
2487 PPGMPAGE pPageSrc = &pCur->RamRange.aPages[0];
2488 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2489 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2490 while (cPagesLeft-- > 0)
2491 {
2492 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys);
2493 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
2494
2495 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
2496 PGM_PAGE_SET_HCPHYS(pPageDst, HCPhys);
2497 PGM_PAGE_SET_TYPE(pPageDst, PGMPAGETYPE_MMIO2);
2498 PGM_PAGE_SET_STATE(pPageDst, PGM_PAGE_STATE_ALLOCATED);
2499 PGM_PAGE_SET_PDE_TYPE(pPageDst, PGM_PAGE_PDE_TYPE_DONTCARE);
2500 PGM_PAGE_SET_PTE_INDEX(pPageDst, 0);
2501 PGM_PAGE_SET_TRACKING(pPageDst, 0);
2502
2503 pVM->pgm.s.cZeroPages--;
2504 GCPhys += PAGE_SIZE;
2505 pPageSrc++;
2506 pPageDst++;
2507 }
2508
2509 /* Flush physical page map TLB. */
2510 PGMPhysInvalidatePageMapTLB(pVM);
2511
2512 if (cPendingPages)
2513 {
2514 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2515 AssertLogRelRCReturn(rc, rc);
2516 }
2517 GMMR3FreePagesCleanup(pReq);
2518
2519 /* Force a PGM pool flush as guest ram references have been changed. */
2520 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
2521 PVMCPU pVCpu = VMMGetCpu(pVM);
2522 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2523 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2524
2525 pgmUnlock(pVM);
2526 }
2527 else
2528 {
2529 RTGCPHYS cb = pCur->RamRange.cb;
2530
2531 /* Clear the tracking data of pages we're going to reactivate. */
2532 PPGMPAGE pPageSrc = &pCur->RamRange.aPages[0];
2533 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2534 while (cPagesLeft-- > 0)
2535 {
2536 PGM_PAGE_SET_TRACKING(pPageSrc, 0);
2537 PGM_PAGE_SET_PTE_INDEX(pPageSrc, 0);
2538 pPageSrc++;
2539 }
2540
2541 /* link in the ram range */
2542 pgmR3PhysLinkRamRange(pVM, &pCur->RamRange, pRamPrev);
2543 pgmUnlock(pVM);
2544
2545 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_MMIO2);
2546 }
2547
2548 PGMPhysInvalidatePageMapTLB(pVM);
2549 return VINF_SUCCESS;
2550}
2551
2552
2553/**
2554 * Unmaps a MMIO2 region.
2555 *
2556 * This is done when a guest / the bios / state loading changes the
2557 * PCI config. The replacing of base memory has the same restrictions
2558 * as during registration, of course.
2559 */
2560VMMR3DECL(int) PGMR3PhysMMIO2Unmap(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
2561{
2562 /*
2563 * Validate input
2564 */
2565 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2566 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2567 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2568 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
2569 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
2570 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2571
2572 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2573 AssertReturn(pCur, VERR_NOT_FOUND);
2574 AssertReturn(pCur->fMapped, VERR_WRONG_ORDER);
2575 AssertReturn(pCur->RamRange.GCPhys == GCPhys, VERR_INVALID_PARAMETER);
2576 Assert(pCur->RamRange.GCPhysLast != NIL_RTGCPHYS);
2577
2578 Log(("PGMR3PhysMMIO2Unmap: %RGp-%RGp %s\n",
2579 pCur->RamRange.GCPhys, pCur->RamRange.GCPhysLast, pCur->RamRange.pszDesc));
2580
2581 /*
2582 * Unmap it.
2583 */
2584 pgmLock(pVM);
2585
2586 RTGCPHYS GCPhysRangeREM;
2587 RTGCPHYS cbRangeREM;
2588 bool fInformREM;
2589 if (pCur->fOverlapping)
2590 {
2591 /* Restore the RAM pages we've replaced. */
2592 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2593 while (pRam->GCPhys > pCur->RamRange.GCPhysLast)
2594 pRam = pRam->pNextR3;
2595
2596 PPGMPAGE pPageDst = &pRam->aPages[(pCur->RamRange.GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2597 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2598 while (cPagesLeft-- > 0)
2599 {
2600 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
2601 pVM->pgm.s.cZeroPages++;
2602 pPageDst++;
2603 }
2604
2605 /* Flush physical page map TLB. */
2606 PGMPhysInvalidatePageMapTLB(pVM);
2607
2608 GCPhysRangeREM = NIL_RTGCPHYS; /* shuts up gcc */
2609 cbRangeREM = RTGCPHYS_MAX; /* ditto */
2610 fInformREM = false;
2611 }
2612 else
2613 {
2614 GCPhysRangeREM = pCur->RamRange.GCPhys;
2615 cbRangeREM = pCur->RamRange.cb;
2616 fInformREM = true;
2617
2618 pgmR3PhysUnlinkRamRange(pVM, &pCur->RamRange);
2619 }
2620
2621 pCur->RamRange.GCPhys = NIL_RTGCPHYS;
2622 pCur->RamRange.GCPhysLast = NIL_RTGCPHYS;
2623 pCur->fOverlapping = false;
2624 pCur->fMapped = false;
2625
2626 /* Force a PGM pool flush as guest ram references have been changed. */
2627 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
2628 PVMCPU pVCpu = VMMGetCpu(pVM);
2629 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2630 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2631
2632 PGMPhysInvalidatePageMapTLB(pVM);
2633 pgmUnlock(pVM);
2634
2635 if (fInformREM)
2636 REMR3NotifyPhysRamDeregister(pVM, GCPhysRangeREM, cbRangeREM);
2637
2638 return VINF_SUCCESS;
2639}
2640
2641
2642/**
2643 * Checks if the given address is an MMIO2 base address or not.
2644 *
2645 * @returns true/false accordingly.
2646 * @param pVM Pointer to the shared VM structure.
2647 * @param pDevIns The owner of the memory, optional.
2648 * @param GCPhys The address to check.
2649 */
2650VMMR3DECL(bool) PGMR3PhysMMIO2IsBase(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys)
2651{
2652 /*
2653 * Validate input
2654 */
2655 VM_ASSERT_EMT_RETURN(pVM, false);
2656 AssertPtrReturn(pDevIns, false);
2657 AssertReturn(GCPhys != NIL_RTGCPHYS, false);
2658 AssertReturn(GCPhys != 0, false);
2659 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), false);
2660
2661 /*
2662 * Search the list.
2663 */
2664 pgmLock(pVM);
2665 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
2666 if (pCur->RamRange.GCPhys == GCPhys)
2667 {
2668 Assert(pCur->fMapped);
2669 pgmUnlock(pVM);
2670 return true;
2671 }
2672 pgmUnlock(pVM);
2673 return false;
2674}
2675
2676
2677/**
2678 * Gets the HC physical address of a page in the MMIO2 region.
2679 *
2680 * This is API is intended for MMHyper and shouldn't be called
2681 * by anyone else...
2682 *
2683 * @returns VBox status code.
2684 * @param pVM Pointer to the shared VM structure.
2685 * @param pDevIns The owner of the memory, optional.
2686 * @param iRegion The region.
2687 * @param off The page expressed an offset into the MMIO2 region.
2688 * @param pHCPhys Where to store the result.
2689 */
2690VMMR3DECL(int) PGMR3PhysMMIO2GetHCPhys(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, PRTHCPHYS pHCPhys)
2691{
2692 /*
2693 * Validate input
2694 */
2695 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2696 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2697 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2698
2699 pgmLock(pVM);
2700 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2701 AssertReturn(pCur, VERR_NOT_FOUND);
2702 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2703
2704 PCPGMPAGE pPage = &pCur->RamRange.aPages[off >> PAGE_SHIFT];
2705 *pHCPhys = PGM_PAGE_GET_HCPHYS(pPage);
2706 pgmUnlock(pVM);
2707 return VINF_SUCCESS;
2708}
2709
2710
2711/**
2712 * Maps a portion of an MMIO2 region into kernel space (host).
2713 *
2714 * The kernel mapping will become invalid when the MMIO2 memory is deregistered
2715 * or the VM is terminated.
2716 *
2717 * @return VBox status code.
2718 *
2719 * @param pVM Pointer to the shared VM structure.
2720 * @param pDevIns The device owning the MMIO2 memory.
2721 * @param iRegion The region.
2722 * @param off The offset into the region. Must be page aligned.
2723 * @param cb The number of bytes to map. Must be page aligned.
2724 * @param pszDesc Mapping description.
2725 * @param pR0Ptr Where to store the R0 address.
2726 */
2727VMMR3DECL(int) PGMR3PhysMMIO2MapKernel(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, RTGCPHYS cb,
2728 const char *pszDesc, PRTR0PTR pR0Ptr)
2729{
2730 /*
2731 * Validate input.
2732 */
2733 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2734 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2735 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2736
2737 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2738 AssertReturn(pCur, VERR_NOT_FOUND);
2739 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2740 AssertReturn(cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2741 AssertReturn(off + cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2742
2743 /*
2744 * Pass the request on to the support library/driver.
2745 */
2746 int rc = SUPR3PageMapKernel(pCur->pvR3, off, cb, 0, pR0Ptr);
2747
2748 return rc;
2749}
2750
2751
2752/**
2753 * Registers a ROM image.
2754 *
2755 * Shadowed ROM images requires double the amount of backing memory, so,
2756 * don't use that unless you have to. Shadowing of ROM images is process
2757 * where we can select where the reads go and where the writes go. On real
2758 * hardware the chipset provides means to configure this. We provide
2759 * PGMR3PhysProtectROM() for this purpose.
2760 *
2761 * A read-only copy of the ROM image will always be kept around while we
2762 * will allocate RAM pages for the changes on demand (unless all memory
2763 * is configured to be preallocated).
2764 *
2765 * @returns VBox status.
2766 * @param pVM VM Handle.
2767 * @param pDevIns The device instance owning the ROM.
2768 * @param GCPhys First physical address in the range.
2769 * Must be page aligned!
2770 * @param cb The size of the range (in bytes).
2771 * Must be page aligned!
2772 * @param pvBinary Pointer to the binary data backing the ROM image.
2773 * @param cbBinary The size of the binary data pvBinary points to.
2774 * This must be less or equal to @a cb.
2775 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
2776 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
2777 * @param pszDesc Pointer to description string. This must not be freed.
2778 *
2779 * @remark There is no way to remove the rom, automatically on device cleanup or
2780 * manually from the device yet. This isn't difficult in any way, it's
2781 * just not something we expect to be necessary for a while.
2782 */
2783VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
2784 const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
2785{
2786 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p cbBinary=%#x fFlags=%#x pszDesc=%s\n",
2787 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, cbBinary, fFlags, pszDesc));
2788
2789 /*
2790 * Validate input.
2791 */
2792 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2793 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
2794 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
2795 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2796 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2797 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
2798 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2799 AssertReturn(!(fFlags & ~(PGMPHYS_ROM_FLAGS_SHADOWED | PGMPHYS_ROM_FLAGS_PERMANENT_BINARY)), VERR_INVALID_PARAMETER);
2800 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
2801
2802 const uint32_t cPages = cb >> PAGE_SHIFT;
2803
2804 /*
2805 * Find the ROM location in the ROM list first.
2806 */
2807 PPGMROMRANGE pRomPrev = NULL;
2808 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
2809 while (pRom && GCPhysLast >= pRom->GCPhys)
2810 {
2811 if ( GCPhys <= pRom->GCPhysLast
2812 && GCPhysLast >= pRom->GCPhys)
2813 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
2814 GCPhys, GCPhysLast, pszDesc,
2815 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
2816 VERR_PGM_RAM_CONFLICT);
2817 /* next */
2818 pRomPrev = pRom;
2819 pRom = pRom->pNextR3;
2820 }
2821
2822 /*
2823 * Find the RAM location and check for conflicts.
2824 *
2825 * Conflict detection is a bit different than for RAM
2826 * registration since a ROM can be located within a RAM
2827 * range. So, what we have to check for is other memory
2828 * types (other than RAM that is) and that we don't span
2829 * more than one RAM range (layz).
2830 */
2831 bool fRamExists = false;
2832 PPGMRAMRANGE pRamPrev = NULL;
2833 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2834 while (pRam && GCPhysLast >= pRam->GCPhys)
2835 {
2836 if ( GCPhys <= pRam->GCPhysLast
2837 && GCPhysLast >= pRam->GCPhys)
2838 {
2839 /* completely within? */
2840 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
2841 && GCPhysLast <= pRam->GCPhysLast,
2842 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
2843 GCPhys, GCPhysLast, pszDesc,
2844 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2845 VERR_PGM_RAM_CONFLICT);
2846 fRamExists = true;
2847 break;
2848 }
2849
2850 /* next */
2851 pRamPrev = pRam;
2852 pRam = pRam->pNextR3;
2853 }
2854 if (fRamExists)
2855 {
2856 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2857 uint32_t cPagesLeft = cPages;
2858 while (cPagesLeft-- > 0)
2859 {
2860 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
2861 ("%RGp (%R[pgmpage]) isn't a RAM page - registering %RGp-%RGp (%s).\n",
2862 pRam->GCPhys + ((RTGCPHYS)(uintptr_t)(pPage - &pRam->aPages[0]) << PAGE_SHIFT),
2863 pPage, GCPhys, GCPhysLast, pszDesc), VERR_PGM_RAM_CONFLICT);
2864 Assert(PGM_PAGE_IS_ZERO(pPage));
2865 pPage++;
2866 }
2867 }
2868
2869 /*
2870 * Update the base memory reservation if necessary.
2871 */
2872 uint32_t cExtraBaseCost = fRamExists ? 0 : cPages;
2873 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
2874 cExtraBaseCost += cPages;
2875 if (cExtraBaseCost)
2876 {
2877 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
2878 if (RT_FAILURE(rc))
2879 return rc;
2880 }
2881
2882 /*
2883 * Allocate memory for the virgin copy of the RAM.
2884 */
2885 PGMMALLOCATEPAGESREQ pReq;
2886 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cPages, GMMACCOUNT_BASE);
2887 AssertRCReturn(rc, rc);
2888
2889 for (uint32_t iPage = 0; iPage < cPages; iPage++)
2890 {
2891 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << PAGE_SHIFT);
2892 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
2893 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
2894 }
2895
2896 pgmLock(pVM);
2897 rc = GMMR3AllocatePagesPerform(pVM, pReq);
2898 pgmUnlock(pVM);
2899 if (RT_FAILURE(rc))
2900 {
2901 GMMR3AllocatePagesCleanup(pReq);
2902 return rc;
2903 }
2904
2905 /*
2906 * Allocate the new ROM range and RAM range (if necessary).
2907 */
2908 PPGMROMRANGE pRomNew;
2909 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMROMRANGE, aPages[cPages]), 0, MM_TAG_PGM_PHYS, (void **)&pRomNew);
2910 if (RT_SUCCESS(rc))
2911 {
2912 PPGMRAMRANGE pRamNew = NULL;
2913 if (!fRamExists)
2914 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), sizeof(PGMPAGE), MM_TAG_PGM_PHYS, (void **)&pRamNew);
2915 if (RT_SUCCESS(rc))
2916 {
2917 pgmLock(pVM);
2918
2919 /*
2920 * Initialize and insert the RAM range (if required).
2921 */
2922 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
2923 if (!fRamExists)
2924 {
2925 pRamNew->pSelfR0 = MMHyperCCToR0(pVM, pRamNew);
2926 pRamNew->pSelfRC = MMHyperCCToRC(pVM, pRamNew);
2927 pRamNew->GCPhys = GCPhys;
2928 pRamNew->GCPhysLast = GCPhysLast;
2929 pRamNew->cb = cb;
2930 pRamNew->pszDesc = pszDesc;
2931 pRamNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_ROM;
2932 pRamNew->pvR3 = NULL;
2933 pRamNew->paLSPages = NULL;
2934
2935 PPGMPAGE pPage = &pRamNew->aPages[0];
2936 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
2937 {
2938 PGM_PAGE_INIT(pPage,
2939 pReq->aPages[iPage].HCPhysGCPhys,
2940 pReq->aPages[iPage].idPage,
2941 PGMPAGETYPE_ROM,
2942 PGM_PAGE_STATE_ALLOCATED);
2943
2944 pRomPage->Virgin = *pPage;
2945 }
2946
2947 pVM->pgm.s.cAllPages += cPages;
2948 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
2949 }
2950 else
2951 {
2952 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2953 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
2954 {
2955 PGM_PAGE_SET_TYPE(pPage, PGMPAGETYPE_ROM);
2956 PGM_PAGE_SET_HCPHYS(pPage, pReq->aPages[iPage].HCPhysGCPhys);
2957 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ALLOCATED);
2958 PGM_PAGE_SET_PAGEID(pPage, pReq->aPages[iPage].idPage);
2959 PGM_PAGE_SET_PDE_TYPE(pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
2960 PGM_PAGE_SET_PTE_INDEX(pPage, 0);
2961 PGM_PAGE_SET_TRACKING(pPage, 0);
2962
2963 pRomPage->Virgin = *pPage;
2964 }
2965
2966 pRamNew = pRam;
2967
2968 pVM->pgm.s.cZeroPages -= cPages;
2969 }
2970 pVM->pgm.s.cPrivatePages += cPages;
2971
2972 /* Flush physical page map TLB. */
2973 PGMPhysInvalidatePageMapTLB(pVM);
2974
2975 pgmUnlock(pVM);
2976
2977
2978 /*
2979 * !HACK ALERT! REM + (Shadowed) ROM ==> mess.
2980 *
2981 * If it's shadowed we'll register the handler after the ROM notification
2982 * so we get the access handler callbacks that we should. If it isn't
2983 * shadowed we'll do it the other way around to make REM use the built-in
2984 * ROM behavior and not the handler behavior (which is to route all access
2985 * to PGM atm).
2986 */
2987 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
2988 {
2989 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, true /* fShadowed */);
2990 rc = PGMR3HandlerPhysicalRegister(pVM,
2991 fFlags & PGMPHYS_ROM_FLAGS_SHADOWED
2992 ? PGMPHYSHANDLERTYPE_PHYSICAL_ALL
2993 : PGMPHYSHANDLERTYPE_PHYSICAL_WRITE,
2994 GCPhys, GCPhysLast,
2995 pgmR3PhysRomWriteHandler, pRomNew,
2996 NULL, "pgmPhysRomWriteHandler", MMHyperCCToR0(pVM, pRomNew),
2997 NULL, "pgmPhysRomWriteHandler", MMHyperCCToRC(pVM, pRomNew), pszDesc);
2998 }
2999 else
3000 {
3001 rc = PGMR3HandlerPhysicalRegister(pVM,
3002 fFlags & PGMPHYS_ROM_FLAGS_SHADOWED
3003 ? PGMPHYSHANDLERTYPE_PHYSICAL_ALL
3004 : PGMPHYSHANDLERTYPE_PHYSICAL_WRITE,
3005 GCPhys, GCPhysLast,
3006 pgmR3PhysRomWriteHandler, pRomNew,
3007 NULL, "pgmPhysRomWriteHandler", MMHyperCCToR0(pVM, pRomNew),
3008 NULL, "pgmPhysRomWriteHandler", MMHyperCCToRC(pVM, pRomNew), pszDesc);
3009 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, false /* fShadowed */);
3010 }
3011 if (RT_SUCCESS(rc))
3012 {
3013 pgmLock(pVM);
3014
3015 /*
3016 * Copy the image over to the virgin pages.
3017 * This must be done after linking in the RAM range.
3018 */
3019 size_t cbBinaryLeft = cbBinary;
3020 PPGMPAGE pRamPage = &pRamNew->aPages[(GCPhys - pRamNew->GCPhys) >> PAGE_SHIFT];
3021 for (uint32_t iPage = 0; iPage < cPages; iPage++, pRamPage++)
3022 {
3023 void *pvDstPage;
3024 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << PAGE_SHIFT), &pvDstPage);
3025 if (RT_FAILURE(rc))
3026 {
3027 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
3028 break;
3029 }
3030 if (cbBinaryLeft >= PAGE_SIZE)
3031 {
3032 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), PAGE_SIZE);
3033 cbBinaryLeft -= PAGE_SIZE;
3034 }
3035 else
3036 {
3037 ASMMemZeroPage(pvDstPage); /* (shouldn't be necessary, but can't hurt either) */
3038 if (cbBinaryLeft > 0)
3039 {
3040 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), cbBinaryLeft);
3041 cbBinaryLeft = 0;
3042 }
3043 }
3044 }
3045 if (RT_SUCCESS(rc))
3046 {
3047 /*
3048 * Initialize the ROM range.
3049 * Note that the Virgin member of the pages has already been initialized above.
3050 */
3051 pRomNew->GCPhys = GCPhys;
3052 pRomNew->GCPhysLast = GCPhysLast;
3053 pRomNew->cb = cb;
3054 pRomNew->fFlags = fFlags;
3055 pRomNew->idSavedState = UINT8_MAX;
3056 pRomNew->cbOriginal = cbBinary;
3057#ifdef VBOX_STRICT
3058 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY
3059 ? pvBinary : RTMemDup(pvBinary, cbBinary);
3060#else
3061 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY ? pvBinary : NULL;
3062#endif
3063 pRomNew->pszDesc = pszDesc;
3064
3065 for (unsigned iPage = 0; iPage < cPages; iPage++)
3066 {
3067 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
3068 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
3069 PGM_PAGE_INIT_ZERO(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
3070 }
3071
3072 /* update the page count stats for the shadow pages. */
3073 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3074 {
3075 pVM->pgm.s.cZeroPages += cPages;
3076 pVM->pgm.s.cAllPages += cPages;
3077 }
3078
3079 /*
3080 * Insert the ROM range, tell REM and return successfully.
3081 */
3082 pRomNew->pNextR3 = pRom;
3083 pRomNew->pNextR0 = pRom ? MMHyperCCToR0(pVM, pRom) : NIL_RTR0PTR;
3084 pRomNew->pNextRC = pRom ? MMHyperCCToRC(pVM, pRom) : NIL_RTRCPTR;
3085
3086 if (pRomPrev)
3087 {
3088 pRomPrev->pNextR3 = pRomNew;
3089 pRomPrev->pNextR0 = MMHyperCCToR0(pVM, pRomNew);
3090 pRomPrev->pNextRC = MMHyperCCToRC(pVM, pRomNew);
3091 }
3092 else
3093 {
3094 pVM->pgm.s.pRomRangesR3 = pRomNew;
3095 pVM->pgm.s.pRomRangesR0 = MMHyperCCToR0(pVM, pRomNew);
3096 pVM->pgm.s.pRomRangesRC = MMHyperCCToRC(pVM, pRomNew);
3097 }
3098
3099 PGMPhysInvalidatePageMapTLB(pVM);
3100 GMMR3AllocatePagesCleanup(pReq);
3101 pgmUnlock(pVM);
3102 return VINF_SUCCESS;
3103 }
3104
3105 /* bail out */
3106
3107 pgmUnlock(pVM);
3108 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
3109 AssertRC(rc2);
3110 pgmLock(pVM);
3111 }
3112
3113 if (!fRamExists)
3114 {
3115 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
3116 MMHyperFree(pVM, pRamNew);
3117 }
3118 }
3119 MMHyperFree(pVM, pRomNew);
3120 }
3121
3122 /** @todo Purge the mapping cache or something... */
3123 GMMR3FreeAllocatedPages(pVM, pReq);
3124 GMMR3AllocatePagesCleanup(pReq);
3125 pgmUnlock(pVM);
3126 return rc;
3127}
3128
3129
3130/**
3131 * \#PF Handler callback for ROM write accesses.
3132 *
3133 * @returns VINF_SUCCESS if the handler have carried out the operation.
3134 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
3135 * @param pVM VM Handle.
3136 * @param GCPhys The physical address the guest is writing to.
3137 * @param pvPhys The HC mapping of that address.
3138 * @param pvBuf What the guest is reading/writing.
3139 * @param cbBuf How much it's reading/writing.
3140 * @param enmAccessType The access type.
3141 * @param pvUser User argument.
3142 */
3143static DECLCALLBACK(int) pgmR3PhysRomWriteHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf,
3144 PGMACCESSTYPE enmAccessType, void *pvUser)
3145{
3146 PPGMROMRANGE pRom = (PPGMROMRANGE)pvUser;
3147 const uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
3148 Assert(iPage < (pRom->cb >> PAGE_SHIFT));
3149 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
3150 Log5(("pgmR3PhysRomWriteHandler: %d %c %#08RGp %#04zx\n", pRomPage->enmProt, enmAccessType == PGMACCESSTYPE_READ ? 'R' : 'W', GCPhys, cbBuf));
3151
3152 if (enmAccessType == PGMACCESSTYPE_READ)
3153 {
3154 switch (pRomPage->enmProt)
3155 {
3156 /*
3157 * Take the default action.
3158 */
3159 case PGMROMPROT_READ_ROM_WRITE_IGNORE:
3160 case PGMROMPROT_READ_RAM_WRITE_IGNORE:
3161 case PGMROMPROT_READ_ROM_WRITE_RAM:
3162 case PGMROMPROT_READ_RAM_WRITE_RAM:
3163 return VINF_PGM_HANDLER_DO_DEFAULT;
3164
3165 default:
3166 AssertMsgFailedReturn(("enmProt=%d iPage=%d GCPhys=%RGp\n",
3167 pRom->aPages[iPage].enmProt, iPage, GCPhys),
3168 VERR_INTERNAL_ERROR);
3169 }
3170 }
3171 else
3172 {
3173 Assert(enmAccessType == PGMACCESSTYPE_WRITE);
3174 switch (pRomPage->enmProt)
3175 {
3176 /*
3177 * Ignore writes.
3178 */
3179 case PGMROMPROT_READ_ROM_WRITE_IGNORE:
3180 case PGMROMPROT_READ_RAM_WRITE_IGNORE:
3181 return VINF_SUCCESS;
3182
3183 /*
3184 * Write to the RAM page.
3185 */
3186 case PGMROMPROT_READ_ROM_WRITE_RAM:
3187 case PGMROMPROT_READ_RAM_WRITE_RAM: /* yes this will get here too, it's *way* simpler that way. */
3188 {
3189 /* This should be impossible now, pvPhys doesn't work cross page anylonger. */
3190 Assert(((GCPhys - pRom->GCPhys + cbBuf - 1) >> PAGE_SHIFT) == iPage);
3191
3192 /*
3193 * Take the lock, do lazy allocation, map the page and copy the data.
3194 *
3195 * Note that we have to bypass the mapping TLB since it works on
3196 * guest physical addresses and entering the shadow page would
3197 * kind of screw things up...
3198 */
3199 int rc = pgmLock(pVM);
3200 AssertRC(rc);
3201
3202 PPGMPAGE pShadowPage = &pRomPage->Shadow;
3203 if (!PGMROMPROT_IS_ROM(pRomPage->enmProt))
3204 {
3205 pShadowPage = pgmPhysGetPage(&pVM->pgm.s, GCPhys);
3206 AssertLogRelReturn(pShadowPage, VERR_INTERNAL_ERROR);
3207 }
3208
3209 void *pvDstPage;
3210 rc = pgmPhysPageMakeWritableAndMap(pVM, pShadowPage, GCPhys & X86_PTE_PG_MASK, &pvDstPage);
3211 if (RT_SUCCESS(rc))
3212 {
3213 memcpy((uint8_t *)pvDstPage + (GCPhys & PAGE_OFFSET_MASK), pvBuf, cbBuf);
3214 pRomPage->LiveSave.fWrittenTo = true;
3215 }
3216
3217 pgmUnlock(pVM);
3218 return rc;
3219 }
3220
3221 default:
3222 AssertMsgFailedReturn(("enmProt=%d iPage=%d GCPhys=%RGp\n",
3223 pRom->aPages[iPage].enmProt, iPage, GCPhys),
3224 VERR_INTERNAL_ERROR);
3225 }
3226 }
3227}
3228
3229
3230/**
3231 * Called by PGMR3Reset to reset the shadow, switch to the virgin,
3232 * and verify that the virgin part is untouched.
3233 *
3234 * This is done after the normal memory has been cleared.
3235 *
3236 * ASSUMES that the caller owns the PGM lock.
3237 *
3238 * @param pVM The VM handle.
3239 */
3240int pgmR3PhysRomReset(PVM pVM)
3241{
3242 Assert(PGMIsLockOwner(pVM));
3243 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3244 {
3245 const uint32_t cPages = pRom->cb >> PAGE_SHIFT;
3246
3247 if (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3248 {
3249 /*
3250 * Reset the physical handler.
3251 */
3252 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
3253 AssertRCReturn(rc, rc);
3254
3255 /*
3256 * What we do with the shadow pages depends on the memory
3257 * preallocation option. If not enabled, we'll just throw
3258 * out all the dirty pages and replace them by the zero page.
3259 */
3260 if (!pVM->pgm.s.fRamPreAlloc)
3261 {
3262 /* Free the dirty pages. */
3263 uint32_t cPendingPages = 0;
3264 PGMMFREEPAGESREQ pReq;
3265 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
3266 AssertRCReturn(rc, rc);
3267
3268 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3269 if ( !PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow)
3270 && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow))
3271 {
3272 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
3273 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, &pRom->aPages[iPage].Shadow,
3274 pRom->GCPhys + (iPage << PAGE_SHIFT));
3275 AssertLogRelRCReturn(rc, rc);
3276 }
3277
3278 if (cPendingPages)
3279 {
3280 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
3281 AssertLogRelRCReturn(rc, rc);
3282 }
3283 GMMR3FreePagesCleanup(pReq);
3284 }
3285 else
3286 {
3287 /* clear all the shadow pages. */
3288 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3289 {
3290 if (PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow))
3291 continue;
3292 Assert(!PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow));
3293 void *pvDstPage;
3294 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
3295 rc = pgmPhysPageMakeWritableAndMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pvDstPage);
3296 if (RT_FAILURE(rc))
3297 break;
3298 ASMMemZeroPage(pvDstPage);
3299 }
3300 AssertRCReturn(rc, rc);
3301 }
3302 }
3303
3304#ifdef VBOX_STRICT
3305 /*
3306 * Verify that the virgin page is unchanged if possible.
3307 */
3308 if (pRom->pvOriginal)
3309 {
3310 size_t cbSrcLeft = pRom->cbOriginal;
3311 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
3312 for (uint32_t iPage = 0; iPage < cPages && cbSrcLeft > 0; iPage++, pbSrcPage += PAGE_SIZE)
3313 {
3314 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
3315 void const *pvDstPage;
3316 int rc = pgmPhysPageMapReadOnly(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPage);
3317 if (RT_FAILURE(rc))
3318 break;
3319
3320 if (memcmp(pvDstPage, pbSrcPage, RT_MIN(cbSrcLeft, PAGE_SIZE)))
3321 LogRel(("pgmR3PhysRomReset: %RGp rom page changed (%s) - loaded saved state?\n",
3322 GCPhys, pRom->pszDesc));
3323 cbSrcLeft -= RT_MIN(cbSrcLeft, PAGE_SIZE);
3324 }
3325 }
3326#endif
3327 }
3328
3329 return VINF_SUCCESS;
3330}
3331
3332
3333/**
3334 * Called by PGMR3Term to free resources.
3335 *
3336 * ASSUMES that the caller owns the PGM lock.
3337 *
3338 * @param pVM The VM handle.
3339 */
3340void pgmR3PhysRomTerm(PVM pVM)
3341{
3342#ifdef RT_STRICT
3343 /*
3344 * Free the heap copy of the original bits.
3345 */
3346 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3347 {
3348 if ( pRom->pvOriginal
3349 && !(pRom->fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY))
3350 {
3351 RTMemFree((void *)pRom->pvOriginal);
3352 pRom->pvOriginal = NULL;
3353 }
3354 }
3355#endif
3356}
3357
3358
3359/**
3360 * Change the shadowing of a range of ROM pages.
3361 *
3362 * This is intended for implementing chipset specific memory registers
3363 * and will not be very strict about the input. It will silently ignore
3364 * any pages that are not the part of a shadowed ROM.
3365 *
3366 * @returns VBox status code.
3367 * @retval VINF_PGM_SYNC_CR3
3368 *
3369 * @param pVM Pointer to the shared VM structure.
3370 * @param GCPhys Where to start. Page aligned.
3371 * @param cb How much to change. Page aligned.
3372 * @param enmProt The new ROM protection.
3373 */
3374VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
3375{
3376 /*
3377 * Check input
3378 */
3379 if (!cb)
3380 return VINF_SUCCESS;
3381 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3382 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3383 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
3384 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3385 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
3386
3387 /*
3388 * Process the request.
3389 */
3390 pgmLock(pVM);
3391 int rc = VINF_SUCCESS;
3392 bool fFlushTLB = false;
3393 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3394 {
3395 if ( GCPhys <= pRom->GCPhysLast
3396 && GCPhysLast >= pRom->GCPhys
3397 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
3398 {
3399 /*
3400 * Iterate the relevant pages and make necessary the changes.
3401 */
3402 bool fChanges = false;
3403 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
3404 ? pRom->cb >> PAGE_SHIFT
3405 : (GCPhysLast - pRom->GCPhys + 1) >> PAGE_SHIFT;
3406 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
3407 iPage < cPages;
3408 iPage++)
3409 {
3410 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
3411 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
3412 {
3413 fChanges = true;
3414
3415 /* flush references to the page. */
3416 PPGMPAGE pRamPage = pgmPhysGetPage(&pVM->pgm.s, pRom->GCPhys + (iPage << PAGE_SHIFT));
3417 int rc2 = pgmPoolTrackUpdateGCPhys(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT), pRamPage,
3418 true /*fFlushPTEs*/, &fFlushTLB);
3419 if (rc2 != VINF_SUCCESS && (rc == VINF_SUCCESS || RT_FAILURE(rc2)))
3420 rc = rc2;
3421
3422 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
3423 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
3424
3425 *pOld = *pRamPage;
3426 *pRamPage = *pNew;
3427 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
3428 }
3429 pRomPage->enmProt = enmProt;
3430 }
3431
3432 /*
3433 * Reset the access handler if we made changes, no need
3434 * to optimize this.
3435 */
3436 if (fChanges)
3437 {
3438 int rc2 = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
3439 if (RT_FAILURE(rc2))
3440 {
3441 pgmUnlock(pVM);
3442 AssertRC(rc);
3443 return rc2;
3444 }
3445 }
3446
3447 /* Advance - cb isn't updated. */
3448 GCPhys = pRom->GCPhys + (cPages << PAGE_SHIFT);
3449 }
3450 }
3451 pgmUnlock(pVM);
3452 if (fFlushTLB)
3453 PGM_INVL_ALL_VCPU_TLBS(pVM);
3454
3455 return rc;
3456}
3457
3458
3459/**
3460 * Sets the Address Gate 20 state.
3461 *
3462 * @param pVCpu The VCPU to operate on.
3463 * @param fEnable True if the gate should be enabled.
3464 * False if the gate should be disabled.
3465 */
3466VMMDECL(void) PGMR3PhysSetA20(PVMCPU pVCpu, bool fEnable)
3467{
3468 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVCpu->pgm.s.fA20Enabled));
3469 if (pVCpu->pgm.s.fA20Enabled != fEnable)
3470 {
3471 pVCpu->pgm.s.fA20Enabled = fEnable;
3472 pVCpu->pgm.s.GCPhysA20Mask = ~(RTGCPHYS)(!fEnable << 20);
3473 REMR3A20Set(pVCpu->pVMR3, pVCpu, fEnable);
3474 /** @todo we're not handling this correctly for VT-x / AMD-V. See #2911 */
3475 }
3476}
3477
3478#ifdef PGM_WITH_LARGE_ADDRESS_SPACE_ON_32_BIT_HOST
3479/**
3480 * Tree enumeration callback for dealing with age rollover.
3481 * It will perform a simple compression of the current age.
3482 */
3483static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
3484{
3485 Assert(PGMIsLockOwner((PVM)pvUser));
3486 /* Age compression - ASSUMES iNow == 4. */
3487 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3488 if (pChunk->iAge >= UINT32_C(0xffffff00))
3489 pChunk->iAge = 3;
3490 else if (pChunk->iAge >= UINT32_C(0xfffff000))
3491 pChunk->iAge = 2;
3492 else if (pChunk->iAge)
3493 pChunk->iAge = 1;
3494 else /* iAge = 0 */
3495 pChunk->iAge = 4;
3496 return 0;
3497}
3498
3499
3500/**
3501 * Tree enumeration callback that updates the chunks that have
3502 * been used since the last
3503 */
3504static DECLCALLBACK(int) pgmR3PhysChunkAgeingCallback(PAVLU32NODECORE pNode, void *pvUser)
3505{
3506 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3507 if (!pChunk->iAge)
3508 {
3509 PVM pVM = (PVM)pvUser;
3510 pChunk->iAge = pVM->pgm.s.ChunkR3Map.iNow;
3511 }
3512 return 0;
3513}
3514
3515
3516/**
3517 * Performs ageing of the ring-3 chunk mappings.
3518 *
3519 * @param pVM The VM handle.
3520 */
3521VMMR3DECL(void) PGMR3PhysChunkAgeing(PVM pVM)
3522{
3523 pgmLock(pVM);
3524 pVM->pgm.s.ChunkR3Map.AgeingCountdown = RT_MIN(pVM->pgm.s.ChunkR3Map.cMax / 4, 1024);
3525 pVM->pgm.s.ChunkR3Map.iNow++;
3526 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
3527 {
3528 pVM->pgm.s.ChunkR3Map.iNow = 4;
3529 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, pVM);
3530 }
3531 else
3532 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingCallback, pVM);
3533 pgmUnlock(pVM);
3534}
3535
3536
3537/**
3538 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
3539 */
3540typedef struct PGMR3PHYSCHUNKUNMAPCB
3541{
3542 PVM pVM; /**< The VM handle. */
3543 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
3544 uint32_t iLastAge; /**< Highest age found so far. */
3545} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
3546
3547
3548/**
3549 * Callback used to find the mapping that's been unused for
3550 * the longest time.
3551 */
3552static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLU32NODECORE pNode, void *pvUser)
3553{
3554 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3555 PPGMR3PHYSCHUNKUNMAPCB pArg = (PPGMR3PHYSCHUNKUNMAPCB)pvUser;
3556
3557 if ( pChunk->iAge
3558 && !pChunk->cRefs
3559 && pArg->iLastAge < pChunk->iAge)
3560 {
3561 /*
3562 * Check that it's not in any of the TLBs.
3563 */
3564 PVM pVM = pArg->pVM;
3565 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
3566 if (pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk == pChunk)
3567 {
3568 pChunk = NULL;
3569 break;
3570 }
3571 if (pChunk)
3572 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbHC.aEntries); i++)
3573 if (pVM->pgm.s.PhysTlbHC.aEntries[i].pMap == pChunk)
3574 {
3575 pChunk = NULL;
3576 break;
3577 }
3578 if (pChunk)
3579 {
3580 pArg->pChunk = pChunk;
3581 pArg->iLastAge = pChunk->iAge;
3582 }
3583 }
3584 return 0;
3585}
3586
3587
3588/**
3589 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
3590 *
3591 * The candidate will not be part of any TLBs, so no need to flush
3592 * anything afterwards.
3593 *
3594 * @returns Chunk id.
3595 * @param pVM The VM handle.
3596 */
3597static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
3598{
3599 Assert(PGMIsLockOwner(pVM));
3600
3601 /*
3602 * Do tree ageing first?
3603 */
3604 if (pVM->pgm.s.ChunkR3Map.AgeingCountdown-- == 0)
3605 {
3606 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkAging, a);
3607 PGMR3PhysChunkAgeing(pVM);
3608 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkAging, a);
3609 }
3610
3611 /*
3612 * Enumerate the age tree starting with the left most node.
3613 */
3614 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3615 PGMR3PHYSCHUNKUNMAPCB Args;
3616 Args.pVM = pVM;
3617 Args.pChunk = NULL;
3618 Args.iLastAge = 0;
3619 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, &Args);
3620 Assert(Args.pChunk);
3621 if (Args.pChunk)
3622 {
3623 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3624 return Args.pChunk->Core.Key;
3625 }
3626
3627 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3628 return INT32_MAX;
3629}
3630
3631/**
3632 * Rendezvous callback used by pgmR3PhysUnmapChunk that unmaps a chunk
3633 *
3634 * This is only called on one of the EMTs while the other ones are waiting for
3635 * it to complete this function.
3636 *
3637 * @returns VINF_SUCCESS (VBox strict status code).
3638 * @param pVM The VM handle.
3639 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
3640 * @param pvUser User pointer. Unused
3641 *
3642 */
3643DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysUnmapChunkRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
3644{
3645 int rc = VINF_SUCCESS;
3646 pgmLock(pVM);
3647
3648 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
3649 {
3650 /* Flush the pgm pool cache; call the internal rendezvous handler as we're already in a rendezvous handler here. */
3651 /* todo: also not really efficient to unmap a chunk that contains PD or PT pages. */
3652 pgmR3PoolClearAllRendezvous(pVM, &pVM->aCpus[0], NULL /* no need to flush the REM TLB as we already did that above */);
3653
3654 /*
3655 * Request the ring-0 part to unmap a chunk to make space in the mapping cache.
3656 */
3657 GMMMAPUNMAPCHUNKREQ Req;
3658 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
3659 Req.Hdr.cbReq = sizeof(Req);
3660 Req.pvR3 = NULL;
3661 Req.idChunkMap = NIL_GMM_CHUNKID;
3662 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
3663
3664 if (Req.idChunkUnmap != INT32_MAX)
3665 {
3666 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
3667 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
3668 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
3669 if (RT_SUCCESS(rc))
3670 {
3671 /* remove the unmapped one. */
3672 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
3673 AssertRelease(pUnmappedChunk);
3674 pUnmappedChunk->pv = NULL;
3675 pUnmappedChunk->Core.Key = UINT32_MAX;
3676#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3677 MMR3HeapFree(pUnmappedChunk);
3678#else
3679 MMR3UkHeapFree(pVM, pUnmappedChunk, MM_TAG_PGM_CHUNK_MAPPING);
3680#endif
3681 pVM->pgm.s.ChunkR3Map.c--;
3682 pVM->pgm.s.cUnmappedChunks++;
3683
3684 /* Flush dangling PGM pointers (R3 & R0 ptrs to GC physical addresses) */
3685 /* todo: we should not flush chunks which include cr3 mappings. */
3686 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
3687 {
3688 PPGMCPU pPGM = &pVM->aCpus[idCpu].pgm.s;
3689
3690 pPGM->pGst32BitPdR3 = NULL;
3691 pPGM->pGstPaePdptR3 = NULL;
3692 pPGM->pGstAmd64Pml4R3 = NULL;
3693#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
3694 pPGM->pGst32BitPdR0 = NIL_RTR0PTR;
3695 pPGM->pGstPaePdptR0 = NIL_RTR0PTR;
3696 pPGM->pGstAmd64Pml4R0 = NIL_RTR0PTR;
3697#endif
3698 for (unsigned i = 0; i < RT_ELEMENTS(pPGM->apGstPaePDsR3); i++)
3699 {
3700 pPGM->apGstPaePDsR3[i] = NULL;
3701#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
3702 pPGM->apGstPaePDsR0[i] = NIL_RTR0PTR;
3703#endif
3704 }
3705
3706 /* Flush REM TLBs. */
3707 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
3708 }
3709
3710 /* Flush REM translation blocks. */
3711 REMFlushTBs(pVM);
3712 }
3713 }
3714 }
3715 pgmUnlock(pVM);
3716 return rc;
3717}
3718
3719/**
3720 * Unmap a chunk to free up virtual address space (request packet handler for pgmR3PhysChunkMap)
3721 *
3722 * @returns VBox status code.
3723 * @param pVM The VM to operate on.
3724 */
3725void pgmR3PhysUnmapChunk(PVM pVM)
3726{
3727 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysUnmapChunkRendezvous, NULL);
3728 AssertRC(rc);
3729}
3730#endif /* PGM_WITH_LARGE_ADDRESS_SPACE_ON_32_BIT_HOST */
3731
3732/**
3733 * Maps the given chunk into the ring-3 mapping cache.
3734 *
3735 * This will call ring-0.
3736 *
3737 * @returns VBox status code.
3738 * @param pVM The VM handle.
3739 * @param idChunk The chunk in question.
3740 * @param ppChunk Where to store the chunk tracking structure.
3741 *
3742 * @remarks Called from within the PGM critical section.
3743 * @remarks Can be called from any thread!
3744 */
3745int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
3746{
3747 int rc;
3748
3749 Assert(PGMIsLockOwner(pVM));
3750 /*
3751 * Allocate a new tracking structure first.
3752 */
3753#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3754 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
3755#else
3756 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3UkHeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk), NULL);
3757#endif
3758 AssertReturn(pChunk, VERR_NO_MEMORY);
3759 pChunk->Core.Key = idChunk;
3760
3761 /*
3762 * Request the ring-0 part to map the chunk in question.
3763 */
3764 GMMMAPUNMAPCHUNKREQ Req;
3765 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
3766 Req.Hdr.cbReq = sizeof(Req);
3767 Req.pvR3 = NULL;
3768 Req.idChunkMap = idChunk;
3769 Req.idChunkUnmap = NIL_GMM_CHUNKID;
3770
3771 /* Must be callable from any thread, so can't use VMMR3CallR0. */
3772 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
3773 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, NIL_VMCPUID, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
3774 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
3775 if (RT_SUCCESS(rc))
3776 {
3777 /*
3778 * Update the tree.
3779 */
3780 /* insert the new one. */
3781 AssertPtr(Req.pvR3);
3782 pChunk->pv = Req.pvR3;
3783 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
3784 AssertRelease(fRc);
3785 pVM->pgm.s.ChunkR3Map.c++;
3786 pVM->pgm.s.cMappedChunks++;
3787
3788 /* If we're running out of virtual address space, then we should unmap another chunk. */
3789 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
3790 {
3791#ifdef PGM_WITH_LARGE_ADDRESS_SPACE_ON_32_BIT_HOST
3792 /* Postpone the unmap operation (which requires a rendezvous operation) as we own the PGM lock here. */
3793 rc = VMR3ReqCallNoWaitU(pVM->pUVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysUnmapChunk, 1, pVM);
3794 AssertRC(rc);
3795#else
3796 AssertFatalFailed(); /* can't happen */
3797#endif
3798 }
3799 }
3800 else
3801 {
3802 AssertRC(rc);
3803#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3804 MMR3HeapFree(pChunk);
3805#else
3806 MMR3UkHeapFree(pVM, pChunk, MM_TAG_PGM_CHUNK_MAPPING);
3807#endif
3808 pChunk = NULL;
3809 }
3810
3811 *ppChunk = pChunk;
3812 return rc;
3813}
3814
3815
3816/**
3817 * For VMMCALLRING3_PGM_MAP_CHUNK, considered internal.
3818 *
3819 * @returns see pgmR3PhysChunkMap.
3820 * @param pVM The VM handle.
3821 * @param idChunk The chunk to map.
3822 */
3823VMMR3DECL(int) PGMR3PhysChunkMap(PVM pVM, uint32_t idChunk)
3824{
3825 PPGMCHUNKR3MAP pChunk;
3826 int rc;
3827
3828 pgmLock(pVM);
3829 rc = pgmR3PhysChunkMap(pVM, idChunk, &pChunk);
3830 pgmUnlock(pVM);
3831 return rc;
3832}
3833
3834
3835/**
3836 * Invalidates the TLB for the ring-3 mapping cache.
3837 *
3838 * @param pVM The VM handle.
3839 */
3840VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
3841{
3842 pgmLock(pVM);
3843 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
3844 {
3845 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
3846 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
3847 }
3848 /* The page map TLB references chunks, so invalidate that one too. */
3849 PGMPhysInvalidatePageMapTLB(pVM);
3850 pgmUnlock(pVM);
3851}
3852
3853
3854/**
3855 * Response to VMMCALLRING3_PGM_ALLOCATE_LARGE_PAGE to allocate a large (2MB) page
3856 * for use with a nested paging PDE.
3857 *
3858 * @returns The following VBox status codes.
3859 * @retval VINF_SUCCESS on success.
3860 * @retval VINF_EM_NO_MEMORY if we're out of memory.
3861 *
3862 * @param pVM The VM handle.
3863 * @param GCPhys GC physical start address of the 2 MB range
3864 */
3865VMMR3DECL(int) PGMR3PhysAllocateLargeHandyPage(PVM pVM, RTGCPHYS GCPhys)
3866{
3867#ifdef PGM_WITH_LARGE_PAGES
3868 uint64_t u64TimeStamp1, u64TimeStamp2;
3869
3870 pgmLock(pVM);
3871
3872 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
3873 u64TimeStamp1 = RTTimeMilliTS();
3874 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_LARGE_HANDY_PAGE, 0, NULL);
3875 u64TimeStamp2 = RTTimeMilliTS();
3876 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
3877 if (RT_SUCCESS(rc))
3878 {
3879 Assert(pVM->pgm.s.cLargeHandyPages == 1);
3880
3881 uint32_t idPage = pVM->pgm.s.aLargeHandyPage[0].idPage;
3882 RTHCPHYS HCPhys = pVM->pgm.s.aLargeHandyPage[0].HCPhysGCPhys;
3883
3884 void *pv;
3885
3886 /* Map the large page into our address space.
3887 *
3888 * Note: assuming that within the 2 MB range:
3889 * - GCPhys + PAGE_SIZE = HCPhys + PAGE_SIZE (whole point of this exercise)
3890 * - user space mapping is continuous as well
3891 * - page id (GCPhys) + 1 = page id (GCPhys + PAGE_SIZE)
3892 */
3893 rc = pgmPhysPageMapByPageID(pVM, idPage, HCPhys, &pv);
3894 AssertLogRelMsg(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n", idPage, HCPhys, rc));
3895
3896 if (RT_SUCCESS(rc))
3897 {
3898 /*
3899 * Clear the pages.
3900 */
3901 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
3902 for (unsigned i = 0; i < _2M/PAGE_SIZE; i++)
3903 {
3904 ASMMemZeroPage(pv);
3905
3906 PPGMPAGE pPage;
3907 rc = pgmPhysGetPageEx(&pVM->pgm.s, GCPhys, &pPage);
3908 AssertRC(rc);
3909
3910 Assert(PGM_PAGE_IS_ZERO(pPage));
3911 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatRZPageReplaceZero);
3912 pVM->pgm.s.cZeroPages--;
3913
3914 /*
3915 * Do the PGMPAGE modifications.
3916 */
3917 pVM->pgm.s.cPrivatePages++;
3918 PGM_PAGE_SET_HCPHYS(pPage, HCPhys);
3919 PGM_PAGE_SET_PAGEID(pPage, idPage);
3920 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ALLOCATED);
3921 PGM_PAGE_SET_PDE_TYPE(pPage, PGM_PAGE_PDE_TYPE_PDE);
3922 PGM_PAGE_SET_PTE_INDEX(pPage, 0);
3923 PGM_PAGE_SET_TRACKING(pPage, 0);
3924
3925 /* Somewhat dirty assumption that page ids are increasing. */
3926 idPage++;
3927
3928 HCPhys += PAGE_SIZE;
3929 GCPhys += PAGE_SIZE;
3930
3931 pv = (void *)((uintptr_t)pv + PAGE_SIZE);
3932
3933 Log3(("PGMR3PhysAllocateLargePage: idPage=%#x HCPhys=%RGp\n", idPage, HCPhys));
3934 }
3935 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
3936
3937 /* Flush all TLBs. */
3938 PGM_INVL_ALL_VCPU_TLBS(pVM);
3939 PGMPhysInvalidatePageMapTLB(pVM);
3940 }
3941 pVM->pgm.s.cLargeHandyPages = 0;
3942 }
3943
3944 if (RT_SUCCESS(rc))
3945 {
3946 static uint32_t cTimeOut = 0;
3947 uint64_t u64TimeStampDelta = u64TimeStamp2 - u64TimeStamp1;
3948
3949 if (u64TimeStampDelta > 100)
3950 {
3951 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatLargePageOverflow);
3952 if ( ++cTimeOut > 10
3953 || u64TimeStampDelta > 1000 /* more than one second forces an early retirement from allocating large pages. */)
3954 {
3955 /* If repeated attempts to allocate a large page takes more than 100 ms, then we fall back to normal 4k pages.
3956 * E.g. Vista 64 tries to move memory around, which takes a huge amount of time.
3957 */
3958 LogRel(("PGMR3PhysAllocateLargePage: allocating large pages takes too long (last attempt %d ms; nr of timeouts %d); DISABLE\n", u64TimeStampDelta, cTimeOut));
3959 PGMSetLargePageUsage(pVM, false);
3960 }
3961 }
3962 else
3963 if (cTimeOut > 0)
3964 cTimeOut--;
3965 }
3966
3967 pgmUnlock(pVM);
3968 return rc;
3969#else
3970 return VERR_NOT_IMPLEMENTED;
3971#endif /* PGM_WITH_LARGE_PAGES */
3972}
3973
3974
3975/**
3976 * Response to VM_FF_PGM_NEED_HANDY_PAGES and VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES.
3977 *
3978 * This function will also work the VM_FF_PGM_NO_MEMORY force action flag, to
3979 * signal and clear the out of memory condition. When contracted, this API is
3980 * used to try clear the condition when the user wants to resume.
3981 *
3982 * @returns The following VBox status codes.
3983 * @retval VINF_SUCCESS on success. FFs cleared.
3984 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in
3985 * this case and it gets accompanied by VM_FF_PGM_NO_MEMORY.
3986 *
3987 * @param pVM The VM handle.
3988 *
3989 * @remarks The VINF_EM_NO_MEMORY status is for the benefit of the FF processing
3990 * in EM.cpp and shouldn't be propagated outside TRPM, HWACCM, EM and
3991 * pgmPhysEnsureHandyPage. There is one exception to this in the \#PF
3992 * handler.
3993 */
3994VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
3995{
3996 pgmLock(pVM);
3997
3998 /*
3999 * Allocate more pages, noting down the index of the first new page.
4000 */
4001 uint32_t iClear = pVM->pgm.s.cHandyPages;
4002 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_INTERNAL_ERROR);
4003 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
4004 int rcAlloc = VINF_SUCCESS;
4005 int rcSeed = VINF_SUCCESS;
4006 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
4007 while (rc == VERR_GMM_SEED_ME)
4008 {
4009 void *pvChunk;
4010 rcAlloc = rc = SUPR3PageAlloc(GMM_CHUNK_SIZE >> PAGE_SHIFT, &pvChunk);
4011 if (RT_SUCCESS(rc))
4012 {
4013 rcSeed = rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_SEED_CHUNK, (uintptr_t)pvChunk, NULL);
4014 if (RT_FAILURE(rc))
4015 SUPR3PageFree(pvChunk, GMM_CHUNK_SIZE >> PAGE_SHIFT);
4016 }
4017 if (RT_SUCCESS(rc))
4018 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
4019 }
4020
4021 /* 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) */
4022 if ( rc == VERR_GMM_HIT_VM_ACCOUNT_LIMIT
4023 && pVM->pgm.s.cHandyPages > 0)
4024 {
4025 /* Still handy pages left, so don't panic. */
4026 rc = VINF_SUCCESS;
4027 }
4028
4029 if (RT_SUCCESS(rc))
4030 {
4031 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
4032 Assert(pVM->pgm.s.cHandyPages > 0);
4033 VM_FF_CLEAR(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
4034 VM_FF_CLEAR(pVM, VM_FF_PGM_NO_MEMORY);
4035
4036 /*
4037 * Clear the pages.
4038 */
4039 while (iClear < pVM->pgm.s.cHandyPages)
4040 {
4041 PGMMPAGEDESC pPage = &pVM->pgm.s.aHandyPages[iClear];
4042 void *pv;
4043 rc = pgmPhysPageMapByPageID(pVM, pPage->idPage, pPage->HCPhysGCPhys, &pv);
4044 AssertLogRelMsgBreak(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n", pPage->idPage, pPage->HCPhysGCPhys, rc));
4045 ASMMemZeroPage(pv);
4046 iClear++;
4047 Log3(("PGMR3PhysAllocateHandyPages: idPage=%#x HCPhys=%RGp\n", pPage->idPage, pPage->HCPhysGCPhys));
4048 }
4049 }
4050 else
4051 {
4052 uint64_t cAllocPages, cMaxPages, cBalloonPages;
4053
4054 /*
4055 * We should never get here unless there is a genuine shortage of
4056 * memory (or some internal error). Flag the error so the VM can be
4057 * suspended ASAP and the user informed. If we're totally out of
4058 * handy pages we will return failure.
4059 */
4060 /* Report the failure. */
4061 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc rcAlloc=%Rrc rcSeed=%Rrc cHandyPages=%#x\n"
4062 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
4063 rc, rcAlloc, rcSeed,
4064 pVM->pgm.s.cHandyPages,
4065 pVM->pgm.s.cAllPages,
4066 pVM->pgm.s.cPrivatePages,
4067 pVM->pgm.s.cSharedPages,
4068 pVM->pgm.s.cZeroPages));
4069
4070 if (GMMR3QueryMemoryStats(pVM, &cAllocPages, &cMaxPages, &cBalloonPages) == VINF_SUCCESS)
4071 {
4072 LogRel(("GMM: Statistics:\n"
4073 " Allocated pages: %RX64\n"
4074 " Maximum pages: %RX64\n"
4075 " Ballooned pages: %RX64\n", cAllocPages, cMaxPages, cBalloonPages));
4076 }
4077
4078 if ( rc != VERR_NO_MEMORY
4079 && rc != VERR_LOCK_FAILED)
4080 {
4081 for (uint32_t i = 0; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
4082 {
4083 LogRel(("PGM: aHandyPages[#%#04x] = {.HCPhysGCPhys=%RHp, .idPage=%#08x, .idSharedPage=%#08x}\n",
4084 i, pVM->pgm.s.aHandyPages[i].HCPhysGCPhys, pVM->pgm.s.aHandyPages[i].idPage,
4085 pVM->pgm.s.aHandyPages[i].idSharedPage));
4086 uint32_t const idPage = pVM->pgm.s.aHandyPages[i].idPage;
4087 if (idPage != NIL_GMM_PAGEID)
4088 {
4089 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
4090 pRam;
4091 pRam = pRam->pNextR3)
4092 {
4093 uint32_t const cPages = pRam->cb >> PAGE_SHIFT;
4094 for (uint32_t iPage = 0; iPage < cPages; iPage++)
4095 if (PGM_PAGE_GET_PAGEID(&pRam->aPages[iPage]) == idPage)
4096 LogRel(("PGM: Used by %RGp %R[pgmpage] (%s)\n",
4097 pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pRam->aPages[iPage], pRam->pszDesc));
4098 }
4099 }
4100 }
4101 }
4102
4103 /* Set the FFs and adjust rc. */
4104 VM_FF_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
4105 VM_FF_SET(pVM, VM_FF_PGM_NO_MEMORY);
4106 if ( rc == VERR_NO_MEMORY
4107 || rc == VERR_LOCK_FAILED)
4108 rc = VINF_EM_NO_MEMORY;
4109 }
4110
4111 pgmUnlock(pVM);
4112 return rc;
4113}
4114
4115
4116/**
4117 * Frees the specified RAM page and replaces it with the ZERO page.
4118 *
4119 * This is used by ballooning, remapping MMIO2, RAM reset and state loading.
4120 *
4121 * @param pVM Pointer to the shared VM structure.
4122 * @param pReq Pointer to the request.
4123 * @param pcPendingPages Where the number of pages waiting to be freed are
4124 * kept. This will normally be incremented.
4125 * @param pPage Pointer to the page structure.
4126 * @param GCPhys The guest physical address of the page, if applicable.
4127 *
4128 * @remarks The caller must own the PGM lock.
4129 */
4130int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys)
4131{
4132 /*
4133 * Assert sanity.
4134 */
4135 Assert(PGMIsLockOwner(pVM));
4136 if (RT_UNLIKELY( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM
4137 && PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_ROM_SHADOW))
4138 {
4139 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
4140 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
4141 }
4142 Assert(PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE);
4143
4144 if ( PGM_PAGE_IS_ZERO(pPage)
4145 || PGM_PAGE_IS_BALLOONED(pPage))
4146 return VINF_SUCCESS;
4147
4148 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
4149 Log3(("pgmPhysFreePage: idPage=%#x GCPhys=%RGp pPage=%R[pgmpage]\n", idPage, GCPhys, pPage));
4150 if (RT_UNLIKELY( idPage == NIL_GMM_PAGEID
4151 || idPage > GMM_PAGEID_LAST
4152 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID))
4153 {
4154 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
4155 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
4156 }
4157
4158 /* update page count stats. */
4159 if (PGM_PAGE_IS_SHARED(pPage))
4160 pVM->pgm.s.cSharedPages--;
4161 else
4162 pVM->pgm.s.cPrivatePages--;
4163 pVM->pgm.s.cZeroPages++;
4164
4165 /* Deal with write monitored pages. */
4166 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
4167 {
4168 PGM_PAGE_SET_WRITTEN_TO(pPage);
4169 pVM->pgm.s.cWrittenToPages++;
4170 }
4171
4172 /*
4173 * pPage = ZERO page.
4174 */
4175 PGM_PAGE_SET_HCPHYS(pPage, pVM->pgm.s.HCPhysZeroPg);
4176 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
4177 PGM_PAGE_SET_PAGEID(pPage, NIL_GMM_PAGEID);
4178 PGM_PAGE_SET_PDE_TYPE(pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4179 PGM_PAGE_SET_PTE_INDEX(pPage, 0);
4180 PGM_PAGE_SET_TRACKING(pPage, 0);
4181
4182 /* Flush physical page map TLB entry. */
4183 PGMPhysInvalidatePageMapTLBEntry(pVM, GCPhys);
4184
4185 /*
4186 * Make sure it's not in the handy page array.
4187 */
4188 for (uint32_t i = pVM->pgm.s.cHandyPages; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
4189 {
4190 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
4191 {
4192 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
4193 break;
4194 }
4195 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
4196 {
4197 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
4198 break;
4199 }
4200 }
4201
4202 /*
4203 * Push it onto the page array.
4204 */
4205 uint32_t iPage = *pcPendingPages;
4206 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
4207 *pcPendingPages += 1;
4208
4209 pReq->aPages[iPage].idPage = idPage;
4210
4211 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
4212 return VINF_SUCCESS;
4213
4214 /*
4215 * Flush the pages.
4216 */
4217 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
4218 if (RT_SUCCESS(rc))
4219 {
4220 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
4221 *pcPendingPages = 0;
4222 }
4223 return rc;
4224}
4225
4226
4227/**
4228 * Converts a GC physical address to a HC ring-3 pointer, with some
4229 * additional checks.
4230 *
4231 * @returns VBox status code.
4232 * @retval VINF_SUCCESS on success.
4233 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
4234 * access handler of some kind.
4235 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
4236 * accesses or is odd in any way.
4237 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
4238 *
4239 * @param pVM The VM handle.
4240 * @param GCPhys The GC physical address to convert.
4241 * @param fWritable Whether write access is required.
4242 * @param ppv Where to store the pointer corresponding to GCPhys on
4243 * success.
4244 */
4245VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
4246{
4247 pgmLock(pVM);
4248
4249 PPGMRAMRANGE pRam;
4250 PPGMPAGE pPage;
4251 int rc = pgmPhysGetPageAndRangeEx(&pVM->pgm.s, GCPhys, &pPage, &pRam);
4252 if (RT_SUCCESS(rc))
4253 {
4254 if (PGM_PAGE_IS_BALLOONED(pPage))
4255 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4256 else if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
4257 rc = VINF_SUCCESS;
4258 else
4259 {
4260 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
4261 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
4262 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
4263 {
4264 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
4265 * in -norawr0 mode. */
4266 if (fWritable)
4267 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4268 }
4269 else
4270 {
4271 /* Temporarily disabled physical handler(s), since the recompiler
4272 doesn't get notified when it's reset we'll have to pretend it's
4273 operating normally. */
4274 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
4275 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
4276 else
4277 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4278 }
4279 }
4280 if (RT_SUCCESS(rc))
4281 {
4282 int rc2;
4283
4284 /* Make sure what we return is writable. */
4285 if (fWritable)
4286 switch (PGM_PAGE_GET_STATE(pPage))
4287 {
4288 case PGM_PAGE_STATE_ALLOCATED:
4289 break;
4290 case PGM_PAGE_STATE_BALLOONED:
4291 AssertFailed();
4292 break;
4293 case PGM_PAGE_STATE_ZERO:
4294 case PGM_PAGE_STATE_SHARED:
4295 if (rc == VINF_PGM_PHYS_TLB_CATCH_WRITE)
4296 break;
4297 case PGM_PAGE_STATE_WRITE_MONITORED:
4298 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)PAGE_OFFSET_MASK);
4299 AssertLogRelRCReturn(rc2, rc2);
4300 break;
4301 }
4302
4303 /* Get a ring-3 mapping of the address. */
4304 PPGMPAGER3MAPTLBE pTlbe;
4305 rc2 = pgmPhysPageQueryTlbe(&pVM->pgm.s, GCPhys, &pTlbe);
4306 AssertLogRelRCReturn(rc2, rc2);
4307 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
4308 /** @todo mapping/locking hell; this isn't horribly efficient since
4309 * pgmPhysPageLoadIntoTlb will repeat the lookup we've done here. */
4310
4311 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
4312 }
4313 else
4314 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
4315
4316 /* else: handler catching all access, no pointer returned. */
4317 }
4318 else
4319 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
4320
4321 pgmUnlock(pVM);
4322 return rc;
4323}
4324
Note: See TracBrowser for help on using the repository browser.

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