VirtualBox

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

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

PGM: Fixed large pages and write monitoring (live snapshot). Added checks for PGM_PAGE_PDE_TYPE_PDE_DISABLED in a few places where only PGM_PAGE_PDE_TYPE_PDE was checked for (might have missed some).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 154.6 KB
Line 
1/* $Id: PGMPhys.cpp 36009 2011-02-17 10:15:02Z 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 pgmPhysPageWriteMonitor(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1012 break;
1013
1014 case PGM_PAGE_STATE_SHARED:
1015 AssertFailed();
1016 break;
1017
1018 case PGM_PAGE_STATE_WRITE_MONITORED: /* nothing to change. */
1019 default:
1020 break;
1021 }
1022 }
1023 }
1024 }
1025 pgmR3PoolWriteProtectPages(pVM);
1026 PGM_INVL_ALL_VCPU_TLBS(pVM);
1027 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1028 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
1029
1030 pgmUnlock(pVM);
1031 return rc;
1032}
1033
1034/**
1035 * Protect all physical RAM to monitor writes
1036 *
1037 * @returns VBox status code.
1038 * @param pVM The VM handle.
1039 */
1040VMMR3DECL(int) PGMR3PhysWriteProtectRAM(PVM pVM)
1041{
1042 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1043
1044 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysWriteProtectRAMRendezvous, NULL);
1045 AssertRC(rc);
1046 return rc;
1047}
1048
1049/**
1050 * Enumerate all dirty FT pages
1051 *
1052 * @returns VBox status code.
1053 * @param pVM The VM handle.
1054 * @param pfnEnum Enumerate callback handler
1055 * @param pvUser Enumerate callback handler parameter
1056 */
1057VMMR3DECL(int) PGMR3PhysEnumDirtyFTPages(PVM pVM, PFNPGMENUMDIRTYFTPAGES pfnEnum, void *pvUser)
1058{
1059 int rc = VINF_SUCCESS;
1060
1061 pgmLock(pVM);
1062 for (PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
1063 pRam;
1064 pRam = pRam->CTX_SUFF(pNext))
1065 {
1066 unsigned cPages = pRam->cb >> PAGE_SHIFT;
1067 for (unsigned iPage = 0; iPage < cPages; iPage++)
1068 {
1069 PPGMPAGE pPage = &pRam->aPages[iPage];
1070 PGMPAGETYPE enmPageType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage);
1071
1072 if ( RT_LIKELY(enmPageType == PGMPAGETYPE_RAM)
1073 || enmPageType == PGMPAGETYPE_MMIO2)
1074 {
1075 /*
1076 * A RAM page.
1077 */
1078 switch (PGM_PAGE_GET_STATE(pPage))
1079 {
1080 case PGM_PAGE_STATE_ALLOCATED:
1081 case PGM_PAGE_STATE_WRITE_MONITORED:
1082 if ( !PGM_PAGE_IS_WRITTEN_TO(pPage) /* not very recently updated? */
1083 && PGM_PAGE_IS_FT_DIRTY(pPage))
1084 {
1085 unsigned cbPageRange = PAGE_SIZE;
1086 unsigned iPageClean = iPage + 1;
1087 RTGCPHYS GCPhysPage = pRam->GCPhys + iPage * PAGE_SIZE;
1088 uint8_t *pu8Page = NULL;
1089 PGMPAGEMAPLOCK Lock;
1090
1091 /* Find the next clean page, so we can merge adjacent dirty pages. */
1092 for (; iPageClean < cPages; iPageClean++)
1093 {
1094 PPGMPAGE pPageNext = &pRam->aPages[iPageClean];
1095 if ( RT_UNLIKELY(PGM_PAGE_GET_TYPE(pPageNext) != PGMPAGETYPE_RAM)
1096 || PGM_PAGE_GET_STATE(pPageNext) != PGM_PAGE_STATE_ALLOCATED
1097 || PGM_PAGE_IS_WRITTEN_TO(pPageNext)
1098 || !PGM_PAGE_IS_FT_DIRTY(pPageNext)
1099 /* Crossing a chunk boundary? */
1100 || (GCPhysPage & GMM_PAGEID_IDX_MASK) != ((GCPhysPage + cbPageRange) & GMM_PAGEID_IDX_MASK)
1101 )
1102 break;
1103
1104 cbPageRange += PAGE_SIZE;
1105 }
1106
1107 rc = PGMPhysGCPhys2CCPtrReadOnly(pVM, GCPhysPage, (const void **)&pu8Page, &Lock);
1108 if (RT_SUCCESS(rc))
1109 {
1110 /** @todo this is risky; the range might be changed, but little choice as the sync costs a lot of time */
1111 pgmUnlock(pVM);
1112 pfnEnum(pVM, GCPhysPage, pu8Page, cbPageRange, pvUser);
1113 pgmLock(pVM);
1114 PGMPhysReleasePageMappingLock(pVM, &Lock);
1115 }
1116
1117 for (iPage; iPage < iPageClean; iPage++)
1118 PGM_PAGE_CLEAR_FT_DIRTY(&pRam->aPages[iPage]);
1119
1120 iPage = iPageClean - 1;
1121 }
1122 break;
1123 }
1124 }
1125 }
1126 }
1127 pgmUnlock(pVM);
1128 return rc;
1129}
1130
1131
1132/**
1133 * Gets the number of ram ranges.
1134 *
1135 * @returns Number of ram ranges. Returns UINT32_MAX if @a pVM is invalid.
1136 * @param pVM The VM handle.
1137 */
1138VMMR3DECL(uint32_t) PGMR3PhysGetRamRangeCount(PVM pVM)
1139{
1140 VM_ASSERT_VALID_EXT_RETURN(pVM, UINT32_MAX);
1141
1142 pgmLock(pVM);
1143 uint32_t cRamRanges = 0;
1144 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRanges); pCur; pCur = pCur->CTX_SUFF(pNext))
1145 cRamRanges++;
1146 pgmUnlock(pVM);
1147 return cRamRanges;
1148}
1149
1150
1151/**
1152 * Get information about a range.
1153 *
1154 * @returns VINF_SUCCESS or VERR_OUT_OF_RANGE.
1155 * @param pVM The VM handle
1156 * @param iRange The ordinal of the range.
1157 * @param pGCPhysStart Where to return the start of the range. Optional.
1158 * @param pGCPhysLast Where to return the address of the last byte in the
1159 * range. Optional.
1160 * @param pfIsMmio Where to indicate that this is a pure MMIO range.
1161 * Optional.
1162 */
1163VMMR3DECL(int) PGMR3PhysGetRange(PVM pVM, uint32_t iRange, PRTGCPHYS pGCPhysStart, PRTGCPHYS pGCPhysLast,
1164 const char **ppszDesc, bool *pfIsMmio)
1165{
1166 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1167
1168 pgmLock(pVM);
1169 uint32_t iCurRange = 0;
1170 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRanges); pCur; pCur = pCur->CTX_SUFF(pNext), iCurRange++)
1171 if (iCurRange == iRange)
1172 {
1173 if (pGCPhysStart)
1174 *pGCPhysStart = pCur->GCPhys;
1175 if (pGCPhysLast)
1176 *pGCPhysLast = pCur->GCPhysLast;
1177 if (pfIsMmio)
1178 *pfIsMmio = !!(pCur->fFlags & PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO);
1179
1180 pgmUnlock(pVM);
1181 return VINF_SUCCESS;
1182 }
1183 pgmUnlock(pVM);
1184 return VERR_OUT_OF_RANGE;
1185}
1186
1187
1188/**
1189 * Query the amount of free memory inside VMMR0
1190 *
1191 * @returns VBox status code.
1192 * @param pVM The VM handle.
1193 * @param puTotalAllocSize Pointer to total allocated memory inside VMMR0 (in bytes)
1194 * @param puTotalFreeSize Pointer to total free (allocated but not used yet) memory inside VMMR0 (in bytes)
1195 * @param puTotalBalloonSize Pointer to total ballooned memory inside VMMR0 (in bytes)
1196 * @param puTotalSharedSize Pointer to total shared memory inside VMMR0 (in bytes)
1197 */
1198VMMR3DECL(int) PGMR3QueryVMMMemoryStats(PVM pVM, uint64_t *puTotalAllocSize, uint64_t *puTotalFreeSize, uint64_t *puTotalBalloonSize, uint64_t *puTotalSharedSize)
1199{
1200 int rc;
1201
1202 uint64_t cAllocPages = 0, cFreePages = 0, cBalloonPages = 0, cSharedPages = 0;
1203 rc = GMMR3QueryHypervisorMemoryStats(pVM, &cAllocPages, &cFreePages, &cBalloonPages, &cSharedPages);
1204 AssertRCReturn(rc, rc);
1205
1206 if (puTotalAllocSize)
1207 *puTotalAllocSize = cAllocPages * _4K;
1208
1209 if (puTotalFreeSize)
1210 *puTotalFreeSize = cFreePages * _4K;
1211
1212 if (puTotalBalloonSize)
1213 *puTotalBalloonSize = cBalloonPages * _4K;
1214
1215 if (puTotalSharedSize)
1216 *puTotalSharedSize = cSharedPages * _4K;
1217
1218 Log(("PGMR3QueryVMMMemoryStats: all=%x free=%x ballooned=%x shared=%x\n", cAllocPages, cFreePages, cBalloonPages, cSharedPages));
1219 return VINF_SUCCESS;
1220}
1221
1222/**
1223 * Query memory stats for the VM
1224 *
1225 * @returns VBox status code.
1226 * @param pVM The VM handle.
1227 * @param puTotalAllocSize Pointer to total allocated memory inside the VM (in bytes)
1228 * @param puTotalFreeSize Pointer to total free (allocated but not used yet) memory inside the VM (in bytes)
1229 * @param puTotalBalloonSize Pointer to total ballooned memory inside the VM (in bytes)
1230 * @param puTotalSharedSize Pointer to total shared memory inside the VM (in bytes)
1231 */
1232VMMR3DECL(int) PGMR3QueryMemoryStats(PVM pVM, uint64_t *pulTotalMem, uint64_t *pulPrivateMem, uint64_t *puTotalSharedMem, uint64_t *puTotalZeroMem)
1233{
1234 if (pulTotalMem)
1235 *pulTotalMem = (uint64_t)pVM->pgm.s.cAllPages * _4K;
1236
1237 if (pulPrivateMem)
1238 *pulPrivateMem = (uint64_t)pVM->pgm.s.cPrivatePages * _4K;
1239
1240 if (puTotalSharedMem)
1241 *puTotalSharedMem = (uint64_t)pVM->pgm.s.cReusedSharedPages * _4K;
1242
1243 if (puTotalZeroMem)
1244 *puTotalZeroMem = (uint64_t)pVM->pgm.s.cZeroPages * _4K;
1245
1246 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));
1247 return VINF_SUCCESS;
1248}
1249
1250/**
1251 * PGMR3PhysRegisterRam worker that initializes and links a RAM range.
1252 *
1253 * @param pVM The VM handle.
1254 * @param pNew The new RAM range.
1255 * @param GCPhys The address of the RAM range.
1256 * @param GCPhysLast The last address of the RAM range.
1257 * @param RCPtrNew The RC address if the range is floating. NIL_RTRCPTR
1258 * if in HMA.
1259 * @param R0PtrNew Ditto for R0.
1260 * @param pszDesc The description.
1261 * @param pPrev The previous RAM range (for linking).
1262 */
1263static void pgmR3PhysInitAndLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast,
1264 RTRCPTR RCPtrNew, RTR0PTR R0PtrNew, const char *pszDesc, PPGMRAMRANGE pPrev)
1265{
1266 /*
1267 * Initialize the range.
1268 */
1269 pNew->pSelfR0 = R0PtrNew != NIL_RTR0PTR ? R0PtrNew : MMHyperCCToR0(pVM, pNew);
1270 pNew->pSelfRC = RCPtrNew != NIL_RTRCPTR ? RCPtrNew : MMHyperCCToRC(pVM, pNew);
1271 pNew->GCPhys = GCPhys;
1272 pNew->GCPhysLast = GCPhysLast;
1273 pNew->cb = GCPhysLast - GCPhys + 1;
1274 pNew->pszDesc = pszDesc;
1275 pNew->fFlags = RCPtrNew != NIL_RTRCPTR ? PGM_RAM_RANGE_FLAGS_FLOATING : 0;
1276 pNew->pvR3 = NULL;
1277 pNew->paLSPages = NULL;
1278
1279 uint32_t const cPages = pNew->cb >> PAGE_SHIFT;
1280 RTGCPHYS iPage = cPages;
1281 while (iPage-- > 0)
1282 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_RAM);
1283
1284 /* Update the page count stats. */
1285 pVM->pgm.s.cZeroPages += cPages;
1286 pVM->pgm.s.cAllPages += cPages;
1287
1288 /*
1289 * Link it.
1290 */
1291 pgmR3PhysLinkRamRange(pVM, pNew, pPrev);
1292}
1293
1294
1295/**
1296 * Relocate a floating RAM range.
1297 *
1298 * @copydoc FNPGMRELOCATE.
1299 */
1300static DECLCALLBACK(bool) pgmR3PhysRamRangeRelocate(PVM pVM, RTGCPTR GCPtrOld, RTGCPTR GCPtrNew, PGMRELOCATECALL enmMode, void *pvUser)
1301{
1302 PPGMRAMRANGE pRam = (PPGMRAMRANGE)pvUser;
1303 Assert(pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING);
1304 Assert(pRam->pSelfRC == GCPtrOld + PAGE_SIZE);
1305
1306 switch (enmMode)
1307 {
1308 case PGMRELOCATECALL_SUGGEST:
1309 return true;
1310 case PGMRELOCATECALL_RELOCATE:
1311 {
1312 /* Update myself and then relink all the ranges. */
1313 pgmLock(pVM);
1314 pRam->pSelfRC = (RTRCPTR)(GCPtrNew + PAGE_SIZE);
1315 pgmR3PhysRelinkRamRanges(pVM);
1316 pgmUnlock(pVM);
1317 return true;
1318 }
1319
1320 default:
1321 AssertFailedReturn(false);
1322 }
1323}
1324
1325
1326/**
1327 * PGMR3PhysRegisterRam worker that registers a high chunk.
1328 *
1329 * @returns VBox status code.
1330 * @param pVM The VM handle.
1331 * @param GCPhys The address of the RAM.
1332 * @param cRamPages The number of RAM pages to register.
1333 * @param cbChunk The size of the PGMRAMRANGE guest mapping.
1334 * @param iChunk The chunk number.
1335 * @param pszDesc The RAM range description.
1336 * @param ppPrev Previous RAM range pointer. In/Out.
1337 */
1338static int pgmR3PhysRegisterHighRamChunk(PVM pVM, RTGCPHYS GCPhys, uint32_t cRamPages,
1339 uint32_t cbChunk, uint32_t iChunk, const char *pszDesc,
1340 PPGMRAMRANGE *ppPrev)
1341{
1342 const char *pszDescChunk = iChunk == 0
1343 ? pszDesc
1344 : MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s (#%u)", pszDesc, iChunk + 1);
1345 AssertReturn(pszDescChunk, VERR_NO_MEMORY);
1346
1347 /*
1348 * Allocate memory for the new chunk.
1349 */
1350 size_t const cChunkPages = RT_ALIGN_Z(RT_UOFFSETOF(PGMRAMRANGE, aPages[cRamPages]), PAGE_SIZE) >> PAGE_SHIFT;
1351 PSUPPAGE paChunkPages = (PSUPPAGE)RTMemTmpAllocZ(sizeof(SUPPAGE) * cChunkPages);
1352 AssertReturn(paChunkPages, VERR_NO_TMP_MEMORY);
1353 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
1354 void *pvChunk = NULL;
1355 int rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk,
1356#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1357 VMMIsHwVirtExtForced(pVM) ? &R0PtrChunk : NULL,
1358#else
1359 NULL,
1360#endif
1361 paChunkPages);
1362 if (RT_SUCCESS(rc))
1363 {
1364#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1365 if (!VMMIsHwVirtExtForced(pVM))
1366 R0PtrChunk = NIL_RTR0PTR;
1367#else
1368 R0PtrChunk = (uintptr_t)pvChunk;
1369#endif
1370 memset(pvChunk, 0, cChunkPages << PAGE_SHIFT);
1371
1372 PPGMRAMRANGE pNew = (PPGMRAMRANGE)pvChunk;
1373
1374 /*
1375 * Create a mapping and map the pages into it.
1376 * We push these in below the HMA.
1377 */
1378 RTGCPTR GCPtrChunkMap = pVM->pgm.s.GCPtrPrevRamRangeMapping - cbChunk;
1379 rc = PGMR3MapPT(pVM, GCPtrChunkMap, cbChunk, 0 /*fFlags*/, pgmR3PhysRamRangeRelocate, pNew, pszDescChunk);
1380 if (RT_SUCCESS(rc))
1381 {
1382 pVM->pgm.s.GCPtrPrevRamRangeMapping = GCPtrChunkMap;
1383
1384 RTGCPTR const GCPtrChunk = GCPtrChunkMap + PAGE_SIZE;
1385 RTGCPTR GCPtrPage = GCPtrChunk;
1386 for (uint32_t iPage = 0; iPage < cChunkPages && RT_SUCCESS(rc); iPage++, GCPtrPage += PAGE_SIZE)
1387 rc = PGMMap(pVM, GCPtrPage, paChunkPages[iPage].Phys, PAGE_SIZE, 0);
1388 if (RT_SUCCESS(rc))
1389 {
1390 /*
1391 * Ok, init and link the range.
1392 */
1393 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhys + ((RTGCPHYS)cRamPages << PAGE_SHIFT) - 1,
1394 (RTRCPTR)GCPtrChunk, R0PtrChunk, pszDescChunk, *ppPrev);
1395 *ppPrev = pNew;
1396 }
1397 }
1398
1399 if (RT_FAILURE(rc))
1400 SUPR3PageFreeEx(pvChunk, cChunkPages);
1401 }
1402
1403 RTMemTmpFree(paChunkPages);
1404 return rc;
1405}
1406
1407
1408/**
1409 * Sets up a range RAM.
1410 *
1411 * This will check for conflicting registrations, make a resource
1412 * reservation for the memory (with GMM), and setup the per-page
1413 * tracking structures (PGMPAGE).
1414 *
1415 * @returns VBox status code.
1416 * @param pVM Pointer to the shared VM structure.
1417 * @param GCPhys The physical address of the RAM.
1418 * @param cb The size of the RAM.
1419 * @param pszDesc The description - not copied, so, don't free or change it.
1420 */
1421VMMR3DECL(int) PGMR3PhysRegisterRam(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, const char *pszDesc)
1422{
1423 /*
1424 * Validate input.
1425 */
1426 Log(("PGMR3PhysRegisterRam: GCPhys=%RGp cb=%RGp pszDesc=%s\n", GCPhys, cb, pszDesc));
1427 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
1428 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
1429 AssertReturn(cb > 0, VERR_INVALID_PARAMETER);
1430 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1431 AssertMsgReturn(GCPhysLast > GCPhys, ("The range wraps! GCPhys=%RGp cb=%RGp\n", GCPhys, cb), VERR_INVALID_PARAMETER);
1432 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1433 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1434
1435 pgmLock(pVM);
1436
1437 /*
1438 * Find range location and check for conflicts.
1439 * (We don't lock here because the locking by EMT is only required on update.)
1440 */
1441 PPGMRAMRANGE pPrev = NULL;
1442 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
1443 while (pRam && GCPhysLast >= pRam->GCPhys)
1444 {
1445 if ( GCPhysLast >= pRam->GCPhys
1446 && GCPhys <= pRam->GCPhysLast)
1447 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
1448 GCPhys, GCPhysLast, pszDesc,
1449 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1450 VERR_PGM_RAM_CONFLICT);
1451
1452 /* next */
1453 pPrev = pRam;
1454 pRam = pRam->pNextR3;
1455 }
1456
1457 /*
1458 * Register it with GMM (the API bitches).
1459 */
1460 const RTGCPHYS cPages = cb >> PAGE_SHIFT;
1461 int rc = MMR3IncreaseBaseReservation(pVM, cPages);
1462 if (RT_FAILURE(rc))
1463 {
1464 pgmUnlock(pVM);
1465 return rc;
1466 }
1467
1468 if ( GCPhys >= _4G
1469 && cPages > 256)
1470 {
1471 /*
1472 * The PGMRAMRANGE structures for the high memory can get very big.
1473 * In order to avoid SUPR3PageAllocEx allocation failures due to the
1474 * allocation size limit there and also to avoid being unable to find
1475 * guest mapping space for them, we split this memory up into 4MB in
1476 * (potential) raw-mode configs and 16MB chunks in forced AMD-V/VT-x
1477 * mode.
1478 *
1479 * The first and last page of each mapping are guard pages and marked
1480 * not-present. So, we've got 4186112 and 16769024 bytes available for
1481 * the PGMRAMRANGE structure.
1482 *
1483 * Note! The sizes used here will influence the saved state.
1484 */
1485 uint32_t cbChunk;
1486 uint32_t cPagesPerChunk;
1487 if (VMMIsHwVirtExtForced(pVM))
1488 {
1489 cbChunk = 16U*_1M;
1490 cPagesPerChunk = 1048048; /* max ~1048059 */
1491 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 1048048 < 16U*_1M - PAGE_SIZE * 2);
1492 }
1493 else
1494 {
1495 cbChunk = 4U*_1M;
1496 cPagesPerChunk = 261616; /* max ~261627 */
1497 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 261616 < 4U*_1M - PAGE_SIZE * 2);
1498 }
1499 AssertRelease(RT_UOFFSETOF(PGMRAMRANGE, aPages[cPagesPerChunk]) + PAGE_SIZE * 2 <= cbChunk);
1500
1501 RTGCPHYS cPagesLeft = cPages;
1502 RTGCPHYS GCPhysChunk = GCPhys;
1503 uint32_t iChunk = 0;
1504 while (cPagesLeft > 0)
1505 {
1506 uint32_t cPagesInChunk = cPagesLeft;
1507 if (cPagesInChunk > cPagesPerChunk)
1508 cPagesInChunk = cPagesPerChunk;
1509
1510 rc = pgmR3PhysRegisterHighRamChunk(pVM, GCPhysChunk, cPagesInChunk, cbChunk, iChunk, pszDesc, &pPrev);
1511 AssertRCReturn(rc, rc);
1512
1513 /* advance */
1514 GCPhysChunk += (RTGCPHYS)cPagesInChunk << PAGE_SHIFT;
1515 cPagesLeft -= cPagesInChunk;
1516 iChunk++;
1517 }
1518 }
1519 else
1520 {
1521 /*
1522 * Allocate, initialize and link the new RAM range.
1523 */
1524 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
1525 PPGMRAMRANGE pNew;
1526 rc = MMR3HyperAllocOnceNoRel(pVM, cbRamRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
1527 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
1528
1529 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhysLast, NIL_RTRCPTR, NIL_RTR0PTR, pszDesc, pPrev);
1530 }
1531 PGMPhysInvalidatePageMapTLB(pVM);
1532 pgmUnlock(pVM);
1533
1534 /*
1535 * Notify REM.
1536 */
1537 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_RAM);
1538
1539 return VINF_SUCCESS;
1540}
1541
1542
1543/**
1544 * Worker called by PGMR3InitFinalize if we're configured to pre-allocate RAM.
1545 *
1546 * We do this late in the init process so that all the ROM and MMIO ranges have
1547 * been registered already and we don't go wasting memory on them.
1548 *
1549 * @returns VBox status code.
1550 *
1551 * @param pVM Pointer to the shared VM structure.
1552 */
1553int pgmR3PhysRamPreAllocate(PVM pVM)
1554{
1555 Assert(pVM->pgm.s.fRamPreAlloc);
1556 Log(("pgmR3PhysRamPreAllocate: enter\n"));
1557
1558 /*
1559 * Walk the RAM ranges and allocate all RAM pages, halt at
1560 * the first allocation error.
1561 */
1562 uint64_t cPages = 0;
1563 uint64_t NanoTS = RTTimeNanoTS();
1564 pgmLock(pVM);
1565 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3; pRam; pRam = pRam->pNextR3)
1566 {
1567 PPGMPAGE pPage = &pRam->aPages[0];
1568 RTGCPHYS GCPhys = pRam->GCPhys;
1569 uint32_t cLeft = pRam->cb >> PAGE_SHIFT;
1570 while (cLeft-- > 0)
1571 {
1572 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM)
1573 {
1574 switch (PGM_PAGE_GET_STATE(pPage))
1575 {
1576 case PGM_PAGE_STATE_ZERO:
1577 {
1578 int rc = pgmPhysAllocPage(pVM, pPage, GCPhys);
1579 if (RT_FAILURE(rc))
1580 {
1581 LogRel(("PGM: RAM Pre-allocation failed at %RGp (in %s) with rc=%Rrc\n", GCPhys, pRam->pszDesc, rc));
1582 pgmUnlock(pVM);
1583 return rc;
1584 }
1585 cPages++;
1586 break;
1587 }
1588
1589 case PGM_PAGE_STATE_BALLOONED:
1590 case PGM_PAGE_STATE_ALLOCATED:
1591 case PGM_PAGE_STATE_WRITE_MONITORED:
1592 case PGM_PAGE_STATE_SHARED:
1593 /* nothing to do here. */
1594 break;
1595 }
1596 }
1597
1598 /* next */
1599 pPage++;
1600 GCPhys += PAGE_SIZE;
1601 }
1602 }
1603 pgmUnlock(pVM);
1604 NanoTS = RTTimeNanoTS() - NanoTS;
1605
1606 LogRel(("PGM: Pre-allocated %llu pages in %llu ms\n", cPages, NanoTS / 1000000));
1607 Log(("pgmR3PhysRamPreAllocate: returns VINF_SUCCESS\n"));
1608 return VINF_SUCCESS;
1609}
1610
1611
1612/**
1613 * Resets (zeros) the RAM.
1614 *
1615 * ASSUMES that the caller owns the PGM lock.
1616 *
1617 * @returns VBox status code.
1618 * @param pVM Pointer to the shared VM structure.
1619 */
1620int pgmR3PhysRamReset(PVM pVM)
1621{
1622 Assert(PGMIsLockOwner(pVM));
1623
1624 /* Reset the memory balloon. */
1625 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
1626 AssertRC(rc);
1627
1628#ifdef VBOX_WITH_PAGE_SHARING
1629 /* Clear all registered shared modules. */
1630 rc = GMMR3ResetSharedModules(pVM);
1631 AssertRC(rc);
1632#endif
1633 /* Reset counters. */
1634 pVM->pgm.s.cReusedSharedPages = 0;
1635 pVM->pgm.s.cBalloonedPages = 0;
1636
1637 /*
1638 * We batch up pages that should be freed instead of calling GMM for
1639 * each and every one of them.
1640 */
1641 uint32_t cPendingPages = 0;
1642 PGMMFREEPAGESREQ pReq;
1643 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1644 AssertLogRelRCReturn(rc, rc);
1645
1646 /*
1647 * Walk the ram ranges.
1648 */
1649 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3; pRam; pRam = pRam->pNextR3)
1650 {
1651 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
1652 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
1653
1654 if (!pVM->pgm.s.fRamPreAlloc)
1655 {
1656 /* Replace all RAM pages by ZERO pages. */
1657 while (iPage-- > 0)
1658 {
1659 PPGMPAGE pPage = &pRam->aPages[iPage];
1660 switch (PGM_PAGE_GET_TYPE(pPage))
1661 {
1662 case PGMPAGETYPE_RAM:
1663 /* Do not replace pages part of a 2 MB continuous range
1664 with zero pages, but zero them instead. */
1665 if ( PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE
1666 || PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE_DISABLED)
1667 {
1668 void *pvPage;
1669 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
1670 AssertLogRelRCReturn(rc, rc);
1671 ASMMemZeroPage(pvPage);
1672 }
1673 else 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 if (!PGM_PAGE_IS_ZERO(pPage))
1679 {
1680 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1681 AssertLogRelRCReturn(rc, rc);
1682 }
1683 break;
1684
1685 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
1686 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
1687 true /*fDoAccounting*/);
1688 break;
1689
1690 case PGMPAGETYPE_MMIO2:
1691 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
1692 case PGMPAGETYPE_ROM:
1693 case PGMPAGETYPE_MMIO:
1694 break;
1695 default:
1696 AssertFailed();
1697 }
1698 } /* for each page */
1699 }
1700 else
1701 {
1702 /* Zero the memory. */
1703 while (iPage-- > 0)
1704 {
1705 PPGMPAGE pPage = &pRam->aPages[iPage];
1706 switch (PGM_PAGE_GET_TYPE(pPage))
1707 {
1708 case PGMPAGETYPE_RAM:
1709 switch (PGM_PAGE_GET_STATE(pPage))
1710 {
1711 case PGM_PAGE_STATE_ZERO:
1712 break;
1713
1714 case PGM_PAGE_STATE_BALLOONED:
1715 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
1716 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
1717 break;
1718
1719 case PGM_PAGE_STATE_SHARED:
1720 case PGM_PAGE_STATE_WRITE_MONITORED:
1721 rc = pgmPhysPageMakeWritable(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1722 AssertLogRelRCReturn(rc, rc);
1723 /* no break */
1724
1725 case PGM_PAGE_STATE_ALLOCATED:
1726 {
1727 void *pvPage;
1728 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
1729 AssertLogRelRCReturn(rc, rc);
1730 ASMMemZeroPage(pvPage);
1731 break;
1732 }
1733 }
1734 break;
1735
1736 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
1737 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
1738 true /*fDoAccounting*/);
1739 break;
1740
1741 case PGMPAGETYPE_MMIO2:
1742 case PGMPAGETYPE_ROM_SHADOW:
1743 case PGMPAGETYPE_ROM:
1744 case PGMPAGETYPE_MMIO:
1745 break;
1746 default:
1747 AssertFailed();
1748
1749 }
1750 } /* for each page */
1751 }
1752
1753 }
1754
1755 /*
1756 * Finish off any pages pending freeing.
1757 */
1758 if (cPendingPages)
1759 {
1760 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
1761 AssertLogRelRCReturn(rc, rc);
1762 }
1763 GMMR3FreePagesCleanup(pReq);
1764
1765 return VINF_SUCCESS;
1766}
1767
1768/**
1769 * Frees all RAM during VM termination
1770 *
1771 * ASSUMES that the caller owns the PGM lock.
1772 *
1773 * @returns VBox status code.
1774 * @param pVM Pointer to the shared VM structure.
1775 */
1776int pgmR3PhysRamTerm(PVM pVM)
1777{
1778 Assert(PGMIsLockOwner(pVM));
1779
1780 /* Reset the memory balloon. */
1781 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
1782 AssertRC(rc);
1783
1784#ifdef VBOX_WITH_PAGE_SHARING
1785 /* Clear all registered shared modules. */
1786 rc = GMMR3ResetSharedModules(pVM);
1787 AssertRC(rc);
1788#endif
1789
1790 /*
1791 * We batch up pages that should be freed instead of calling GMM for
1792 * each and every one of them.
1793 */
1794 uint32_t cPendingPages = 0;
1795 PGMMFREEPAGESREQ pReq;
1796 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1797 AssertLogRelRCReturn(rc, rc);
1798
1799 /*
1800 * Walk the ram ranges.
1801 */
1802 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3; pRam; pRam = pRam->pNextR3)
1803 {
1804 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
1805 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
1806
1807 /* Replace all RAM pages by ZERO pages. */
1808 while (iPage-- > 0)
1809 {
1810 PPGMPAGE pPage = &pRam->aPages[iPage];
1811 switch (PGM_PAGE_GET_TYPE(pPage))
1812 {
1813 case PGMPAGETYPE_RAM:
1814 /* Free all shared pages. Private pages are automatically freed during GMM VM cleanup. */
1815 if (PGM_PAGE_IS_SHARED(pPage))
1816 {
1817 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1818 AssertLogRelRCReturn(rc, rc);
1819 }
1820 break;
1821
1822 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
1823 case PGMPAGETYPE_MMIO2:
1824 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
1825 case PGMPAGETYPE_ROM:
1826 case PGMPAGETYPE_MMIO:
1827 break;
1828 default:
1829 AssertFailed();
1830 }
1831 } /* for each page */
1832 }
1833
1834 /*
1835 * Finish off any pages pending freeing.
1836 */
1837 if (cPendingPages)
1838 {
1839 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
1840 AssertLogRelRCReturn(rc, rc);
1841 }
1842 GMMR3FreePagesCleanup(pReq);
1843 return VINF_SUCCESS;
1844}
1845
1846/**
1847 * This is the interface IOM is using to register an MMIO region.
1848 *
1849 * It will check for conflicts and ensure that a RAM range structure
1850 * is present before calling the PGMR3HandlerPhysicalRegister API to
1851 * register the callbacks.
1852 *
1853 * @returns VBox status code.
1854 *
1855 * @param pVM Pointer to the shared VM structure.
1856 * @param GCPhys The start of the MMIO region.
1857 * @param cb The size of the MMIO region.
1858 * @param pfnHandlerR3 The address of the ring-3 handler. (IOMR3MMIOHandler)
1859 * @param pvUserR3 The user argument for R3.
1860 * @param pfnHandlerR0 The address of the ring-0 handler. (IOMMMIOHandler)
1861 * @param pvUserR0 The user argument for R0.
1862 * @param pfnHandlerRC The address of the RC handler. (IOMMMIOHandler)
1863 * @param pvUserRC The user argument for RC.
1864 * @param pszDesc The description of the MMIO region.
1865 */
1866VMMR3DECL(int) PGMR3PhysMMIORegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb,
1867 R3PTRTYPE(PFNPGMR3PHYSHANDLER) pfnHandlerR3, RTR3PTR pvUserR3,
1868 R0PTRTYPE(PFNPGMR0PHYSHANDLER) pfnHandlerR0, RTR0PTR pvUserR0,
1869 RCPTRTYPE(PFNPGMRCPHYSHANDLER) pfnHandlerRC, RTRCPTR pvUserRC,
1870 R3PTRTYPE(const char *) pszDesc)
1871{
1872 /*
1873 * Assert on some assumption.
1874 */
1875 VM_ASSERT_EMT(pVM);
1876 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
1877 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
1878 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1879 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
1880
1881 /*
1882 * Make sure there's a RAM range structure for the region.
1883 */
1884 int rc;
1885 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1886 bool fRamExists = false;
1887 PPGMRAMRANGE pRamPrev = NULL;
1888 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
1889 while (pRam && GCPhysLast >= pRam->GCPhys)
1890 {
1891 if ( GCPhysLast >= pRam->GCPhys
1892 && GCPhys <= pRam->GCPhysLast)
1893 {
1894 /* Simplification: all within the same range. */
1895 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
1896 && GCPhysLast <= pRam->GCPhysLast,
1897 ("%RGp-%RGp (MMIO/%s) falls partly outside %RGp-%RGp (%s)\n",
1898 GCPhys, GCPhysLast, pszDesc,
1899 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1900 VERR_PGM_RAM_CONFLICT);
1901
1902 /* Check that it's all RAM or MMIO pages. */
1903 PCPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
1904 uint32_t cLeft = cb >> PAGE_SHIFT;
1905 while (cLeft-- > 0)
1906 {
1907 AssertLogRelMsgReturn( PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM
1908 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO,
1909 ("%RGp-%RGp (MMIO/%s): %RGp is not a RAM or MMIO page - type=%d desc=%s\n",
1910 GCPhys, GCPhysLast, pszDesc, PGM_PAGE_GET_TYPE(pPage), pRam->pszDesc),
1911 VERR_PGM_RAM_CONFLICT);
1912 pPage++;
1913 }
1914
1915 /* Looks good. */
1916 fRamExists = true;
1917 break;
1918 }
1919
1920 /* next */
1921 pRamPrev = pRam;
1922 pRam = pRam->pNextR3;
1923 }
1924 PPGMRAMRANGE pNew;
1925 if (fRamExists)
1926 {
1927 pNew = NULL;
1928
1929 /*
1930 * Make all the pages in the range MMIO/ZERO pages, freeing any
1931 * RAM pages currently mapped here. This might not be 100% correct
1932 * for PCI memory, but we're doing the same thing for MMIO2 pages.
1933 */
1934 rc = pgmLock(pVM);
1935 if (RT_SUCCESS(rc))
1936 {
1937 rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, PGMPAGETYPE_MMIO);
1938 pgmUnlock(pVM);
1939 }
1940 AssertRCReturn(rc, rc);
1941
1942 /* Force a PGM pool flush as guest ram references have been changed. */
1943 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
1944 PVMCPU pVCpu = VMMGetCpu(pVM);
1945 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
1946 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
1947 }
1948 else
1949 {
1950 pgmLock(pVM);
1951
1952 /*
1953 * No RAM range, insert an ad hoc one.
1954 *
1955 * Note that we don't have to tell REM about this range because
1956 * PGMHandlerPhysicalRegisterEx will do that for us.
1957 */
1958 Log(("PGMR3PhysMMIORegister: Adding ad hoc MMIO range for %RGp-%RGp %s\n", GCPhys, GCPhysLast, pszDesc));
1959
1960 const uint32_t cPages = cb >> PAGE_SHIFT;
1961 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
1962 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), 16, MM_TAG_PGM_PHYS, (void **)&pNew);
1963 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
1964
1965 /* Initialize the range. */
1966 pNew->pSelfR0 = MMHyperCCToR0(pVM, pNew);
1967 pNew->pSelfRC = MMHyperCCToRC(pVM, pNew);
1968 pNew->GCPhys = GCPhys;
1969 pNew->GCPhysLast = GCPhysLast;
1970 pNew->cb = cb;
1971 pNew->pszDesc = pszDesc;
1972 pNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO;
1973 pNew->pvR3 = NULL;
1974 pNew->paLSPages = NULL;
1975
1976 uint32_t iPage = cPages;
1977 while (iPage-- > 0)
1978 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_MMIO);
1979 Assert(PGM_PAGE_GET_TYPE(&pNew->aPages[0]) == PGMPAGETYPE_MMIO);
1980
1981 /* update the page count stats. */
1982 pVM->pgm.s.cPureMmioPages += cPages;
1983 pVM->pgm.s.cAllPages += cPages;
1984
1985 /* link it */
1986 pgmR3PhysLinkRamRange(pVM, pNew, pRamPrev);
1987
1988 pgmUnlock(pVM);
1989 }
1990
1991 /*
1992 * Register the access handler.
1993 */
1994 rc = PGMHandlerPhysicalRegisterEx(pVM, PGMPHYSHANDLERTYPE_MMIO, GCPhys, GCPhysLast,
1995 pfnHandlerR3, pvUserR3,
1996 pfnHandlerR0, pvUserR0,
1997 pfnHandlerRC, pvUserRC, pszDesc);
1998 if ( RT_FAILURE(rc)
1999 && !fRamExists)
2000 {
2001 pVM->pgm.s.cPureMmioPages -= cb >> PAGE_SHIFT;
2002 pVM->pgm.s.cAllPages -= cb >> PAGE_SHIFT;
2003
2004 /* remove the ad hoc range. */
2005 pgmR3PhysUnlinkRamRange2(pVM, pNew, pRamPrev);
2006 pNew->cb = pNew->GCPhys = pNew->GCPhysLast = NIL_RTGCPHYS;
2007 MMHyperFree(pVM, pRam);
2008 }
2009 PGMPhysInvalidatePageMapTLB(pVM);
2010
2011 return rc;
2012}
2013
2014
2015/**
2016 * This is the interface IOM is using to register an MMIO region.
2017 *
2018 * It will take care of calling PGMHandlerPhysicalDeregister and clean up
2019 * any ad hoc PGMRAMRANGE left behind.
2020 *
2021 * @returns VBox status code.
2022 * @param pVM Pointer to the shared VM structure.
2023 * @param GCPhys The start of the MMIO region.
2024 * @param cb The size of the MMIO region.
2025 */
2026VMMR3DECL(int) PGMR3PhysMMIODeregister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb)
2027{
2028 VM_ASSERT_EMT(pVM);
2029
2030 /*
2031 * First deregister the handler, then check if we should remove the ram range.
2032 */
2033 int rc = PGMHandlerPhysicalDeregister(pVM, GCPhys);
2034 if (RT_SUCCESS(rc))
2035 {
2036 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2037 PPGMRAMRANGE pRamPrev = NULL;
2038 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2039 while (pRam && GCPhysLast >= pRam->GCPhys)
2040 {
2041 /** @todo We're being a bit too careful here. rewrite. */
2042 if ( GCPhysLast == pRam->GCPhysLast
2043 && GCPhys == pRam->GCPhys)
2044 {
2045 Assert(pRam->cb == cb);
2046
2047 /*
2048 * See if all the pages are dead MMIO pages.
2049 */
2050 uint32_t const cPages = cb >> PAGE_SHIFT;
2051 bool fAllMMIO = true;
2052 uint32_t iPage = 0;
2053 uint32_t cLeft = cPages;
2054 while (cLeft-- > 0)
2055 {
2056 PPGMPAGE pPage = &pRam->aPages[iPage];
2057 if ( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_MMIO
2058 /*|| not-out-of-action later */)
2059 {
2060 fAllMMIO = false;
2061 Assert(PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_MMIO2_ALIAS_MMIO);
2062 AssertMsgFailed(("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
2063 break;
2064 }
2065 Assert(PGM_PAGE_IS_ZERO(pPage));
2066 pPage++;
2067 }
2068 if (fAllMMIO)
2069 {
2070 /*
2071 * Ad-hoc range, unlink and free it.
2072 */
2073 Log(("PGMR3PhysMMIODeregister: Freeing ad hoc MMIO range for %RGp-%RGp %s\n",
2074 GCPhys, GCPhysLast, pRam->pszDesc));
2075
2076 pVM->pgm.s.cAllPages -= cPages;
2077 pVM->pgm.s.cPureMmioPages -= cPages;
2078
2079 pgmR3PhysUnlinkRamRange2(pVM, pRam, pRamPrev);
2080 pRam->cb = pRam->GCPhys = pRam->GCPhysLast = NIL_RTGCPHYS;
2081 MMHyperFree(pVM, pRam);
2082 break;
2083 }
2084 }
2085
2086 /*
2087 * Range match? It will all be within one range (see PGMAllHandler.cpp).
2088 */
2089 if ( GCPhysLast >= pRam->GCPhys
2090 && GCPhys <= pRam->GCPhysLast)
2091 {
2092 Assert(GCPhys >= pRam->GCPhys);
2093 Assert(GCPhysLast <= pRam->GCPhysLast);
2094
2095 /*
2096 * Turn the pages back into RAM pages.
2097 */
2098 uint32_t iPage = (GCPhys - pRam->GCPhys) >> PAGE_SHIFT;
2099 uint32_t cLeft = cb >> PAGE_SHIFT;
2100 while (cLeft--)
2101 {
2102 PPGMPAGE pPage = &pRam->aPages[iPage];
2103 AssertMsg(PGM_PAGE_IS_MMIO(pPage), ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
2104 AssertMsg(PGM_PAGE_IS_ZERO(pPage), ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
2105 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO)
2106 PGM_PAGE_SET_TYPE(pPage, PGMPAGETYPE_RAM);
2107 }
2108 break;
2109 }
2110
2111 /* next */
2112 pRamPrev = pRam;
2113 pRam = pRam->pNextR3;
2114 }
2115 }
2116
2117 /* Force a PGM pool flush as guest ram references have been changed. */
2118 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
2119 PVMCPU pVCpu = VMMGetCpu(pVM);
2120 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2121 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2122
2123 PGMPhysInvalidatePageMapTLB(pVM);
2124 return rc;
2125}
2126
2127
2128/**
2129 * Locate a MMIO2 range.
2130 *
2131 * @returns Pointer to the MMIO2 range.
2132 * @param pVM Pointer to the shared VM structure.
2133 * @param pDevIns The device instance owning the region.
2134 * @param iRegion The region.
2135 */
2136DECLINLINE(PPGMMMIO2RANGE) pgmR3PhysMMIO2Find(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
2137{
2138 /*
2139 * Search the list.
2140 */
2141 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
2142 if ( pCur->pDevInsR3 == pDevIns
2143 && pCur->iRegion == iRegion)
2144 return pCur;
2145 return NULL;
2146}
2147
2148
2149/**
2150 * Allocate and register an MMIO2 region.
2151 *
2152 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's RAM
2153 * associated with a device. It is also non-shared memory with a permanent
2154 * ring-3 mapping and page backing (presently).
2155 *
2156 * A MMIO2 range may overlap with base memory if a lot of RAM is configured for
2157 * the VM, in which case we'll drop the base memory pages. Presently we will
2158 * make no attempt to preserve anything that happens to be present in the base
2159 * memory that is replaced, this is of course incorrectly but it's too much
2160 * effort.
2161 *
2162 * @returns VBox status code.
2163 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
2164 * memory.
2165 * @retval VERR_ALREADY_EXISTS if the region already exists.
2166 *
2167 * @param pVM Pointer to the shared VM structure.
2168 * @param pDevIns The device instance owning the region.
2169 * @param iRegion The region number. If the MMIO2 memory is a PCI
2170 * I/O region this number has to be the number of that
2171 * region. Otherwise it can be any number safe
2172 * UINT8_MAX.
2173 * @param cb The size of the region. Must be page aligned.
2174 * @param fFlags Reserved for future use, must be zero.
2175 * @param ppv Where to store the pointer to the ring-3 mapping of
2176 * the memory.
2177 * @param pszDesc The description.
2178 */
2179VMMR3DECL(int) PGMR3PhysMMIO2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags, void **ppv, const char *pszDesc)
2180{
2181 /*
2182 * Validate input.
2183 */
2184 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2185 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2186 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2187 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
2188 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2189 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
2190 AssertReturn(pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion) == NULL, VERR_ALREADY_EXISTS);
2191 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2192 AssertReturn(cb, VERR_INVALID_PARAMETER);
2193 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
2194
2195 const uint32_t cPages = cb >> PAGE_SHIFT;
2196 AssertLogRelReturn(((RTGCPHYS)cPages << PAGE_SHIFT) == cb, VERR_INVALID_PARAMETER);
2197 AssertLogRelReturn(cPages <= INT32_MAX / 2, VERR_NO_MEMORY);
2198
2199 /*
2200 * For the 2nd+ instance, mangle the description string so it's unique.
2201 */
2202 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
2203 {
2204 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
2205 if (!pszDesc)
2206 return VERR_NO_MEMORY;
2207 }
2208
2209 /*
2210 * Try reserve and allocate the backing memory first as this is what is
2211 * most likely to fail.
2212 */
2213 int rc = MMR3AdjustFixedReservation(pVM, cPages, pszDesc);
2214 if (RT_SUCCESS(rc))
2215 {
2216 void *pvPages;
2217 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cPages * sizeof(SUPPAGE));
2218 if (RT_SUCCESS(rc))
2219 rc = SUPR3PageAllocEx(cPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
2220 if (RT_SUCCESS(rc))
2221 {
2222 memset(pvPages, 0, cPages * PAGE_SIZE);
2223
2224 /*
2225 * Create the MMIO2 range record for it.
2226 */
2227 const size_t cbRange = RT_OFFSETOF(PGMMMIO2RANGE, RamRange.aPages[cPages]);
2228 PPGMMMIO2RANGE pNew;
2229 rc = MMR3HyperAllocOnceNoRel(pVM, cbRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
2230 AssertLogRelMsgRC(rc, ("cbRamRange=%zu\n", cbRange));
2231 if (RT_SUCCESS(rc))
2232 {
2233 pNew->pDevInsR3 = pDevIns;
2234 pNew->pvR3 = pvPages;
2235 //pNew->pNext = NULL;
2236 //pNew->fMapped = false;
2237 //pNew->fOverlapping = false;
2238 pNew->iRegion = iRegion;
2239 pNew->idSavedState = UINT8_MAX;
2240 pNew->RamRange.pSelfR0 = MMHyperCCToR0(pVM, &pNew->RamRange);
2241 pNew->RamRange.pSelfRC = MMHyperCCToRC(pVM, &pNew->RamRange);
2242 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
2243 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
2244 pNew->RamRange.pszDesc = pszDesc;
2245 pNew->RamRange.cb = cb;
2246 pNew->RamRange.fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO2;
2247 pNew->RamRange.pvR3 = pvPages;
2248 //pNew->RamRange.paLSPages = NULL;
2249
2250 uint32_t iPage = cPages;
2251 while (iPage-- > 0)
2252 {
2253 PGM_PAGE_INIT(&pNew->RamRange.aPages[iPage],
2254 paPages[iPage].Phys, NIL_GMM_PAGEID,
2255 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
2256 }
2257
2258 /* update page count stats */
2259 pVM->pgm.s.cAllPages += cPages;
2260 pVM->pgm.s.cPrivatePages += cPages;
2261
2262 /*
2263 * Link it into the list.
2264 * Since there is no particular order, just push it.
2265 */
2266 pgmLock(pVM);
2267 pNew->pNextR3 = pVM->pgm.s.pMmio2RangesR3;
2268 pVM->pgm.s.pMmio2RangesR3 = pNew;
2269 pgmUnlock(pVM);
2270
2271 *ppv = pvPages;
2272 RTMemTmpFree(paPages);
2273 PGMPhysInvalidatePageMapTLB(pVM);
2274 return VINF_SUCCESS;
2275 }
2276
2277 SUPR3PageFreeEx(pvPages, cPages);
2278 }
2279 RTMemTmpFree(paPages);
2280 MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pszDesc);
2281 }
2282 if (pDevIns->iInstance > 0)
2283 MMR3HeapFree((void *)pszDesc);
2284 return rc;
2285}
2286
2287
2288/**
2289 * Deregisters and frees an MMIO2 region.
2290 *
2291 * Any physical (and virtual) access handlers registered for the region must
2292 * be deregistered before calling this function.
2293 *
2294 * @returns VBox status code.
2295 * @param pVM Pointer to the shared VM structure.
2296 * @param pDevIns The device instance owning the region.
2297 * @param iRegion The region. If it's UINT32_MAX it'll be a wildcard match.
2298 */
2299VMMR3DECL(int) PGMR3PhysMMIO2Deregister(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
2300{
2301 /*
2302 * Validate input.
2303 */
2304 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2305 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2306 AssertReturn(iRegion <= UINT8_MAX || iRegion == UINT32_MAX, VERR_INVALID_PARAMETER);
2307
2308 pgmLock(pVM);
2309 int rc = VINF_SUCCESS;
2310 unsigned cFound = 0;
2311 PPGMMMIO2RANGE pPrev = NULL;
2312 PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3;
2313 while (pCur)
2314 {
2315 if ( pCur->pDevInsR3 == pDevIns
2316 && ( iRegion == UINT32_MAX
2317 || pCur->iRegion == iRegion))
2318 {
2319 cFound++;
2320
2321 /*
2322 * Unmap it if it's mapped.
2323 */
2324 if (pCur->fMapped)
2325 {
2326 int rc2 = PGMR3PhysMMIO2Unmap(pVM, pCur->pDevInsR3, pCur->iRegion, pCur->RamRange.GCPhys);
2327 AssertRC(rc2);
2328 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2329 rc = rc2;
2330 }
2331
2332 /*
2333 * Unlink it
2334 */
2335 PPGMMMIO2RANGE pNext = pCur->pNextR3;
2336 if (pPrev)
2337 pPrev->pNextR3 = pNext;
2338 else
2339 pVM->pgm.s.pMmio2RangesR3 = pNext;
2340 pCur->pNextR3 = NULL;
2341
2342 /*
2343 * Free the memory.
2344 */
2345 int rc2 = SUPR3PageFreeEx(pCur->pvR3, pCur->RamRange.cb >> PAGE_SHIFT);
2346 AssertRC(rc2);
2347 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2348 rc = rc2;
2349
2350 uint32_t const cPages = pCur->RamRange.cb >> PAGE_SHIFT;
2351 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pCur->RamRange.pszDesc);
2352 AssertRC(rc2);
2353 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2354 rc = rc2;
2355
2356 /* we're leaking hyper memory here if done at runtime. */
2357#ifdef VBOX_STRICT
2358 VMSTATE const enmState = VMR3GetState(pVM);
2359 AssertMsg( enmState == VMSTATE_POWERING_OFF
2360 || enmState == VMSTATE_POWERING_OFF_LS
2361 || enmState == VMSTATE_OFF
2362 || enmState == VMSTATE_OFF_LS
2363 || enmState == VMSTATE_DESTROYING
2364 || enmState == VMSTATE_TERMINATED
2365 || enmState == VMSTATE_CREATING
2366 , ("%s\n", VMR3GetStateName(enmState)));
2367#endif
2368 /*rc = MMHyperFree(pVM, pCur);
2369 AssertRCReturn(rc, rc); - not safe, see the alloc call. */
2370
2371
2372 /* update page count stats */
2373 pVM->pgm.s.cAllPages -= cPages;
2374 pVM->pgm.s.cPrivatePages -= cPages;
2375
2376 /* next */
2377 pCur = pNext;
2378 }
2379 else
2380 {
2381 pPrev = pCur;
2382 pCur = pCur->pNextR3;
2383 }
2384 }
2385 PGMPhysInvalidatePageMapTLB(pVM);
2386 pgmUnlock(pVM);
2387 return !cFound && iRegion != UINT32_MAX ? VERR_NOT_FOUND : rc;
2388}
2389
2390
2391/**
2392 * Maps a MMIO2 region.
2393 *
2394 * This is done when a guest / the bios / state loading changes the
2395 * PCI config. The replacing of base memory has the same restrictions
2396 * as during registration, of course.
2397 *
2398 * @returns VBox status code.
2399 *
2400 * @param pVM Pointer to the shared VM structure.
2401 * @param pDevIns The
2402 */
2403VMMR3DECL(int) PGMR3PhysMMIO2Map(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
2404{
2405 /*
2406 * Validate input
2407 */
2408 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2409 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2410 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2411 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
2412 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
2413 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2414
2415 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2416 AssertReturn(pCur, VERR_NOT_FOUND);
2417 AssertReturn(!pCur->fMapped, VERR_WRONG_ORDER);
2418 Assert(pCur->RamRange.GCPhys == NIL_RTGCPHYS);
2419 Assert(pCur->RamRange.GCPhysLast == NIL_RTGCPHYS);
2420
2421 const RTGCPHYS GCPhysLast = GCPhys + pCur->RamRange.cb - 1;
2422 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2423
2424 /*
2425 * Find our location in the ram range list, checking for
2426 * restriction we don't bother implementing yet (partially overlapping).
2427 */
2428 bool fRamExists = false;
2429 PPGMRAMRANGE pRamPrev = NULL;
2430 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2431 while (pRam && GCPhysLast >= pRam->GCPhys)
2432 {
2433 if ( GCPhys <= pRam->GCPhysLast
2434 && GCPhysLast >= pRam->GCPhys)
2435 {
2436 /* completely within? */
2437 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
2438 && GCPhysLast <= pRam->GCPhysLast,
2439 ("%RGp-%RGp (MMIO2/%s) falls partly outside %RGp-%RGp (%s)\n",
2440 GCPhys, GCPhysLast, pCur->RamRange.pszDesc,
2441 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2442 VERR_PGM_RAM_CONFLICT);
2443 fRamExists = true;
2444 break;
2445 }
2446
2447 /* next */
2448 pRamPrev = pRam;
2449 pRam = pRam->pNextR3;
2450 }
2451 if (fRamExists)
2452 {
2453 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2454 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2455 while (cPagesLeft-- > 0)
2456 {
2457 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
2458 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
2459 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pCur->RamRange.pszDesc),
2460 VERR_PGM_RAM_CONFLICT);
2461 pPage++;
2462 }
2463 }
2464 Log(("PGMR3PhysMMIO2Map: %RGp-%RGp fRamExists=%RTbool %s\n",
2465 GCPhys, GCPhysLast, fRamExists, pCur->RamRange.pszDesc));
2466
2467 /*
2468 * Make the changes.
2469 */
2470 pgmLock(pVM);
2471
2472 pCur->RamRange.GCPhys = GCPhys;
2473 pCur->RamRange.GCPhysLast = GCPhysLast;
2474 pCur->fMapped = true;
2475 pCur->fOverlapping = fRamExists;
2476
2477 if (fRamExists)
2478 {
2479/** @todo use pgmR3PhysFreePageRange here. */
2480 uint32_t cPendingPages = 0;
2481 PGMMFREEPAGESREQ pReq;
2482 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2483 AssertLogRelRCReturn(rc, rc);
2484
2485 /* replace the pages, freeing all present RAM pages. */
2486 PPGMPAGE pPageSrc = &pCur->RamRange.aPages[0];
2487 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2488 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2489 while (cPagesLeft-- > 0)
2490 {
2491 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys);
2492 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
2493
2494 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
2495 PGM_PAGE_SET_HCPHYS(pPageDst, HCPhys);
2496 PGM_PAGE_SET_TYPE(pPageDst, PGMPAGETYPE_MMIO2);
2497 PGM_PAGE_SET_STATE(pPageDst, PGM_PAGE_STATE_ALLOCATED);
2498 PGM_PAGE_SET_PDE_TYPE(pPageDst, PGM_PAGE_PDE_TYPE_DONTCARE);
2499 PGM_PAGE_SET_PTE_INDEX(pPageDst, 0);
2500 PGM_PAGE_SET_TRACKING(pPageDst, 0);
2501
2502 pVM->pgm.s.cZeroPages--;
2503 GCPhys += PAGE_SIZE;
2504 pPageSrc++;
2505 pPageDst++;
2506 }
2507
2508 /* Flush physical page map TLB. */
2509 PGMPhysInvalidatePageMapTLB(pVM);
2510
2511 if (cPendingPages)
2512 {
2513 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2514 AssertLogRelRCReturn(rc, rc);
2515 }
2516 GMMR3FreePagesCleanup(pReq);
2517
2518 /* Force a PGM pool flush as guest ram references have been changed. */
2519 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
2520 PVMCPU pVCpu = VMMGetCpu(pVM);
2521 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2522 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2523
2524 pgmUnlock(pVM);
2525 }
2526 else
2527 {
2528 RTGCPHYS cb = pCur->RamRange.cb;
2529
2530 /* Clear the tracking data of pages we're going to reactivate. */
2531 PPGMPAGE pPageSrc = &pCur->RamRange.aPages[0];
2532 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2533 while (cPagesLeft-- > 0)
2534 {
2535 PGM_PAGE_SET_TRACKING(pPageSrc, 0);
2536 PGM_PAGE_SET_PTE_INDEX(pPageSrc, 0);
2537 pPageSrc++;
2538 }
2539
2540 /* link in the ram range */
2541 pgmR3PhysLinkRamRange(pVM, &pCur->RamRange, pRamPrev);
2542 pgmUnlock(pVM);
2543
2544 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_MMIO2);
2545 }
2546
2547 PGMPhysInvalidatePageMapTLB(pVM);
2548 return VINF_SUCCESS;
2549}
2550
2551
2552/**
2553 * Unmaps a MMIO2 region.
2554 *
2555 * This is done when a guest / the bios / state loading changes the
2556 * PCI config. The replacing of base memory has the same restrictions
2557 * as during registration, of course.
2558 */
2559VMMR3DECL(int) PGMR3PhysMMIO2Unmap(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
2560{
2561 /*
2562 * Validate input
2563 */
2564 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2565 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2566 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2567 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
2568 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
2569 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2570
2571 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2572 AssertReturn(pCur, VERR_NOT_FOUND);
2573 AssertReturn(pCur->fMapped, VERR_WRONG_ORDER);
2574 AssertReturn(pCur->RamRange.GCPhys == GCPhys, VERR_INVALID_PARAMETER);
2575 Assert(pCur->RamRange.GCPhysLast != NIL_RTGCPHYS);
2576
2577 Log(("PGMR3PhysMMIO2Unmap: %RGp-%RGp %s\n",
2578 pCur->RamRange.GCPhys, pCur->RamRange.GCPhysLast, pCur->RamRange.pszDesc));
2579
2580 /*
2581 * Unmap it.
2582 */
2583 pgmLock(pVM);
2584
2585 RTGCPHYS GCPhysRangeREM;
2586 RTGCPHYS cbRangeREM;
2587 bool fInformREM;
2588 if (pCur->fOverlapping)
2589 {
2590 /* Restore the RAM pages we've replaced. */
2591 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2592 while (pRam->GCPhys > pCur->RamRange.GCPhysLast)
2593 pRam = pRam->pNextR3;
2594
2595 PPGMPAGE pPageDst = &pRam->aPages[(pCur->RamRange.GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2596 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2597 while (cPagesLeft-- > 0)
2598 {
2599 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
2600 pVM->pgm.s.cZeroPages++;
2601 pPageDst++;
2602 }
2603
2604 /* Flush physical page map TLB. */
2605 PGMPhysInvalidatePageMapTLB(pVM);
2606
2607 GCPhysRangeREM = NIL_RTGCPHYS; /* shuts up gcc */
2608 cbRangeREM = RTGCPHYS_MAX; /* ditto */
2609 fInformREM = false;
2610 }
2611 else
2612 {
2613 GCPhysRangeREM = pCur->RamRange.GCPhys;
2614 cbRangeREM = pCur->RamRange.cb;
2615 fInformREM = true;
2616
2617 pgmR3PhysUnlinkRamRange(pVM, &pCur->RamRange);
2618 }
2619
2620 pCur->RamRange.GCPhys = NIL_RTGCPHYS;
2621 pCur->RamRange.GCPhysLast = NIL_RTGCPHYS;
2622 pCur->fOverlapping = false;
2623 pCur->fMapped = false;
2624
2625 /* Force a PGM pool flush as guest ram references have been changed. */
2626 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
2627 PVMCPU pVCpu = VMMGetCpu(pVM);
2628 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2629 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2630
2631 PGMPhysInvalidatePageMapTLB(pVM);
2632 pgmUnlock(pVM);
2633
2634 if (fInformREM)
2635 REMR3NotifyPhysRamDeregister(pVM, GCPhysRangeREM, cbRangeREM);
2636
2637 return VINF_SUCCESS;
2638}
2639
2640
2641/**
2642 * Checks if the given address is an MMIO2 base address or not.
2643 *
2644 * @returns true/false accordingly.
2645 * @param pVM Pointer to the shared VM structure.
2646 * @param pDevIns The owner of the memory, optional.
2647 * @param GCPhys The address to check.
2648 */
2649VMMR3DECL(bool) PGMR3PhysMMIO2IsBase(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys)
2650{
2651 /*
2652 * Validate input
2653 */
2654 VM_ASSERT_EMT_RETURN(pVM, false);
2655 AssertPtrReturn(pDevIns, false);
2656 AssertReturn(GCPhys != NIL_RTGCPHYS, false);
2657 AssertReturn(GCPhys != 0, false);
2658 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), false);
2659
2660 /*
2661 * Search the list.
2662 */
2663 pgmLock(pVM);
2664 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
2665 if (pCur->RamRange.GCPhys == GCPhys)
2666 {
2667 Assert(pCur->fMapped);
2668 pgmUnlock(pVM);
2669 return true;
2670 }
2671 pgmUnlock(pVM);
2672 return false;
2673}
2674
2675
2676/**
2677 * Gets the HC physical address of a page in the MMIO2 region.
2678 *
2679 * This is API is intended for MMHyper and shouldn't be called
2680 * by anyone else...
2681 *
2682 * @returns VBox status code.
2683 * @param pVM Pointer to the shared VM structure.
2684 * @param pDevIns The owner of the memory, optional.
2685 * @param iRegion The region.
2686 * @param off The page expressed an offset into the MMIO2 region.
2687 * @param pHCPhys Where to store the result.
2688 */
2689VMMR3DECL(int) PGMR3PhysMMIO2GetHCPhys(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, PRTHCPHYS pHCPhys)
2690{
2691 /*
2692 * Validate input
2693 */
2694 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2695 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2696 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2697
2698 pgmLock(pVM);
2699 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2700 AssertReturn(pCur, VERR_NOT_FOUND);
2701 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2702
2703 PCPGMPAGE pPage = &pCur->RamRange.aPages[off >> PAGE_SHIFT];
2704 *pHCPhys = PGM_PAGE_GET_HCPHYS(pPage);
2705 pgmUnlock(pVM);
2706 return VINF_SUCCESS;
2707}
2708
2709
2710/**
2711 * Maps a portion of an MMIO2 region into kernel space (host).
2712 *
2713 * The kernel mapping will become invalid when the MMIO2 memory is deregistered
2714 * or the VM is terminated.
2715 *
2716 * @return VBox status code.
2717 *
2718 * @param pVM Pointer to the shared VM structure.
2719 * @param pDevIns The device owning the MMIO2 memory.
2720 * @param iRegion The region.
2721 * @param off The offset into the region. Must be page aligned.
2722 * @param cb The number of bytes to map. Must be page aligned.
2723 * @param pszDesc Mapping description.
2724 * @param pR0Ptr Where to store the R0 address.
2725 */
2726VMMR3DECL(int) PGMR3PhysMMIO2MapKernel(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, RTGCPHYS cb,
2727 const char *pszDesc, PRTR0PTR pR0Ptr)
2728{
2729 /*
2730 * Validate input.
2731 */
2732 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2733 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2734 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2735
2736 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2737 AssertReturn(pCur, VERR_NOT_FOUND);
2738 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2739 AssertReturn(cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2740 AssertReturn(off + cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2741
2742 /*
2743 * Pass the request on to the support library/driver.
2744 */
2745 int rc = SUPR3PageMapKernel(pCur->pvR3, off, cb, 0, pR0Ptr);
2746
2747 return rc;
2748}
2749
2750
2751/**
2752 * Registers a ROM image.
2753 *
2754 * Shadowed ROM images requires double the amount of backing memory, so,
2755 * don't use that unless you have to. Shadowing of ROM images is process
2756 * where we can select where the reads go and where the writes go. On real
2757 * hardware the chipset provides means to configure this. We provide
2758 * PGMR3PhysProtectROM() for this purpose.
2759 *
2760 * A read-only copy of the ROM image will always be kept around while we
2761 * will allocate RAM pages for the changes on demand (unless all memory
2762 * is configured to be preallocated).
2763 *
2764 * @returns VBox status.
2765 * @param pVM VM Handle.
2766 * @param pDevIns The device instance owning the ROM.
2767 * @param GCPhys First physical address in the range.
2768 * Must be page aligned!
2769 * @param cb The size of the range (in bytes).
2770 * Must be page aligned!
2771 * @param pvBinary Pointer to the binary data backing the ROM image.
2772 * @param cbBinary The size of the binary data pvBinary points to.
2773 * This must be less or equal to @a cb.
2774 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
2775 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
2776 * @param pszDesc Pointer to description string. This must not be freed.
2777 *
2778 * @remark There is no way to remove the rom, automatically on device cleanup or
2779 * manually from the device yet. This isn't difficult in any way, it's
2780 * just not something we expect to be necessary for a while.
2781 */
2782VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
2783 const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
2784{
2785 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p cbBinary=%#x fFlags=%#x pszDesc=%s\n",
2786 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, cbBinary, fFlags, pszDesc));
2787
2788 /*
2789 * Validate input.
2790 */
2791 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2792 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
2793 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
2794 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2795 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2796 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
2797 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2798 AssertReturn(!(fFlags & ~(PGMPHYS_ROM_FLAGS_SHADOWED | PGMPHYS_ROM_FLAGS_PERMANENT_BINARY)), VERR_INVALID_PARAMETER);
2799 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
2800
2801 const uint32_t cPages = cb >> PAGE_SHIFT;
2802
2803 /*
2804 * Find the ROM location in the ROM list first.
2805 */
2806 PPGMROMRANGE pRomPrev = NULL;
2807 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
2808 while (pRom && GCPhysLast >= pRom->GCPhys)
2809 {
2810 if ( GCPhys <= pRom->GCPhysLast
2811 && GCPhysLast >= pRom->GCPhys)
2812 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
2813 GCPhys, GCPhysLast, pszDesc,
2814 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
2815 VERR_PGM_RAM_CONFLICT);
2816 /* next */
2817 pRomPrev = pRom;
2818 pRom = pRom->pNextR3;
2819 }
2820
2821 /*
2822 * Find the RAM location and check for conflicts.
2823 *
2824 * Conflict detection is a bit different than for RAM
2825 * registration since a ROM can be located within a RAM
2826 * range. So, what we have to check for is other memory
2827 * types (other than RAM that is) and that we don't span
2828 * more than one RAM range (layz).
2829 */
2830 bool fRamExists = false;
2831 PPGMRAMRANGE pRamPrev = NULL;
2832 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2833 while (pRam && GCPhysLast >= pRam->GCPhys)
2834 {
2835 if ( GCPhys <= pRam->GCPhysLast
2836 && GCPhysLast >= pRam->GCPhys)
2837 {
2838 /* completely within? */
2839 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
2840 && GCPhysLast <= pRam->GCPhysLast,
2841 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
2842 GCPhys, GCPhysLast, pszDesc,
2843 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2844 VERR_PGM_RAM_CONFLICT);
2845 fRamExists = true;
2846 break;
2847 }
2848
2849 /* next */
2850 pRamPrev = pRam;
2851 pRam = pRam->pNextR3;
2852 }
2853 if (fRamExists)
2854 {
2855 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2856 uint32_t cPagesLeft = cPages;
2857 while (cPagesLeft-- > 0)
2858 {
2859 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
2860 ("%RGp (%R[pgmpage]) isn't a RAM page - registering %RGp-%RGp (%s).\n",
2861 pRam->GCPhys + ((RTGCPHYS)(uintptr_t)(pPage - &pRam->aPages[0]) << PAGE_SHIFT),
2862 pPage, GCPhys, GCPhysLast, pszDesc), VERR_PGM_RAM_CONFLICT);
2863 Assert(PGM_PAGE_IS_ZERO(pPage));
2864 pPage++;
2865 }
2866 }
2867
2868 /*
2869 * Update the base memory reservation if necessary.
2870 */
2871 uint32_t cExtraBaseCost = fRamExists ? 0 : cPages;
2872 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
2873 cExtraBaseCost += cPages;
2874 if (cExtraBaseCost)
2875 {
2876 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
2877 if (RT_FAILURE(rc))
2878 return rc;
2879 }
2880
2881 /*
2882 * Allocate memory for the virgin copy of the RAM.
2883 */
2884 PGMMALLOCATEPAGESREQ pReq;
2885 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cPages, GMMACCOUNT_BASE);
2886 AssertRCReturn(rc, rc);
2887
2888 for (uint32_t iPage = 0; iPage < cPages; iPage++)
2889 {
2890 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << PAGE_SHIFT);
2891 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
2892 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
2893 }
2894
2895 pgmLock(pVM);
2896 rc = GMMR3AllocatePagesPerform(pVM, pReq);
2897 pgmUnlock(pVM);
2898 if (RT_FAILURE(rc))
2899 {
2900 GMMR3AllocatePagesCleanup(pReq);
2901 return rc;
2902 }
2903
2904 /*
2905 * Allocate the new ROM range and RAM range (if necessary).
2906 */
2907 PPGMROMRANGE pRomNew;
2908 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMROMRANGE, aPages[cPages]), 0, MM_TAG_PGM_PHYS, (void **)&pRomNew);
2909 if (RT_SUCCESS(rc))
2910 {
2911 PPGMRAMRANGE pRamNew = NULL;
2912 if (!fRamExists)
2913 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), sizeof(PGMPAGE), MM_TAG_PGM_PHYS, (void **)&pRamNew);
2914 if (RT_SUCCESS(rc))
2915 {
2916 pgmLock(pVM);
2917
2918 /*
2919 * Initialize and insert the RAM range (if required).
2920 */
2921 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
2922 if (!fRamExists)
2923 {
2924 pRamNew->pSelfR0 = MMHyperCCToR0(pVM, pRamNew);
2925 pRamNew->pSelfRC = MMHyperCCToRC(pVM, pRamNew);
2926 pRamNew->GCPhys = GCPhys;
2927 pRamNew->GCPhysLast = GCPhysLast;
2928 pRamNew->cb = cb;
2929 pRamNew->pszDesc = pszDesc;
2930 pRamNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_ROM;
2931 pRamNew->pvR3 = NULL;
2932 pRamNew->paLSPages = NULL;
2933
2934 PPGMPAGE pPage = &pRamNew->aPages[0];
2935 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
2936 {
2937 PGM_PAGE_INIT(pPage,
2938 pReq->aPages[iPage].HCPhysGCPhys,
2939 pReq->aPages[iPage].idPage,
2940 PGMPAGETYPE_ROM,
2941 PGM_PAGE_STATE_ALLOCATED);
2942
2943 pRomPage->Virgin = *pPage;
2944 }
2945
2946 pVM->pgm.s.cAllPages += cPages;
2947 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
2948 }
2949 else
2950 {
2951 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2952 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
2953 {
2954 PGM_PAGE_SET_TYPE(pPage, PGMPAGETYPE_ROM);
2955 PGM_PAGE_SET_HCPHYS(pPage, pReq->aPages[iPage].HCPhysGCPhys);
2956 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ALLOCATED);
2957 PGM_PAGE_SET_PAGEID(pPage, pReq->aPages[iPage].idPage);
2958 PGM_PAGE_SET_PDE_TYPE(pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
2959 PGM_PAGE_SET_PTE_INDEX(pPage, 0);
2960 PGM_PAGE_SET_TRACKING(pPage, 0);
2961
2962 pRomPage->Virgin = *pPage;
2963 }
2964
2965 pRamNew = pRam;
2966
2967 pVM->pgm.s.cZeroPages -= cPages;
2968 }
2969 pVM->pgm.s.cPrivatePages += cPages;
2970
2971 /* Flush physical page map TLB. */
2972 PGMPhysInvalidatePageMapTLB(pVM);
2973
2974 pgmUnlock(pVM);
2975
2976
2977 /*
2978 * !HACK ALERT! REM + (Shadowed) ROM ==> mess.
2979 *
2980 * If it's shadowed we'll register the handler after the ROM notification
2981 * so we get the access handler callbacks that we should. If it isn't
2982 * shadowed we'll do it the other way around to make REM use the built-in
2983 * ROM behavior and not the handler behavior (which is to route all access
2984 * to PGM atm).
2985 */
2986 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
2987 {
2988 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, true /* fShadowed */);
2989 rc = PGMR3HandlerPhysicalRegister(pVM,
2990 fFlags & PGMPHYS_ROM_FLAGS_SHADOWED
2991 ? PGMPHYSHANDLERTYPE_PHYSICAL_ALL
2992 : PGMPHYSHANDLERTYPE_PHYSICAL_WRITE,
2993 GCPhys, GCPhysLast,
2994 pgmR3PhysRomWriteHandler, pRomNew,
2995 NULL, "pgmPhysRomWriteHandler", MMHyperCCToR0(pVM, pRomNew),
2996 NULL, "pgmPhysRomWriteHandler", MMHyperCCToRC(pVM, pRomNew), pszDesc);
2997 }
2998 else
2999 {
3000 rc = PGMR3HandlerPhysicalRegister(pVM,
3001 fFlags & PGMPHYS_ROM_FLAGS_SHADOWED
3002 ? PGMPHYSHANDLERTYPE_PHYSICAL_ALL
3003 : PGMPHYSHANDLERTYPE_PHYSICAL_WRITE,
3004 GCPhys, GCPhysLast,
3005 pgmR3PhysRomWriteHandler, pRomNew,
3006 NULL, "pgmPhysRomWriteHandler", MMHyperCCToR0(pVM, pRomNew),
3007 NULL, "pgmPhysRomWriteHandler", MMHyperCCToRC(pVM, pRomNew), pszDesc);
3008 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, false /* fShadowed */);
3009 }
3010 if (RT_SUCCESS(rc))
3011 {
3012 pgmLock(pVM);
3013
3014 /*
3015 * Copy the image over to the virgin pages.
3016 * This must be done after linking in the RAM range.
3017 */
3018 size_t cbBinaryLeft = cbBinary;
3019 PPGMPAGE pRamPage = &pRamNew->aPages[(GCPhys - pRamNew->GCPhys) >> PAGE_SHIFT];
3020 for (uint32_t iPage = 0; iPage < cPages; iPage++, pRamPage++)
3021 {
3022 void *pvDstPage;
3023 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << PAGE_SHIFT), &pvDstPage);
3024 if (RT_FAILURE(rc))
3025 {
3026 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
3027 break;
3028 }
3029 if (cbBinaryLeft >= PAGE_SIZE)
3030 {
3031 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), PAGE_SIZE);
3032 cbBinaryLeft -= PAGE_SIZE;
3033 }
3034 else
3035 {
3036 ASMMemZeroPage(pvDstPage); /* (shouldn't be necessary, but can't hurt either) */
3037 if (cbBinaryLeft > 0)
3038 {
3039 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), cbBinaryLeft);
3040 cbBinaryLeft = 0;
3041 }
3042 }
3043 }
3044 if (RT_SUCCESS(rc))
3045 {
3046 /*
3047 * Initialize the ROM range.
3048 * Note that the Virgin member of the pages has already been initialized above.
3049 */
3050 pRomNew->GCPhys = GCPhys;
3051 pRomNew->GCPhysLast = GCPhysLast;
3052 pRomNew->cb = cb;
3053 pRomNew->fFlags = fFlags;
3054 pRomNew->idSavedState = UINT8_MAX;
3055 pRomNew->cbOriginal = cbBinary;
3056#ifdef VBOX_STRICT
3057 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY
3058 ? pvBinary : RTMemDup(pvBinary, cbBinary);
3059#else
3060 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY ? pvBinary : NULL;
3061#endif
3062 pRomNew->pszDesc = pszDesc;
3063
3064 for (unsigned iPage = 0; iPage < cPages; iPage++)
3065 {
3066 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
3067 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
3068 PGM_PAGE_INIT_ZERO(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
3069 }
3070
3071 /* update the page count stats for the shadow pages. */
3072 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3073 {
3074 pVM->pgm.s.cZeroPages += cPages;
3075 pVM->pgm.s.cAllPages += cPages;
3076 }
3077
3078 /*
3079 * Insert the ROM range, tell REM and return successfully.
3080 */
3081 pRomNew->pNextR3 = pRom;
3082 pRomNew->pNextR0 = pRom ? MMHyperCCToR0(pVM, pRom) : NIL_RTR0PTR;
3083 pRomNew->pNextRC = pRom ? MMHyperCCToRC(pVM, pRom) : NIL_RTRCPTR;
3084
3085 if (pRomPrev)
3086 {
3087 pRomPrev->pNextR3 = pRomNew;
3088 pRomPrev->pNextR0 = MMHyperCCToR0(pVM, pRomNew);
3089 pRomPrev->pNextRC = MMHyperCCToRC(pVM, pRomNew);
3090 }
3091 else
3092 {
3093 pVM->pgm.s.pRomRangesR3 = pRomNew;
3094 pVM->pgm.s.pRomRangesR0 = MMHyperCCToR0(pVM, pRomNew);
3095 pVM->pgm.s.pRomRangesRC = MMHyperCCToRC(pVM, pRomNew);
3096 }
3097
3098 PGMPhysInvalidatePageMapTLB(pVM);
3099 GMMR3AllocatePagesCleanup(pReq);
3100 pgmUnlock(pVM);
3101 return VINF_SUCCESS;
3102 }
3103
3104 /* bail out */
3105
3106 pgmUnlock(pVM);
3107 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
3108 AssertRC(rc2);
3109 pgmLock(pVM);
3110 }
3111
3112 if (!fRamExists)
3113 {
3114 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
3115 MMHyperFree(pVM, pRamNew);
3116 }
3117 }
3118 MMHyperFree(pVM, pRomNew);
3119 }
3120
3121 /** @todo Purge the mapping cache or something... */
3122 GMMR3FreeAllocatedPages(pVM, pReq);
3123 GMMR3AllocatePagesCleanup(pReq);
3124 pgmUnlock(pVM);
3125 return rc;
3126}
3127
3128
3129/**
3130 * \#PF Handler callback for ROM write accesses.
3131 *
3132 * @returns VINF_SUCCESS if the handler have carried out the operation.
3133 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
3134 * @param pVM VM Handle.
3135 * @param GCPhys The physical address the guest is writing to.
3136 * @param pvPhys The HC mapping of that address.
3137 * @param pvBuf What the guest is reading/writing.
3138 * @param cbBuf How much it's reading/writing.
3139 * @param enmAccessType The access type.
3140 * @param pvUser User argument.
3141 */
3142static DECLCALLBACK(int) pgmR3PhysRomWriteHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf,
3143 PGMACCESSTYPE enmAccessType, void *pvUser)
3144{
3145 PPGMROMRANGE pRom = (PPGMROMRANGE)pvUser;
3146 const uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
3147 Assert(iPage < (pRom->cb >> PAGE_SHIFT));
3148 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
3149 Log5(("pgmR3PhysRomWriteHandler: %d %c %#08RGp %#04zx\n", pRomPage->enmProt, enmAccessType == PGMACCESSTYPE_READ ? 'R' : 'W', GCPhys, cbBuf));
3150
3151 if (enmAccessType == PGMACCESSTYPE_READ)
3152 {
3153 switch (pRomPage->enmProt)
3154 {
3155 /*
3156 * Take the default action.
3157 */
3158 case PGMROMPROT_READ_ROM_WRITE_IGNORE:
3159 case PGMROMPROT_READ_RAM_WRITE_IGNORE:
3160 case PGMROMPROT_READ_ROM_WRITE_RAM:
3161 case PGMROMPROT_READ_RAM_WRITE_RAM:
3162 return VINF_PGM_HANDLER_DO_DEFAULT;
3163
3164 default:
3165 AssertMsgFailedReturn(("enmProt=%d iPage=%d GCPhys=%RGp\n",
3166 pRom->aPages[iPage].enmProt, iPage, GCPhys),
3167 VERR_INTERNAL_ERROR);
3168 }
3169 }
3170 else
3171 {
3172 Assert(enmAccessType == PGMACCESSTYPE_WRITE);
3173 switch (pRomPage->enmProt)
3174 {
3175 /*
3176 * Ignore writes.
3177 */
3178 case PGMROMPROT_READ_ROM_WRITE_IGNORE:
3179 case PGMROMPROT_READ_RAM_WRITE_IGNORE:
3180 return VINF_SUCCESS;
3181
3182 /*
3183 * Write to the RAM page.
3184 */
3185 case PGMROMPROT_READ_ROM_WRITE_RAM:
3186 case PGMROMPROT_READ_RAM_WRITE_RAM: /* yes this will get here too, it's *way* simpler that way. */
3187 {
3188 /* This should be impossible now, pvPhys doesn't work cross page anylonger. */
3189 Assert(((GCPhys - pRom->GCPhys + cbBuf - 1) >> PAGE_SHIFT) == iPage);
3190
3191 /*
3192 * Take the lock, do lazy allocation, map the page and copy the data.
3193 *
3194 * Note that we have to bypass the mapping TLB since it works on
3195 * guest physical addresses and entering the shadow page would
3196 * kind of screw things up...
3197 */
3198 int rc = pgmLock(pVM);
3199 AssertRC(rc);
3200
3201 PPGMPAGE pShadowPage = &pRomPage->Shadow;
3202 if (!PGMROMPROT_IS_ROM(pRomPage->enmProt))
3203 {
3204 pShadowPage = pgmPhysGetPage(&pVM->pgm.s, GCPhys);
3205 AssertLogRelReturn(pShadowPage, VERR_INTERNAL_ERROR);
3206 }
3207
3208 void *pvDstPage;
3209 rc = pgmPhysPageMakeWritableAndMap(pVM, pShadowPage, GCPhys & X86_PTE_PG_MASK, &pvDstPage);
3210 if (RT_SUCCESS(rc))
3211 {
3212 memcpy((uint8_t *)pvDstPage + (GCPhys & PAGE_OFFSET_MASK), pvBuf, cbBuf);
3213 pRomPage->LiveSave.fWrittenTo = true;
3214 }
3215
3216 pgmUnlock(pVM);
3217 return rc;
3218 }
3219
3220 default:
3221 AssertMsgFailedReturn(("enmProt=%d iPage=%d GCPhys=%RGp\n",
3222 pRom->aPages[iPage].enmProt, iPage, GCPhys),
3223 VERR_INTERNAL_ERROR);
3224 }
3225 }
3226}
3227
3228
3229/**
3230 * Called by PGMR3Reset to reset the shadow, switch to the virgin,
3231 * and verify that the virgin part is untouched.
3232 *
3233 * This is done after the normal memory has been cleared.
3234 *
3235 * ASSUMES that the caller owns the PGM lock.
3236 *
3237 * @param pVM The VM handle.
3238 */
3239int pgmR3PhysRomReset(PVM pVM)
3240{
3241 Assert(PGMIsLockOwner(pVM));
3242 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3243 {
3244 const uint32_t cPages = pRom->cb >> PAGE_SHIFT;
3245
3246 if (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3247 {
3248 /*
3249 * Reset the physical handler.
3250 */
3251 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
3252 AssertRCReturn(rc, rc);
3253
3254 /*
3255 * What we do with the shadow pages depends on the memory
3256 * preallocation option. If not enabled, we'll just throw
3257 * out all the dirty pages and replace them by the zero page.
3258 */
3259 if (!pVM->pgm.s.fRamPreAlloc)
3260 {
3261 /* Free the dirty pages. */
3262 uint32_t cPendingPages = 0;
3263 PGMMFREEPAGESREQ pReq;
3264 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
3265 AssertRCReturn(rc, rc);
3266
3267 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3268 if ( !PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow)
3269 && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow))
3270 {
3271 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
3272 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, &pRom->aPages[iPage].Shadow,
3273 pRom->GCPhys + (iPage << PAGE_SHIFT));
3274 AssertLogRelRCReturn(rc, rc);
3275 }
3276
3277 if (cPendingPages)
3278 {
3279 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
3280 AssertLogRelRCReturn(rc, rc);
3281 }
3282 GMMR3FreePagesCleanup(pReq);
3283 }
3284 else
3285 {
3286 /* clear all the shadow pages. */
3287 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3288 {
3289 if (PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow))
3290 continue;
3291 Assert(!PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow));
3292 void *pvDstPage;
3293 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
3294 rc = pgmPhysPageMakeWritableAndMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pvDstPage);
3295 if (RT_FAILURE(rc))
3296 break;
3297 ASMMemZeroPage(pvDstPage);
3298 }
3299 AssertRCReturn(rc, rc);
3300 }
3301 }
3302
3303#ifdef VBOX_STRICT
3304 /*
3305 * Verify that the virgin page is unchanged if possible.
3306 */
3307 if (pRom->pvOriginal)
3308 {
3309 size_t cbSrcLeft = pRom->cbOriginal;
3310 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
3311 for (uint32_t iPage = 0; iPage < cPages && cbSrcLeft > 0; iPage++, pbSrcPage += PAGE_SIZE)
3312 {
3313 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
3314 void const *pvDstPage;
3315 int rc = pgmPhysPageMapReadOnly(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPage);
3316 if (RT_FAILURE(rc))
3317 break;
3318
3319 if (memcmp(pvDstPage, pbSrcPage, RT_MIN(cbSrcLeft, PAGE_SIZE)))
3320 LogRel(("pgmR3PhysRomReset: %RGp rom page changed (%s) - loaded saved state?\n",
3321 GCPhys, pRom->pszDesc));
3322 cbSrcLeft -= RT_MIN(cbSrcLeft, PAGE_SIZE);
3323 }
3324 }
3325#endif
3326 }
3327
3328 return VINF_SUCCESS;
3329}
3330
3331
3332/**
3333 * Called by PGMR3Term to free resources.
3334 *
3335 * ASSUMES that the caller owns the PGM lock.
3336 *
3337 * @param pVM The VM handle.
3338 */
3339void pgmR3PhysRomTerm(PVM pVM)
3340{
3341#ifdef RT_STRICT
3342 /*
3343 * Free the heap copy of the original bits.
3344 */
3345 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3346 {
3347 if ( pRom->pvOriginal
3348 && !(pRom->fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY))
3349 {
3350 RTMemFree((void *)pRom->pvOriginal);
3351 pRom->pvOriginal = NULL;
3352 }
3353 }
3354#endif
3355}
3356
3357
3358/**
3359 * Change the shadowing of a range of ROM pages.
3360 *
3361 * This is intended for implementing chipset specific memory registers
3362 * and will not be very strict about the input. It will silently ignore
3363 * any pages that are not the part of a shadowed ROM.
3364 *
3365 * @returns VBox status code.
3366 * @retval VINF_PGM_SYNC_CR3
3367 *
3368 * @param pVM Pointer to the shared VM structure.
3369 * @param GCPhys Where to start. Page aligned.
3370 * @param cb How much to change. Page aligned.
3371 * @param enmProt The new ROM protection.
3372 */
3373VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
3374{
3375 /*
3376 * Check input
3377 */
3378 if (!cb)
3379 return VINF_SUCCESS;
3380 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3381 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3382 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
3383 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3384 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
3385
3386 /*
3387 * Process the request.
3388 */
3389 pgmLock(pVM);
3390 int rc = VINF_SUCCESS;
3391 bool fFlushTLB = false;
3392 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3393 {
3394 if ( GCPhys <= pRom->GCPhysLast
3395 && GCPhysLast >= pRom->GCPhys
3396 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
3397 {
3398 /*
3399 * Iterate the relevant pages and make necessary the changes.
3400 */
3401 bool fChanges = false;
3402 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
3403 ? pRom->cb >> PAGE_SHIFT
3404 : (GCPhysLast - pRom->GCPhys + 1) >> PAGE_SHIFT;
3405 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
3406 iPage < cPages;
3407 iPage++)
3408 {
3409 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
3410 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
3411 {
3412 fChanges = true;
3413
3414 /* flush references to the page. */
3415 PPGMPAGE pRamPage = pgmPhysGetPage(&pVM->pgm.s, pRom->GCPhys + (iPage << PAGE_SHIFT));
3416 int rc2 = pgmPoolTrackUpdateGCPhys(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT), pRamPage,
3417 true /*fFlushPTEs*/, &fFlushTLB);
3418 if (rc2 != VINF_SUCCESS && (rc == VINF_SUCCESS || RT_FAILURE(rc2)))
3419 rc = rc2;
3420
3421 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
3422 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
3423
3424 *pOld = *pRamPage;
3425 *pRamPage = *pNew;
3426 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
3427 }
3428 pRomPage->enmProt = enmProt;
3429 }
3430
3431 /*
3432 * Reset the access handler if we made changes, no need
3433 * to optimize this.
3434 */
3435 if (fChanges)
3436 {
3437 int rc2 = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
3438 if (RT_FAILURE(rc2))
3439 {
3440 pgmUnlock(pVM);
3441 AssertRC(rc);
3442 return rc2;
3443 }
3444 }
3445
3446 /* Advance - cb isn't updated. */
3447 GCPhys = pRom->GCPhys + (cPages << PAGE_SHIFT);
3448 }
3449 }
3450 pgmUnlock(pVM);
3451 if (fFlushTLB)
3452 PGM_INVL_ALL_VCPU_TLBS(pVM);
3453
3454 return rc;
3455}
3456
3457
3458/**
3459 * Sets the Address Gate 20 state.
3460 *
3461 * @param pVCpu The VCPU to operate on.
3462 * @param fEnable True if the gate should be enabled.
3463 * False if the gate should be disabled.
3464 */
3465VMMDECL(void) PGMR3PhysSetA20(PVMCPU pVCpu, bool fEnable)
3466{
3467 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVCpu->pgm.s.fA20Enabled));
3468 if (pVCpu->pgm.s.fA20Enabled != fEnable)
3469 {
3470 pVCpu->pgm.s.fA20Enabled = fEnable;
3471 pVCpu->pgm.s.GCPhysA20Mask = ~(RTGCPHYS)(!fEnable << 20);
3472 REMR3A20Set(pVCpu->pVMR3, pVCpu, fEnable);
3473 /** @todo we're not handling this correctly for VT-x / AMD-V. See #2911 */
3474 }
3475}
3476
3477#ifdef PGM_WITH_LARGE_ADDRESS_SPACE_ON_32_BIT_HOST
3478/**
3479 * Tree enumeration callback for dealing with age rollover.
3480 * It will perform a simple compression of the current age.
3481 */
3482static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
3483{
3484 Assert(PGMIsLockOwner((PVM)pvUser));
3485 /* Age compression - ASSUMES iNow == 4. */
3486 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3487 if (pChunk->iAge >= UINT32_C(0xffffff00))
3488 pChunk->iAge = 3;
3489 else if (pChunk->iAge >= UINT32_C(0xfffff000))
3490 pChunk->iAge = 2;
3491 else if (pChunk->iAge)
3492 pChunk->iAge = 1;
3493 else /* iAge = 0 */
3494 pChunk->iAge = 4;
3495 return 0;
3496}
3497
3498
3499/**
3500 * Tree enumeration callback that updates the chunks that have
3501 * been used since the last
3502 */
3503static DECLCALLBACK(int) pgmR3PhysChunkAgeingCallback(PAVLU32NODECORE pNode, void *pvUser)
3504{
3505 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3506 if (!pChunk->iAge)
3507 {
3508 PVM pVM = (PVM)pvUser;
3509 pChunk->iAge = pVM->pgm.s.ChunkR3Map.iNow;
3510 }
3511 return 0;
3512}
3513
3514
3515/**
3516 * Performs ageing of the ring-3 chunk mappings.
3517 *
3518 * @param pVM The VM handle.
3519 */
3520VMMR3DECL(void) PGMR3PhysChunkAgeing(PVM pVM)
3521{
3522 pgmLock(pVM);
3523 pVM->pgm.s.ChunkR3Map.AgeingCountdown = RT_MIN(pVM->pgm.s.ChunkR3Map.cMax / 4, 1024);
3524 pVM->pgm.s.ChunkR3Map.iNow++;
3525 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
3526 {
3527 pVM->pgm.s.ChunkR3Map.iNow = 4;
3528 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, pVM);
3529 }
3530 else
3531 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingCallback, pVM);
3532 pgmUnlock(pVM);
3533}
3534
3535
3536/**
3537 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
3538 */
3539typedef struct PGMR3PHYSCHUNKUNMAPCB
3540{
3541 PVM pVM; /**< The VM handle. */
3542 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
3543 uint32_t iLastAge; /**< Highest age found so far. */
3544} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
3545
3546
3547/**
3548 * Callback used to find the mapping that's been unused for
3549 * the longest time.
3550 */
3551static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLU32NODECORE pNode, void *pvUser)
3552{
3553 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3554 PPGMR3PHYSCHUNKUNMAPCB pArg = (PPGMR3PHYSCHUNKUNMAPCB)pvUser;
3555
3556 if ( pChunk->iAge
3557 && !pChunk->cRefs
3558 && pArg->iLastAge < pChunk->iAge)
3559 {
3560 /*
3561 * Check that it's not in any of the TLBs.
3562 */
3563 PVM pVM = pArg->pVM;
3564 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
3565 if (pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk == pChunk)
3566 {
3567 pChunk = NULL;
3568 break;
3569 }
3570 if (pChunk)
3571 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbHC.aEntries); i++)
3572 if (pVM->pgm.s.PhysTlbHC.aEntries[i].pMap == pChunk)
3573 {
3574 pChunk = NULL;
3575 break;
3576 }
3577 if (pChunk)
3578 {
3579 pArg->pChunk = pChunk;
3580 pArg->iLastAge = pChunk->iAge;
3581 }
3582 }
3583 return 0;
3584}
3585
3586
3587/**
3588 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
3589 *
3590 * The candidate will not be part of any TLBs, so no need to flush
3591 * anything afterwards.
3592 *
3593 * @returns Chunk id.
3594 * @param pVM The VM handle.
3595 */
3596static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
3597{
3598 Assert(PGMIsLockOwner(pVM));
3599
3600 /*
3601 * Do tree ageing first?
3602 */
3603 if (pVM->pgm.s.ChunkR3Map.AgeingCountdown-- == 0)
3604 {
3605 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkAging, a);
3606 PGMR3PhysChunkAgeing(pVM);
3607 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkAging, a);
3608 }
3609
3610 /*
3611 * Enumerate the age tree starting with the left most node.
3612 */
3613 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3614 PGMR3PHYSCHUNKUNMAPCB Args;
3615 Args.pVM = pVM;
3616 Args.pChunk = NULL;
3617 Args.iLastAge = 0;
3618 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, &Args);
3619 Assert(Args.pChunk);
3620 if (Args.pChunk)
3621 {
3622 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3623 return Args.pChunk->Core.Key;
3624 }
3625
3626 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3627 return INT32_MAX;
3628}
3629
3630/**
3631 * Rendezvous callback used by pgmR3PhysUnmapChunk that unmaps a chunk
3632 *
3633 * This is only called on one of the EMTs while the other ones are waiting for
3634 * it to complete this function.
3635 *
3636 * @returns VINF_SUCCESS (VBox strict status code).
3637 * @param pVM The VM handle.
3638 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
3639 * @param pvUser User pointer. Unused
3640 *
3641 */
3642DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysUnmapChunkRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
3643{
3644 int rc = VINF_SUCCESS;
3645 pgmLock(pVM);
3646
3647 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
3648 {
3649 /* Flush the pgm pool cache; call the internal rendezvous handler as we're already in a rendezvous handler here. */
3650 /* todo: also not really efficient to unmap a chunk that contains PD or PT pages. */
3651 pgmR3PoolClearAllRendezvous(pVM, &pVM->aCpus[0], NULL /* no need to flush the REM TLB as we already did that above */);
3652
3653 /*
3654 * Request the ring-0 part to unmap a chunk to make space in the mapping cache.
3655 */
3656 GMMMAPUNMAPCHUNKREQ Req;
3657 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
3658 Req.Hdr.cbReq = sizeof(Req);
3659 Req.pvR3 = NULL;
3660 Req.idChunkMap = NIL_GMM_CHUNKID;
3661 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
3662
3663 if (Req.idChunkUnmap != INT32_MAX)
3664 {
3665 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
3666 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
3667 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
3668 if (RT_SUCCESS(rc))
3669 {
3670 /* remove the unmapped one. */
3671 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
3672 AssertRelease(pUnmappedChunk);
3673 pUnmappedChunk->pv = NULL;
3674 pUnmappedChunk->Core.Key = UINT32_MAX;
3675#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3676 MMR3HeapFree(pUnmappedChunk);
3677#else
3678 MMR3UkHeapFree(pVM, pUnmappedChunk, MM_TAG_PGM_CHUNK_MAPPING);
3679#endif
3680 pVM->pgm.s.ChunkR3Map.c--;
3681 pVM->pgm.s.cUnmappedChunks++;
3682
3683 /* Flush dangling PGM pointers (R3 & R0 ptrs to GC physical addresses) */
3684 /* todo: we should not flush chunks which include cr3 mappings. */
3685 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
3686 {
3687 PPGMCPU pPGM = &pVM->aCpus[idCpu].pgm.s;
3688
3689 pPGM->pGst32BitPdR3 = NULL;
3690 pPGM->pGstPaePdptR3 = NULL;
3691 pPGM->pGstAmd64Pml4R3 = NULL;
3692#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
3693 pPGM->pGst32BitPdR0 = NIL_RTR0PTR;
3694 pPGM->pGstPaePdptR0 = NIL_RTR0PTR;
3695 pPGM->pGstAmd64Pml4R0 = NIL_RTR0PTR;
3696#endif
3697 for (unsigned i = 0; i < RT_ELEMENTS(pPGM->apGstPaePDsR3); i++)
3698 {
3699 pPGM->apGstPaePDsR3[i] = NULL;
3700#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
3701 pPGM->apGstPaePDsR0[i] = NIL_RTR0PTR;
3702#endif
3703 }
3704
3705 /* Flush REM TLBs. */
3706 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
3707 }
3708
3709 /* Flush REM translation blocks. */
3710 REMFlushTBs(pVM);
3711 }
3712 }
3713 }
3714 pgmUnlock(pVM);
3715 return rc;
3716}
3717
3718/**
3719 * Unmap a chunk to free up virtual address space (request packet handler for pgmR3PhysChunkMap)
3720 *
3721 * @returns VBox status code.
3722 * @param pVM The VM to operate on.
3723 */
3724void pgmR3PhysUnmapChunk(PVM pVM)
3725{
3726 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysUnmapChunkRendezvous, NULL);
3727 AssertRC(rc);
3728}
3729#endif /* PGM_WITH_LARGE_ADDRESS_SPACE_ON_32_BIT_HOST */
3730
3731/**
3732 * Maps the given chunk into the ring-3 mapping cache.
3733 *
3734 * This will call ring-0.
3735 *
3736 * @returns VBox status code.
3737 * @param pVM The VM handle.
3738 * @param idChunk The chunk in question.
3739 * @param ppChunk Where to store the chunk tracking structure.
3740 *
3741 * @remarks Called from within the PGM critical section.
3742 * @remarks Can be called from any thread!
3743 */
3744int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
3745{
3746 int rc;
3747
3748 Assert(PGMIsLockOwner(pVM));
3749 /*
3750 * Allocate a new tracking structure first.
3751 */
3752#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3753 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
3754#else
3755 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3UkHeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk), NULL);
3756#endif
3757 AssertReturn(pChunk, VERR_NO_MEMORY);
3758 pChunk->Core.Key = idChunk;
3759
3760 /*
3761 * Request the ring-0 part to map the chunk in question.
3762 */
3763 GMMMAPUNMAPCHUNKREQ Req;
3764 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
3765 Req.Hdr.cbReq = sizeof(Req);
3766 Req.pvR3 = NULL;
3767 Req.idChunkMap = idChunk;
3768 Req.idChunkUnmap = NIL_GMM_CHUNKID;
3769
3770 /* Must be callable from any thread, so can't use VMMR3CallR0. */
3771 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
3772 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, NIL_VMCPUID, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
3773 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
3774 if (RT_SUCCESS(rc))
3775 {
3776 /*
3777 * Update the tree.
3778 */
3779 /* insert the new one. */
3780 AssertPtr(Req.pvR3);
3781 pChunk->pv = Req.pvR3;
3782 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
3783 AssertRelease(fRc);
3784 pVM->pgm.s.ChunkR3Map.c++;
3785 pVM->pgm.s.cMappedChunks++;
3786
3787 /* If we're running out of virtual address space, then we should unmap another chunk. */
3788 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
3789 {
3790#ifdef PGM_WITH_LARGE_ADDRESS_SPACE_ON_32_BIT_HOST
3791 /* Postpone the unmap operation (which requires a rendezvous operation) as we own the PGM lock here. */
3792 rc = VMR3ReqCallNoWaitU(pVM->pUVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysUnmapChunk, 1, pVM);
3793 AssertRC(rc);
3794#else
3795 AssertFatalFailed(); /* can't happen */
3796#endif
3797 }
3798 }
3799 else
3800 {
3801 AssertRC(rc);
3802#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3803 MMR3HeapFree(pChunk);
3804#else
3805 MMR3UkHeapFree(pVM, pChunk, MM_TAG_PGM_CHUNK_MAPPING);
3806#endif
3807 pChunk = NULL;
3808 }
3809
3810 *ppChunk = pChunk;
3811 return rc;
3812}
3813
3814
3815/**
3816 * For VMMCALLRING3_PGM_MAP_CHUNK, considered internal.
3817 *
3818 * @returns see pgmR3PhysChunkMap.
3819 * @param pVM The VM handle.
3820 * @param idChunk The chunk to map.
3821 */
3822VMMR3DECL(int) PGMR3PhysChunkMap(PVM pVM, uint32_t idChunk)
3823{
3824 PPGMCHUNKR3MAP pChunk;
3825 int rc;
3826
3827 pgmLock(pVM);
3828 rc = pgmR3PhysChunkMap(pVM, idChunk, &pChunk);
3829 pgmUnlock(pVM);
3830 return rc;
3831}
3832
3833
3834/**
3835 * Invalidates the TLB for the ring-3 mapping cache.
3836 *
3837 * @param pVM The VM handle.
3838 */
3839VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
3840{
3841 pgmLock(pVM);
3842 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
3843 {
3844 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
3845 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
3846 }
3847 /* The page map TLB references chunks, so invalidate that one too. */
3848 PGMPhysInvalidatePageMapTLB(pVM);
3849 pgmUnlock(pVM);
3850}
3851
3852
3853/**
3854 * Response to VMMCALLRING3_PGM_ALLOCATE_LARGE_PAGE to allocate a large (2MB) page
3855 * for use with a nested paging PDE.
3856 *
3857 * @returns The following VBox status codes.
3858 * @retval VINF_SUCCESS on success.
3859 * @retval VINF_EM_NO_MEMORY if we're out of memory.
3860 *
3861 * @param pVM The VM handle.
3862 * @param GCPhys GC physical start address of the 2 MB range
3863 */
3864VMMR3DECL(int) PGMR3PhysAllocateLargeHandyPage(PVM pVM, RTGCPHYS GCPhys)
3865{
3866#ifdef PGM_WITH_LARGE_PAGES
3867 uint64_t u64TimeStamp1, u64TimeStamp2;
3868
3869 pgmLock(pVM);
3870
3871 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
3872 u64TimeStamp1 = RTTimeMilliTS();
3873 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_LARGE_HANDY_PAGE, 0, NULL);
3874 u64TimeStamp2 = RTTimeMilliTS();
3875 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
3876 if (RT_SUCCESS(rc))
3877 {
3878 Assert(pVM->pgm.s.cLargeHandyPages == 1);
3879
3880 uint32_t idPage = pVM->pgm.s.aLargeHandyPage[0].idPage;
3881 RTHCPHYS HCPhys = pVM->pgm.s.aLargeHandyPage[0].HCPhysGCPhys;
3882
3883 void *pv;
3884
3885 /* Map the large page into our address space.
3886 *
3887 * Note: assuming that within the 2 MB range:
3888 * - GCPhys + PAGE_SIZE = HCPhys + PAGE_SIZE (whole point of this exercise)
3889 * - user space mapping is continuous as well
3890 * - page id (GCPhys) + 1 = page id (GCPhys + PAGE_SIZE)
3891 */
3892 rc = pgmPhysPageMapByPageID(pVM, idPage, HCPhys, &pv);
3893 AssertLogRelMsg(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n", idPage, HCPhys, rc));
3894
3895 if (RT_SUCCESS(rc))
3896 {
3897 /*
3898 * Clear the pages.
3899 */
3900 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
3901 for (unsigned i = 0; i < _2M/PAGE_SIZE; i++)
3902 {
3903 ASMMemZeroPage(pv);
3904
3905 PPGMPAGE pPage;
3906 rc = pgmPhysGetPageEx(&pVM->pgm.s, GCPhys, &pPage);
3907 AssertRC(rc);
3908
3909 Assert(PGM_PAGE_IS_ZERO(pPage));
3910 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatRZPageReplaceZero);
3911 pVM->pgm.s.cZeroPages--;
3912
3913 /*
3914 * Do the PGMPAGE modifications.
3915 */
3916 pVM->pgm.s.cPrivatePages++;
3917 PGM_PAGE_SET_HCPHYS(pPage, HCPhys);
3918 PGM_PAGE_SET_PAGEID(pPage, idPage);
3919 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ALLOCATED);
3920 PGM_PAGE_SET_PDE_TYPE(pPage, PGM_PAGE_PDE_TYPE_PDE);
3921 PGM_PAGE_SET_PTE_INDEX(pPage, 0);
3922 PGM_PAGE_SET_TRACKING(pPage, 0);
3923
3924 /* Somewhat dirty assumption that page ids are increasing. */
3925 idPage++;
3926
3927 HCPhys += PAGE_SIZE;
3928 GCPhys += PAGE_SIZE;
3929
3930 pv = (void *)((uintptr_t)pv + PAGE_SIZE);
3931
3932 Log3(("PGMR3PhysAllocateLargePage: idPage=%#x HCPhys=%RGp\n", idPage, HCPhys));
3933 }
3934 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
3935
3936 /* Flush all TLBs. */
3937 PGM_INVL_ALL_VCPU_TLBS(pVM);
3938 PGMPhysInvalidatePageMapTLB(pVM);
3939 }
3940 pVM->pgm.s.cLargeHandyPages = 0;
3941 }
3942
3943 if (RT_SUCCESS(rc))
3944 {
3945 static uint32_t cTimeOut = 0;
3946 uint64_t u64TimeStampDelta = u64TimeStamp2 - u64TimeStamp1;
3947
3948 if (u64TimeStampDelta > 100)
3949 {
3950 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatLargePageOverflow);
3951 if ( ++cTimeOut > 10
3952 || u64TimeStampDelta > 1000 /* more than one second forces an early retirement from allocating large pages. */)
3953 {
3954 /* If repeated attempts to allocate a large page takes more than 100 ms, then we fall back to normal 4k pages.
3955 * E.g. Vista 64 tries to move memory around, which takes a huge amount of time.
3956 */
3957 LogRel(("PGMR3PhysAllocateLargePage: allocating large pages takes too long (last attempt %d ms; nr of timeouts %d); DISABLE\n", u64TimeStampDelta, cTimeOut));
3958 PGMSetLargePageUsage(pVM, false);
3959 }
3960 }
3961 else
3962 if (cTimeOut > 0)
3963 cTimeOut--;
3964 }
3965
3966 pgmUnlock(pVM);
3967 return rc;
3968#else
3969 return VERR_NOT_IMPLEMENTED;
3970#endif /* PGM_WITH_LARGE_PAGES */
3971}
3972
3973
3974/**
3975 * Response to VM_FF_PGM_NEED_HANDY_PAGES and VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES.
3976 *
3977 * This function will also work the VM_FF_PGM_NO_MEMORY force action flag, to
3978 * signal and clear the out of memory condition. When contracted, this API is
3979 * used to try clear the condition when the user wants to resume.
3980 *
3981 * @returns The following VBox status codes.
3982 * @retval VINF_SUCCESS on success. FFs cleared.
3983 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in
3984 * this case and it gets accompanied by VM_FF_PGM_NO_MEMORY.
3985 *
3986 * @param pVM The VM handle.
3987 *
3988 * @remarks The VINF_EM_NO_MEMORY status is for the benefit of the FF processing
3989 * in EM.cpp and shouldn't be propagated outside TRPM, HWACCM, EM and
3990 * pgmPhysEnsureHandyPage. There is one exception to this in the \#PF
3991 * handler.
3992 */
3993VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
3994{
3995 pgmLock(pVM);
3996
3997 /*
3998 * Allocate more pages, noting down the index of the first new page.
3999 */
4000 uint32_t iClear = pVM->pgm.s.cHandyPages;
4001 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_INTERNAL_ERROR);
4002 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
4003 int rcAlloc = VINF_SUCCESS;
4004 int rcSeed = VINF_SUCCESS;
4005 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
4006 while (rc == VERR_GMM_SEED_ME)
4007 {
4008 void *pvChunk;
4009 rcAlloc = rc = SUPR3PageAlloc(GMM_CHUNK_SIZE >> PAGE_SHIFT, &pvChunk);
4010 if (RT_SUCCESS(rc))
4011 {
4012 rcSeed = rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_SEED_CHUNK, (uintptr_t)pvChunk, NULL);
4013 if (RT_FAILURE(rc))
4014 SUPR3PageFree(pvChunk, GMM_CHUNK_SIZE >> PAGE_SHIFT);
4015 }
4016 if (RT_SUCCESS(rc))
4017 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
4018 }
4019
4020 /* 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) */
4021 if ( rc == VERR_GMM_HIT_VM_ACCOUNT_LIMIT
4022 && pVM->pgm.s.cHandyPages > 0)
4023 {
4024 /* Still handy pages left, so don't panic. */
4025 rc = VINF_SUCCESS;
4026 }
4027
4028 if (RT_SUCCESS(rc))
4029 {
4030 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
4031 Assert(pVM->pgm.s.cHandyPages > 0);
4032 VM_FF_CLEAR(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
4033 VM_FF_CLEAR(pVM, VM_FF_PGM_NO_MEMORY);
4034
4035 /*
4036 * Clear the pages.
4037 */
4038 while (iClear < pVM->pgm.s.cHandyPages)
4039 {
4040 PGMMPAGEDESC pPage = &pVM->pgm.s.aHandyPages[iClear];
4041 void *pv;
4042 rc = pgmPhysPageMapByPageID(pVM, pPage->idPage, pPage->HCPhysGCPhys, &pv);
4043 AssertLogRelMsgBreak(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n", pPage->idPage, pPage->HCPhysGCPhys, rc));
4044 ASMMemZeroPage(pv);
4045 iClear++;
4046 Log3(("PGMR3PhysAllocateHandyPages: idPage=%#x HCPhys=%RGp\n", pPage->idPage, pPage->HCPhysGCPhys));
4047 }
4048 }
4049 else
4050 {
4051 uint64_t cAllocPages, cMaxPages, cBalloonPages;
4052
4053 /*
4054 * We should never get here unless there is a genuine shortage of
4055 * memory (or some internal error). Flag the error so the VM can be
4056 * suspended ASAP and the user informed. If we're totally out of
4057 * handy pages we will return failure.
4058 */
4059 /* Report the failure. */
4060 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc rcAlloc=%Rrc rcSeed=%Rrc cHandyPages=%#x\n"
4061 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
4062 rc, rcAlloc, rcSeed,
4063 pVM->pgm.s.cHandyPages,
4064 pVM->pgm.s.cAllPages,
4065 pVM->pgm.s.cPrivatePages,
4066 pVM->pgm.s.cSharedPages,
4067 pVM->pgm.s.cZeroPages));
4068
4069 if (GMMR3QueryMemoryStats(pVM, &cAllocPages, &cMaxPages, &cBalloonPages) == VINF_SUCCESS)
4070 {
4071 LogRel(("GMM: Statistics:\n"
4072 " Allocated pages: %RX64\n"
4073 " Maximum pages: %RX64\n"
4074 " Ballooned pages: %RX64\n", cAllocPages, cMaxPages, cBalloonPages));
4075 }
4076
4077 if ( rc != VERR_NO_MEMORY
4078 && rc != VERR_LOCK_FAILED)
4079 {
4080 for (uint32_t i = 0; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
4081 {
4082 LogRel(("PGM: aHandyPages[#%#04x] = {.HCPhysGCPhys=%RHp, .idPage=%#08x, .idSharedPage=%#08x}\n",
4083 i, pVM->pgm.s.aHandyPages[i].HCPhysGCPhys, pVM->pgm.s.aHandyPages[i].idPage,
4084 pVM->pgm.s.aHandyPages[i].idSharedPage));
4085 uint32_t const idPage = pVM->pgm.s.aHandyPages[i].idPage;
4086 if (idPage != NIL_GMM_PAGEID)
4087 {
4088 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
4089 pRam;
4090 pRam = pRam->pNextR3)
4091 {
4092 uint32_t const cPages = pRam->cb >> PAGE_SHIFT;
4093 for (uint32_t iPage = 0; iPage < cPages; iPage++)
4094 if (PGM_PAGE_GET_PAGEID(&pRam->aPages[iPage]) == idPage)
4095 LogRel(("PGM: Used by %RGp %R[pgmpage] (%s)\n",
4096 pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pRam->aPages[iPage], pRam->pszDesc));
4097 }
4098 }
4099 }
4100 }
4101
4102 /* Set the FFs and adjust rc. */
4103 VM_FF_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
4104 VM_FF_SET(pVM, VM_FF_PGM_NO_MEMORY);
4105 if ( rc == VERR_NO_MEMORY
4106 || rc == VERR_LOCK_FAILED)
4107 rc = VINF_EM_NO_MEMORY;
4108 }
4109
4110 pgmUnlock(pVM);
4111 return rc;
4112}
4113
4114
4115/**
4116 * Frees the specified RAM page and replaces it with the ZERO page.
4117 *
4118 * This is used by ballooning, remapping MMIO2, RAM reset and state loading.
4119 *
4120 * @param pVM Pointer to the shared VM structure.
4121 * @param pReq Pointer to the request.
4122 * @param pcPendingPages Where the number of pages waiting to be freed are
4123 * kept. This will normally be incremented.
4124 * @param pPage Pointer to the page structure.
4125 * @param GCPhys The guest physical address of the page, if applicable.
4126 *
4127 * @remarks The caller must own the PGM lock.
4128 */
4129int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys)
4130{
4131 /*
4132 * Assert sanity.
4133 */
4134 Assert(PGMIsLockOwner(pVM));
4135 if (RT_UNLIKELY( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM
4136 && PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_ROM_SHADOW))
4137 {
4138 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
4139 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
4140 }
4141
4142 /** @todo What about ballooning of large pages??! */
4143 Assert( PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE
4144 && PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE_DISABLED);
4145
4146 if ( PGM_PAGE_IS_ZERO(pPage)
4147 || PGM_PAGE_IS_BALLOONED(pPage))
4148 return VINF_SUCCESS;
4149
4150 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
4151 Log3(("pgmPhysFreePage: idPage=%#x GCPhys=%RGp pPage=%R[pgmpage]\n", idPage, GCPhys, pPage));
4152 if (RT_UNLIKELY( idPage == NIL_GMM_PAGEID
4153 || idPage > GMM_PAGEID_LAST
4154 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID))
4155 {
4156 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
4157 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
4158 }
4159
4160 /* update page count stats. */
4161 if (PGM_PAGE_IS_SHARED(pPage))
4162 pVM->pgm.s.cSharedPages--;
4163 else
4164 pVM->pgm.s.cPrivatePages--;
4165 pVM->pgm.s.cZeroPages++;
4166
4167 /* Deal with write monitored pages. */
4168 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
4169 {
4170 PGM_PAGE_SET_WRITTEN_TO(pPage);
4171 pVM->pgm.s.cWrittenToPages++;
4172 }
4173
4174 /*
4175 * pPage = ZERO page.
4176 */
4177 PGM_PAGE_SET_HCPHYS(pPage, pVM->pgm.s.HCPhysZeroPg);
4178 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
4179 PGM_PAGE_SET_PAGEID(pPage, NIL_GMM_PAGEID);
4180 PGM_PAGE_SET_PDE_TYPE(pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4181 PGM_PAGE_SET_PTE_INDEX(pPage, 0);
4182 PGM_PAGE_SET_TRACKING(pPage, 0);
4183
4184 /* Flush physical page map TLB entry. */
4185 PGMPhysInvalidatePageMapTLBEntry(pVM, GCPhys);
4186
4187 /*
4188 * Make sure it's not in the handy page array.
4189 */
4190 for (uint32_t i = pVM->pgm.s.cHandyPages; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
4191 {
4192 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
4193 {
4194 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
4195 break;
4196 }
4197 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
4198 {
4199 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
4200 break;
4201 }
4202 }
4203
4204 /*
4205 * Push it onto the page array.
4206 */
4207 uint32_t iPage = *pcPendingPages;
4208 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
4209 *pcPendingPages += 1;
4210
4211 pReq->aPages[iPage].idPage = idPage;
4212
4213 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
4214 return VINF_SUCCESS;
4215
4216 /*
4217 * Flush the pages.
4218 */
4219 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
4220 if (RT_SUCCESS(rc))
4221 {
4222 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
4223 *pcPendingPages = 0;
4224 }
4225 return rc;
4226}
4227
4228
4229/**
4230 * Converts a GC physical address to a HC ring-3 pointer, with some
4231 * additional checks.
4232 *
4233 * @returns VBox status code.
4234 * @retval VINF_SUCCESS on success.
4235 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
4236 * access handler of some kind.
4237 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
4238 * accesses or is odd in any way.
4239 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
4240 *
4241 * @param pVM The VM handle.
4242 * @param GCPhys The GC physical address to convert.
4243 * @param fWritable Whether write access is required.
4244 * @param ppv Where to store the pointer corresponding to GCPhys on
4245 * success.
4246 */
4247VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
4248{
4249 pgmLock(pVM);
4250
4251 PPGMRAMRANGE pRam;
4252 PPGMPAGE pPage;
4253 int rc = pgmPhysGetPageAndRangeEx(&pVM->pgm.s, GCPhys, &pPage, &pRam);
4254 if (RT_SUCCESS(rc))
4255 {
4256 if (PGM_PAGE_IS_BALLOONED(pPage))
4257 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4258 else if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
4259 rc = VINF_SUCCESS;
4260 else
4261 {
4262 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
4263 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
4264 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
4265 {
4266 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
4267 * in -norawr0 mode. */
4268 if (fWritable)
4269 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4270 }
4271 else
4272 {
4273 /* Temporarily disabled physical handler(s), since the recompiler
4274 doesn't get notified when it's reset we'll have to pretend it's
4275 operating normally. */
4276 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
4277 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
4278 else
4279 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4280 }
4281 }
4282 if (RT_SUCCESS(rc))
4283 {
4284 int rc2;
4285
4286 /* Make sure what we return is writable. */
4287 if (fWritable)
4288 switch (PGM_PAGE_GET_STATE(pPage))
4289 {
4290 case PGM_PAGE_STATE_ALLOCATED:
4291 break;
4292 case PGM_PAGE_STATE_BALLOONED:
4293 AssertFailed();
4294 break;
4295 case PGM_PAGE_STATE_ZERO:
4296 case PGM_PAGE_STATE_SHARED:
4297 if (rc == VINF_PGM_PHYS_TLB_CATCH_WRITE)
4298 break;
4299 case PGM_PAGE_STATE_WRITE_MONITORED:
4300 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)PAGE_OFFSET_MASK);
4301 AssertLogRelRCReturn(rc2, rc2);
4302 break;
4303 }
4304
4305 /* Get a ring-3 mapping of the address. */
4306 PPGMPAGER3MAPTLBE pTlbe;
4307 rc2 = pgmPhysPageQueryTlbe(&pVM->pgm.s, GCPhys, &pTlbe);
4308 AssertLogRelRCReturn(rc2, rc2);
4309 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
4310 /** @todo mapping/locking hell; this isn't horribly efficient since
4311 * pgmPhysPageLoadIntoTlb will repeat the lookup we've done here. */
4312
4313 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
4314 }
4315 else
4316 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
4317
4318 /* else: handler catching all access, no pointer returned. */
4319 }
4320 else
4321 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
4322
4323 pgmUnlock(pVM);
4324 return rc;
4325}
4326
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