VirtualBox

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

Last change on this file since 20404 was 20404, checked in by vboxsync, 16 years ago

Inform REM outside of the pgm lock.

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