VirtualBox

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

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

PGMPhysPageMap cleanup.

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