VirtualBox

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

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

Flush first, then free

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