VirtualBox

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

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

Deal with MMIO2 pages as well (FTM)

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