VirtualBox

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

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

Change balloon page type back to zero when deflated.

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