VirtualBox

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

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

Compile fix

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