VirtualBox

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

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

PGMR3PhysAllocHandyPages: More release log info when we're running out of memory.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 117.1 KB
Line 
1/* $Id: PGMPhys.cpp 18144 2009-03-23 15:20:41Z 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
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 /* Count dirty shadow pages. */
2161 uint32_t cDirty = 0;
2162 uint32_t iPage = cPages;
2163 while (iPage-- > 0)
2164 if (PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) != PGM_PAGE_STATE_ZERO)
2165 cDirty++;
2166 if (cDirty)
2167 {
2168 /* Free the dirty pages. */
2169 PGMMFREEPAGESREQ pReq;
2170 rc = GMMR3FreePagesPrepare(pVM, &pReq, cDirty, GMMACCOUNT_BASE);
2171 AssertRCReturn(rc, rc);
2172
2173 uint32_t iReqPage = 0;
2174 for (iPage = 0; iPage < cPages; iPage++)
2175 if (PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) != PGM_PAGE_STATE_ZERO)
2176 {
2177 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
2178 pReq->aPages[iReqPage].idPage = PGM_PAGE_GET_PAGEID(&pRom->aPages[iPage].Shadow);
2179 iReqPage++;
2180 }
2181
2182 rc = GMMR3FreePagesPerform(pVM, pReq, cDirty);
2183 GMMR3FreePagesCleanup(pReq);
2184 AssertRCReturn(rc, rc);
2185
2186 /* setup the zero page. */
2187 for (iPage = 0; iPage < cPages; iPage++)
2188 if (PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) != PGM_PAGE_STATE_ZERO)
2189 PGM_PAGE_INIT_ZERO_REAL(&pRom->aPages[iPage].Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
2190
2191 /* update the page count stats. */
2192 pVM->pgm.s.cPrivatePages -= cDirty;
2193 pVM->pgm.s.cZeroPages += cDirty;
2194 }
2195 }
2196 else
2197 {
2198 /* clear all the pages. */
2199 for (uint32_t iPage = 0; iPage < cPages; iPage++)
2200 {
2201 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) != PGM_PAGE_STATE_ZERO);
2202
2203 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
2204 rc = pgmPhysPageMakeWritable(pVM, &pRom->aPages[iPage].Shadow, GCPhys);
2205 if (RT_FAILURE(rc))
2206 break;
2207
2208 void *pvDstPage;
2209 PPGMPAGEMAP pMapIgnored;
2210 rc = pgmPhysPageMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pMapIgnored, &pvDstPage);
2211 if (RT_FAILURE(rc))
2212 break;
2213 ASMMemZeroPage(pvDstPage);
2214 }
2215 AssertRCReturn(rc, rc);
2216 }
2217 }
2218
2219#ifdef VBOX_STRICT
2220 /*
2221 * Verify that the virgin page is unchanged if possible.
2222 */
2223 if (pRom->pvOriginal)
2224 {
2225 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
2226 for (uint32_t iPage = 0; iPage < cPages; iPage++, pbSrcPage += PAGE_SIZE)
2227 {
2228 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
2229 PPGMPAGEMAP pMapIgnored;
2230 void *pvDstPage;
2231 int rc = pgmPhysPageMap(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pMapIgnored, &pvDstPage);
2232 if (RT_FAILURE(rc))
2233 break;
2234 if (memcmp(pvDstPage, pbSrcPage, PAGE_SIZE))
2235 LogRel(("pgmR3PhysRomReset: %RGp rom page changed (%s) - loaded saved state?\n",
2236 GCPhys, pRom->pszDesc));
2237 }
2238 }
2239#endif
2240 }
2241
2242 return VINF_SUCCESS;
2243}
2244
2245
2246/**
2247 * Change the shadowing of a range of ROM pages.
2248 *
2249 * This is intended for implementing chipset specific memory registers
2250 * and will not be very strict about the input. It will silently ignore
2251 * any pages that are not the part of a shadowed ROM.
2252 *
2253 * @returns VBox status code.
2254 * @param pVM Pointer to the shared VM structure.
2255 * @param GCPhys Where to start. Page aligned.
2256 * @param cb How much to change. Page aligned.
2257 * @param enmProt The new ROM protection.
2258 */
2259VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
2260{
2261 /*
2262 * Check input
2263 */
2264 if (!cb)
2265 return VINF_SUCCESS;
2266 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2267 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2268 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2269 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2270 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
2271
2272 /*
2273 * Process the request.
2274 */
2275 bool fFlushedPool = false;
2276 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
2277 if ( GCPhys <= pRom->GCPhysLast
2278 && GCPhysLast >= pRom->GCPhys
2279 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
2280 {
2281 /*
2282 * Iterate the relevant pages and the ncessary make changes.
2283 */
2284 bool fChanges = false;
2285 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
2286 ? pRom->cb >> PAGE_SHIFT
2287 : (GCPhysLast - pRom->GCPhys + 1) >> PAGE_SHIFT;
2288 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
2289 iPage < cPages;
2290 iPage++)
2291 {
2292 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
2293 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
2294 {
2295 fChanges = true;
2296
2297 /* flush the page pool first so we don't leave any usage references dangling. */
2298 if (!fFlushedPool)
2299 {
2300 pgmPoolFlushAll(pVM);
2301 fFlushedPool = true;
2302 }
2303
2304 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
2305 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
2306 PPGMPAGE pRamPage = pgmPhysGetPage(&pVM->pgm.s, pRom->GCPhys + (iPage << PAGE_SHIFT));
2307
2308 *pOld = *pRamPage;
2309 *pRamPage = *pNew;
2310 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
2311 }
2312 pRomPage->enmProt = enmProt;
2313 }
2314
2315 /*
2316 * Reset the access handler if we made changes, no need
2317 * to optimize this.
2318 */
2319 if (fChanges)
2320 {
2321 int rc = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
2322 AssertRCReturn(rc, rc);
2323 }
2324
2325 /* Advance - cb isn't updated. */
2326 GCPhys = pRom->GCPhys + (cPages << PAGE_SHIFT);
2327 }
2328
2329 return VINF_SUCCESS;
2330}
2331
2332#ifndef VBOX_WITH_NEW_PHYS_CODE
2333
2334/**
2335 * Interface that the MMR3RamRegister(), MMR3RomRegister() and MMIO handler
2336 * registration APIs calls to inform PGM about memory registrations.
2337 *
2338 * It registers the physical memory range with PGM. MM is responsible
2339 * for the toplevel things - allocation and locking - while PGM is taking
2340 * care of all the details and implements the physical address space virtualization.
2341 *
2342 * @returns VBox status.
2343 * @param pVM The VM handle.
2344 * @param pvRam HC virtual address of the RAM range. (page aligned)
2345 * @param GCPhys GC physical address of the RAM range. (page aligned)
2346 * @param cb Size of the RAM range. (page aligned)
2347 * @param fFlags Flags, MM_RAM_*.
2348 * @param paPages Pointer an array of physical page descriptors.
2349 * @param pszDesc Description string.
2350 */
2351VMMR3DECL(int) PGMR3PhysRegister(PVM pVM, void *pvRam, RTGCPHYS GCPhys, size_t cb, unsigned fFlags, const SUPPAGE *paPages, const char *pszDesc)
2352{
2353 /*
2354 * Validate input.
2355 * (Not so important because callers are only MMR3PhysRegister()
2356 * and PGMR3HandlerPhysicalRegisterEx(), but anyway...)
2357 */
2358 Log(("PGMR3PhysRegister %08X %x bytes flags %x %s\n", GCPhys, cb, fFlags, pszDesc));
2359
2360 Assert((fFlags & (MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_DYNAMIC_ALLOC)) || paPages);
2361 /*Assert(!(fFlags & MM_RAM_FLAGS_RESERVED) || !paPages);*/
2362 Assert((fFlags == (MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_MMIO)) || (fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC) || pvRam);
2363 /*Assert(!(fFlags & MM_RAM_FLAGS_RESERVED) || !pvRam);*/
2364 Assert(!(fFlags & ~0xfff));
2365 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb && cb);
2366 Assert(RT_ALIGN_P(pvRam, PAGE_SIZE) == pvRam);
2367 Assert(!(fFlags & ~(MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_ROM | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_MMIO2 | MM_RAM_FLAGS_DYNAMIC_ALLOC)));
2368 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2369 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2370 if (GCPhysLast < GCPhys)
2371 {
2372 AssertMsgFailed(("The range wraps! GCPhys=%RGp cb=%#x\n", GCPhys, cb));
2373 return VERR_INVALID_PARAMETER;
2374 }
2375
2376 /*
2377 * Find range location and check for conflicts.
2378 */
2379 PPGMRAMRANGE pPrev = NULL;
2380 PPGMRAMRANGE pCur = pVM->pgm.s.pRamRangesR3;
2381 while (pCur)
2382 {
2383 if (GCPhys <= pCur->GCPhysLast && GCPhysLast >= pCur->GCPhys)
2384 {
2385 AssertMsgFailed(("Conflict! This cannot happen!\n"));
2386 return VERR_PGM_RAM_CONFLICT;
2387 }
2388 if (GCPhysLast < pCur->GCPhys)
2389 break;
2390
2391 /* next */
2392 pPrev = pCur;
2393 pCur = pCur->pNextR3;
2394 }
2395
2396 /*
2397 * Allocate RAM range.
2398 * Small ranges are allocated from the heap, big ones have separate mappings.
2399 */
2400 size_t cbRam = RT_OFFSETOF(PGMRAMRANGE, aPages[cb >> PAGE_SHIFT]);
2401 PPGMRAMRANGE pNew;
2402 int rc = VERR_NO_MEMORY;
2403 if (cbRam > PAGE_SIZE / 2)
2404 { /* large */
2405 cbRam = RT_ALIGN_Z(cbRam, PAGE_SIZE);
2406 rc = MMR3HyperAllocOnceNoRel(pVM, cbRam, PAGE_SIZE, MM_TAG_PGM_PHYS, (void **)&pNew);
2407 AssertMsgRC(rc, ("MMR3HyperAllocOnceNoRel(,%#x,,) -> %Rrc\n", cbRam, rc));
2408 }
2409 else
2410 { /* small */
2411 rc = MMHyperAlloc(pVM, cbRam, 16, MM_TAG_PGM, (void **)&pNew);
2412 AssertMsgRC(rc, ("MMHyperAlloc(,%#x,,,) -> %Rrc\n", cbRam, rc));
2413 }
2414 if (RT_SUCCESS(rc))
2415 {
2416 /*
2417 * Initialize the range.
2418 */
2419 pNew->pvR3 = pvRam;
2420 pNew->GCPhys = GCPhys;
2421 pNew->GCPhysLast = GCPhysLast;
2422 pNew->cb = cb;
2423 pNew->fFlags = fFlags;
2424 pNew->paChunkR3Ptrs = NULL;
2425
2426 unsigned iPage = (unsigned)(cb >> PAGE_SHIFT);
2427 if (paPages)
2428 {
2429 while (iPage-- > 0)
2430 {
2431 PGM_PAGE_INIT(&pNew->aPages[iPage], paPages[iPage].Phys & X86_PTE_PAE_PG_MASK, NIL_GMM_PAGEID,
2432 fFlags & MM_RAM_FLAGS_MMIO2 ? PGMPAGETYPE_MMIO2 : PGMPAGETYPE_RAM,
2433 PGM_PAGE_STATE_ALLOCATED);
2434 pNew->aPages[iPage].HCPhys |= fFlags; /** @todo PAGE FLAGS*/
2435 }
2436 }
2437 else if (fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC)
2438 {
2439 /* Allocate memory for chunk to HC ptr lookup array. */
2440 rc = MMHyperAlloc(pVM, (cb >> PGM_DYNAMIC_CHUNK_SHIFT) * sizeof(void *), 16, MM_TAG_PGM, (void **)&pNew->paChunkR3Ptrs);
2441 AssertMsgReturn(rc == VINF_SUCCESS, ("MMHyperAlloc(,%#x,,,) -> %Rrc\n", cbRam, cb), rc);
2442
2443 /* Physical memory will be allocated on demand. */
2444 while (iPage-- > 0)
2445 {
2446 PGM_PAGE_INIT(&pNew->aPages[iPage], 0, NIL_GMM_PAGEID, PGMPAGETYPE_RAM, PGM_PAGE_STATE_ZERO);
2447 pNew->aPages[iPage].HCPhys = fFlags; /** @todo PAGE FLAGS */
2448 }
2449 }
2450 else
2451 {
2452 Assert(fFlags == (MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_MMIO));
2453 RTHCPHYS HCPhysDummyPage = MMR3PageDummyHCPhys(pVM);
2454 while (iPage-- > 0)
2455 {
2456 PGM_PAGE_INIT(&pNew->aPages[iPage], HCPhysDummyPage, NIL_GMM_PAGEID, PGMPAGETYPE_MMIO, PGM_PAGE_STATE_ZERO);
2457 pNew->aPages[iPage].HCPhys |= fFlags; /** @todo PAGE FLAGS*/
2458 }
2459 }
2460
2461 /*
2462 * Insert the new RAM range.
2463 */
2464 pgmLock(pVM);
2465 pNew->pNextR3 = pCur;
2466 pNew->pNextR0 = pCur ? MMHyperCCToR0(pVM, pCur) : NIL_RTR0PTR;
2467 pNew->pNextRC = pCur ? MMHyperCCToRC(pVM, pCur) : NIL_RTRCPTR;
2468 if (pPrev)
2469 {
2470 pPrev->pNextR3 = pNew;
2471 pPrev->pNextR0 = MMHyperCCToR0(pVM, pNew);
2472 pPrev->pNextRC = MMHyperCCToRC(pVM, pNew);
2473 }
2474 else
2475 {
2476 pVM->pgm.s.pRamRangesR3 = pNew;
2477 pVM->pgm.s.pRamRangesR0 = MMHyperCCToR0(pVM, pNew);
2478 pVM->pgm.s.pRamRangesRC = MMHyperCCToRC(pVM, pNew);
2479 }
2480 pgmUnlock(pVM);
2481 }
2482 return rc;
2483}
2484
2485
2486/**
2487 * Register a chunk of a the physical memory range with PGM. MM is responsible
2488 * for the toplevel things - allocation and locking - while PGM is taking
2489 * care of all the details and implements the physical address space virtualization.
2490 *
2491 *
2492 * @returns VBox status.
2493 * @param pVM The VM handle.
2494 * @param pvRam HC virtual address of the RAM range. (page aligned)
2495 * @param GCPhys GC physical address of the RAM range. (page aligned)
2496 * @param cb Size of the RAM range. (page aligned)
2497 * @param fFlags Flags, MM_RAM_*.
2498 * @param paPages Pointer an array of physical page descriptors.
2499 * @param pszDesc Description string.
2500 */
2501VMMR3DECL(int) PGMR3PhysRegisterChunk(PVM pVM, void *pvRam, RTGCPHYS GCPhys, size_t cb, unsigned fFlags, const SUPPAGE *paPages, const char *pszDesc)
2502{
2503 NOREF(pszDesc);
2504
2505 /*
2506 * Validate input.
2507 * (Not so important because callers are only MMR3PhysRegister()
2508 * and PGMR3HandlerPhysicalRegisterEx(), but anyway...)
2509 */
2510 Log(("PGMR3PhysRegisterChunk %08X %x bytes flags %x %s\n", GCPhys, cb, fFlags, pszDesc));
2511
2512 Assert(paPages);
2513 Assert(pvRam);
2514 Assert(!(fFlags & ~0xfff));
2515 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb && cb);
2516 Assert(RT_ALIGN_P(pvRam, PAGE_SIZE) == pvRam);
2517 Assert(!(fFlags & ~(MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_ROM | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_MMIO2 | MM_RAM_FLAGS_DYNAMIC_ALLOC)));
2518 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2519 Assert(VM_IS_EMT(pVM));
2520 Assert(!(GCPhys & PGM_DYNAMIC_CHUNK_OFFSET_MASK));
2521 Assert(cb == PGM_DYNAMIC_CHUNK_SIZE);
2522
2523 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2524 if (GCPhysLast < GCPhys)
2525 {
2526 AssertMsgFailed(("The range wraps! GCPhys=%RGp cb=%#x\n", GCPhys, cb));
2527 return VERR_INVALID_PARAMETER;
2528 }
2529
2530 /*
2531 * Find existing range location.
2532 */
2533 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
2534 while (pRam)
2535 {
2536 RTGCPHYS off = GCPhys - pRam->GCPhys;
2537 if ( off < pRam->cb
2538 && (pRam->fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC))
2539 break;
2540
2541 pRam = pRam->CTX_SUFF(pNext);
2542 }
2543 AssertReturn(pRam, VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS);
2544
2545 unsigned off = (GCPhys - pRam->GCPhys) >> PAGE_SHIFT;
2546 unsigned iPage = (unsigned)(cb >> PAGE_SHIFT);
2547 if (paPages)
2548 {
2549 while (iPage-- > 0)
2550 pRam->aPages[off + iPage].HCPhys = (paPages[iPage].Phys & X86_PTE_PAE_PG_MASK) | fFlags; /** @todo PAGE FLAGS */
2551 }
2552 off >>= (PGM_DYNAMIC_CHUNK_SHIFT - PAGE_SHIFT);
2553 pRam->paChunkR3Ptrs[off] = (uintptr_t)pvRam;
2554
2555 /* Notify the recompiler. */
2556 REMR3NotifyPhysRamChunkRegister(pVM, GCPhys, PGM_DYNAMIC_CHUNK_SIZE, (RTHCUINTPTR)pvRam, fFlags);
2557
2558 return VINF_SUCCESS;
2559}
2560
2561
2562/**
2563 * Allocate missing physical pages for an existing guest RAM range.
2564 *
2565 * @returns VBox status.
2566 * @param pVM The VM handle.
2567 * @param GCPhys GC physical address of the RAM range. (page aligned)
2568 */
2569VMMR3DECL(int) PGM3PhysGrowRange(PVM pVM, PCRTGCPHYS pGCPhys)
2570{
2571 RTGCPHYS GCPhys = *pGCPhys;
2572
2573 /*
2574 * Walk range list.
2575 */
2576 pgmLock(pVM);
2577
2578 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
2579 while (pRam)
2580 {
2581 RTGCPHYS off = GCPhys - pRam->GCPhys;
2582 if ( off < pRam->cb
2583 && (pRam->fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC))
2584 {
2585 bool fRangeExists = false;
2586 unsigned off = (GCPhys - pRam->GCPhys) >> PGM_DYNAMIC_CHUNK_SHIFT;
2587
2588 /* Note: A request made from another thread may end up in EMT after somebody else has already allocated the range. */
2589 if (pRam->paChunkR3Ptrs[off])
2590 fRangeExists = true;
2591
2592 pgmUnlock(pVM);
2593 if (fRangeExists)
2594 return VINF_SUCCESS;
2595 return pgmr3PhysGrowRange(pVM, GCPhys);
2596 }
2597
2598 pRam = pRam->CTX_SUFF(pNext);
2599 }
2600 pgmUnlock(pVM);
2601 return VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS;
2602}
2603
2604
2605/**
2606 * Allocate missing physical pages for an existing guest RAM range.
2607 *
2608 * @returns VBox status.
2609 * @param pVM The VM handle.
2610 * @param pRamRange RAM range
2611 * @param GCPhys GC physical address of the RAM range. (page aligned)
2612 */
2613int pgmr3PhysGrowRange(PVM pVM, RTGCPHYS GCPhys)
2614{
2615 void *pvRam;
2616 int rc;
2617
2618 /* We must execute this function in the EMT thread, otherwise we'll run into problems. */
2619 if (!VM_IS_EMT(pVM))
2620 {
2621 PVMREQ pReq;
2622 const RTGCPHYS GCPhysParam = GCPhys;
2623
2624 AssertMsg(!PDMCritSectIsOwner(&pVM->pgm.s.CritSect), ("We own the PGM lock -> deadlock danger!!\n"));
2625
2626 rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)PGM3PhysGrowRange, 2, pVM, &GCPhysParam);
2627 if (RT_SUCCESS(rc))
2628 {
2629 rc = pReq->iStatus;
2630 VMR3ReqFree(pReq);
2631 }
2632 return rc;
2633 }
2634
2635 /* Round down to chunk boundary */
2636 GCPhys = GCPhys & PGM_DYNAMIC_CHUNK_BASE_MASK;
2637
2638 STAM_COUNTER_INC(&pVM->pgm.s.StatR3DynRamGrow);
2639 STAM_COUNTER_ADD(&pVM->pgm.s.StatR3DynRamTotal, PGM_DYNAMIC_CHUNK_SIZE/(1024*1024));
2640
2641 Log(("pgmr3PhysGrowRange: allocate chunk of size 0x%X at %RGp\n", PGM_DYNAMIC_CHUNK_SIZE, GCPhys));
2642
2643 unsigned cPages = PGM_DYNAMIC_CHUNK_SIZE >> PAGE_SHIFT;
2644
2645 for (;;)
2646 {
2647 rc = SUPPageAlloc(cPages, &pvRam);
2648 if (RT_SUCCESS(rc))
2649 {
2650 rc = MMR3PhysRegisterEx(pVM, pvRam, GCPhys, PGM_DYNAMIC_CHUNK_SIZE, 0, MM_PHYS_TYPE_DYNALLOC_CHUNK, "Main Memory");
2651 if (RT_SUCCESS(rc))
2652 return rc;
2653
2654 SUPPageFree(pvRam, cPages);
2655 }
2656
2657 VMSTATE enmVMState = VMR3GetState(pVM);
2658 if (enmVMState != VMSTATE_RUNNING)
2659 {
2660 AssertMsgFailed(("Out of memory while trying to allocate a guest RAM chunk at %RGp!\n", GCPhys));
2661 LogRel(("PGM: Out of memory while trying to allocate a guest RAM chunk at %RGp (VMstate=%s)!\n", GCPhys, VMR3GetStateName(enmVMState)));
2662 return rc;
2663 }
2664
2665 LogRel(("pgmr3PhysGrowRange: out of memory. pause until the user resumes execution.\n"));
2666
2667 /* Pause first, then inform Main. */
2668 rc = VMR3SuspendNoSave(pVM);
2669 AssertRC(rc);
2670
2671 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");
2672
2673 /* Wait for resume event; will only return in that case. If the VM is stopped, the EMT thread will be destroyed. */
2674 rc = VMR3WaitForResume(pVM);
2675
2676 /* Retry */
2677 LogRel(("pgmr3PhysGrowRange: VM execution resumed -> retry.\n"));
2678 }
2679}
2680
2681
2682/**
2683 * Interface MMR3RomRegister() and MMR3PhysReserve calls to update the
2684 * flags of existing RAM ranges.
2685 *
2686 * @returns VBox status.
2687 * @param pVM The VM handle.
2688 * @param GCPhys GC physical address of the RAM range. (page aligned)
2689 * @param cb Size of the RAM range. (page aligned)
2690 * @param fFlags The Or flags, MM_RAM_* \#defines.
2691 * @param fMask The and mask for the flags.
2692 */
2693VMMR3DECL(int) PGMR3PhysSetFlags(PVM pVM, RTGCPHYS GCPhys, size_t cb, unsigned fFlags, unsigned fMask)
2694{
2695 Log(("PGMR3PhysSetFlags %08X %x %x %x\n", GCPhys, cb, fFlags, fMask));
2696
2697 /*
2698 * Validate input.
2699 * (Not so important because caller is always MMR3RomRegister() and MMR3PhysReserve(), but anyway...)
2700 */
2701 Assert(!(fFlags & ~(MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_ROM | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_MMIO2)));
2702 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb && cb);
2703 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2704 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2705 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2706
2707 /*
2708 * Lookup the range.
2709 */
2710 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
2711 while (pRam && GCPhys > pRam->GCPhysLast)
2712 pRam = pRam->CTX_SUFF(pNext);
2713 if ( !pRam
2714 || GCPhys > pRam->GCPhysLast
2715 || GCPhysLast < pRam->GCPhys)
2716 {
2717 AssertMsgFailed(("No RAM range for %RGp-%RGp\n", GCPhys, GCPhysLast));
2718 return VERR_INVALID_PARAMETER;
2719 }
2720
2721 /*
2722 * Update the requested flags.
2723 */
2724 RTHCPHYS fFullMask = ~(RTHCPHYS)(MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_ROM | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_MMIO2)
2725 | fMask;
2726 unsigned iPageEnd = (GCPhysLast - pRam->GCPhys + 1) >> PAGE_SHIFT;
2727 unsigned iPage = (GCPhys - pRam->GCPhys) >> PAGE_SHIFT;
2728 for ( ; iPage < iPageEnd; iPage++)
2729 pRam->aPages[iPage].HCPhys = (pRam->aPages[iPage].HCPhys & fFullMask) | fFlags; /** @todo PAGE FLAGS */
2730
2731 return VINF_SUCCESS;
2732}
2733
2734#endif /* !VBOX_WITH_NEW_PHYS_CODE */
2735
2736/**
2737 * Sets the Address Gate 20 state.
2738 *
2739 * @param pVM VM handle.
2740 * @param fEnable True if the gate should be enabled.
2741 * False if the gate should be disabled.
2742 */
2743VMMDECL(void) PGMR3PhysSetA20(PVM pVM, bool fEnable)
2744{
2745 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVM->pgm.s.fA20Enabled));
2746 if (pVM->pgm.s.fA20Enabled != fEnable)
2747 {
2748 pVM->pgm.s.fA20Enabled = fEnable;
2749 pVM->pgm.s.GCPhysA20Mask = ~(RTGCPHYS)(!fEnable << 20);
2750 REMR3A20Set(pVM, fEnable);
2751 /** @todo we're not handling this correctly for VT-x / AMD-V. See #2911 */
2752 }
2753}
2754
2755
2756/**
2757 * Tree enumeration callback for dealing with age rollover.
2758 * It will perform a simple compression of the current age.
2759 */
2760static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
2761{
2762 /* Age compression - ASSUMES iNow == 4. */
2763 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
2764 if (pChunk->iAge >= UINT32_C(0xffffff00))
2765 pChunk->iAge = 3;
2766 else if (pChunk->iAge >= UINT32_C(0xfffff000))
2767 pChunk->iAge = 2;
2768 else if (pChunk->iAge)
2769 pChunk->iAge = 1;
2770 else /* iAge = 0 */
2771 pChunk->iAge = 4;
2772
2773 /* reinsert */
2774 PVM pVM = (PVM)pvUser;
2775 RTAvllU32Remove(&pVM->pgm.s.ChunkR3Map.pAgeTree, pChunk->AgeCore.Key);
2776 pChunk->AgeCore.Key = pChunk->iAge;
2777 RTAvllU32Insert(&pVM->pgm.s.ChunkR3Map.pAgeTree, &pChunk->AgeCore);
2778 return 0;
2779}
2780
2781
2782/**
2783 * Tree enumeration callback that updates the chunks that have
2784 * been used since the last
2785 */
2786static DECLCALLBACK(int) pgmR3PhysChunkAgeingCallback(PAVLU32NODECORE pNode, void *pvUser)
2787{
2788 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
2789 if (!pChunk->iAge)
2790 {
2791 PVM pVM = (PVM)pvUser;
2792 RTAvllU32Remove(&pVM->pgm.s.ChunkR3Map.pAgeTree, pChunk->AgeCore.Key);
2793 pChunk->AgeCore.Key = pChunk->iAge = pVM->pgm.s.ChunkR3Map.iNow;
2794 RTAvllU32Insert(&pVM->pgm.s.ChunkR3Map.pAgeTree, &pChunk->AgeCore);
2795 }
2796
2797 return 0;
2798}
2799
2800
2801/**
2802 * Performs ageing of the ring-3 chunk mappings.
2803 *
2804 * @param pVM The VM handle.
2805 */
2806VMMR3DECL(void) PGMR3PhysChunkAgeing(PVM pVM)
2807{
2808 pVM->pgm.s.ChunkR3Map.AgeingCountdown = RT_MIN(pVM->pgm.s.ChunkR3Map.cMax / 4, 1024);
2809 pVM->pgm.s.ChunkR3Map.iNow++;
2810 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
2811 {
2812 pVM->pgm.s.ChunkR3Map.iNow = 4;
2813 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, pVM);
2814 }
2815 else
2816 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingCallback, pVM);
2817}
2818
2819
2820/**
2821 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
2822 */
2823typedef struct PGMR3PHYSCHUNKUNMAPCB
2824{
2825 PVM pVM; /**< The VM handle. */
2826 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
2827} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
2828
2829
2830/**
2831 * Callback used to find the mapping that's been unused for
2832 * the longest time.
2833 */
2834static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLLU32NODECORE pNode, void *pvUser)
2835{
2836 do
2837 {
2838 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)((uint8_t *)pNode - RT_OFFSETOF(PGMCHUNKR3MAP, AgeCore));
2839 if ( pChunk->iAge
2840 && !pChunk->cRefs)
2841 {
2842 /*
2843 * Check that it's not in any of the TLBs.
2844 */
2845 PVM pVM = ((PPGMR3PHYSCHUNKUNMAPCB)pvUser)->pVM;
2846 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
2847 if (pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk == pChunk)
2848 {
2849 pChunk = NULL;
2850 break;
2851 }
2852 if (pChunk)
2853 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbHC.aEntries); i++)
2854 if (pVM->pgm.s.PhysTlbHC.aEntries[i].pMap == pChunk)
2855 {
2856 pChunk = NULL;
2857 break;
2858 }
2859 if (pChunk)
2860 {
2861 ((PPGMR3PHYSCHUNKUNMAPCB)pvUser)->pChunk = pChunk;
2862 return 1; /* done */
2863 }
2864 }
2865
2866 /* next with the same age - this version of the AVL API doesn't enumerate the list, so we have to do it. */
2867 pNode = pNode->pList;
2868 } while (pNode);
2869 return 0;
2870}
2871
2872
2873/**
2874 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
2875 *
2876 * The candidate will not be part of any TLBs, so no need to flush
2877 * anything afterwards.
2878 *
2879 * @returns Chunk id.
2880 * @param pVM The VM handle.
2881 */
2882static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
2883{
2884 /*
2885 * Do tree ageing first?
2886 */
2887 if (pVM->pgm.s.ChunkR3Map.AgeingCountdown-- == 0)
2888 PGMR3PhysChunkAgeing(pVM);
2889
2890 /*
2891 * Enumerate the age tree starting with the left most node.
2892 */
2893 PGMR3PHYSCHUNKUNMAPCB Args;
2894 Args.pVM = pVM;
2895 Args.pChunk = NULL;
2896 if (RTAvllU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pAgeTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, pVM))
2897 return Args.pChunk->Core.Key;
2898 return INT32_MAX;
2899}
2900
2901
2902/**
2903 * Maps the given chunk into the ring-3 mapping cache.
2904 *
2905 * This will call ring-0.
2906 *
2907 * @returns VBox status code.
2908 * @param pVM The VM handle.
2909 * @param idChunk The chunk in question.
2910 * @param ppChunk Where to store the chunk tracking structure.
2911 *
2912 * @remarks Called from within the PGM critical section.
2913 */
2914int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
2915{
2916 int rc;
2917 /*
2918 * Allocate a new tracking structure first.
2919 */
2920#if 0 /* for later when we've got a separate mapping method for ring-0. */
2921 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAlloc(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
2922 AssertReturn(pChunk, VERR_NO_MEMORY);
2923#else
2924 PPGMCHUNKR3MAP pChunk;
2925 rc = MMHyperAlloc(pVM, sizeof(*pChunk), 0, MM_TAG_PGM_CHUNK_MAPPING, (void **)&pChunk);
2926 AssertRCReturn(rc, rc);
2927#endif
2928 pChunk->Core.Key = idChunk;
2929 pChunk->AgeCore.Key = pVM->pgm.s.ChunkR3Map.iNow;
2930 pChunk->iAge = 0;
2931 pChunk->cRefs = 0;
2932 pChunk->cPermRefs = 0;
2933 pChunk->pv = NULL;
2934
2935 /*
2936 * Request the ring-0 part to map the chunk in question and if
2937 * necessary unmap another one to make space in the mapping cache.
2938 */
2939 GMMMAPUNMAPCHUNKREQ Req;
2940 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
2941 Req.Hdr.cbReq = sizeof(Req);
2942 Req.pvR3 = NULL;
2943 Req.idChunkMap = idChunk;
2944 Req.idChunkUnmap = NIL_GMM_CHUNKID;
2945 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
2946 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
2947 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
2948 if (RT_SUCCESS(rc))
2949 {
2950 /*
2951 * Update the tree.
2952 */
2953 /* insert the new one. */
2954 AssertPtr(Req.pvR3);
2955 pChunk->pv = Req.pvR3;
2956 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
2957 AssertRelease(fRc);
2958 pVM->pgm.s.ChunkR3Map.c++;
2959
2960 fRc = RTAvllU32Insert(&pVM->pgm.s.ChunkR3Map.pAgeTree, &pChunk->AgeCore);
2961 AssertRelease(fRc);
2962
2963 /* remove the unmapped one. */
2964 if (Req.idChunkUnmap != NIL_GMM_CHUNKID)
2965 {
2966 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
2967 AssertRelease(pUnmappedChunk);
2968 pUnmappedChunk->pv = NULL;
2969 pUnmappedChunk->Core.Key = UINT32_MAX;
2970#if 0 /* for later when we've got a separate mapping method for ring-0. */
2971 MMR3HeapFree(pUnmappedChunk);
2972#else
2973 MMHyperFree(pVM, pUnmappedChunk);
2974#endif
2975 pVM->pgm.s.ChunkR3Map.c--;
2976 }
2977 }
2978 else
2979 {
2980 AssertRC(rc);
2981#if 0 /* for later when we've got a separate mapping method for ring-0. */
2982 MMR3HeapFree(pChunk);
2983#else
2984 MMHyperFree(pVM, pChunk);
2985#endif
2986 pChunk = NULL;
2987 }
2988
2989 *ppChunk = pChunk;
2990 return rc;
2991}
2992
2993
2994/**
2995 * For VMMCALLHOST_PGM_MAP_CHUNK, considered internal.
2996 *
2997 * @returns see pgmR3PhysChunkMap.
2998 * @param pVM The VM handle.
2999 * @param idChunk The chunk to map.
3000 */
3001VMMR3DECL(int) PGMR3PhysChunkMap(PVM pVM, uint32_t idChunk)
3002{
3003 PPGMCHUNKR3MAP pChunk;
3004 return pgmR3PhysChunkMap(pVM, idChunk, &pChunk);
3005}
3006
3007
3008/**
3009 * Invalidates the TLB for the ring-3 mapping cache.
3010 *
3011 * @param pVM The VM handle.
3012 */
3013VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
3014{
3015 pgmLock(pVM);
3016 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
3017 {
3018 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
3019 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
3020 }
3021 pgmUnlock(pVM);
3022}
3023
3024
3025/**
3026 * Response to VM_FF_PGM_NEED_HANDY_PAGES and VMMCALLHOST_PGM_ALLOCATE_HANDY_PAGES.
3027 *
3028 * @returns The following VBox status codes.
3029 * @retval VINF_SUCCESS on success. FF cleared.
3030 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in this case.
3031 *
3032 * @param pVM The VM handle.
3033 */
3034VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
3035{
3036 pgmLock(pVM);
3037
3038 /*
3039 * Allocate more pages, noting down the index of the first new page.
3040 */
3041 uint32_t iClear = pVM->pgm.s.cHandyPages;
3042 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_INTERNAL_ERROR);
3043 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
3044 int rcAlloc = VINF_SUCCESS;
3045 int rcSeed = VINF_SUCCESS;
3046 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
3047 while (rc == VERR_GMM_SEED_ME)
3048 {
3049 void *pvChunk;
3050 rcAlloc = rc = SUPPageAlloc(GMM_CHUNK_SIZE >> PAGE_SHIFT, &pvChunk);
3051 if (RT_SUCCESS(rc))
3052 {
3053 rcSeed = rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_SEED_CHUNK, (uintptr_t)pvChunk, NULL);
3054 if (RT_FAILURE(rc))
3055 SUPPageFree(pvChunk, GMM_CHUNK_SIZE >> PAGE_SHIFT);
3056 }
3057 if (RT_SUCCESS(rc))
3058 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
3059 }
3060
3061 /*
3062 * Clear the pages.
3063 */
3064 if (RT_SUCCESS(rc))
3065 {
3066 while (iClear < pVM->pgm.s.cHandyPages)
3067 {
3068 PGMMPAGEDESC pPage = &pVM->pgm.s.aHandyPages[iClear];
3069 void *pv;
3070 rc = pgmPhysPageMapByPageID(pVM, pPage->idPage, pPage->HCPhysGCPhys, &pv);
3071 AssertLogRelMsgBreak(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc", pPage->idPage, pPage->HCPhysGCPhys, rc));
3072 ASMMemZeroPage(pv);
3073 iClear++;
3074 }
3075
3076 VM_FF_CLEAR(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
3077 }
3078 else
3079 {
3080 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc rcAlloc=%Rrc rcSeed=%Rrc cHandyPages=%#x\n"
3081 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
3082 rc, rcSeed, rcAlloc,
3083 pVM->pgm.s.cHandyPages,
3084 pVM->pgm.s.cAllPages,
3085 pVM->pgm.s.cPrivatePages,
3086 pVM->pgm.s.cSharedPages,
3087 pVM->pgm.s.cZeroPages));
3088 rc = VERR_EM_NO_MEMORY;
3089 //rc = VINF_EM_NO_MEMORY;
3090 //VM_FF_SET(pVM, VM_FF_PGM_WE_ARE_SCREWED?);
3091 }
3092
3093/** @todo Do proper VERR_EM_NO_MEMORY reporting. */
3094 AssertMsg( pVM->pgm.s.cHandyPages == RT_ELEMENTS(pVM->pgm.s.aHandyPages)
3095 || rc != VINF_SUCCESS, ("%d rc=%Rrc\n", pVM->pgm.s.cHandyPages, rc));
3096
3097 pgmUnlock(pVM);
3098 Assert(rc == VINF_SUCCESS || rc == VINF_EM_NO_MEMORY || rc == VERR_EM_NO_MEMORY);
3099 return rc;
3100}
3101
3102
3103/**
3104 * Frees the specified RAM page and replaces it with the ZERO page.
3105 *
3106 * This is used by ballooning, remapping MMIO2 and RAM reset.
3107 *
3108 * @param pVM Pointer to the shared VM structure.
3109 * @param pReq Pointer to the request.
3110 * @param pPage Pointer to the page structure.
3111 * @param GCPhys The guest physical address of the page, if applicable.
3112 *
3113 * @remarks The caller must own the PGM lock.
3114 */
3115static int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys)
3116{
3117 /*
3118 * Assert sanity.
3119 */
3120 Assert(PDMCritSectIsOwner(&pVM->pgm.s.CritSect));
3121 if (RT_UNLIKELY(PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM))
3122 {
3123 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
3124 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
3125 }
3126
3127 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_ZERO)
3128 return VINF_SUCCESS;
3129
3130 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
3131 if (RT_UNLIKELY( idPage == NIL_GMM_PAGEID
3132 || idPage > GMM_PAGEID_LAST
3133 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID))
3134 {
3135 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
3136 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
3137 }
3138
3139 /* update page count stats. */
3140 if (PGM_PAGE_IS_SHARED(pPage))
3141 pVM->pgm.s.cSharedPages--;
3142 else
3143 pVM->pgm.s.cPrivatePages--;
3144 pVM->pgm.s.cZeroPages++;
3145
3146 /*
3147 * pPage = ZERO page.
3148 */
3149 PGM_PAGE_SET_HCPHYS(pPage, pVM->pgm.s.HCPhysZeroPg);
3150 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
3151 PGM_PAGE_SET_PAGEID(pPage, NIL_GMM_PAGEID);
3152
3153 /*
3154 * Make sure it's not in the handy page array.
3155 */
3156 uint32_t i = pVM->pgm.s.cHandyPages;
3157 while (i < RT_ELEMENTS(pVM->pgm.s.aHandyPages))
3158 {
3159 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
3160 {
3161 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
3162 break;
3163 }
3164 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
3165 {
3166 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
3167 break;
3168 }
3169 i++;
3170 }
3171
3172 /*
3173 * Push it onto the page array.
3174 */
3175 uint32_t iPage = *pcPendingPages;
3176 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
3177 *pcPendingPages += 1;
3178
3179 pReq->aPages[iPage].idPage = idPage;
3180
3181 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
3182 return VINF_SUCCESS;
3183
3184 /*
3185 * Flush the pages.
3186 */
3187 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
3188 if (RT_SUCCESS(rc))
3189 {
3190 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
3191 *pcPendingPages = 0;
3192 }
3193 return rc;
3194}
3195
3196
3197/**
3198 * Converts a GC physical address to a HC ring-3 pointer, with some
3199 * additional checks.
3200 *
3201 * @returns VBox status code.
3202 * @retval VINF_SUCCESS on success.
3203 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
3204 * access handler of some kind.
3205 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
3206 * accesses or is odd in any way.
3207 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
3208 *
3209 * @param pVM The VM handle.
3210 * @param GCPhys The GC physical address to convert.
3211 * @param fWritable Whether write access is required.
3212 * @param ppv Where to store the pointer corresponding to GCPhys on
3213 * success.
3214 */
3215VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
3216{
3217 pgmLock(pVM);
3218
3219 PPGMRAMRANGE pRam;
3220 PPGMPAGE pPage;
3221 int rc = pgmPhysGetPageAndRangeEx(&pVM->pgm.s, GCPhys, &pPage, &pRam);
3222 if (RT_SUCCESS(rc))
3223 {
3224#ifdef VBOX_WITH_NEW_PHYS_CODE
3225 if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
3226 rc = VINF_SUCCESS;
3227 else
3228 {
3229 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
3230 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
3231 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
3232 {
3233 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
3234 * in -norawr0 mode. */
3235 if (fWritable)
3236 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
3237 }
3238 else
3239 {
3240 /* Temporariliy disabled phycial handler(s), since the recompiler
3241 doesn't get notified when it's reset we'll have to pretend its
3242 operating normally. */
3243 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
3244 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
3245 else
3246 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
3247 }
3248 }
3249 if (RT_SUCCESS(rc))
3250 {
3251 int rc2;
3252
3253 /* Make sure what we return is writable. */
3254 if (fWritable && rc != VINF_PGM_PHYS_TLB_CATCH_WRITE)
3255 switch (PGM_PAGE_GET_STATE(pPage))
3256 {
3257 case PGM_PAGE_STATE_ALLOCATED:
3258 break;
3259 case PGM_PAGE_STATE_ZERO:
3260 case PGM_PAGE_STATE_SHARED:
3261 case PGM_PAGE_STATE_WRITE_MONITORED:
3262 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)PAGE_OFFSET_MASK);
3263 AssertLogRelRCReturn(rc2, rc2);
3264 break;
3265 }
3266
3267 /* Get a ring-3 mapping of the address. */
3268 PPGMPAGER3MAPTLBE pTlbe;
3269 rc2 = pgmPhysPageQueryTlbe(&pVM->pgm.s, GCPhys, &pTlbe);
3270 AssertLogRelRCReturn(rc2, rc2);
3271 *ppv = (void *)((uintptr_t)pTlbe->pv | (GCPhys & PAGE_OFFSET_MASK));
3272 /** @todo mapping/locking hell; this isn't horribly efficient since
3273 * pgmPhysPageLoadIntoTlb will repeate the lookup we've done here. */
3274
3275 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
3276 }
3277 else
3278 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
3279
3280 /* else: handler catching all access, no pointer returned. */
3281
3282#else
3283 if (0)
3284 /* nothing */;
3285 else if (PGM_PAGE_HAS_ANY_HANDLERS(pPage))
3286 {
3287 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
3288 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
3289 else if (fWritable && PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
3290 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
3291 else
3292 {
3293 /* Temporariliy disabled phycial handler(s), since the recompiler
3294 doesn't get notified when it's reset we'll have to pretend its
3295 operating normally. */
3296 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
3297 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
3298 else
3299 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
3300 }
3301 }
3302 else
3303 rc = VINF_SUCCESS;
3304 if (RT_SUCCESS(rc))
3305 {
3306 if (pRam->fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC)
3307 {
3308 AssertMsg(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM, ("GCPhys=%RGp type=%d\n", GCPhys, PGM_PAGE_GET_TYPE(pPage)));
3309 RTGCPHYS off = GCPhys - pRam->GCPhys;
3310 unsigned iChunk = (off >> PGM_DYNAMIC_CHUNK_SHIFT);
3311 *ppv = (void *)(pRam->paChunkR3Ptrs[iChunk] + (off & PGM_DYNAMIC_CHUNK_OFFSET_MASK));
3312 }
3313 else if (RT_LIKELY(pRam->pvR3))
3314 {
3315 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)));
3316 RTGCPHYS off = GCPhys - pRam->GCPhys;
3317 *ppv = (uint8_t *)pRam->pvR3 + off;
3318 }
3319 else
3320 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
3321 }
3322#endif /* !VBOX_WITH_NEW_PHYS_CODE */
3323 }
3324 else
3325 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
3326
3327 pgmUnlock(pVM);
3328 return rc;
3329}
3330
3331
3332
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