VirtualBox

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

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

PGMPAGE: Removed the PGM_PAGE_WITH_BIT_FIELD bits.

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