VirtualBox

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

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

PGMPhys: Fixed bug in the freeing of shadowed ROM pages during reset (the immeidate cause of the restore regression). More logging.

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