VirtualBox

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

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

PGMSavedState: New state saved state format in the works.

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