VirtualBox

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

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

During state loading; don't free a zero page if it's part of a large page.

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