VirtualBox

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

Last change on this file since 32106 was 32106, checked in by vboxsync, 15 years ago

Minor update

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