VirtualBox

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

Last change on this file since 54985 was 54823, checked in by vboxsync, 10 years ago

VMM: Map the hyper heap in ring-0 on 64-bit systems.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 170.0 KB
Line 
1/* $Id: PGMPhys.cpp 54823 2015-03-17 22:43:02Z vboxsync $ */
2/** @file
3 * PGM - Page Manager and Monitor, Physical Memory Addressing.
4 */
5
6/*
7 * Copyright (C) 2006-2014 Oracle Corporation
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
18
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#define LOG_GROUP LOG_GROUP_PGM_PHYS
23#include <VBox/vmm/pgm.h>
24#include <VBox/vmm/iom.h>
25#include <VBox/vmm/mm.h>
26#include <VBox/vmm/stam.h>
27#ifdef VBOX_WITH_REM
28# include <VBox/vmm/rem.h>
29#endif
30#include <VBox/vmm/pdmdev.h>
31#include "PGMInternal.h"
32#include <VBox/vmm/vm.h>
33#include <VBox/vmm/uvm.h>
34#include "PGMInline.h"
35#include <VBox/sup.h>
36#include <VBox/param.h>
37#include <VBox/err.h>
38#include <VBox/log.h>
39#include <iprt/assert.h>
40#include <iprt/alloc.h>
41#include <iprt/asm.h>
42#ifdef VBOX_STRICT
43# include <iprt/crc.h>
44#endif
45#include <iprt/thread.h>
46#include <iprt/string.h>
47#include <iprt/system.h>
48
49
50/*******************************************************************************
51* Defined Constants And Macros *
52*******************************************************************************/
53/** The number of pages to free in one batch. */
54#define PGMPHYS_FREE_PAGE_BATCH_SIZE 128
55
56
57/*******************************************************************************
58* Internal Functions *
59*******************************************************************************/
60static DECLCALLBACK(int) pgmR3PhysRomWriteHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser);
61
62
63/*
64 * PGMR3PhysReadU8-64
65 * PGMR3PhysWriteU8-64
66 */
67#define PGMPHYSFN_READNAME PGMR3PhysReadU8
68#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU8
69#define PGMPHYS_DATASIZE 1
70#define PGMPHYS_DATATYPE uint8_t
71#include "PGMPhysRWTmpl.h"
72
73#define PGMPHYSFN_READNAME PGMR3PhysReadU16
74#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU16
75#define PGMPHYS_DATASIZE 2
76#define PGMPHYS_DATATYPE uint16_t
77#include "PGMPhysRWTmpl.h"
78
79#define PGMPHYSFN_READNAME PGMR3PhysReadU32
80#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU32
81#define PGMPHYS_DATASIZE 4
82#define PGMPHYS_DATATYPE uint32_t
83#include "PGMPhysRWTmpl.h"
84
85#define PGMPHYSFN_READNAME PGMR3PhysReadU64
86#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU64
87#define PGMPHYS_DATASIZE 8
88#define PGMPHYS_DATATYPE uint64_t
89#include "PGMPhysRWTmpl.h"
90
91
92/**
93 * EMT worker for PGMR3PhysReadExternal.
94 */
95static DECLCALLBACK(int) pgmR3PhysReadExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, void *pvBuf, size_t cbRead)
96{
97 PGMPhysRead(pVM, *pGCPhys, pvBuf, cbRead);
98 return VINF_SUCCESS;
99}
100
101
102/**
103 * Read from physical memory, external users.
104 *
105 * @returns VBox status code.
106 * @retval VINF_SUCCESS.
107 *
108 * @param pVM Pointer to the VM.
109 * @param GCPhys Physical address to read from.
110 * @param pvBuf Where to read into.
111 * @param cbRead How many bytes to read.
112 *
113 * @thread Any but EMTs.
114 */
115VMMR3DECL(int) PGMR3PhysReadExternal(PVM pVM, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead)
116{
117 VM_ASSERT_OTHER_THREAD(pVM);
118
119 AssertMsgReturn(cbRead > 0, ("don't even think about reading zero bytes!\n"), VINF_SUCCESS);
120 LogFlow(("PGMR3PhysReadExternal: %RGp %d\n", GCPhys, cbRead));
121
122 pgmLock(pVM);
123
124 /*
125 * Copy loop on ram ranges.
126 */
127 PPGMRAMRANGE pRam = pgmPhysGetRangeAtOrAbove(pVM, GCPhys);
128 for (;;)
129 {
130 /* Inside range or not? */
131 if (pRam && GCPhys >= pRam->GCPhys)
132 {
133 /*
134 * Must work our way thru this page by page.
135 */
136 RTGCPHYS off = GCPhys - pRam->GCPhys;
137 while (off < pRam->cb)
138 {
139 unsigned iPage = off >> PAGE_SHIFT;
140 PPGMPAGE pPage = &pRam->aPages[iPage];
141
142 /*
143 * If the page has an ALL access handler, we'll have to
144 * delegate the job to EMT.
145 */
146 if ( PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)
147 || PGM_PAGE_IS_SPECIAL_ALIAS_MMIO(pPage))
148 {
149 pgmUnlock(pVM);
150
151 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysReadExternalEMT, 4,
152 pVM, &GCPhys, pvBuf, cbRead);
153 }
154 Assert(!PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(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 PGMPAGEMAPLOCK PgMpLck;
163 const void *pvSrc;
164 int rc = pgmPhysGCPhys2CCPtrInternalReadOnly(pVM, pPage, pRam->GCPhys + off, &pvSrc, &PgMpLck);
165 if (RT_SUCCESS(rc))
166 {
167 memcpy(pvBuf, pvSrc, cb);
168 pgmPhysReleaseInternalPageMappingLock(pVM, &PgMpLck);
169 }
170 else
171 {
172 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternalReadOnly failed on %RGp / %R[pgmpage] -> %Rrc\n",
173 pRam->GCPhys + off, pPage, rc));
174 memset(pvBuf, 0xff, cb);
175 }
176
177 /* next page */
178 if (cb >= cbRead)
179 {
180 pgmUnlock(pVM);
181 return VINF_SUCCESS;
182 }
183 cbRead -= cb;
184 off += cb;
185 GCPhys += cb;
186 pvBuf = (char *)pvBuf + cb;
187 } /* walk pages in ram range. */
188 }
189 else
190 {
191 LogFlow(("PGMPhysRead: Unassigned %RGp size=%u\n", GCPhys, cbRead));
192
193 /*
194 * Unassigned address space.
195 */
196 size_t cb = pRam ? pRam->GCPhys - GCPhys : ~(size_t)0;
197 if (cb >= cbRead)
198 {
199 memset(pvBuf, 0xff, cbRead);
200 break;
201 }
202 memset(pvBuf, 0xff, cb);
203
204 cbRead -= cb;
205 pvBuf = (char *)pvBuf + cb;
206 GCPhys += cb;
207 }
208
209 /* Advance range if necessary. */
210 while (pRam && GCPhys > pRam->GCPhysLast)
211 pRam = pRam->CTX_SUFF(pNext);
212 } /* Ram range walk */
213
214 pgmUnlock(pVM);
215
216 return VINF_SUCCESS;
217}
218
219
220/**
221 * EMT worker for PGMR3PhysWriteExternal.
222 */
223static DECLCALLBACK(int) pgmR3PhysWriteExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, const void *pvBuf, size_t cbWrite)
224{
225 /** @todo VERR_EM_NO_MEMORY */
226 PGMPhysWrite(pVM, *pGCPhys, pvBuf, cbWrite);
227 return VINF_SUCCESS;
228}
229
230
231/**
232 * Write to physical memory, external users.
233 *
234 * @returns VBox status code.
235 * @retval VINF_SUCCESS.
236 * @retval VERR_EM_NO_MEMORY.
237 *
238 * @param pVM Pointer to the VM.
239 * @param GCPhys Physical address to write to.
240 * @param pvBuf What to write.
241 * @param cbWrite How many bytes to write.
242 * @param pszWho Who is writing. For tracking down who is writing
243 * after we've saved the state.
244 *
245 * @thread Any but EMTs.
246 */
247VMMDECL(int) PGMR3PhysWriteExternal(PVM pVM, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite, const char *pszWho)
248{
249 VM_ASSERT_OTHER_THREAD(pVM);
250
251 AssertMsg(!pVM->pgm.s.fNoMorePhysWrites,
252 ("Calling PGMR3PhysWriteExternal after pgmR3Save()! GCPhys=%RGp cbWrite=%#x pszWho=%s\n",
253 GCPhys, cbWrite, pszWho));
254 AssertMsgReturn(cbWrite > 0, ("don't even think about writing zero bytes!\n"), VINF_SUCCESS);
255 LogFlow(("PGMR3PhysWriteExternal: %RGp %d\n", GCPhys, cbWrite));
256
257 pgmLock(pVM);
258
259 /*
260 * Copy loop on ram ranges, stop when we hit something difficult.
261 */
262 PPGMRAMRANGE pRam = pgmPhysGetRangeAtOrAbove(pVM, GCPhys);
263 for (;;)
264 {
265 /* Inside range or not? */
266 if (pRam && GCPhys >= pRam->GCPhys)
267 {
268 /*
269 * Must work our way thru this page by page.
270 */
271 RTGCPTR off = GCPhys - pRam->GCPhys;
272 while (off < pRam->cb)
273 {
274 RTGCPTR iPage = off >> PAGE_SHIFT;
275 PPGMPAGE pPage = &pRam->aPages[iPage];
276
277 /*
278 * Is the page problematic, we have to do the work on the EMT.
279 *
280 * Allocating writable pages and access handlers are
281 * problematic, write monitored pages are simple and can be
282 * dealt with here.
283 */
284 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
285 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED
286 || PGM_PAGE_IS_SPECIAL_ALIAS_MMIO(pPage))
287 {
288 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
289 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
290 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage);
291 else
292 {
293 pgmUnlock(pVM);
294
295 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysWriteExternalEMT, 4,
296 pVM, &GCPhys, pvBuf, cbWrite);
297 }
298 }
299 Assert(!PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage));
300
301 /*
302 * Simple stuff, go ahead.
303 */
304 size_t cb = PAGE_SIZE - (off & PAGE_OFFSET_MASK);
305 if (cb > cbWrite)
306 cb = cbWrite;
307 PGMPAGEMAPLOCK PgMpLck;
308 void *pvDst;
309 int rc = pgmPhysGCPhys2CCPtrInternal(pVM, pPage, pRam->GCPhys + off, &pvDst, &PgMpLck);
310 if (RT_SUCCESS(rc))
311 {
312 memcpy(pvDst, pvBuf, cb);
313 pgmPhysReleaseInternalPageMappingLock(pVM, &PgMpLck);
314 }
315 else
316 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternal failed on %RGp / %R[pgmpage] -> %Rrc\n",
317 pRam->GCPhys + off, pPage, rc));
318
319 /* next page */
320 if (cb >= cbWrite)
321 {
322 pgmUnlock(pVM);
323 return VINF_SUCCESS;
324 }
325
326 cbWrite -= cb;
327 off += cb;
328 GCPhys += cb;
329 pvBuf = (const char *)pvBuf + cb;
330 } /* walk pages in ram range */
331 }
332 else
333 {
334 /*
335 * Unassigned address space, skip it.
336 */
337 if (!pRam)
338 break;
339 size_t cb = pRam->GCPhys - GCPhys;
340 if (cb >= cbWrite)
341 break;
342 cbWrite -= cb;
343 pvBuf = (const char *)pvBuf + cb;
344 GCPhys += cb;
345 }
346
347 /* Advance range if necessary. */
348 while (pRam && GCPhys > pRam->GCPhysLast)
349 pRam = pRam->CTX_SUFF(pNext);
350 } /* Ram range walk */
351
352 pgmUnlock(pVM);
353 return VINF_SUCCESS;
354}
355
356
357/**
358 * VMR3ReqCall worker for PGMR3PhysGCPhys2CCPtrExternal to make pages writable.
359 *
360 * @returns see PGMR3PhysGCPhys2CCPtrExternal
361 * @param pVM Pointer to the VM.
362 * @param pGCPhys Pointer to the guest physical address.
363 * @param ppv Where to store the mapping address.
364 * @param pLock Where to store the lock.
365 */
366static DECLCALLBACK(int) pgmR3PhysGCPhys2CCPtrDelegated(PVM pVM, PRTGCPHYS pGCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
367{
368 /*
369 * Just hand it to PGMPhysGCPhys2CCPtr and check that it's not a page with
370 * an access handler after it succeeds.
371 */
372 int rc = pgmLock(pVM);
373 AssertRCReturn(rc, rc);
374
375 rc = PGMPhysGCPhys2CCPtr(pVM, *pGCPhys, ppv, pLock);
376 if (RT_SUCCESS(rc))
377 {
378 PPGMPAGEMAPTLBE pTlbe;
379 int rc2 = pgmPhysPageQueryTlbe(pVM, *pGCPhys, &pTlbe);
380 AssertFatalRC(rc2);
381 PPGMPAGE pPage = pTlbe->pPage;
382 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
383 {
384 PGMPhysReleasePageMappingLock(pVM, pLock);
385 rc = VERR_PGM_PHYS_PAGE_RESERVED;
386 }
387 else if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
388#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
389 || pgmPoolIsDirtyPage(pVM, *pGCPhys)
390#endif
391 )
392 {
393 /* We *must* flush any corresponding pgm pool page here, otherwise we'll
394 * not be informed about writes and keep bogus gst->shw mappings around.
395 */
396 pgmPoolFlushPageByGCPhys(pVM, *pGCPhys);
397 Assert(!PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage));
398 /** @todo r=bird: return VERR_PGM_PHYS_PAGE_RESERVED here if it still has
399 * active handlers, see the PGMR3PhysGCPhys2CCPtrExternal docs. */
400 }
401 }
402
403 pgmUnlock(pVM);
404 return rc;
405}
406
407
408/**
409 * Requests the mapping of a guest page into ring-3, external threads.
410 *
411 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
412 * release it.
413 *
414 * This API will assume your intention is to write to the page, and will
415 * therefore replace shared and zero pages. If you do not intend to modify the
416 * page, use the PGMR3PhysGCPhys2CCPtrReadOnlyExternal() API.
417 *
418 * @returns VBox status code.
419 * @retval VINF_SUCCESS on success.
420 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
421 * backing or if the page has any active access handlers. The caller
422 * must fall back on using PGMR3PhysWriteExternal.
423 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
424 *
425 * @param pVM Pointer to the VM.
426 * @param GCPhys The guest physical address of the page that should be mapped.
427 * @param ppv Where to store the address corresponding to GCPhys.
428 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
429 *
430 * @remark Avoid calling this API from within critical sections (other than the
431 * PGM one) because of the deadlock risk when we have to delegating the
432 * task to an EMT.
433 * @thread Any.
434 */
435VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrExternal(PVM pVM, RTGCPHYS GCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
436{
437 AssertPtr(ppv);
438 AssertPtr(pLock);
439
440 Assert(VM_IS_EMT(pVM) || !PGMIsLockOwner(pVM));
441
442 int rc = pgmLock(pVM);
443 AssertRCReturn(rc, rc);
444
445 /*
446 * Query the Physical TLB entry for the page (may fail).
447 */
448 PPGMPAGEMAPTLBE pTlbe;
449 rc = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
450 if (RT_SUCCESS(rc))
451 {
452 PPGMPAGE pPage = pTlbe->pPage;
453 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
454 rc = VERR_PGM_PHYS_PAGE_RESERVED;
455 else
456 {
457 /*
458 * If the page is shared, the zero page, or being write monitored
459 * it must be converted to an page that's writable if possible.
460 * We can only deal with write monitored pages here, the rest have
461 * to be on an EMT.
462 */
463 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
464 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED
465#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
466 || pgmPoolIsDirtyPage(pVM, GCPhys)
467#endif
468 )
469 {
470 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
471 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
472#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
473 && !pgmPoolIsDirtyPage(pVM, GCPhys)
474#endif
475 )
476 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage);
477 else
478 {
479 pgmUnlock(pVM);
480
481 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysGCPhys2CCPtrDelegated, 4,
482 pVM, &GCPhys, ppv, pLock);
483 }
484 }
485
486 /*
487 * Now, just perform the locking and calculate the return address.
488 */
489 PPGMPAGEMAP pMap = pTlbe->pMap;
490 if (pMap)
491 pMap->cRefs++;
492
493 unsigned cLocks = PGM_PAGE_GET_WRITE_LOCKS(pPage);
494 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
495 {
496 if (cLocks == 0)
497 pVM->pgm.s.cWriteLockedPages++;
498 PGM_PAGE_INC_WRITE_LOCKS(pPage);
499 }
500 else if (cLocks != PGM_PAGE_GET_WRITE_LOCKS(pPage))
501 {
502 PGM_PAGE_INC_WRITE_LOCKS(pPage);
503 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent write locked state!\n", GCPhys, pPage));
504 if (pMap)
505 pMap->cRefs++; /* Extra ref to prevent it from going away. */
506 }
507
508 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
509 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_WRITE;
510 pLock->pvMap = pMap;
511 }
512 }
513
514 pgmUnlock(pVM);
515 return rc;
516}
517
518
519/**
520 * Requests the mapping of a guest page into ring-3, external threads.
521 *
522 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
523 * release it.
524 *
525 * @returns VBox status code.
526 * @retval VINF_SUCCESS on success.
527 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
528 * backing or if the page as an active ALL access handler. The caller
529 * must fall back on using PGMPhysRead.
530 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
531 *
532 * @param pVM Pointer to the VM.
533 * @param GCPhys The guest physical address of the page that should be mapped.
534 * @param ppv Where to store the address corresponding to GCPhys.
535 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
536 *
537 * @remark Avoid calling this API from within critical sections (other than
538 * the PGM one) because of the deadlock risk.
539 * @thread Any.
540 */
541VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrReadOnlyExternal(PVM pVM, RTGCPHYS GCPhys, void const **ppv, PPGMPAGEMAPLOCK pLock)
542{
543 int rc = pgmLock(pVM);
544 AssertRCReturn(rc, rc);
545
546 /*
547 * Query the Physical TLB entry for the page (may fail).
548 */
549 PPGMPAGEMAPTLBE pTlbe;
550 rc = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
551 if (RT_SUCCESS(rc))
552 {
553 PPGMPAGE pPage = pTlbe->pPage;
554#if 1
555 /* MMIO pages doesn't have any readable backing. */
556 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
557 rc = VERR_PGM_PHYS_PAGE_RESERVED;
558#else
559 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
560 rc = VERR_PGM_PHYS_PAGE_RESERVED;
561#endif
562 else
563 {
564 /*
565 * Now, just perform the locking and calculate the return address.
566 */
567 PPGMPAGEMAP pMap = pTlbe->pMap;
568 if (pMap)
569 pMap->cRefs++;
570
571 unsigned cLocks = PGM_PAGE_GET_READ_LOCKS(pPage);
572 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
573 {
574 if (cLocks == 0)
575 pVM->pgm.s.cReadLockedPages++;
576 PGM_PAGE_INC_READ_LOCKS(pPage);
577 }
578 else if (cLocks != PGM_PAGE_GET_READ_LOCKS(pPage))
579 {
580 PGM_PAGE_INC_READ_LOCKS(pPage);
581 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent readonly locked state!\n", GCPhys, pPage));
582 if (pMap)
583 pMap->cRefs++; /* Extra ref to prevent it from going away. */
584 }
585
586 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
587 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_READ;
588 pLock->pvMap = pMap;
589 }
590 }
591
592 pgmUnlock(pVM);
593 return rc;
594}
595
596
597#define MAKE_LEAF(a_pNode) \
598 do { \
599 (a_pNode)->pLeftR3 = NIL_RTR3PTR; \
600 (a_pNode)->pRightR3 = NIL_RTR3PTR; \
601 (a_pNode)->pLeftR0 = NIL_RTR0PTR; \
602 (a_pNode)->pRightR0 = NIL_RTR0PTR; \
603 (a_pNode)->pLeftRC = NIL_RTRCPTR; \
604 (a_pNode)->pRightRC = NIL_RTRCPTR; \
605 } while (0)
606
607#define INSERT_LEFT(a_pParent, a_pNode) \
608 do { \
609 (a_pParent)->pLeftR3 = (a_pNode); \
610 (a_pParent)->pLeftR0 = (a_pNode)->pSelfR0; \
611 (a_pParent)->pLeftRC = (a_pNode)->pSelfRC; \
612 } while (0)
613#define INSERT_RIGHT(a_pParent, a_pNode) \
614 do { \
615 (a_pParent)->pRightR3 = (a_pNode); \
616 (a_pParent)->pRightR0 = (a_pNode)->pSelfR0; \
617 (a_pParent)->pRightRC = (a_pNode)->pSelfRC; \
618 } while (0)
619
620
621/**
622 * Recursive tree builder.
623 *
624 * @param ppRam Pointer to the iterator variable.
625 * @param iHeight The hight about normal leaf nodes. Inserts a leaf
626 * node if 0.
627 */
628static PPGMRAMRANGE pgmR3PhysRebuildRamRangeSearchTreesRecursively(PPGMRAMRANGE *ppRam, int iDepth)
629{
630 PPGMRAMRANGE pRam;
631 if (iDepth <= 0)
632 {
633 /*
634 * Leaf node.
635 */
636 pRam = *ppRam;
637 if (pRam)
638 {
639 *ppRam = pRam->pNextR3;
640 MAKE_LEAF(pRam);
641 }
642 }
643 else
644 {
645
646 /*
647 * Intermediate node.
648 */
649 PPGMRAMRANGE pLeft = pgmR3PhysRebuildRamRangeSearchTreesRecursively(ppRam, iDepth - 1);
650
651 pRam = *ppRam;
652 if (!pRam)
653 return pLeft;
654 *ppRam = pRam->pNextR3;
655 MAKE_LEAF(pRam);
656 INSERT_LEFT(pRam, pLeft);
657
658 PPGMRAMRANGE pRight = pgmR3PhysRebuildRamRangeSearchTreesRecursively(ppRam, iDepth - 1);
659 if (pRight)
660 INSERT_RIGHT(pRam, pRight);
661 }
662 return pRam;
663}
664
665
666/**
667 * Rebuilds the RAM range search trees.
668 *
669 * @param pVM Pointer to the VM.
670 */
671static void pgmR3PhysRebuildRamRangeSearchTrees(PVM pVM)
672{
673
674 /*
675 * Create the reasonably balanced tree in a sequential fashion.
676 * For simplicity (laziness) we use standard recursion here.
677 */
678 int iDepth = 0;
679 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
680 PPGMRAMRANGE pRoot = pgmR3PhysRebuildRamRangeSearchTreesRecursively(&pRam, 0);
681 while (pRam)
682 {
683 PPGMRAMRANGE pLeft = pRoot;
684
685 pRoot = pRam;
686 pRam = pRam->pNextR3;
687 MAKE_LEAF(pRoot);
688 INSERT_LEFT(pRoot, pLeft);
689
690 PPGMRAMRANGE pRight = pgmR3PhysRebuildRamRangeSearchTreesRecursively(&pRam, iDepth);
691 if (pRight)
692 INSERT_RIGHT(pRoot, pRight);
693 /** @todo else: rotate the tree. */
694
695 iDepth++;
696 }
697
698 pVM->pgm.s.pRamRangeTreeR3 = pRoot;
699 pVM->pgm.s.pRamRangeTreeR0 = pRoot ? pRoot->pSelfR0 : NIL_RTR0PTR;
700 pVM->pgm.s.pRamRangeTreeRC = pRoot ? pRoot->pSelfRC : NIL_RTRCPTR;
701
702#ifdef VBOX_STRICT
703 /*
704 * Verify that the above code works.
705 */
706 unsigned cRanges = 0;
707 for (pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
708 cRanges++;
709 Assert(cRanges > 0);
710
711 unsigned cMaxDepth = ASMBitLastSetU32(cRanges);
712 if ((1U << cMaxDepth) < cRanges)
713 cMaxDepth++;
714
715 for (pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
716 {
717 unsigned cDepth = 0;
718 PPGMRAMRANGE pRam2 = pVM->pgm.s.pRamRangeTreeR3;
719 for (;;)
720 {
721 if (pRam == pRam2)
722 break;
723 Assert(pRam2);
724 if (pRam->GCPhys < pRam2->GCPhys)
725 pRam2 = pRam2->pLeftR3;
726 else
727 pRam2 = pRam2->pRightR3;
728 }
729 AssertMsg(cDepth <= cMaxDepth, ("cDepth=%d cMaxDepth=%d\n", cDepth, cMaxDepth));
730 }
731#endif /* VBOX_STRICT */
732}
733
734#undef MAKE_LEAF
735#undef INSERT_LEFT
736#undef INSERT_RIGHT
737
738/**
739 * Relinks the RAM ranges using the pSelfRC and pSelfR0 pointers.
740 *
741 * Called when anything was relocated.
742 *
743 * @param pVM Pointer to the VM.
744 */
745void pgmR3PhysRelinkRamRanges(PVM pVM)
746{
747 PPGMRAMRANGE pCur;
748
749#ifdef VBOX_STRICT
750 for (pCur = pVM->pgm.s.pRamRangesXR3; pCur; pCur = pCur->pNextR3)
751 {
752 Assert((pCur->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pCur->pSelfR0 == MMHyperCCToR0(pVM, pCur));
753 Assert((pCur->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pCur->pSelfRC == MMHyperCCToRC(pVM, pCur));
754 Assert((pCur->GCPhys & PAGE_OFFSET_MASK) == 0);
755 Assert((pCur->GCPhysLast & PAGE_OFFSET_MASK) == PAGE_OFFSET_MASK);
756 Assert((pCur->cb & PAGE_OFFSET_MASK) == 0);
757 Assert(pCur->cb == pCur->GCPhysLast - pCur->GCPhys + 1);
758 for (PPGMRAMRANGE pCur2 = pVM->pgm.s.pRamRangesXR3; pCur2; pCur2 = pCur2->pNextR3)
759 Assert( pCur2 == pCur
760 || strcmp(pCur2->pszDesc, pCur->pszDesc)); /** @todo fix MMIO ranges!! */
761 }
762#endif
763
764 pCur = pVM->pgm.s.pRamRangesXR3;
765 if (pCur)
766 {
767 pVM->pgm.s.pRamRangesXR0 = pCur->pSelfR0;
768 pVM->pgm.s.pRamRangesXRC = pCur->pSelfRC;
769
770 for (; pCur->pNextR3; pCur = pCur->pNextR3)
771 {
772 pCur->pNextR0 = pCur->pNextR3->pSelfR0;
773 pCur->pNextRC = pCur->pNextR3->pSelfRC;
774 }
775
776 Assert(pCur->pNextR0 == NIL_RTR0PTR);
777 Assert(pCur->pNextRC == NIL_RTRCPTR);
778 }
779 else
780 {
781 Assert(pVM->pgm.s.pRamRangesXR0 == NIL_RTR0PTR);
782 Assert(pVM->pgm.s.pRamRangesXRC == NIL_RTRCPTR);
783 }
784 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
785
786 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
787}
788
789
790/**
791 * Links a new RAM range into the list.
792 *
793 * @param pVM Pointer to the VM.
794 * @param pNew Pointer to the new list entry.
795 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
796 */
797static void pgmR3PhysLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, PPGMRAMRANGE pPrev)
798{
799 AssertMsg(pNew->pszDesc, ("%RGp-%RGp\n", pNew->GCPhys, pNew->GCPhysLast));
800 Assert((pNew->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pNew->pSelfR0 == MMHyperCCToR0(pVM, pNew));
801 Assert((pNew->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pNew->pSelfRC == MMHyperCCToRC(pVM, pNew));
802
803 pgmLock(pVM);
804
805 PPGMRAMRANGE pRam = pPrev ? pPrev->pNextR3 : pVM->pgm.s.pRamRangesXR3;
806 pNew->pNextR3 = pRam;
807 pNew->pNextR0 = pRam ? pRam->pSelfR0 : NIL_RTR0PTR;
808 pNew->pNextRC = pRam ? pRam->pSelfRC : NIL_RTRCPTR;
809
810 if (pPrev)
811 {
812 pPrev->pNextR3 = pNew;
813 pPrev->pNextR0 = pNew->pSelfR0;
814 pPrev->pNextRC = pNew->pSelfRC;
815 }
816 else
817 {
818 pVM->pgm.s.pRamRangesXR3 = pNew;
819 pVM->pgm.s.pRamRangesXR0 = pNew->pSelfR0;
820 pVM->pgm.s.pRamRangesXRC = pNew->pSelfRC;
821 }
822 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
823
824 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
825 pgmUnlock(pVM);
826}
827
828
829/**
830 * Unlink an existing RAM range from the list.
831 *
832 * @param pVM Pointer to the VM.
833 * @param pRam Pointer to the new list entry.
834 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
835 */
836static void pgmR3PhysUnlinkRamRange2(PVM pVM, PPGMRAMRANGE pRam, PPGMRAMRANGE pPrev)
837{
838 Assert(pPrev ? pPrev->pNextR3 == pRam : pVM->pgm.s.pRamRangesXR3 == pRam);
839 Assert((pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pRam->pSelfR0 == MMHyperCCToR0(pVM, pRam));
840 Assert((pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pRam->pSelfRC == MMHyperCCToRC(pVM, pRam));
841
842 pgmLock(pVM);
843
844 PPGMRAMRANGE pNext = pRam->pNextR3;
845 if (pPrev)
846 {
847 pPrev->pNextR3 = pNext;
848 pPrev->pNextR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
849 pPrev->pNextRC = pNext ? pNext->pSelfRC : NIL_RTRCPTR;
850 }
851 else
852 {
853 Assert(pVM->pgm.s.pRamRangesXR3 == pRam);
854 pVM->pgm.s.pRamRangesXR3 = pNext;
855 pVM->pgm.s.pRamRangesXR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
856 pVM->pgm.s.pRamRangesXRC = pNext ? pNext->pSelfRC : NIL_RTRCPTR;
857 }
858 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
859
860 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
861 pgmUnlock(pVM);
862}
863
864
865/**
866 * Unlink an existing RAM range from the list.
867 *
868 * @param pVM Pointer to the VM.
869 * @param pRam Pointer to the new list entry.
870 */
871static void pgmR3PhysUnlinkRamRange(PVM pVM, PPGMRAMRANGE pRam)
872{
873 pgmLock(pVM);
874
875 /* find prev. */
876 PPGMRAMRANGE pPrev = NULL;
877 PPGMRAMRANGE pCur = pVM->pgm.s.pRamRangesXR3;
878 while (pCur != pRam)
879 {
880 pPrev = pCur;
881 pCur = pCur->pNextR3;
882 }
883 AssertFatal(pCur);
884
885 pgmR3PhysUnlinkRamRange2(pVM, pRam, pPrev);
886 pgmUnlock(pVM);
887}
888
889
890/**
891 * Frees a range of pages, replacing them with ZERO pages of the specified type.
892 *
893 * @returns VBox status code.
894 * @param pVM Pointer to the VM.
895 * @param pRam The RAM range in which the pages resides.
896 * @param GCPhys The address of the first page.
897 * @param GCPhysLast The address of the last page.
898 * @param uType The page type to replace then with.
899 */
900static int pgmR3PhysFreePageRange(PVM pVM, PPGMRAMRANGE pRam, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast, uint8_t uType)
901{
902 PGM_LOCK_ASSERT_OWNER(pVM);
903 uint32_t cPendingPages = 0;
904 PGMMFREEPAGESREQ pReq;
905 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
906 AssertLogRelRCReturn(rc, rc);
907
908 /* Iterate the pages. */
909 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
910 uint32_t cPagesLeft = ((GCPhysLast - GCPhys) >> PAGE_SHIFT) + 1;
911 while (cPagesLeft-- > 0)
912 {
913 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys);
914 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
915
916 PGM_PAGE_SET_TYPE(pVM, pPageDst, uType);
917
918 GCPhys += PAGE_SIZE;
919 pPageDst++;
920 }
921
922 if (cPendingPages)
923 {
924 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
925 AssertLogRelRCReturn(rc, rc);
926 }
927 GMMR3FreePagesCleanup(pReq);
928
929 return rc;
930}
931
932#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
933
934/**
935 * Rendezvous callback used by PGMR3ChangeMemBalloon that changes the memory balloon size
936 *
937 * This is only called on one of the EMTs while the other ones are waiting for
938 * it to complete this function.
939 *
940 * @returns VINF_SUCCESS (VBox strict status code).
941 * @param pVM Pointer to the VM.
942 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
943 * @param pvUser User parameter
944 */
945static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysChangeMemBalloonRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
946{
947 uintptr_t *paUser = (uintptr_t *)pvUser;
948 bool fInflate = !!paUser[0];
949 unsigned cPages = paUser[1];
950 RTGCPHYS *paPhysPage = (RTGCPHYS *)paUser[2];
951 uint32_t cPendingPages = 0;
952 PGMMFREEPAGESREQ pReq;
953 int rc;
954
955 Log(("pgmR3PhysChangeMemBalloonRendezvous: %s %x pages\n", (fInflate) ? "inflate" : "deflate", cPages));
956 pgmLock(pVM);
957
958 if (fInflate)
959 {
960 /* Flush the PGM pool cache as we might have stale references to pages that we just freed. */
961 pgmR3PoolClearAllRendezvous(pVM, pVCpu, NULL);
962
963 /* Replace pages with ZERO pages. */
964 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
965 if (RT_FAILURE(rc))
966 {
967 pgmUnlock(pVM);
968 AssertLogRelRC(rc);
969 return rc;
970 }
971
972 /* Iterate the pages. */
973 for (unsigned i = 0; i < cPages; i++)
974 {
975 PPGMPAGE pPage = pgmPhysGetPage(pVM, paPhysPage[i]);
976 if ( pPage == NULL
977 || PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM)
978 {
979 Log(("pgmR3PhysChangeMemBalloonRendezvous: invalid physical page %RGp pPage->u3Type=%d\n", paPhysPage[i], pPage ? PGM_PAGE_GET_TYPE(pPage) : 0));
980 break;
981 }
982
983 LogFlow(("balloon page: %RGp\n", paPhysPage[i]));
984
985 /* Flush the shadow PT if this page was previously used as a guest page table. */
986 pgmPoolFlushPageByGCPhys(pVM, paPhysPage[i]);
987
988 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, paPhysPage[i]);
989 if (RT_FAILURE(rc))
990 {
991 pgmUnlock(pVM);
992 AssertLogRelRC(rc);
993 return rc;
994 }
995 Assert(PGM_PAGE_IS_ZERO(pPage));
996 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_BALLOONED);
997 }
998
999 if (cPendingPages)
1000 {
1001 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
1002 if (RT_FAILURE(rc))
1003 {
1004 pgmUnlock(pVM);
1005 AssertLogRelRC(rc);
1006 return rc;
1007 }
1008 }
1009 GMMR3FreePagesCleanup(pReq);
1010 }
1011 else
1012 {
1013 /* Iterate the pages. */
1014 for (unsigned i = 0; i < cPages; i++)
1015 {
1016 PPGMPAGE pPage = pgmPhysGetPage(pVM, paPhysPage[i]);
1017 AssertBreak(pPage && PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM);
1018
1019 LogFlow(("Free ballooned page: %RGp\n", paPhysPage[i]));
1020
1021 Assert(PGM_PAGE_IS_BALLOONED(pPage));
1022
1023 /* Change back to zero page. */
1024 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
1025 }
1026
1027 /* Note that we currently do not map any ballooned pages in our shadow page tables, so no need to flush the pgm pool. */
1028 }
1029
1030 /* Notify GMM about the balloon change. */
1031 rc = GMMR3BalloonedPages(pVM, (fInflate) ? GMMBALLOONACTION_INFLATE : GMMBALLOONACTION_DEFLATE, cPages);
1032 if (RT_SUCCESS(rc))
1033 {
1034 if (!fInflate)
1035 {
1036 Assert(pVM->pgm.s.cBalloonedPages >= cPages);
1037 pVM->pgm.s.cBalloonedPages -= cPages;
1038 }
1039 else
1040 pVM->pgm.s.cBalloonedPages += cPages;
1041 }
1042
1043 pgmUnlock(pVM);
1044
1045 /* Flush the recompiler's TLB as well. */
1046 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1047 CPUMSetChangedFlags(&pVM->aCpus[i], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
1048
1049 AssertLogRelRC(rc);
1050 return rc;
1051}
1052
1053
1054/**
1055 * Frees a range of ram pages, replacing them with ZERO pages; helper for PGMR3PhysFreeRamPages
1056 *
1057 * @returns VBox status code.
1058 * @param pVM Pointer to the VM.
1059 * @param fInflate Inflate or deflate memory balloon
1060 * @param cPages Number of pages to free
1061 * @param paPhysPage Array of guest physical addresses
1062 */
1063static DECLCALLBACK(void) pgmR3PhysChangeMemBalloonHelper(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
1064{
1065 uintptr_t paUser[3];
1066
1067 paUser[0] = fInflate;
1068 paUser[1] = cPages;
1069 paUser[2] = (uintptr_t)paPhysPage;
1070 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
1071 AssertRC(rc);
1072
1073 /* Made a copy in PGMR3PhysFreeRamPages; free it here. */
1074 RTMemFree(paPhysPage);
1075}
1076
1077#endif /* 64-bit host && (Windows || Solaris || Linux || FreeBSD) */
1078
1079/**
1080 * Inflate or deflate a memory balloon
1081 *
1082 * @returns VBox status code.
1083 * @param pVM Pointer to the VM.
1084 * @param fInflate Inflate or deflate memory balloon
1085 * @param cPages Number of pages to free
1086 * @param paPhysPage Array of guest physical addresses
1087 */
1088VMMR3DECL(int) PGMR3PhysChangeMemBalloon(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
1089{
1090 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
1091#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
1092 int rc;
1093
1094 /* Older additions (ancient non-functioning balloon code) pass wrong physical addresses. */
1095 AssertReturn(!(paPhysPage[0] & 0xfff), VERR_INVALID_PARAMETER);
1096
1097 /* We own the IOM lock here and could cause a deadlock by waiting for another VCPU that is blocking on the IOM lock.
1098 * In the SMP case we post a request packet to postpone the job.
1099 */
1100 if (pVM->cCpus > 1)
1101 {
1102 unsigned cbPhysPage = cPages * sizeof(paPhysPage[0]);
1103 RTGCPHYS *paPhysPageCopy = (RTGCPHYS *)RTMemAlloc(cbPhysPage);
1104 AssertReturn(paPhysPageCopy, VERR_NO_MEMORY);
1105
1106 memcpy(paPhysPageCopy, paPhysPage, cbPhysPage);
1107
1108 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysChangeMemBalloonHelper, 4, pVM, fInflate, cPages, paPhysPageCopy);
1109 AssertRC(rc);
1110 }
1111 else
1112 {
1113 uintptr_t paUser[3];
1114
1115 paUser[0] = fInflate;
1116 paUser[1] = cPages;
1117 paUser[2] = (uintptr_t)paPhysPage;
1118 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
1119 AssertRC(rc);
1120 }
1121 return rc;
1122
1123#else
1124 NOREF(pVM); NOREF(fInflate); NOREF(cPages); NOREF(paPhysPage);
1125 return VERR_NOT_IMPLEMENTED;
1126#endif
1127}
1128
1129
1130/**
1131 * Rendezvous callback used by PGMR3WriteProtectRAM that write protects all
1132 * physical RAM.
1133 *
1134 * This is only called on one of the EMTs while the other ones are waiting for
1135 * it to complete this function.
1136 *
1137 * @returns VINF_SUCCESS (VBox strict status code).
1138 * @param pVM Pointer to the VM.
1139 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
1140 * @param pvUser User parameter, unused.
1141 */
1142static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysWriteProtectRAMRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
1143{
1144 int rc = VINF_SUCCESS;
1145 NOREF(pvUser); NOREF(pVCpu);
1146
1147 pgmLock(pVM);
1148#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
1149 pgmPoolResetDirtyPages(pVM);
1150#endif
1151
1152 /** @todo pointless to write protect the physical page pointed to by RSP. */
1153
1154 for (PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRangesX);
1155 pRam;
1156 pRam = pRam->CTX_SUFF(pNext))
1157 {
1158 uint32_t cPages = pRam->cb >> PAGE_SHIFT;
1159 for (uint32_t iPage = 0; iPage < cPages; iPage++)
1160 {
1161 PPGMPAGE pPage = &pRam->aPages[iPage];
1162 PGMPAGETYPE enmPageType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage);
1163
1164 if ( RT_LIKELY(enmPageType == PGMPAGETYPE_RAM)
1165 || enmPageType == PGMPAGETYPE_MMIO2)
1166 {
1167 /*
1168 * A RAM page.
1169 */
1170 switch (PGM_PAGE_GET_STATE(pPage))
1171 {
1172 case PGM_PAGE_STATE_ALLOCATED:
1173 /** @todo Optimize this: Don't always re-enable write
1174 * monitoring if the page is known to be very busy. */
1175 if (PGM_PAGE_IS_WRITTEN_TO(pPage))
1176 {
1177 PGM_PAGE_CLEAR_WRITTEN_TO(pVM, pPage);
1178 /* Remember this dirty page for the next (memory) sync. */
1179 PGM_PAGE_SET_FT_DIRTY(pPage);
1180 }
1181
1182 pgmPhysPageWriteMonitor(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1183 break;
1184
1185 case PGM_PAGE_STATE_SHARED:
1186 AssertFailed();
1187 break;
1188
1189 case PGM_PAGE_STATE_WRITE_MONITORED: /* nothing to change. */
1190 default:
1191 break;
1192 }
1193 }
1194 }
1195 }
1196 pgmR3PoolWriteProtectPages(pVM);
1197 PGM_INVL_ALL_VCPU_TLBS(pVM);
1198 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1199 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
1200
1201 pgmUnlock(pVM);
1202 return rc;
1203}
1204
1205/**
1206 * Protect all physical RAM to monitor writes
1207 *
1208 * @returns VBox status code.
1209 * @param pVM Pointer to the VM.
1210 */
1211VMMR3DECL(int) PGMR3PhysWriteProtectRAM(PVM pVM)
1212{
1213 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1214
1215 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysWriteProtectRAMRendezvous, NULL);
1216 AssertRC(rc);
1217 return rc;
1218}
1219
1220/**
1221 * Enumerate all dirty FT pages.
1222 *
1223 * @returns VBox status code.
1224 * @param pVM Pointer to the VM.
1225 * @param pfnEnum Enumerate callback handler.
1226 * @param pvUser Enumerate callback handler parameter.
1227 */
1228VMMR3DECL(int) PGMR3PhysEnumDirtyFTPages(PVM pVM, PFNPGMENUMDIRTYFTPAGES pfnEnum, void *pvUser)
1229{
1230 int rc = VINF_SUCCESS;
1231
1232 pgmLock(pVM);
1233 for (PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRangesX);
1234 pRam;
1235 pRam = pRam->CTX_SUFF(pNext))
1236 {
1237 uint32_t cPages = pRam->cb >> PAGE_SHIFT;
1238 for (uint32_t iPage = 0; iPage < cPages; iPage++)
1239 {
1240 PPGMPAGE pPage = &pRam->aPages[iPage];
1241 PGMPAGETYPE enmPageType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage);
1242
1243 if ( RT_LIKELY(enmPageType == PGMPAGETYPE_RAM)
1244 || enmPageType == PGMPAGETYPE_MMIO2)
1245 {
1246 /*
1247 * A RAM page.
1248 */
1249 switch (PGM_PAGE_GET_STATE(pPage))
1250 {
1251 case PGM_PAGE_STATE_ALLOCATED:
1252 case PGM_PAGE_STATE_WRITE_MONITORED:
1253 if ( !PGM_PAGE_IS_WRITTEN_TO(pPage) /* not very recently updated? */
1254 && PGM_PAGE_IS_FT_DIRTY(pPage))
1255 {
1256 unsigned cbPageRange = PAGE_SIZE;
1257 unsigned iPageClean = iPage + 1;
1258 RTGCPHYS GCPhysPage = pRam->GCPhys + iPage * PAGE_SIZE;
1259 uint8_t *pu8Page = NULL;
1260 PGMPAGEMAPLOCK Lock;
1261
1262 /* Find the next clean page, so we can merge adjacent dirty pages. */
1263 for (; iPageClean < cPages; iPageClean++)
1264 {
1265 PPGMPAGE pPageNext = &pRam->aPages[iPageClean];
1266 if ( RT_UNLIKELY(PGM_PAGE_GET_TYPE(pPageNext) != PGMPAGETYPE_RAM)
1267 || PGM_PAGE_GET_STATE(pPageNext) != PGM_PAGE_STATE_ALLOCATED
1268 || PGM_PAGE_IS_WRITTEN_TO(pPageNext)
1269 || !PGM_PAGE_IS_FT_DIRTY(pPageNext)
1270 /* Crossing a chunk boundary? */
1271 || (GCPhysPage & GMM_PAGEID_IDX_MASK) != ((GCPhysPage + cbPageRange) & GMM_PAGEID_IDX_MASK)
1272 )
1273 break;
1274
1275 cbPageRange += PAGE_SIZE;
1276 }
1277
1278 rc = PGMPhysGCPhys2CCPtrReadOnly(pVM, GCPhysPage, (const void **)&pu8Page, &Lock);
1279 if (RT_SUCCESS(rc))
1280 {
1281 /** @todo this is risky; the range might be changed, but little choice as the sync
1282 * costs a lot of time. */
1283 pgmUnlock(pVM);
1284 pfnEnum(pVM, GCPhysPage, pu8Page, cbPageRange, pvUser);
1285 pgmLock(pVM);
1286 PGMPhysReleasePageMappingLock(pVM, &Lock);
1287 }
1288
1289 for (iPage; iPage < iPageClean; iPage++)
1290 PGM_PAGE_CLEAR_FT_DIRTY(&pRam->aPages[iPage]);
1291
1292 iPage = iPageClean - 1;
1293 }
1294 break;
1295 }
1296 }
1297 }
1298 }
1299 pgmUnlock(pVM);
1300 return rc;
1301}
1302
1303
1304/**
1305 * Gets the number of ram ranges.
1306 *
1307 * @returns Number of ram ranges. Returns UINT32_MAX if @a pVM is invalid.
1308 * @param pVM Pointer to the VM.
1309 */
1310VMMR3DECL(uint32_t) PGMR3PhysGetRamRangeCount(PVM pVM)
1311{
1312 VM_ASSERT_VALID_EXT_RETURN(pVM, UINT32_MAX);
1313
1314 pgmLock(pVM);
1315 uint32_t cRamRanges = 0;
1316 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRangesX); pCur; pCur = pCur->CTX_SUFF(pNext))
1317 cRamRanges++;
1318 pgmUnlock(pVM);
1319 return cRamRanges;
1320}
1321
1322
1323/**
1324 * Get information about a range.
1325 *
1326 * @returns VINF_SUCCESS or VERR_OUT_OF_RANGE.
1327 * @param pVM Pointer to the VM.
1328 * @param iRange The ordinal of the range.
1329 * @param pGCPhysStart Where to return the start of the range. Optional.
1330 * @param pGCPhysLast Where to return the address of the last byte in the
1331 * range. Optional.
1332 * @param pfIsMmio Where to indicate that this is a pure MMIO range.
1333 * Optional.
1334 */
1335VMMR3DECL(int) PGMR3PhysGetRange(PVM pVM, uint32_t iRange, PRTGCPHYS pGCPhysStart, PRTGCPHYS pGCPhysLast,
1336 const char **ppszDesc, bool *pfIsMmio)
1337{
1338 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1339
1340 pgmLock(pVM);
1341 uint32_t iCurRange = 0;
1342 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRangesX); pCur; pCur = pCur->CTX_SUFF(pNext), iCurRange++)
1343 if (iCurRange == iRange)
1344 {
1345 if (pGCPhysStart)
1346 *pGCPhysStart = pCur->GCPhys;
1347 if (pGCPhysLast)
1348 *pGCPhysLast = pCur->GCPhysLast;
1349 if (ppszDesc)
1350 *ppszDesc = pCur->pszDesc;
1351 if (pfIsMmio)
1352 *pfIsMmio = !!(pCur->fFlags & PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO);
1353
1354 pgmUnlock(pVM);
1355 return VINF_SUCCESS;
1356 }
1357 pgmUnlock(pVM);
1358 return VERR_OUT_OF_RANGE;
1359}
1360
1361
1362/**
1363 * Query the amount of free memory inside VMMR0
1364 *
1365 * @returns VBox status code.
1366 * @param pUVM The user mode VM handle.
1367 * @param pcbAllocMem Where to return the amount of memory allocated
1368 * by VMs.
1369 * @param pcbFreeMem Where to return the amount of memory that is
1370 * allocated from the host but not currently used
1371 * by any VMs.
1372 * @param pcbBallonedMem Where to return the sum of memory that is
1373 * currently ballooned by the VMs.
1374 * @param pcbSharedMem Where to return the amount of memory that is
1375 * currently shared.
1376 */
1377VMMR3DECL(int) PGMR3QueryGlobalMemoryStats(PUVM pUVM, uint64_t *pcbAllocMem, uint64_t *pcbFreeMem,
1378 uint64_t *pcbBallonedMem, uint64_t *pcbSharedMem)
1379{
1380 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
1381 VM_ASSERT_VALID_EXT_RETURN(pUVM->pVM, VERR_INVALID_VM_HANDLE);
1382
1383 uint64_t cAllocPages = 0;
1384 uint64_t cFreePages = 0;
1385 uint64_t cBalloonPages = 0;
1386 uint64_t cSharedPages = 0;
1387 int rc = GMMR3QueryHypervisorMemoryStats(pUVM->pVM, &cAllocPages, &cFreePages, &cBalloonPages, &cSharedPages);
1388 AssertRCReturn(rc, rc);
1389
1390 if (pcbAllocMem)
1391 *pcbAllocMem = cAllocPages * _4K;
1392
1393 if (pcbFreeMem)
1394 *pcbFreeMem = cFreePages * _4K;
1395
1396 if (pcbBallonedMem)
1397 *pcbBallonedMem = cBalloonPages * _4K;
1398
1399 if (pcbSharedMem)
1400 *pcbSharedMem = cSharedPages * _4K;
1401
1402 Log(("PGMR3QueryVMMMemoryStats: all=%llx free=%llx ballooned=%llx shared=%llx\n",
1403 cAllocPages, cFreePages, cBalloonPages, cSharedPages));
1404 return VINF_SUCCESS;
1405}
1406
1407
1408/**
1409 * Query memory stats for the VM.
1410 *
1411 * @returns VBox status code.
1412 * @param pUVM The user mode VM handle.
1413 * @param pcbTotalMem Where to return total amount memory the VM may
1414 * possibly use.
1415 * @param pcbPrivateMem Where to return the amount of private memory
1416 * currently allocated.
1417 * @param pcbSharedMem Where to return the amount of actually shared
1418 * memory currently used by the VM.
1419 * @param pcbZeroMem Where to return the amount of memory backed by
1420 * zero pages.
1421 *
1422 * @remarks The total mem is normally larger than the sum of the three
1423 * components. There are two reasons for this, first the amount of
1424 * shared memory is what we're sure is shared instead of what could
1425 * possibly be shared with someone. Secondly, because the total may
1426 * include some pure MMIO pages that doesn't go into any of the three
1427 * sub-counts.
1428 *
1429 * @todo Why do we return reused shared pages instead of anything that could
1430 * potentially be shared? Doesn't this mean the first VM gets a much
1431 * lower number of shared pages?
1432 */
1433VMMR3DECL(int) PGMR3QueryMemoryStats(PUVM pUVM, uint64_t *pcbTotalMem, uint64_t *pcbPrivateMem,
1434 uint64_t *pcbSharedMem, uint64_t *pcbZeroMem)
1435{
1436 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
1437 PVM pVM = pUVM->pVM;
1438 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1439
1440 if (pcbTotalMem)
1441 *pcbTotalMem = (uint64_t)pVM->pgm.s.cAllPages * PAGE_SIZE;
1442
1443 if (pcbPrivateMem)
1444 *pcbPrivateMem = (uint64_t)pVM->pgm.s.cPrivatePages * PAGE_SIZE;
1445
1446 if (pcbSharedMem)
1447 *pcbSharedMem = (uint64_t)pVM->pgm.s.cReusedSharedPages * PAGE_SIZE;
1448
1449 if (pcbZeroMem)
1450 *pcbZeroMem = (uint64_t)pVM->pgm.s.cZeroPages * PAGE_SIZE;
1451
1452 Log(("PGMR3QueryMemoryStats: all=%x private=%x reused=%x zero=%x\n", pVM->pgm.s.cAllPages, pVM->pgm.s.cPrivatePages, pVM->pgm.s.cReusedSharedPages, pVM->pgm.s.cZeroPages));
1453 return VINF_SUCCESS;
1454}
1455
1456
1457/**
1458 * PGMR3PhysRegisterRam worker that initializes and links a RAM range.
1459 *
1460 * @param pVM Pointer to the VM.
1461 * @param pNew The new RAM range.
1462 * @param GCPhys The address of the RAM range.
1463 * @param GCPhysLast The last address of the RAM range.
1464 * @param RCPtrNew The RC address if the range is floating. NIL_RTRCPTR
1465 * if in HMA.
1466 * @param R0PtrNew Ditto for R0.
1467 * @param pszDesc The description.
1468 * @param pPrev The previous RAM range (for linking).
1469 */
1470static void pgmR3PhysInitAndLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast,
1471 RTRCPTR RCPtrNew, RTR0PTR R0PtrNew, const char *pszDesc, PPGMRAMRANGE pPrev)
1472{
1473 /*
1474 * Initialize the range.
1475 */
1476 pNew->pSelfR0 = R0PtrNew != NIL_RTR0PTR ? R0PtrNew : MMHyperCCToR0(pVM, pNew);
1477 pNew->pSelfRC = RCPtrNew != NIL_RTRCPTR ? RCPtrNew : MMHyperCCToRC(pVM, pNew);
1478 pNew->GCPhys = GCPhys;
1479 pNew->GCPhysLast = GCPhysLast;
1480 pNew->cb = GCPhysLast - GCPhys + 1;
1481 pNew->pszDesc = pszDesc;
1482 pNew->fFlags = RCPtrNew != NIL_RTRCPTR ? PGM_RAM_RANGE_FLAGS_FLOATING : 0;
1483 pNew->pvR3 = NULL;
1484 pNew->paLSPages = NULL;
1485
1486 uint32_t const cPages = pNew->cb >> PAGE_SHIFT;
1487 RTGCPHYS iPage = cPages;
1488 while (iPage-- > 0)
1489 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_RAM);
1490
1491 /* Update the page count stats. */
1492 pVM->pgm.s.cZeroPages += cPages;
1493 pVM->pgm.s.cAllPages += cPages;
1494
1495 /*
1496 * Link it.
1497 */
1498 pgmR3PhysLinkRamRange(pVM, pNew, pPrev);
1499}
1500
1501
1502/**
1503 * Relocate a floating RAM range.
1504 *
1505 * @copydoc FNPGMRELOCATE.
1506 */
1507static DECLCALLBACK(bool) pgmR3PhysRamRangeRelocate(PVM pVM, RTGCPTR GCPtrOld, RTGCPTR GCPtrNew, PGMRELOCATECALL enmMode, void *pvUser)
1508{
1509 PPGMRAMRANGE pRam = (PPGMRAMRANGE)pvUser;
1510 Assert(pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING);
1511 Assert(pRam->pSelfRC == GCPtrOld + PAGE_SIZE);
1512
1513 switch (enmMode)
1514 {
1515 case PGMRELOCATECALL_SUGGEST:
1516 return true;
1517
1518 case PGMRELOCATECALL_RELOCATE:
1519 {
1520 /*
1521 * Update myself, then relink all the ranges and flush the RC TLB.
1522 */
1523 pgmLock(pVM);
1524
1525 pRam->pSelfRC = (RTRCPTR)(GCPtrNew + PAGE_SIZE);
1526
1527 pgmR3PhysRelinkRamRanges(pVM);
1528 for (unsigned i = 0; i < PGM_RAMRANGE_TLB_ENTRIES; i++)
1529 pVM->pgm.s.apRamRangesTlbRC[i] = NIL_RTRCPTR;
1530
1531 pgmUnlock(pVM);
1532 return true;
1533 }
1534
1535 default:
1536 AssertFailedReturn(false);
1537 }
1538}
1539
1540
1541/**
1542 * PGMR3PhysRegisterRam worker that registers a high chunk.
1543 *
1544 * @returns VBox status code.
1545 * @param pVM Pointer to the VM.
1546 * @param GCPhys The address of the RAM.
1547 * @param cRamPages The number of RAM pages to register.
1548 * @param cbChunk The size of the PGMRAMRANGE guest mapping.
1549 * @param iChunk The chunk number.
1550 * @param pszDesc The RAM range description.
1551 * @param ppPrev Previous RAM range pointer. In/Out.
1552 */
1553static int pgmR3PhysRegisterHighRamChunk(PVM pVM, RTGCPHYS GCPhys, uint32_t cRamPages,
1554 uint32_t cbChunk, uint32_t iChunk, const char *pszDesc,
1555 PPGMRAMRANGE *ppPrev)
1556{
1557 const char *pszDescChunk = iChunk == 0
1558 ? pszDesc
1559 : MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s (#%u)", pszDesc, iChunk + 1);
1560 AssertReturn(pszDescChunk, VERR_NO_MEMORY);
1561
1562 /*
1563 * Allocate memory for the new chunk.
1564 */
1565 size_t const cChunkPages = RT_ALIGN_Z(RT_UOFFSETOF(PGMRAMRANGE, aPages[cRamPages]), PAGE_SIZE) >> PAGE_SHIFT;
1566 PSUPPAGE paChunkPages = (PSUPPAGE)RTMemTmpAllocZ(sizeof(SUPPAGE) * cChunkPages);
1567 AssertReturn(paChunkPages, VERR_NO_TMP_MEMORY);
1568 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
1569 void *pvChunk = NULL;
1570 int rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk,
1571#if defined(VBOX_WITH_MORE_RING0_MEM_MAPPINGS)
1572 &R0PtrChunk,
1573#elif defined(VBOX_WITH_2X_4GB_ADDR_SPACE)
1574 HMIsEnabled(pVM) ? &R0PtrChunk : NULL,
1575#else
1576 NULL,
1577#endif
1578 paChunkPages);
1579 if (RT_SUCCESS(rc))
1580 {
1581#if defined(VBOX_WITH_MORE_RING0_MEM_MAPPINGS)
1582 Assert(R0PtrChunk != NIL_RTR0PTR);
1583#elif defined(VBOX_WITH_2X_4GB_ADDR_SPACE)
1584 if (!HMIsEnabled(pVM))
1585 R0PtrChunk = NIL_RTR0PTR;
1586#else
1587 R0PtrChunk = (uintptr_t)pvChunk;
1588#endif
1589 memset(pvChunk, 0, cChunkPages << PAGE_SHIFT);
1590
1591 PPGMRAMRANGE pNew = (PPGMRAMRANGE)pvChunk;
1592
1593 /*
1594 * Create a mapping and map the pages into it.
1595 * We push these in below the HMA.
1596 */
1597 RTGCPTR GCPtrChunkMap = pVM->pgm.s.GCPtrPrevRamRangeMapping - cbChunk;
1598 rc = PGMR3MapPT(pVM, GCPtrChunkMap, cbChunk, 0 /*fFlags*/, pgmR3PhysRamRangeRelocate, pNew, pszDescChunk);
1599 if (RT_SUCCESS(rc))
1600 {
1601 pVM->pgm.s.GCPtrPrevRamRangeMapping = GCPtrChunkMap;
1602
1603 RTGCPTR const GCPtrChunk = GCPtrChunkMap + PAGE_SIZE;
1604 RTGCPTR GCPtrPage = GCPtrChunk;
1605 for (uint32_t iPage = 0; iPage < cChunkPages && RT_SUCCESS(rc); iPage++, GCPtrPage += PAGE_SIZE)
1606 rc = PGMMap(pVM, GCPtrPage, paChunkPages[iPage].Phys, PAGE_SIZE, 0);
1607 if (RT_SUCCESS(rc))
1608 {
1609 /*
1610 * Ok, init and link the range.
1611 */
1612 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhys + ((RTGCPHYS)cRamPages << PAGE_SHIFT) - 1,
1613 (RTRCPTR)GCPtrChunk, R0PtrChunk, pszDescChunk, *ppPrev);
1614 *ppPrev = pNew;
1615 }
1616 }
1617
1618 if (RT_FAILURE(rc))
1619 SUPR3PageFreeEx(pvChunk, cChunkPages);
1620 }
1621
1622 RTMemTmpFree(paChunkPages);
1623 return rc;
1624}
1625
1626
1627/**
1628 * Sets up a range RAM.
1629 *
1630 * This will check for conflicting registrations, make a resource
1631 * reservation for the memory (with GMM), and setup the per-page
1632 * tracking structures (PGMPAGE).
1633 *
1634 * @returns VBox status code.
1635 * @param pVM Pointer to the VM.
1636 * @param GCPhys The physical address of the RAM.
1637 * @param cb The size of the RAM.
1638 * @param pszDesc The description - not copied, so, don't free or change it.
1639 */
1640VMMR3DECL(int) PGMR3PhysRegisterRam(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, const char *pszDesc)
1641{
1642 /*
1643 * Validate input.
1644 */
1645 Log(("PGMR3PhysRegisterRam: GCPhys=%RGp cb=%RGp pszDesc=%s\n", GCPhys, cb, pszDesc));
1646 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
1647 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
1648 AssertReturn(cb > 0, VERR_INVALID_PARAMETER);
1649 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1650 AssertMsgReturn(GCPhysLast > GCPhys, ("The range wraps! GCPhys=%RGp cb=%RGp\n", GCPhys, cb), VERR_INVALID_PARAMETER);
1651 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1652 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1653
1654 pgmLock(pVM);
1655
1656 /*
1657 * Find range location and check for conflicts.
1658 * (We don't lock here because the locking by EMT is only required on update.)
1659 */
1660 PPGMRAMRANGE pPrev = NULL;
1661 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
1662 while (pRam && GCPhysLast >= pRam->GCPhys)
1663 {
1664 if ( GCPhysLast >= pRam->GCPhys
1665 && GCPhys <= pRam->GCPhysLast)
1666 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
1667 GCPhys, GCPhysLast, pszDesc,
1668 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1669 VERR_PGM_RAM_CONFLICT);
1670
1671 /* next */
1672 pPrev = pRam;
1673 pRam = pRam->pNextR3;
1674 }
1675
1676 /*
1677 * Register it with GMM (the API bitches).
1678 */
1679 const RTGCPHYS cPages = cb >> PAGE_SHIFT;
1680 int rc = MMR3IncreaseBaseReservation(pVM, cPages);
1681 if (RT_FAILURE(rc))
1682 {
1683 pgmUnlock(pVM);
1684 return rc;
1685 }
1686
1687 if ( GCPhys >= _4G
1688 && cPages > 256)
1689 {
1690 /*
1691 * The PGMRAMRANGE structures for the high memory can get very big.
1692 * In order to avoid SUPR3PageAllocEx allocation failures due to the
1693 * allocation size limit there and also to avoid being unable to find
1694 * guest mapping space for them, we split this memory up into 4MB in
1695 * (potential) raw-mode configs and 16MB chunks in forced AMD-V/VT-x
1696 * mode.
1697 *
1698 * The first and last page of each mapping are guard pages and marked
1699 * not-present. So, we've got 4186112 and 16769024 bytes available for
1700 * the PGMRAMRANGE structure.
1701 *
1702 * Note! The sizes used here will influence the saved state.
1703 */
1704 uint32_t cbChunk;
1705 uint32_t cPagesPerChunk;
1706 if (HMIsEnabled(pVM))
1707 {
1708 cbChunk = 16U*_1M;
1709 cPagesPerChunk = 1048048; /* max ~1048059 */
1710 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 1048048 < 16U*_1M - PAGE_SIZE * 2);
1711 }
1712 else
1713 {
1714 cbChunk = 4U*_1M;
1715 cPagesPerChunk = 261616; /* max ~261627 */
1716 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 261616 < 4U*_1M - PAGE_SIZE * 2);
1717 }
1718 AssertRelease(RT_UOFFSETOF(PGMRAMRANGE, aPages[cPagesPerChunk]) + PAGE_SIZE * 2 <= cbChunk);
1719
1720 RTGCPHYS cPagesLeft = cPages;
1721 RTGCPHYS GCPhysChunk = GCPhys;
1722 uint32_t iChunk = 0;
1723 while (cPagesLeft > 0)
1724 {
1725 uint32_t cPagesInChunk = cPagesLeft;
1726 if (cPagesInChunk > cPagesPerChunk)
1727 cPagesInChunk = cPagesPerChunk;
1728
1729 rc = pgmR3PhysRegisterHighRamChunk(pVM, GCPhysChunk, cPagesInChunk, cbChunk, iChunk, pszDesc, &pPrev);
1730 AssertRCReturn(rc, rc);
1731
1732 /* advance */
1733 GCPhysChunk += (RTGCPHYS)cPagesInChunk << PAGE_SHIFT;
1734 cPagesLeft -= cPagesInChunk;
1735 iChunk++;
1736 }
1737 }
1738 else
1739 {
1740 /*
1741 * Allocate, initialize and link the new RAM range.
1742 */
1743 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
1744 PPGMRAMRANGE pNew;
1745 rc = MMR3HyperAllocOnceNoRel(pVM, cbRamRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
1746 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
1747
1748 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhysLast, NIL_RTRCPTR, NIL_RTR0PTR, pszDesc, pPrev);
1749 }
1750 pgmPhysInvalidatePageMapTLB(pVM);
1751 pgmUnlock(pVM);
1752
1753#ifdef VBOX_WITH_REM
1754 /*
1755 * Notify REM.
1756 */
1757 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_RAM);
1758#endif
1759
1760 return VINF_SUCCESS;
1761}
1762
1763
1764/**
1765 * Worker called by PGMR3InitFinalize if we're configured to pre-allocate RAM.
1766 *
1767 * We do this late in the init process so that all the ROM and MMIO ranges have
1768 * been registered already and we don't go wasting memory on them.
1769 *
1770 * @returns VBox status code.
1771 *
1772 * @param pVM Pointer to the VM.
1773 */
1774int pgmR3PhysRamPreAllocate(PVM pVM)
1775{
1776 Assert(pVM->pgm.s.fRamPreAlloc);
1777 Log(("pgmR3PhysRamPreAllocate: enter\n"));
1778
1779 /*
1780 * Walk the RAM ranges and allocate all RAM pages, halt at
1781 * the first allocation error.
1782 */
1783 uint64_t cPages = 0;
1784 uint64_t NanoTS = RTTimeNanoTS();
1785 pgmLock(pVM);
1786 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1787 {
1788 PPGMPAGE pPage = &pRam->aPages[0];
1789 RTGCPHYS GCPhys = pRam->GCPhys;
1790 uint32_t cLeft = pRam->cb >> PAGE_SHIFT;
1791 while (cLeft-- > 0)
1792 {
1793 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM)
1794 {
1795 switch (PGM_PAGE_GET_STATE(pPage))
1796 {
1797 case PGM_PAGE_STATE_ZERO:
1798 {
1799 int rc = pgmPhysAllocPage(pVM, pPage, GCPhys);
1800 if (RT_FAILURE(rc))
1801 {
1802 LogRel(("PGM: RAM Pre-allocation failed at %RGp (in %s) with rc=%Rrc\n", GCPhys, pRam->pszDesc, rc));
1803 pgmUnlock(pVM);
1804 return rc;
1805 }
1806 cPages++;
1807 break;
1808 }
1809
1810 case PGM_PAGE_STATE_BALLOONED:
1811 case PGM_PAGE_STATE_ALLOCATED:
1812 case PGM_PAGE_STATE_WRITE_MONITORED:
1813 case PGM_PAGE_STATE_SHARED:
1814 /* nothing to do here. */
1815 break;
1816 }
1817 }
1818
1819 /* next */
1820 pPage++;
1821 GCPhys += PAGE_SIZE;
1822 }
1823 }
1824 pgmUnlock(pVM);
1825 NanoTS = RTTimeNanoTS() - NanoTS;
1826
1827 LogRel(("PGM: Pre-allocated %llu pages in %llu ms\n", cPages, NanoTS / 1000000));
1828 Log(("pgmR3PhysRamPreAllocate: returns VINF_SUCCESS\n"));
1829 return VINF_SUCCESS;
1830}
1831
1832
1833/**
1834 * Checks shared page checksums.
1835 *
1836 * @param pVM Pointer to the shared VM structure.
1837 */
1838void pgmR3PhysAssertSharedPageChecksums(PVM pVM)
1839{
1840#ifdef VBOX_STRICT
1841 pgmLock(pVM);
1842
1843 if (pVM->pgm.s.cSharedPages > 0)
1844 {
1845 /*
1846 * Walk the ram ranges.
1847 */
1848 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1849 {
1850 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
1851 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
1852
1853 while (iPage-- > 0)
1854 {
1855 PPGMPAGE pPage = &pRam->aPages[iPage];
1856 if (PGM_PAGE_IS_SHARED(pPage))
1857 {
1858 uint32_t u32Checksum = pPage->s.u2Unused0 | ((uint32_t)pPage->s.u2Unused1 << 8);
1859 if (!u32Checksum)
1860 {
1861 RTGCPHYS GCPhysPage = pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT);
1862 void const *pvPage;
1863 int rc = pgmPhysPageMapReadOnly(pVM, pPage, GCPhysPage, &pvPage);
1864 if (RT_SUCCESS(rc))
1865 {
1866 uint32_t u32Checksum2 = RTCrc32(pvPage, PAGE_SIZE);
1867# if 0
1868 AssertMsg((u32Checksum2 & UINT32_C(0x00000303)) == u32Checksum, ("GCPhysPage=%RGp\n", GCPhysPage));
1869# else
1870 if ((u32Checksum2 & UINT32_C(0x00000303)) == u32Checksum)
1871 LogFlow(("shpg %#x @ %RGp %#x [OK]\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
1872 else
1873 AssertMsgFailed(("shpg %#x @ %RGp %#x\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
1874# endif
1875 }
1876 else
1877 AssertRC(rc);
1878 }
1879 }
1880
1881 } /* for each page */
1882
1883 } /* for each ram range */
1884 }
1885
1886 pgmUnlock(pVM);
1887#endif /* VBOX_STRICT */
1888 NOREF(pVM);
1889}
1890
1891
1892/**
1893 * Resets the physical memory state.
1894 *
1895 * ASSUMES that the caller owns the PGM lock.
1896 *
1897 * @returns VBox status code.
1898 * @param pVM Pointer to the VM.
1899 */
1900int pgmR3PhysRamReset(PVM pVM)
1901{
1902 PGM_LOCK_ASSERT_OWNER(pVM);
1903
1904 /* Reset the memory balloon. */
1905 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
1906 AssertRC(rc);
1907
1908#ifdef VBOX_WITH_PAGE_SHARING
1909 /* Clear all registered shared modules. */
1910 pgmR3PhysAssertSharedPageChecksums(pVM);
1911 rc = GMMR3ResetSharedModules(pVM);
1912 AssertRC(rc);
1913#endif
1914 /* Reset counters. */
1915 pVM->pgm.s.cReusedSharedPages = 0;
1916 pVM->pgm.s.cBalloonedPages = 0;
1917
1918 return VINF_SUCCESS;
1919}
1920
1921
1922/**
1923 * Resets (zeros) the RAM after all devices and components have been reset.
1924 *
1925 * ASSUMES that the caller owns the PGM lock.
1926 *
1927 * @returns VBox status code.
1928 * @param pVM Pointer to the VM.
1929 */
1930int pgmR3PhysRamZeroAll(PVM pVM)
1931{
1932 PGM_LOCK_ASSERT_OWNER(pVM);
1933
1934 /*
1935 * We batch up pages that should be freed instead of calling GMM for
1936 * each and every one of them.
1937 */
1938 uint32_t cPendingPages = 0;
1939 PGMMFREEPAGESREQ pReq;
1940 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1941 AssertLogRelRCReturn(rc, rc);
1942
1943 /*
1944 * Walk the ram ranges.
1945 */
1946 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1947 {
1948 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
1949 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
1950
1951#ifndef NO_RAM_RESET
1952 if (!pVM->pgm.s.fRamPreAlloc)
1953#else
1954 if (0)
1955#endif
1956 {
1957 /* Replace all RAM pages by ZERO pages. */
1958 while (iPage-- > 0)
1959 {
1960 PPGMPAGE pPage = &pRam->aPages[iPage];
1961 switch (PGM_PAGE_GET_TYPE(pPage))
1962 {
1963 case PGMPAGETYPE_RAM:
1964 /* Do not replace pages part of a 2 MB continuous range
1965 with zero pages, but zero them instead. */
1966 if ( PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE
1967 || PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE_DISABLED)
1968 {
1969 void *pvPage;
1970 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
1971 AssertLogRelRCReturn(rc, rc);
1972 ASMMemZeroPage(pvPage);
1973 }
1974 else if (PGM_PAGE_IS_BALLOONED(pPage))
1975 {
1976 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
1977 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
1978 }
1979 else if (!PGM_PAGE_IS_ZERO(pPage))
1980 {
1981 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1982 AssertLogRelRCReturn(rc, rc);
1983 }
1984 break;
1985
1986 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
1987 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
1988 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
1989 true /*fDoAccounting*/);
1990 break;
1991
1992 case PGMPAGETYPE_MMIO2:
1993 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
1994 case PGMPAGETYPE_ROM:
1995 case PGMPAGETYPE_MMIO:
1996 break;
1997 default:
1998 AssertFailed();
1999 }
2000 } /* for each page */
2001 }
2002 else
2003 {
2004 /* Zero the memory. */
2005 while (iPage-- > 0)
2006 {
2007 PPGMPAGE pPage = &pRam->aPages[iPage];
2008 switch (PGM_PAGE_GET_TYPE(pPage))
2009 {
2010 case PGMPAGETYPE_RAM:
2011 switch (PGM_PAGE_GET_STATE(pPage))
2012 {
2013 case PGM_PAGE_STATE_ZERO:
2014 break;
2015
2016 case PGM_PAGE_STATE_BALLOONED:
2017 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
2018 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
2019 break;
2020
2021 case PGM_PAGE_STATE_SHARED:
2022 case PGM_PAGE_STATE_WRITE_MONITORED:
2023 rc = pgmPhysPageMakeWritable(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
2024 AssertLogRelRCReturn(rc, rc);
2025 /* no break */
2026
2027 case PGM_PAGE_STATE_ALLOCATED:
2028 {
2029 void *pvPage;
2030 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
2031 AssertLogRelRCReturn(rc, rc);
2032#ifndef NO_RAM_RESET
2033 ASMMemZeroPage(pvPage);
2034#endif
2035 break;
2036 }
2037 }
2038 break;
2039
2040 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2041 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
2042 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
2043 true /*fDoAccounting*/);
2044 break;
2045
2046 case PGMPAGETYPE_MMIO2:
2047 case PGMPAGETYPE_ROM_SHADOW:
2048 case PGMPAGETYPE_ROM:
2049 case PGMPAGETYPE_MMIO:
2050 break;
2051 default:
2052 AssertFailed();
2053
2054 }
2055 } /* for each page */
2056 }
2057
2058 }
2059
2060 /*
2061 * Finish off any pages pending freeing.
2062 */
2063 if (cPendingPages)
2064 {
2065 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2066 AssertLogRelRCReturn(rc, rc);
2067 }
2068 GMMR3FreePagesCleanup(pReq);
2069 return VINF_SUCCESS;
2070}
2071
2072
2073/**
2074 * Frees all RAM during VM termination
2075 *
2076 * ASSUMES that the caller owns the PGM lock.
2077 *
2078 * @returns VBox status code.
2079 * @param pVM Pointer to the VM.
2080 */
2081int pgmR3PhysRamTerm(PVM pVM)
2082{
2083 PGM_LOCK_ASSERT_OWNER(pVM);
2084
2085 /* Reset the memory balloon. */
2086 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
2087 AssertRC(rc);
2088
2089#ifdef VBOX_WITH_PAGE_SHARING
2090 /*
2091 * Clear all registered shared modules.
2092 */
2093 pgmR3PhysAssertSharedPageChecksums(pVM);
2094 rc = GMMR3ResetSharedModules(pVM);
2095 AssertRC(rc);
2096
2097 /*
2098 * Flush the handy pages updates to make sure no shared pages are hiding
2099 * in there. (No unlikely if the VM shuts down, apparently.)
2100 */
2101 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_FLUSH_HANDY_PAGES, 0, NULL);
2102#endif
2103
2104 /*
2105 * We batch up pages that should be freed instead of calling GMM for
2106 * each and every one of them.
2107 */
2108 uint32_t cPendingPages = 0;
2109 PGMMFREEPAGESREQ pReq;
2110 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2111 AssertLogRelRCReturn(rc, rc);
2112
2113 /*
2114 * Walk the ram ranges.
2115 */
2116 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2117 {
2118 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
2119 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
2120
2121 while (iPage-- > 0)
2122 {
2123 PPGMPAGE pPage = &pRam->aPages[iPage];
2124 switch (PGM_PAGE_GET_TYPE(pPage))
2125 {
2126 case PGMPAGETYPE_RAM:
2127 /* Free all shared pages. Private pages are automatically freed during GMM VM cleanup. */
2128 /** @todo change this to explicitly free private pages here. */
2129 if (PGM_PAGE_IS_SHARED(pPage))
2130 {
2131 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
2132 AssertLogRelRCReturn(rc, rc);
2133 }
2134 break;
2135
2136 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2137 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO:
2138 case PGMPAGETYPE_MMIO2:
2139 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
2140 case PGMPAGETYPE_ROM:
2141 case PGMPAGETYPE_MMIO:
2142 break;
2143 default:
2144 AssertFailed();
2145 }
2146 } /* for each page */
2147 }
2148
2149 /*
2150 * Finish off any pages pending freeing.
2151 */
2152 if (cPendingPages)
2153 {
2154 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2155 AssertLogRelRCReturn(rc, rc);
2156 }
2157 GMMR3FreePagesCleanup(pReq);
2158 return VINF_SUCCESS;
2159}
2160
2161
2162/**
2163 * This is the interface IOM is using to register an MMIO region.
2164 *
2165 * It will check for conflicts and ensure that a RAM range structure
2166 * is present before calling the PGMR3HandlerPhysicalRegister API to
2167 * register the callbacks.
2168 *
2169 * @returns VBox status code.
2170 *
2171 * @param pVM Pointer to the VM.
2172 * @param GCPhys The start of the MMIO region.
2173 * @param cb The size of the MMIO region.
2174 * @param pfnHandlerR3 The address of the ring-3 handler. (IOMR3MMIOHandler)
2175 * @param pvUserR3 The user argument for R3.
2176 * @param pfnHandlerR0 The address of the ring-0 handler. (IOMMMIOHandler)
2177 * @param pvUserR0 The user argument for R0.
2178 * @param pfnHandlerRC The address of the RC handler. (IOMMMIOHandler)
2179 * @param pvUserRC The user argument for RC.
2180 * @param pszDesc The description of the MMIO region.
2181 */
2182VMMR3DECL(int) PGMR3PhysMMIORegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb,
2183 R3PTRTYPE(PFNPGMR3PHYSHANDLER) pfnHandlerR3, RTR3PTR pvUserR3,
2184 R0PTRTYPE(PFNPGMR0PHYSHANDLER) pfnHandlerR0, RTR0PTR pvUserR0,
2185 RCPTRTYPE(PFNPGMRCPHYSHANDLER) pfnHandlerRC, RTRCPTR pvUserRC,
2186 R3PTRTYPE(const char *) pszDesc)
2187{
2188 /*
2189 * Assert on some assumption.
2190 */
2191 VM_ASSERT_EMT(pVM);
2192 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2193 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2194 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2195 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
2196
2197 int rc = pgmLock(pVM);
2198 AssertRCReturn(rc, rc);
2199
2200 /*
2201 * Make sure there's a RAM range structure for the region.
2202 */
2203 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2204 bool fRamExists = false;
2205 PPGMRAMRANGE pRamPrev = NULL;
2206 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2207 while (pRam && GCPhysLast >= pRam->GCPhys)
2208 {
2209 if ( GCPhysLast >= pRam->GCPhys
2210 && GCPhys <= pRam->GCPhysLast)
2211 {
2212 /* Simplification: all within the same range. */
2213 AssertLogRelMsgReturnStmt( GCPhys >= pRam->GCPhys
2214 && GCPhysLast <= pRam->GCPhysLast,
2215 ("%RGp-%RGp (MMIO/%s) falls partly outside %RGp-%RGp (%s)\n",
2216 GCPhys, GCPhysLast, pszDesc,
2217 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2218 pgmUnlock(pVM),
2219 VERR_PGM_RAM_CONFLICT);
2220
2221 /* Check that it's all RAM or MMIO pages. */
2222 PCPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2223 uint32_t cLeft = cb >> PAGE_SHIFT;
2224 while (cLeft-- > 0)
2225 {
2226 AssertLogRelMsgReturnStmt( PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM
2227 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO,
2228 ("%RGp-%RGp (MMIO/%s): %RGp is not a RAM or MMIO page - type=%d desc=%s\n",
2229 GCPhys, GCPhysLast, pszDesc, pRam->GCPhys, PGM_PAGE_GET_TYPE(pPage), pRam->pszDesc),
2230 pgmUnlock(pVM),
2231 VERR_PGM_RAM_CONFLICT);
2232 pPage++;
2233 }
2234
2235 /* Looks good. */
2236 fRamExists = true;
2237 break;
2238 }
2239
2240 /* next */
2241 pRamPrev = pRam;
2242 pRam = pRam->pNextR3;
2243 }
2244 PPGMRAMRANGE pNew;
2245 if (fRamExists)
2246 {
2247 pNew = NULL;
2248
2249 /*
2250 * Make all the pages in the range MMIO/ZERO pages, freeing any
2251 * RAM pages currently mapped here. This might not be 100% correct
2252 * for PCI memory, but we're doing the same thing for MMIO2 pages.
2253 */
2254 rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, PGMPAGETYPE_MMIO);
2255 AssertRCReturnStmt(rc, pgmUnlock(pVM), rc);
2256
2257 /* Force a PGM pool flush as guest ram references have been changed. */
2258 /** @todo not entirely SMP safe; assuming for now the guest takes
2259 * care of this internally (not touch mapped mmio while changing the
2260 * mapping). */
2261 PVMCPU pVCpu = VMMGetCpu(pVM);
2262 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2263 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2264 }
2265 else
2266 {
2267
2268 /*
2269 * No RAM range, insert an ad hoc one.
2270 *
2271 * Note that we don't have to tell REM about this range because
2272 * PGMHandlerPhysicalRegisterEx will do that for us.
2273 */
2274 Log(("PGMR3PhysMMIORegister: Adding ad hoc MMIO range for %RGp-%RGp %s\n", GCPhys, GCPhysLast, pszDesc));
2275
2276 const uint32_t cPages = cb >> PAGE_SHIFT;
2277 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
2278 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), 16, MM_TAG_PGM_PHYS, (void **)&pNew);
2279 AssertLogRelMsgRCReturnStmt(rc, ("cbRamRange=%zu\n", cbRamRange), pgmUnlock(pVM), rc);
2280
2281 /* Initialize the range. */
2282 pNew->pSelfR0 = MMHyperCCToR0(pVM, pNew);
2283 pNew->pSelfRC = MMHyperCCToRC(pVM, pNew);
2284 pNew->GCPhys = GCPhys;
2285 pNew->GCPhysLast = GCPhysLast;
2286 pNew->cb = cb;
2287 pNew->pszDesc = pszDesc;
2288 pNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO;
2289 pNew->pvR3 = NULL;
2290 pNew->paLSPages = NULL;
2291
2292 uint32_t iPage = cPages;
2293 while (iPage-- > 0)
2294 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_MMIO);
2295 Assert(PGM_PAGE_GET_TYPE(&pNew->aPages[0]) == PGMPAGETYPE_MMIO);
2296
2297 /* update the page count stats. */
2298 pVM->pgm.s.cPureMmioPages += cPages;
2299 pVM->pgm.s.cAllPages += cPages;
2300
2301 /* link it */
2302 pgmR3PhysLinkRamRange(pVM, pNew, pRamPrev);
2303 }
2304
2305 /*
2306 * Register the access handler.
2307 */
2308 rc = PGMHandlerPhysicalRegisterEx(pVM, PGMPHYSHANDLERTYPE_MMIO, GCPhys, GCPhysLast,
2309 pfnHandlerR3, pvUserR3,
2310 pfnHandlerR0, pvUserR0,
2311 pfnHandlerRC, pvUserRC, pszDesc);
2312 if ( RT_FAILURE(rc)
2313 && !fRamExists)
2314 {
2315 pVM->pgm.s.cPureMmioPages -= cb >> PAGE_SHIFT;
2316 pVM->pgm.s.cAllPages -= cb >> PAGE_SHIFT;
2317
2318 /* remove the ad hoc range. */
2319 pgmR3PhysUnlinkRamRange2(pVM, pNew, pRamPrev);
2320 pNew->cb = pNew->GCPhys = pNew->GCPhysLast = NIL_RTGCPHYS;
2321 MMHyperFree(pVM, pRam);
2322 }
2323 pgmPhysInvalidatePageMapTLB(pVM);
2324
2325 pgmUnlock(pVM);
2326 return rc;
2327}
2328
2329
2330/**
2331 * This is the interface IOM is using to register an MMIO region.
2332 *
2333 * It will take care of calling PGMHandlerPhysicalDeregister and clean up
2334 * any ad hoc PGMRAMRANGE left behind.
2335 *
2336 * @returns VBox status code.
2337 * @param pVM Pointer to the VM.
2338 * @param GCPhys The start of the MMIO region.
2339 * @param cb The size of the MMIO region.
2340 */
2341VMMR3DECL(int) PGMR3PhysMMIODeregister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb)
2342{
2343 VM_ASSERT_EMT(pVM);
2344
2345 int rc = pgmLock(pVM);
2346 AssertRCReturn(rc, rc);
2347
2348 /*
2349 * First deregister the handler, then check if we should remove the ram range.
2350 */
2351 rc = PGMHandlerPhysicalDeregister(pVM, GCPhys);
2352 if (RT_SUCCESS(rc))
2353 {
2354 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2355 PPGMRAMRANGE pRamPrev = NULL;
2356 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2357 while (pRam && GCPhysLast >= pRam->GCPhys)
2358 {
2359 /** @todo We're being a bit too careful here. rewrite. */
2360 if ( GCPhysLast == pRam->GCPhysLast
2361 && GCPhys == pRam->GCPhys)
2362 {
2363 Assert(pRam->cb == cb);
2364
2365 /*
2366 * See if all the pages are dead MMIO pages.
2367 */
2368 uint32_t const cPages = cb >> PAGE_SHIFT;
2369 bool fAllMMIO = true;
2370 uint32_t iPage = 0;
2371 uint32_t cLeft = cPages;
2372 while (cLeft-- > 0)
2373 {
2374 PPGMPAGE pPage = &pRam->aPages[iPage];
2375 if ( !PGM_PAGE_IS_MMIO_OR_ALIAS(pPage)
2376 /*|| not-out-of-action later */)
2377 {
2378 fAllMMIO = false;
2379 AssertMsgFailed(("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
2380 break;
2381 }
2382 Assert( PGM_PAGE_IS_ZERO(pPage)
2383 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2_ALIAS_MMIO
2384 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_SPECIAL_ALIAS_MMIO);
2385 pPage++;
2386 }
2387 if (fAllMMIO)
2388 {
2389 /*
2390 * Ad-hoc range, unlink and free it.
2391 */
2392 Log(("PGMR3PhysMMIODeregister: Freeing ad hoc MMIO range for %RGp-%RGp %s\n",
2393 GCPhys, GCPhysLast, pRam->pszDesc));
2394
2395 pVM->pgm.s.cAllPages -= cPages;
2396 pVM->pgm.s.cPureMmioPages -= cPages;
2397
2398 pgmR3PhysUnlinkRamRange2(pVM, pRam, pRamPrev);
2399 pRam->cb = pRam->GCPhys = pRam->GCPhysLast = NIL_RTGCPHYS;
2400 MMHyperFree(pVM, pRam);
2401 break;
2402 }
2403 }
2404
2405 /*
2406 * Range match? It will all be within one range (see PGMAllHandler.cpp).
2407 */
2408 if ( GCPhysLast >= pRam->GCPhys
2409 && GCPhys <= pRam->GCPhysLast)
2410 {
2411 Assert(GCPhys >= pRam->GCPhys);
2412 Assert(GCPhysLast <= pRam->GCPhysLast);
2413
2414 /*
2415 * Turn the pages back into RAM pages.
2416 */
2417 uint32_t iPage = (GCPhys - pRam->GCPhys) >> PAGE_SHIFT;
2418 uint32_t cLeft = cb >> PAGE_SHIFT;
2419 while (cLeft--)
2420 {
2421 PPGMPAGE pPage = &pRam->aPages[iPage];
2422 AssertMsg( (PGM_PAGE_IS_MMIO(pPage) && PGM_PAGE_IS_ZERO(pPage))
2423 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2_ALIAS_MMIO
2424 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_SPECIAL_ALIAS_MMIO,
2425 ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
2426 if (PGM_PAGE_IS_MMIO_OR_ALIAS(pPage))
2427 PGM_PAGE_SET_TYPE(pVM, pPage, PGMPAGETYPE_RAM);
2428 }
2429 break;
2430 }
2431
2432 /* next */
2433 pRamPrev = pRam;
2434 pRam = pRam->pNextR3;
2435 }
2436 }
2437
2438 /* Force a PGM pool flush as guest ram references have been changed. */
2439 /** @todo Not entirely SMP safe; assuming for now the guest takes care of
2440 * this internally (not touch mapped mmio while changing the mapping). */
2441 PVMCPU pVCpu = VMMGetCpu(pVM);
2442 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2443 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2444
2445 pgmPhysInvalidatePageMapTLB(pVM);
2446 pgmPhysInvalidRamRangeTlbs(pVM);
2447 pgmUnlock(pVM);
2448 return rc;
2449}
2450
2451
2452/**
2453 * Locate a MMIO2 range.
2454 *
2455 * @returns Pointer to the MMIO2 range.
2456 * @param pVM Pointer to the VM.
2457 * @param pDevIns The device instance owning the region.
2458 * @param iRegion The region.
2459 */
2460DECLINLINE(PPGMMMIO2RANGE) pgmR3PhysMMIO2Find(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
2461{
2462 /*
2463 * Search the list.
2464 */
2465 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
2466 if ( pCur->pDevInsR3 == pDevIns
2467 && pCur->iRegion == iRegion)
2468 return pCur;
2469 return NULL;
2470}
2471
2472
2473/**
2474 * Allocate and register an MMIO2 region.
2475 *
2476 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's RAM
2477 * associated with a device. It is also non-shared memory with a permanent
2478 * ring-3 mapping and page backing (presently).
2479 *
2480 * A MMIO2 range may overlap with base memory if a lot of RAM is configured for
2481 * the VM, in which case we'll drop the base memory pages. Presently we will
2482 * make no attempt to preserve anything that happens to be present in the base
2483 * memory that is replaced, this is of course incorrect but it's too much
2484 * effort.
2485 *
2486 * @returns VBox status code.
2487 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
2488 * memory.
2489 * @retval VERR_ALREADY_EXISTS if the region already exists.
2490 *
2491 * @param pVM Pointer to the VM.
2492 * @param pDevIns The device instance owning the region.
2493 * @param iRegion The region number. If the MMIO2 memory is a PCI
2494 * I/O region this number has to be the number of that
2495 * region. Otherwise it can be any number safe
2496 * UINT8_MAX.
2497 * @param cb The size of the region. Must be page aligned.
2498 * @param fFlags Reserved for future use, must be zero.
2499 * @param ppv Where to store the pointer to the ring-3 mapping of
2500 * the memory.
2501 * @param pszDesc The description.
2502 */
2503VMMR3DECL(int) PGMR3PhysMMIO2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags,
2504 void **ppv, const char *pszDesc)
2505{
2506 /*
2507 * Validate input.
2508 */
2509 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2510 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2511 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2512 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
2513 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2514 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
2515 AssertReturn(pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion) == NULL, VERR_ALREADY_EXISTS);
2516 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2517 AssertReturn(cb, VERR_INVALID_PARAMETER);
2518 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
2519
2520 const uint32_t cPages = cb >> PAGE_SHIFT;
2521 AssertLogRelReturn(((RTGCPHYS)cPages << PAGE_SHIFT) == cb, VERR_INVALID_PARAMETER);
2522 AssertLogRelReturn(cPages <= PGM_MMIO2_MAX_PAGE_COUNT, VERR_NO_MEMORY);
2523
2524 /*
2525 * For the 2nd+ instance, mangle the description string so it's unique.
2526 */
2527 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
2528 {
2529 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
2530 if (!pszDesc)
2531 return VERR_NO_MEMORY;
2532 }
2533
2534 /*
2535 * Allocate an MMIO2 range ID (not freed on failure).
2536 * The zero ID is not used as it could be confused with NIL_GMM_PAGEID.
2537 */
2538 pgmLock(pVM);
2539 uint8_t idMmio2 = pVM->pgm.s.cMmio2Regions + 1;
2540 if (idMmio2 > PGM_MMIO2_MAX_RANGES)
2541 {
2542 pgmUnlock(pVM);
2543 AssertLogRelFailedReturn(VERR_PGM_TOO_MANY_MMIO2_RANGES);
2544 }
2545 pVM->pgm.s.cMmio2Regions = idMmio2;
2546 pgmUnlock(pVM);
2547
2548 /*
2549 * Try reserve and allocate the backing memory first as this is what is
2550 * most likely to fail.
2551 */
2552 int rc = MMR3AdjustFixedReservation(pVM, cPages, pszDesc);
2553 if (RT_SUCCESS(rc))
2554 {
2555 void *pvPages;
2556 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cPages * sizeof(SUPPAGE));
2557 if (RT_SUCCESS(rc))
2558 rc = SUPR3PageAllocEx(cPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
2559 if (RT_SUCCESS(rc))
2560 {
2561 memset(pvPages, 0, cPages * PAGE_SIZE);
2562
2563 /*
2564 * Create the MMIO2 range record for it.
2565 */
2566 const size_t cbRange = RT_OFFSETOF(PGMMMIO2RANGE, RamRange.aPages[cPages]);
2567 PPGMMMIO2RANGE pNew;
2568 rc = MMR3HyperAllocOnceNoRel(pVM, cbRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
2569 AssertLogRelMsgRC(rc, ("cbRamRange=%zu\n", cbRange));
2570 if (RT_SUCCESS(rc))
2571 {
2572 pNew->pDevInsR3 = pDevIns;
2573 pNew->pvR3 = pvPages;
2574 //pNew->pNext = NULL;
2575 //pNew->fMapped = false;
2576 //pNew->fOverlapping = false;
2577 pNew->iRegion = iRegion;
2578 pNew->idSavedState = UINT8_MAX;
2579 pNew->idMmio2 = idMmio2;
2580 pNew->RamRange.pSelfR0 = MMHyperCCToR0(pVM, &pNew->RamRange);
2581 pNew->RamRange.pSelfRC = MMHyperCCToRC(pVM, &pNew->RamRange);
2582 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
2583 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
2584 pNew->RamRange.pszDesc = pszDesc;
2585 pNew->RamRange.cb = cb;
2586 pNew->RamRange.fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO2;
2587 pNew->RamRange.pvR3 = pvPages;
2588 //pNew->RamRange.paLSPages = NULL;
2589
2590 uint32_t iPage = cPages;
2591 while (iPage-- > 0)
2592 {
2593 PGM_PAGE_INIT(&pNew->RamRange.aPages[iPage],
2594 paPages[iPage].Phys,
2595 PGM_MMIO2_PAGEID_MAKE(idMmio2, iPage),
2596 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
2597 }
2598
2599 /* update page count stats */
2600 pVM->pgm.s.cAllPages += cPages;
2601 pVM->pgm.s.cPrivatePages += cPages;
2602
2603 /*
2604 * Link it into the list.
2605 * Since there is no particular order, just push it.
2606 */
2607 /** @todo we can save us the linked list now, just search the lookup table... */
2608 pgmLock(pVM);
2609 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == NULL);
2610 Assert(pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] == NIL_RTR0PTR);
2611 pNew->pNextR3 = pVM->pgm.s.pMmio2RangesR3;
2612 pVM->pgm.s.pMmio2RangesR3 = pNew;
2613 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = pNew;
2614 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = MMHyperCCToR0(pVM, pNew);
2615 pgmUnlock(pVM);
2616
2617 *ppv = pvPages;
2618 RTMemTmpFree(paPages);
2619 pgmPhysInvalidatePageMapTLB(pVM);
2620 return VINF_SUCCESS;
2621 }
2622
2623 SUPR3PageFreeEx(pvPages, cPages);
2624 }
2625 RTMemTmpFree(paPages);
2626 MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pszDesc);
2627 }
2628 if (pDevIns->iInstance > 0)
2629 MMR3HeapFree((void *)pszDesc);
2630 return rc;
2631}
2632
2633
2634/**
2635 * Deregisters and frees an MMIO2 region.
2636 *
2637 * Any physical (and virtual) access handlers registered for the region must
2638 * be deregistered before calling this function.
2639 *
2640 * @returns VBox status code.
2641 * @param pVM Pointer to the VM.
2642 * @param pDevIns The device instance owning the region.
2643 * @param iRegion The region. If it's UINT32_MAX it'll be a wildcard match.
2644 */
2645VMMR3DECL(int) PGMR3PhysMMIO2Deregister(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
2646{
2647 /*
2648 * Validate input.
2649 */
2650 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2651 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2652 AssertReturn(iRegion <= UINT8_MAX || iRegion == UINT32_MAX, VERR_INVALID_PARAMETER);
2653
2654 pgmLock(pVM);
2655 int rc = VINF_SUCCESS;
2656 unsigned cFound = 0;
2657 PPGMMMIO2RANGE pPrev = NULL;
2658 PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3;
2659 while (pCur)
2660 {
2661 if ( pCur->pDevInsR3 == pDevIns
2662 && ( iRegion == UINT32_MAX
2663 || pCur->iRegion == iRegion))
2664 {
2665 cFound++;
2666
2667 /*
2668 * Unmap it if it's mapped.
2669 */
2670 if (pCur->fMapped)
2671 {
2672 int rc2 = PGMR3PhysMMIO2Unmap(pVM, pCur->pDevInsR3, pCur->iRegion, pCur->RamRange.GCPhys);
2673 AssertRC(rc2);
2674 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2675 rc = rc2;
2676 }
2677
2678 /*
2679 * Unlink it
2680 */
2681 PPGMMMIO2RANGE pNext = pCur->pNextR3;
2682 if (pPrev)
2683 pPrev->pNextR3 = pNext;
2684 else
2685 pVM->pgm.s.pMmio2RangesR3 = pNext;
2686 pCur->pNextR3 = NULL;
2687
2688 uint8_t idMmio2 = pCur->idMmio2;
2689 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == pCur);
2690 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = NULL;
2691 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = NIL_RTR0PTR;
2692
2693 /*
2694 * Free the memory.
2695 */
2696 int rc2 = SUPR3PageFreeEx(pCur->pvR3, pCur->RamRange.cb >> PAGE_SHIFT);
2697 AssertRC(rc2);
2698 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2699 rc = rc2;
2700
2701 uint32_t const cPages = pCur->RamRange.cb >> PAGE_SHIFT;
2702 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pCur->RamRange.pszDesc);
2703 AssertRC(rc2);
2704 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2705 rc = rc2;
2706
2707 /* we're leaking hyper memory here if done at runtime. */
2708#ifdef VBOX_STRICT
2709 VMSTATE const enmState = VMR3GetState(pVM);
2710 AssertMsg( enmState == VMSTATE_POWERING_OFF
2711 || enmState == VMSTATE_POWERING_OFF_LS
2712 || enmState == VMSTATE_OFF
2713 || enmState == VMSTATE_OFF_LS
2714 || enmState == VMSTATE_DESTROYING
2715 || enmState == VMSTATE_TERMINATED
2716 || enmState == VMSTATE_CREATING
2717 , ("%s\n", VMR3GetStateName(enmState)));
2718#endif
2719 /*rc = MMHyperFree(pVM, pCur);
2720 AssertRCReturn(rc, rc); - not safe, see the alloc call. */
2721
2722
2723 /* update page count stats */
2724 pVM->pgm.s.cAllPages -= cPages;
2725 pVM->pgm.s.cPrivatePages -= cPages;
2726
2727 /* next */
2728 pCur = pNext;
2729 }
2730 else
2731 {
2732 pPrev = pCur;
2733 pCur = pCur->pNextR3;
2734 }
2735 }
2736 pgmPhysInvalidatePageMapTLB(pVM);
2737 pgmUnlock(pVM);
2738 return !cFound && iRegion != UINT32_MAX ? VERR_NOT_FOUND : rc;
2739}
2740
2741
2742/**
2743 * Maps a MMIO2 region.
2744 *
2745 * This is done when a guest / the bios / state loading changes the
2746 * PCI config. The replacing of base memory has the same restrictions
2747 * as during registration, of course.
2748 *
2749 * @returns VBox status code.
2750 *
2751 * @param pVM Pointer to the VM.
2752 * @param pDevIns The device instance owning the region.
2753 * @param iRegion The index of the registered region.
2754 * @param GCPhys The guest-physical address to be remapped.
2755 */
2756VMMR3DECL(int) PGMR3PhysMMIO2Map(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
2757{
2758 /*
2759 * Validate input
2760 */
2761 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2762 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2763 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2764 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
2765 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
2766 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2767
2768 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2769 AssertReturn(pCur, VERR_NOT_FOUND);
2770 AssertReturn(!pCur->fMapped, VERR_WRONG_ORDER);
2771 Assert(pCur->RamRange.GCPhys == NIL_RTGCPHYS);
2772 Assert(pCur->RamRange.GCPhysLast == NIL_RTGCPHYS);
2773
2774 const RTGCPHYS GCPhysLast = GCPhys + pCur->RamRange.cb - 1;
2775 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2776
2777 /*
2778 * Find our location in the ram range list, checking for
2779 * restriction we don't bother implementing yet (partially overlapping).
2780 */
2781 bool fRamExists = false;
2782 PPGMRAMRANGE pRamPrev = NULL;
2783 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2784 while (pRam && GCPhysLast >= pRam->GCPhys)
2785 {
2786 if ( GCPhys <= pRam->GCPhysLast
2787 && GCPhysLast >= pRam->GCPhys)
2788 {
2789 /* completely within? */
2790 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
2791 && GCPhysLast <= pRam->GCPhysLast,
2792 ("%RGp-%RGp (MMIO2/%s) falls partly outside %RGp-%RGp (%s)\n",
2793 GCPhys, GCPhysLast, pCur->RamRange.pszDesc,
2794 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2795 VERR_PGM_RAM_CONFLICT);
2796 fRamExists = true;
2797 break;
2798 }
2799
2800 /* next */
2801 pRamPrev = pRam;
2802 pRam = pRam->pNextR3;
2803 }
2804 if (fRamExists)
2805 {
2806 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2807 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2808 while (cPagesLeft-- > 0)
2809 {
2810 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
2811 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
2812 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pCur->RamRange.pszDesc),
2813 VERR_PGM_RAM_CONFLICT);
2814 pPage++;
2815 }
2816 }
2817 Log(("PGMR3PhysMMIO2Map: %RGp-%RGp fRamExists=%RTbool %s\n",
2818 GCPhys, GCPhysLast, fRamExists, pCur->RamRange.pszDesc));
2819
2820 /*
2821 * Make the changes.
2822 */
2823 pgmLock(pVM);
2824
2825 pCur->RamRange.GCPhys = GCPhys;
2826 pCur->RamRange.GCPhysLast = GCPhysLast;
2827 pCur->fMapped = true;
2828 pCur->fOverlapping = fRamExists;
2829
2830 if (fRamExists)
2831 {
2832/** @todo use pgmR3PhysFreePageRange here. */
2833 uint32_t cPendingPages = 0;
2834 PGMMFREEPAGESREQ pReq;
2835 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2836 AssertLogRelRCReturn(rc, rc);
2837
2838 /* replace the pages, freeing all present RAM pages. */
2839 PPGMPAGE pPageSrc = &pCur->RamRange.aPages[0];
2840 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2841 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2842 while (cPagesLeft-- > 0)
2843 {
2844 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys);
2845 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
2846
2847 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
2848 uint32_t const idPage = PGM_PAGE_GET_PAGEID(pPageSrc);
2849 PGM_PAGE_SET_PAGEID(pVM, pPageDst, idPage);
2850 PGM_PAGE_SET_HCPHYS(pVM, pPageDst, HCPhys);
2851 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO2);
2852 PGM_PAGE_SET_STATE(pVM, pPageDst, PGM_PAGE_STATE_ALLOCATED);
2853 PGM_PAGE_SET_PDE_TYPE(pVM, pPageDst, PGM_PAGE_PDE_TYPE_DONTCARE);
2854 PGM_PAGE_SET_PTE_INDEX(pVM, pPageDst, 0);
2855 PGM_PAGE_SET_TRACKING(pVM, pPageDst, 0);
2856
2857 pVM->pgm.s.cZeroPages--;
2858 GCPhys += PAGE_SIZE;
2859 pPageSrc++;
2860 pPageDst++;
2861 }
2862
2863 /* Flush physical page map TLB. */
2864 pgmPhysInvalidatePageMapTLB(pVM);
2865
2866 if (cPendingPages)
2867 {
2868 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2869 AssertLogRelRCReturn(rc, rc);
2870 }
2871 GMMR3FreePagesCleanup(pReq);
2872
2873 /* Force a PGM pool flush as guest ram references have been changed. */
2874 /** @todo not entirely SMP safe; assuming for now the guest takes care of
2875 * this internally (not touch mapped mmio while changing the mapping). */
2876 PVMCPU pVCpu = VMMGetCpu(pVM);
2877 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2878 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2879
2880 pgmUnlock(pVM);
2881 }
2882 else
2883 {
2884 RTGCPHYS cb = pCur->RamRange.cb;
2885
2886 /* Clear the tracking data of pages we're going to reactivate. */
2887 PPGMPAGE pPageSrc = &pCur->RamRange.aPages[0];
2888 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2889 while (cPagesLeft-- > 0)
2890 {
2891 PGM_PAGE_SET_TRACKING(pVM, pPageSrc, 0);
2892 PGM_PAGE_SET_PTE_INDEX(pVM, pPageSrc, 0);
2893 pPageSrc++;
2894 }
2895
2896 /* link in the ram range */
2897 pgmR3PhysLinkRamRange(pVM, &pCur->RamRange, pRamPrev);
2898 pgmUnlock(pVM);
2899
2900#ifdef VBOX_WITH_REM
2901 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_MMIO2);
2902#endif
2903 }
2904
2905 pgmPhysInvalidatePageMapTLB(pVM);
2906 return VINF_SUCCESS;
2907}
2908
2909
2910/**
2911 * Unmaps a MMIO2 region.
2912 *
2913 * This is done when a guest / the bios / state loading changes the
2914 * PCI config. The replacing of base memory has the same restrictions
2915 * as during registration, of course.
2916 */
2917VMMR3DECL(int) PGMR3PhysMMIO2Unmap(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
2918{
2919 /*
2920 * Validate input
2921 */
2922 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2923 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2924 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2925 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
2926 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
2927 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2928
2929 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2930 AssertReturn(pCur, VERR_NOT_FOUND);
2931 AssertReturn(pCur->fMapped, VERR_WRONG_ORDER);
2932 AssertReturn(pCur->RamRange.GCPhys == GCPhys, VERR_INVALID_PARAMETER);
2933 Assert(pCur->RamRange.GCPhysLast != NIL_RTGCPHYS);
2934
2935 Log(("PGMR3PhysMMIO2Unmap: %RGp-%RGp %s\n",
2936 pCur->RamRange.GCPhys, pCur->RamRange.GCPhysLast, pCur->RamRange.pszDesc));
2937
2938 /*
2939 * Unmap it.
2940 */
2941 pgmLock(pVM);
2942
2943#ifdef VBOX_WITH_REM
2944 RTGCPHYS GCPhysRangeREM;
2945 RTGCPHYS cbRangeREM;
2946 bool fInformREM;
2947#endif
2948 if (pCur->fOverlapping)
2949 {
2950 /* Restore the RAM pages we've replaced. */
2951 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2952 while (pRam->GCPhys > pCur->RamRange.GCPhysLast)
2953 pRam = pRam->pNextR3;
2954
2955 PPGMPAGE pPageDst = &pRam->aPages[(pCur->RamRange.GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2956 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2957 while (cPagesLeft-- > 0)
2958 {
2959 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
2960 pVM->pgm.s.cZeroPages++;
2961 pPageDst++;
2962 }
2963
2964 /* Flush physical page map TLB. */
2965 pgmPhysInvalidatePageMapTLB(pVM);
2966#ifdef VBOX_WITH_REM
2967 GCPhysRangeREM = NIL_RTGCPHYS; /* shuts up gcc */
2968 cbRangeREM = RTGCPHYS_MAX; /* ditto */
2969 fInformREM = false;
2970#endif
2971 }
2972 else
2973 {
2974#ifdef VBOX_WITH_REM
2975 GCPhysRangeREM = pCur->RamRange.GCPhys;
2976 cbRangeREM = pCur->RamRange.cb;
2977 fInformREM = true;
2978#endif
2979 pgmR3PhysUnlinkRamRange(pVM, &pCur->RamRange);
2980 }
2981
2982 pCur->RamRange.GCPhys = NIL_RTGCPHYS;
2983 pCur->RamRange.GCPhysLast = NIL_RTGCPHYS;
2984 pCur->fOverlapping = false;
2985 pCur->fMapped = false;
2986
2987 /* Force a PGM pool flush as guest ram references have been changed. */
2988 /** @todo not entirely SMP safe; assuming for now the guest takes care
2989 * of this internally (not touch mapped mmio while changing the
2990 * mapping). */
2991 PVMCPU pVCpu = VMMGetCpu(pVM);
2992 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2993 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2994
2995 pgmPhysInvalidatePageMapTLB(pVM);
2996 pgmPhysInvalidRamRangeTlbs(pVM);
2997 pgmUnlock(pVM);
2998
2999#ifdef VBOX_WITH_REM
3000 if (fInformREM)
3001 REMR3NotifyPhysRamDeregister(pVM, GCPhysRangeREM, cbRangeREM);
3002#endif
3003
3004 return VINF_SUCCESS;
3005}
3006
3007
3008/**
3009 * Checks if the given address is an MMIO2 base address or not.
3010 *
3011 * @returns true/false accordingly.
3012 * @param pVM Pointer to the VM.
3013 * @param pDevIns The owner of the memory, optional.
3014 * @param GCPhys The address to check.
3015 */
3016VMMR3DECL(bool) PGMR3PhysMMIO2IsBase(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys)
3017{
3018 /*
3019 * Validate input
3020 */
3021 VM_ASSERT_EMT_RETURN(pVM, false);
3022 AssertPtrReturn(pDevIns, false);
3023 AssertReturn(GCPhys != NIL_RTGCPHYS, false);
3024 AssertReturn(GCPhys != 0, false);
3025 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), false);
3026
3027 /*
3028 * Search the list.
3029 */
3030 pgmLock(pVM);
3031 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
3032 if (pCur->RamRange.GCPhys == GCPhys)
3033 {
3034 Assert(pCur->fMapped);
3035 pgmUnlock(pVM);
3036 return true;
3037 }
3038 pgmUnlock(pVM);
3039 return false;
3040}
3041
3042
3043/**
3044 * Gets the HC physical address of a page in the MMIO2 region.
3045 *
3046 * This is API is intended for MMHyper and shouldn't be called
3047 * by anyone else...
3048 *
3049 * @returns VBox status code.
3050 * @param pVM Pointer to the VM.
3051 * @param pDevIns The owner of the memory, optional.
3052 * @param iRegion The region.
3053 * @param off The page expressed an offset into the MMIO2 region.
3054 * @param pHCPhys Where to store the result.
3055 */
3056VMMR3DECL(int) PGMR3PhysMMIO2GetHCPhys(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, PRTHCPHYS pHCPhys)
3057{
3058 /*
3059 * Validate input
3060 */
3061 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3062 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3063 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3064
3065 pgmLock(pVM);
3066 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
3067 AssertReturn(pCur, VERR_NOT_FOUND);
3068 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
3069
3070 PCPGMPAGE pPage = &pCur->RamRange.aPages[off >> PAGE_SHIFT];
3071 *pHCPhys = PGM_PAGE_GET_HCPHYS(pPage);
3072 pgmUnlock(pVM);
3073 return VINF_SUCCESS;
3074}
3075
3076
3077/**
3078 * Maps a portion of an MMIO2 region into kernel space (host).
3079 *
3080 * The kernel mapping will become invalid when the MMIO2 memory is deregistered
3081 * or the VM is terminated.
3082 *
3083 * @return VBox status code.
3084 *
3085 * @param pVM Pointer to the VM.
3086 * @param pDevIns The device owning the MMIO2 memory.
3087 * @param iRegion The region.
3088 * @param off The offset into the region. Must be page aligned.
3089 * @param cb The number of bytes to map. Must be page aligned.
3090 * @param pszDesc Mapping description.
3091 * @param pR0Ptr Where to store the R0 address.
3092 */
3093VMMR3DECL(int) PGMR3PhysMMIO2MapKernel(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, RTGCPHYS cb,
3094 const char *pszDesc, PRTR0PTR pR0Ptr)
3095{
3096 /*
3097 * Validate input.
3098 */
3099 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3100 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3101 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3102
3103 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
3104 AssertReturn(pCur, VERR_NOT_FOUND);
3105 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
3106 AssertReturn(cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
3107 AssertReturn(off + cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
3108 NOREF(pszDesc);
3109
3110 /*
3111 * Pass the request on to the support library/driver.
3112 */
3113 int rc = SUPR3PageMapKernel(pCur->pvR3, off, cb, 0, pR0Ptr);
3114
3115 return rc;
3116}
3117
3118
3119/**
3120 * Worker for PGMR3PhysRomRegister.
3121 *
3122 * This is here to simplify lock management, i.e. the caller does all the
3123 * locking and we can simply return without needing to remember to unlock
3124 * anything first.
3125 *
3126 * @returns VBox status.
3127 * @param pVM Pointer to the VM.
3128 * @param pDevIns The device instance owning the ROM.
3129 * @param GCPhys First physical address in the range.
3130 * Must be page aligned!
3131 * @param cb The size of the range (in bytes).
3132 * Must be page aligned!
3133 * @param pvBinary Pointer to the binary data backing the ROM image.
3134 * @param cbBinary The size of the binary data pvBinary points to.
3135 * This must be less or equal to @a cb.
3136 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
3137 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
3138 * @param pszDesc Pointer to description string. This must not be freed.
3139 */
3140static int pgmR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
3141 const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
3142{
3143 /*
3144 * Validate input.
3145 */
3146 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3147 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
3148 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
3149 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
3150 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3151 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
3152 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
3153 AssertReturn(!(fFlags & ~(PGMPHYS_ROM_FLAGS_SHADOWED | PGMPHYS_ROM_FLAGS_PERMANENT_BINARY)), VERR_INVALID_PARAMETER);
3154 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
3155
3156 const uint32_t cPages = cb >> PAGE_SHIFT;
3157
3158 /*
3159 * Find the ROM location in the ROM list first.
3160 */
3161 PPGMROMRANGE pRomPrev = NULL;
3162 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
3163 while (pRom && GCPhysLast >= pRom->GCPhys)
3164 {
3165 if ( GCPhys <= pRom->GCPhysLast
3166 && GCPhysLast >= pRom->GCPhys)
3167 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
3168 GCPhys, GCPhysLast, pszDesc,
3169 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
3170 VERR_PGM_RAM_CONFLICT);
3171 /* next */
3172 pRomPrev = pRom;
3173 pRom = pRom->pNextR3;
3174 }
3175
3176 /*
3177 * Find the RAM location and check for conflicts.
3178 *
3179 * Conflict detection is a bit different than for RAM
3180 * registration since a ROM can be located within a RAM
3181 * range. So, what we have to check for is other memory
3182 * types (other than RAM that is) and that we don't span
3183 * more than one RAM range (layz).
3184 */
3185 bool fRamExists = false;
3186 PPGMRAMRANGE pRamPrev = NULL;
3187 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3188 while (pRam && GCPhysLast >= pRam->GCPhys)
3189 {
3190 if ( GCPhys <= pRam->GCPhysLast
3191 && GCPhysLast >= pRam->GCPhys)
3192 {
3193 /* completely within? */
3194 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
3195 && GCPhysLast <= pRam->GCPhysLast,
3196 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
3197 GCPhys, GCPhysLast, pszDesc,
3198 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
3199 VERR_PGM_RAM_CONFLICT);
3200 fRamExists = true;
3201 break;
3202 }
3203
3204 /* next */
3205 pRamPrev = pRam;
3206 pRam = pRam->pNextR3;
3207 }
3208 if (fRamExists)
3209 {
3210 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3211 uint32_t cPagesLeft = cPages;
3212 while (cPagesLeft-- > 0)
3213 {
3214 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
3215 ("%RGp (%R[pgmpage]) isn't a RAM page - registering %RGp-%RGp (%s).\n",
3216 pRam->GCPhys + ((RTGCPHYS)(uintptr_t)(pPage - &pRam->aPages[0]) << PAGE_SHIFT),
3217 pPage, GCPhys, GCPhysLast, pszDesc), VERR_PGM_RAM_CONFLICT);
3218 Assert(PGM_PAGE_IS_ZERO(pPage));
3219 pPage++;
3220 }
3221 }
3222
3223 /*
3224 * Update the base memory reservation if necessary.
3225 */
3226 uint32_t cExtraBaseCost = fRamExists ? 0 : cPages;
3227 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3228 cExtraBaseCost += cPages;
3229 if (cExtraBaseCost)
3230 {
3231 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
3232 if (RT_FAILURE(rc))
3233 return rc;
3234 }
3235
3236 /*
3237 * Allocate memory for the virgin copy of the RAM.
3238 */
3239 PGMMALLOCATEPAGESREQ pReq;
3240 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cPages, GMMACCOUNT_BASE);
3241 AssertRCReturn(rc, rc);
3242
3243 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3244 {
3245 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << PAGE_SHIFT);
3246 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
3247 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
3248 }
3249
3250 rc = GMMR3AllocatePagesPerform(pVM, pReq);
3251 if (RT_FAILURE(rc))
3252 {
3253 GMMR3AllocatePagesCleanup(pReq);
3254 return rc;
3255 }
3256
3257 /*
3258 * Allocate the new ROM range and RAM range (if necessary).
3259 */
3260 PPGMROMRANGE pRomNew;
3261 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMROMRANGE, aPages[cPages]), 0, MM_TAG_PGM_PHYS, (void **)&pRomNew);
3262 if (RT_SUCCESS(rc))
3263 {
3264 PPGMRAMRANGE pRamNew = NULL;
3265 if (!fRamExists)
3266 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), sizeof(PGMPAGE), MM_TAG_PGM_PHYS, (void **)&pRamNew);
3267 if (RT_SUCCESS(rc))
3268 {
3269 /*
3270 * Initialize and insert the RAM range (if required).
3271 */
3272 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
3273 if (!fRamExists)
3274 {
3275 pRamNew->pSelfR0 = MMHyperCCToR0(pVM, pRamNew);
3276 pRamNew->pSelfRC = MMHyperCCToRC(pVM, pRamNew);
3277 pRamNew->GCPhys = GCPhys;
3278 pRamNew->GCPhysLast = GCPhysLast;
3279 pRamNew->cb = cb;
3280 pRamNew->pszDesc = pszDesc;
3281 pRamNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_ROM;
3282 pRamNew->pvR3 = NULL;
3283 pRamNew->paLSPages = NULL;
3284
3285 PPGMPAGE pPage = &pRamNew->aPages[0];
3286 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
3287 {
3288 PGM_PAGE_INIT(pPage,
3289 pReq->aPages[iPage].HCPhysGCPhys,
3290 pReq->aPages[iPage].idPage,
3291 PGMPAGETYPE_ROM,
3292 PGM_PAGE_STATE_ALLOCATED);
3293
3294 pRomPage->Virgin = *pPage;
3295 }
3296
3297 pVM->pgm.s.cAllPages += cPages;
3298 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
3299 }
3300 else
3301 {
3302 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3303 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
3304 {
3305 PGM_PAGE_SET_TYPE(pVM, pPage, PGMPAGETYPE_ROM);
3306 PGM_PAGE_SET_HCPHYS(pVM, pPage, pReq->aPages[iPage].HCPhysGCPhys);
3307 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ALLOCATED);
3308 PGM_PAGE_SET_PAGEID(pVM, pPage, pReq->aPages[iPage].idPage);
3309 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
3310 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
3311 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
3312
3313 pRomPage->Virgin = *pPage;
3314 }
3315
3316 pRamNew = pRam;
3317
3318 pVM->pgm.s.cZeroPages -= cPages;
3319 }
3320 pVM->pgm.s.cPrivatePages += cPages;
3321
3322 /* Flush physical page map TLB. */
3323 pgmPhysInvalidatePageMapTLB(pVM);
3324
3325
3326 /*
3327 * !HACK ALERT! REM + (Shadowed) ROM ==> mess.
3328 *
3329 * If it's shadowed we'll register the handler after the ROM notification
3330 * so we get the access handler callbacks that we should. If it isn't
3331 * shadowed we'll do it the other way around to make REM use the built-in
3332 * ROM behavior and not the handler behavior (which is to route all access
3333 * to PGM atm).
3334 */
3335 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3336 {
3337#ifdef VBOX_WITH_REM
3338 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, true /* fShadowed */);
3339#endif
3340 rc = PGMR3HandlerPhysicalRegister(pVM, PGMPHYSHANDLERTYPE_PHYSICAL_WRITE, GCPhys, GCPhysLast,
3341 pgmR3PhysRomWriteHandler, pRomNew,
3342 NULL, "pgmPhysRomWriteHandler", MMHyperCCToR0(pVM, pRomNew),
3343 NULL, "pgmPhysRomWriteHandler", MMHyperCCToRC(pVM, pRomNew), pszDesc);
3344 }
3345 else
3346 {
3347 rc = PGMR3HandlerPhysicalRegister(pVM, PGMPHYSHANDLERTYPE_PHYSICAL_WRITE, GCPhys, GCPhysLast,
3348 pgmR3PhysRomWriteHandler, pRomNew,
3349 NULL, "pgmPhysRomWriteHandler", MMHyperCCToR0(pVM, pRomNew),
3350 NULL, "pgmPhysRomWriteHandler", MMHyperCCToRC(pVM, pRomNew), pszDesc);
3351#ifdef VBOX_WITH_REM
3352 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, false /* fShadowed */);
3353#endif
3354 }
3355 if (RT_SUCCESS(rc))
3356 {
3357 /*
3358 * Copy the image over to the virgin pages.
3359 * This must be done after linking in the RAM range.
3360 */
3361 size_t cbBinaryLeft = cbBinary;
3362 PPGMPAGE pRamPage = &pRamNew->aPages[(GCPhys - pRamNew->GCPhys) >> PAGE_SHIFT];
3363 for (uint32_t iPage = 0; iPage < cPages; iPage++, pRamPage++)
3364 {
3365 void *pvDstPage;
3366 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << PAGE_SHIFT), &pvDstPage);
3367 if (RT_FAILURE(rc))
3368 {
3369 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
3370 break;
3371 }
3372 if (cbBinaryLeft >= PAGE_SIZE)
3373 {
3374 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), PAGE_SIZE);
3375 cbBinaryLeft -= PAGE_SIZE;
3376 }
3377 else
3378 {
3379 ASMMemZeroPage(pvDstPage); /* (shouldn't be necessary, but can't hurt either) */
3380 if (cbBinaryLeft > 0)
3381 {
3382 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), cbBinaryLeft);
3383 cbBinaryLeft = 0;
3384 }
3385 }
3386 }
3387 if (RT_SUCCESS(rc))
3388 {
3389 /*
3390 * Initialize the ROM range.
3391 * Note that the Virgin member of the pages has already been initialized above.
3392 */
3393 pRomNew->GCPhys = GCPhys;
3394 pRomNew->GCPhysLast = GCPhysLast;
3395 pRomNew->cb = cb;
3396 pRomNew->fFlags = fFlags;
3397 pRomNew->idSavedState = UINT8_MAX;
3398 pRomNew->cbOriginal = cbBinary;
3399#ifdef VBOX_STRICT
3400 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY
3401 ? pvBinary : RTMemDup(pvBinary, cbBinary);
3402#else
3403 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY ? pvBinary : NULL;
3404#endif
3405 pRomNew->pszDesc = pszDesc;
3406
3407 for (unsigned iPage = 0; iPage < cPages; iPage++)
3408 {
3409 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
3410 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
3411 PGM_PAGE_INIT_ZERO(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
3412 }
3413
3414 /* update the page count stats for the shadow pages. */
3415 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3416 {
3417 pVM->pgm.s.cZeroPages += cPages;
3418 pVM->pgm.s.cAllPages += cPages;
3419 }
3420
3421 /*
3422 * Insert the ROM range, tell REM and return successfully.
3423 */
3424 pRomNew->pNextR3 = pRom;
3425 pRomNew->pNextR0 = pRom ? MMHyperCCToR0(pVM, pRom) : NIL_RTR0PTR;
3426 pRomNew->pNextRC = pRom ? MMHyperCCToRC(pVM, pRom) : NIL_RTRCPTR;
3427
3428 if (pRomPrev)
3429 {
3430 pRomPrev->pNextR3 = pRomNew;
3431 pRomPrev->pNextR0 = MMHyperCCToR0(pVM, pRomNew);
3432 pRomPrev->pNextRC = MMHyperCCToRC(pVM, pRomNew);
3433 }
3434 else
3435 {
3436 pVM->pgm.s.pRomRangesR3 = pRomNew;
3437 pVM->pgm.s.pRomRangesR0 = MMHyperCCToR0(pVM, pRomNew);
3438 pVM->pgm.s.pRomRangesRC = MMHyperCCToRC(pVM, pRomNew);
3439 }
3440
3441 pgmPhysInvalidatePageMapTLB(pVM);
3442 GMMR3AllocatePagesCleanup(pReq);
3443 return VINF_SUCCESS;
3444 }
3445
3446 /* bail out */
3447
3448 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
3449 AssertRC(rc2);
3450 }
3451
3452 if (!fRamExists)
3453 {
3454 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
3455 MMHyperFree(pVM, pRamNew);
3456 }
3457 }
3458 MMHyperFree(pVM, pRomNew);
3459 }
3460
3461 /** @todo Purge the mapping cache or something... */
3462 GMMR3FreeAllocatedPages(pVM, pReq);
3463 GMMR3AllocatePagesCleanup(pReq);
3464 return rc;
3465}
3466
3467
3468/**
3469 * Registers a ROM image.
3470 *
3471 * Shadowed ROM images requires double the amount of backing memory, so,
3472 * don't use that unless you have to. Shadowing of ROM images is process
3473 * where we can select where the reads go and where the writes go. On real
3474 * hardware the chipset provides means to configure this. We provide
3475 * PGMR3PhysProtectROM() for this purpose.
3476 *
3477 * A read-only copy of the ROM image will always be kept around while we
3478 * will allocate RAM pages for the changes on demand (unless all memory
3479 * is configured to be preallocated).
3480 *
3481 * @returns VBox status.
3482 * @param pVM Pointer to the VM.
3483 * @param pDevIns The device instance owning the ROM.
3484 * @param GCPhys First physical address in the range.
3485 * Must be page aligned!
3486 * @param cb The size of the range (in bytes).
3487 * Must be page aligned!
3488 * @param pvBinary Pointer to the binary data backing the ROM image.
3489 * @param cbBinary The size of the binary data pvBinary points to.
3490 * This must be less or equal to @a cb.
3491 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
3492 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
3493 * @param pszDesc Pointer to description string. This must not be freed.
3494 *
3495 * @remark There is no way to remove the rom, automatically on device cleanup or
3496 * manually from the device yet. This isn't difficult in any way, it's
3497 * just not something we expect to be necessary for a while.
3498 */
3499VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
3500 const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
3501{
3502 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p cbBinary=%#x fFlags=%#x pszDesc=%s\n",
3503 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, cbBinary, fFlags, pszDesc));
3504 pgmLock(pVM);
3505 int rc = pgmR3PhysRomRegister(pVM, pDevIns, GCPhys, cb, pvBinary, cbBinary, fFlags, pszDesc);
3506 pgmUnlock(pVM);
3507 return rc;
3508}
3509
3510
3511/**
3512 * \#PF Handler callback for ROM write accesses.
3513 *
3514 * @returns VINF_SUCCESS if the handler have carried out the operation.
3515 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
3516 * @param pVM Pointer to the VM.
3517 * @param GCPhys The physical address the guest is writing to.
3518 * @param pvPhys The HC mapping of that address.
3519 * @param pvBuf What the guest is reading/writing.
3520 * @param cbBuf How much it's reading/writing.
3521 * @param enmAccessType The access type.
3522 * @param pvUser User argument.
3523 */
3524static DECLCALLBACK(int) pgmR3PhysRomWriteHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf,
3525 PGMACCESSTYPE enmAccessType, void *pvUser)
3526{
3527 PPGMROMRANGE pRom = (PPGMROMRANGE)pvUser;
3528 const uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
3529 Assert(iPage < (pRom->cb >> PAGE_SHIFT));
3530 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
3531 Log5(("pgmR3PhysRomWriteHandler: %d %c %#08RGp %#04zx\n", pRomPage->enmProt, enmAccessType == PGMACCESSTYPE_READ ? 'R' : 'W', GCPhys, cbBuf));
3532 NOREF(pvPhys);
3533
3534 if (enmAccessType == PGMACCESSTYPE_READ)
3535 {
3536 switch (pRomPage->enmProt)
3537 {
3538 /*
3539 * Take the default action.
3540 */
3541 case PGMROMPROT_READ_ROM_WRITE_IGNORE:
3542 case PGMROMPROT_READ_RAM_WRITE_IGNORE:
3543 case PGMROMPROT_READ_ROM_WRITE_RAM:
3544 case PGMROMPROT_READ_RAM_WRITE_RAM:
3545 return VINF_PGM_HANDLER_DO_DEFAULT;
3546
3547 default:
3548 AssertMsgFailedReturn(("enmProt=%d iPage=%d GCPhys=%RGp\n",
3549 pRom->aPages[iPage].enmProt, iPage, GCPhys),
3550 VERR_IPE_NOT_REACHED_DEFAULT_CASE);
3551 }
3552 }
3553 else
3554 {
3555 Assert(enmAccessType == PGMACCESSTYPE_WRITE);
3556 switch (pRomPage->enmProt)
3557 {
3558 /*
3559 * Ignore writes.
3560 */
3561 case PGMROMPROT_READ_ROM_WRITE_IGNORE:
3562 case PGMROMPROT_READ_RAM_WRITE_IGNORE:
3563 return VINF_SUCCESS;
3564
3565 /*
3566 * Write to the RAM page.
3567 */
3568 case PGMROMPROT_READ_ROM_WRITE_RAM:
3569 case PGMROMPROT_READ_RAM_WRITE_RAM: /* yes this will get here too, it's *way* simpler that way. */
3570 {
3571 /* This should be impossible now, pvPhys doesn't work cross page anylonger. */
3572 Assert(((GCPhys - pRom->GCPhys + cbBuf - 1) >> PAGE_SHIFT) == iPage);
3573
3574 /*
3575 * Take the lock, do lazy allocation, map the page and copy the data.
3576 *
3577 * Note that we have to bypass the mapping TLB since it works on
3578 * guest physical addresses and entering the shadow page would
3579 * kind of screw things up...
3580 */
3581 int rc = pgmLock(pVM);
3582 AssertRC(rc);
3583
3584 PPGMPAGE pShadowPage = &pRomPage->Shadow;
3585 if (!PGMROMPROT_IS_ROM(pRomPage->enmProt))
3586 {
3587 pShadowPage = pgmPhysGetPage(pVM, GCPhys);
3588 AssertLogRelReturn(pShadowPage, VERR_PGM_PHYS_PAGE_GET_IPE);
3589 }
3590
3591 void *pvDstPage;
3592 rc = pgmPhysPageMakeWritableAndMap(pVM, pShadowPage, GCPhys & X86_PTE_PG_MASK, &pvDstPage);
3593 if (RT_SUCCESS(rc))
3594 {
3595 memcpy((uint8_t *)pvDstPage + (GCPhys & PAGE_OFFSET_MASK), pvBuf, cbBuf);
3596 pRomPage->LiveSave.fWrittenTo = true;
3597 }
3598
3599 pgmUnlock(pVM);
3600 return rc;
3601 }
3602
3603 default:
3604 AssertMsgFailedReturn(("enmProt=%d iPage=%d GCPhys=%RGp\n",
3605 pRom->aPages[iPage].enmProt, iPage, GCPhys),
3606 VERR_IPE_NOT_REACHED_DEFAULT_CASE);
3607 }
3608 }
3609}
3610
3611
3612/**
3613 * Called by PGMR3MemSetup to reset the shadow, switch to the virgin, and verify
3614 * that the virgin part is untouched.
3615 *
3616 * This is done after the normal memory has been cleared.
3617 *
3618 * ASSUMES that the caller owns the PGM lock.
3619 *
3620 * @param pVM Pointer to the VM.
3621 */
3622int pgmR3PhysRomReset(PVM pVM)
3623{
3624 PGM_LOCK_ASSERT_OWNER(pVM);
3625 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3626 {
3627 const uint32_t cPages = pRom->cb >> PAGE_SHIFT;
3628
3629 if (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3630 {
3631 /*
3632 * Reset the physical handler.
3633 */
3634 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
3635 AssertRCReturn(rc, rc);
3636
3637 /*
3638 * What we do with the shadow pages depends on the memory
3639 * preallocation option. If not enabled, we'll just throw
3640 * out all the dirty pages and replace them by the zero page.
3641 */
3642 if (!pVM->pgm.s.fRamPreAlloc)
3643 {
3644 /* Free the dirty pages. */
3645 uint32_t cPendingPages = 0;
3646 PGMMFREEPAGESREQ pReq;
3647 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
3648 AssertRCReturn(rc, rc);
3649
3650 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3651 if ( !PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow)
3652 && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow))
3653 {
3654 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
3655 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, &pRom->aPages[iPage].Shadow,
3656 pRom->GCPhys + (iPage << PAGE_SHIFT));
3657 AssertLogRelRCReturn(rc, rc);
3658 }
3659
3660 if (cPendingPages)
3661 {
3662 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
3663 AssertLogRelRCReturn(rc, rc);
3664 }
3665 GMMR3FreePagesCleanup(pReq);
3666 }
3667 else
3668 {
3669 /* clear all the shadow pages. */
3670 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3671 {
3672 if (PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow))
3673 continue;
3674 Assert(!PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow));
3675 void *pvDstPage;
3676 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
3677 rc = pgmPhysPageMakeWritableAndMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pvDstPage);
3678 if (RT_FAILURE(rc))
3679 break;
3680 ASMMemZeroPage(pvDstPage);
3681 }
3682 AssertRCReturn(rc, rc);
3683 }
3684 }
3685
3686#ifdef VBOX_STRICT
3687 /*
3688 * Verify that the virgin page is unchanged if possible.
3689 */
3690 if (pRom->pvOriginal)
3691 {
3692 size_t cbSrcLeft = pRom->cbOriginal;
3693 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
3694 for (uint32_t iPage = 0; iPage < cPages && cbSrcLeft > 0; iPage++, pbSrcPage += PAGE_SIZE)
3695 {
3696 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
3697 void const *pvDstPage;
3698 int rc = pgmPhysPageMapReadOnly(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPage);
3699 if (RT_FAILURE(rc))
3700 break;
3701
3702 if (memcmp(pvDstPage, pbSrcPage, RT_MIN(cbSrcLeft, PAGE_SIZE)))
3703 {
3704# ifdef DEBUG_bird /* This is darn handy for EFI debugging w/ snapshots, should be made default later. */
3705 void *pvDstPageW;
3706 rc = pgmPhysPageMap(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPageW);
3707 AssertRCReturn(rc, rc);
3708 memcpy(pvDstPageW, pbSrcPage, RT_MIN(cbSrcLeft, PAGE_SIZE));
3709# else
3710 LogRel(("pgmR3PhysRomReset: %RGp rom page changed (%s) - loaded saved state?\n",
3711 GCPhys, pRom->pszDesc));
3712# endif
3713 }
3714 cbSrcLeft -= RT_MIN(cbSrcLeft, PAGE_SIZE);
3715 }
3716 }
3717#endif
3718 }
3719
3720 return VINF_SUCCESS;
3721}
3722
3723
3724/**
3725 * Called by PGMR3Term to free resources.
3726 *
3727 * ASSUMES that the caller owns the PGM lock.
3728 *
3729 * @param pVM Pointer to the VM.
3730 */
3731void pgmR3PhysRomTerm(PVM pVM)
3732{
3733#ifdef RT_STRICT
3734 /*
3735 * Free the heap copy of the original bits.
3736 */
3737 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3738 {
3739 if ( pRom->pvOriginal
3740 && !(pRom->fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY))
3741 {
3742 RTMemFree((void *)pRom->pvOriginal);
3743 pRom->pvOriginal = NULL;
3744 }
3745 }
3746#endif
3747}
3748
3749
3750/**
3751 * Change the shadowing of a range of ROM pages.
3752 *
3753 * This is intended for implementing chipset specific memory registers
3754 * and will not be very strict about the input. It will silently ignore
3755 * any pages that are not the part of a shadowed ROM.
3756 *
3757 * @returns VBox status code.
3758 * @retval VINF_PGM_SYNC_CR3
3759 *
3760 * @param pVM Pointer to the VM.
3761 * @param GCPhys Where to start. Page aligned.
3762 * @param cb How much to change. Page aligned.
3763 * @param enmProt The new ROM protection.
3764 */
3765VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
3766{
3767 /*
3768 * Check input
3769 */
3770 if (!cb)
3771 return VINF_SUCCESS;
3772 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3773 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3774 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
3775 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3776 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
3777
3778 /*
3779 * Process the request.
3780 */
3781 pgmLock(pVM);
3782 int rc = VINF_SUCCESS;
3783 bool fFlushTLB = false;
3784 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3785 {
3786 if ( GCPhys <= pRom->GCPhysLast
3787 && GCPhysLast >= pRom->GCPhys
3788 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
3789 {
3790 /*
3791 * Iterate the relevant pages and make necessary the changes.
3792 */
3793 bool fChanges = false;
3794 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
3795 ? pRom->cb >> PAGE_SHIFT
3796 : (GCPhysLast - pRom->GCPhys + 1) >> PAGE_SHIFT;
3797 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
3798 iPage < cPages;
3799 iPage++)
3800 {
3801 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
3802 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
3803 {
3804 fChanges = true;
3805
3806 /* flush references to the page. */
3807 PPGMPAGE pRamPage = pgmPhysGetPage(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT));
3808 int rc2 = pgmPoolTrackUpdateGCPhys(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT), pRamPage,
3809 true /*fFlushPTEs*/, &fFlushTLB);
3810 if (rc2 != VINF_SUCCESS && (rc == VINF_SUCCESS || RT_FAILURE(rc2)))
3811 rc = rc2;
3812
3813 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
3814 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
3815
3816 *pOld = *pRamPage;
3817 *pRamPage = *pNew;
3818 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
3819 }
3820 pRomPage->enmProt = enmProt;
3821 }
3822
3823 /*
3824 * Reset the access handler if we made changes, no need
3825 * to optimize this.
3826 */
3827 if (fChanges)
3828 {
3829 int rc2 = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
3830 if (RT_FAILURE(rc2))
3831 {
3832 pgmUnlock(pVM);
3833 AssertRC(rc);
3834 return rc2;
3835 }
3836 }
3837
3838 /* Advance - cb isn't updated. */
3839 GCPhys = pRom->GCPhys + (cPages << PAGE_SHIFT);
3840 }
3841 }
3842 pgmUnlock(pVM);
3843 if (fFlushTLB)
3844 PGM_INVL_ALL_VCPU_TLBS(pVM);
3845
3846 return rc;
3847}
3848
3849
3850/**
3851 * Sets the Address Gate 20 state.
3852 *
3853 * @param pVCpu Pointer to the VMCPU.
3854 * @param fEnable True if the gate should be enabled.
3855 * False if the gate should be disabled.
3856 */
3857VMMDECL(void) PGMR3PhysSetA20(PVMCPU pVCpu, bool fEnable)
3858{
3859 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVCpu->pgm.s.fA20Enabled));
3860 if (pVCpu->pgm.s.fA20Enabled != fEnable)
3861 {
3862 pVCpu->pgm.s.fA20Enabled = fEnable;
3863 pVCpu->pgm.s.GCPhysA20Mask = ~((RTGCPHYS)!fEnable << 20);
3864#ifdef VBOX_WITH_REM
3865 REMR3A20Set(pVCpu->pVMR3, pVCpu, fEnable);
3866#endif
3867#ifdef PGM_WITH_A20
3868 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_UPDATE_PAGE_BIT_VIRTUAL;
3869 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3870 pgmR3RefreshShadowModeAfterA20Change(pVCpu);
3871 HMFlushTLB(pVCpu);
3872#endif
3873 STAM_REL_COUNTER_INC(&pVCpu->pgm.s.cA20Changes);
3874 }
3875}
3876
3877
3878/**
3879 * Tree enumeration callback for dealing with age rollover.
3880 * It will perform a simple compression of the current age.
3881 */
3882static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
3883{
3884 /* Age compression - ASSUMES iNow == 4. */
3885 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3886 if (pChunk->iLastUsed >= UINT32_C(0xffffff00))
3887 pChunk->iLastUsed = 3;
3888 else if (pChunk->iLastUsed >= UINT32_C(0xfffff000))
3889 pChunk->iLastUsed = 2;
3890 else if (pChunk->iLastUsed)
3891 pChunk->iLastUsed = 1;
3892 else /* iLastUsed = 0 */
3893 pChunk->iLastUsed = 4;
3894
3895 NOREF(pvUser);
3896 return 0;
3897}
3898
3899
3900/**
3901 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
3902 */
3903typedef struct PGMR3PHYSCHUNKUNMAPCB
3904{
3905 PVM pVM; /**< Pointer to the VM. */
3906 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
3907} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
3908
3909
3910/**
3911 * Callback used to find the mapping that's been unused for
3912 * the longest time.
3913 */
3914static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLU32NODECORE pNode, void *pvUser)
3915{
3916 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3917 PPGMR3PHYSCHUNKUNMAPCB pArg = (PPGMR3PHYSCHUNKUNMAPCB)pvUser;
3918
3919 /*
3920 * Check for locks and compare when last used.
3921 */
3922 if (pChunk->cRefs)
3923 return 0;
3924 if (pChunk->cPermRefs)
3925 return 0;
3926 if ( pArg->pChunk
3927 && pChunk->iLastUsed >= pArg->pChunk->iLastUsed)
3928 return 0;
3929
3930 /*
3931 * Check that it's not in any of the TLBs.
3932 */
3933 PVM pVM = pArg->pVM;
3934 if ( pVM->pgm.s.ChunkR3Map.Tlb.aEntries[PGM_CHUNKR3MAPTLB_IDX(pChunk->Core.Key)].idChunk
3935 == pChunk->Core.Key)
3936 {
3937 pChunk = NULL;
3938 return 0;
3939 }
3940#ifdef VBOX_STRICT
3941 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
3942 {
3943 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk != pChunk);
3944 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk != pChunk->Core.Key);
3945 }
3946#endif
3947
3948 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbHC.aEntries); i++)
3949 if (pVM->pgm.s.PhysTlbHC.aEntries[i].pMap == pChunk)
3950 return 0;
3951
3952 pArg->pChunk = pChunk;
3953 return 0;
3954}
3955
3956
3957/**
3958 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
3959 *
3960 * The candidate will not be part of any TLBs, so no need to flush
3961 * anything afterwards.
3962 *
3963 * @returns Chunk id.
3964 * @param pVM Pointer to the VM.
3965 */
3966static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
3967{
3968 PGM_LOCK_ASSERT_OWNER(pVM);
3969
3970 /*
3971 * Enumerate the age tree starting with the left most node.
3972 */
3973 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3974 PGMR3PHYSCHUNKUNMAPCB Args;
3975 Args.pVM = pVM;
3976 Args.pChunk = NULL;
3977 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, &Args);
3978 Assert(Args.pChunk);
3979 if (Args.pChunk)
3980 {
3981 Assert(Args.pChunk->cRefs == 0);
3982 Assert(Args.pChunk->cPermRefs == 0);
3983 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3984 return Args.pChunk->Core.Key;
3985 }
3986
3987 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3988 return INT32_MAX;
3989}
3990
3991
3992/**
3993 * Rendezvous callback used by pgmR3PhysUnmapChunk that unmaps a chunk
3994 *
3995 * This is only called on one of the EMTs while the other ones are waiting for
3996 * it to complete this function.
3997 *
3998 * @returns VINF_SUCCESS (VBox strict status code).
3999 * @param pVM Pointer to the VM.
4000 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
4001 * @param pvUser User pointer. Unused
4002 *
4003 */
4004static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysUnmapChunkRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
4005{
4006 int rc = VINF_SUCCESS;
4007 pgmLock(pVM);
4008 NOREF(pVCpu); NOREF(pvUser);
4009
4010 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
4011 {
4012 /* Flush the pgm pool cache; call the internal rendezvous handler as we're already in a rendezvous handler here. */
4013 /** @todo also not really efficient to unmap a chunk that contains PD
4014 * or PT pages. */
4015 pgmR3PoolClearAllRendezvous(pVM, &pVM->aCpus[0], NULL /* no need to flush the REM TLB as we already did that above */);
4016
4017 /*
4018 * Request the ring-0 part to unmap a chunk to make space in the mapping cache.
4019 */
4020 GMMMAPUNMAPCHUNKREQ Req;
4021 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
4022 Req.Hdr.cbReq = sizeof(Req);
4023 Req.pvR3 = NULL;
4024 Req.idChunkMap = NIL_GMM_CHUNKID;
4025 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
4026 if (Req.idChunkUnmap != INT32_MAX)
4027 {
4028 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
4029 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
4030 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
4031 if (RT_SUCCESS(rc))
4032 {
4033 /*
4034 * Remove the unmapped one.
4035 */
4036 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
4037 AssertRelease(pUnmappedChunk);
4038 AssertRelease(!pUnmappedChunk->cRefs);
4039 AssertRelease(!pUnmappedChunk->cPermRefs);
4040 pUnmappedChunk->pv = NULL;
4041 pUnmappedChunk->Core.Key = UINT32_MAX;
4042#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
4043 MMR3HeapFree(pUnmappedChunk);
4044#else
4045 MMR3UkHeapFree(pVM, pUnmappedChunk, MM_TAG_PGM_CHUNK_MAPPING);
4046#endif
4047 pVM->pgm.s.ChunkR3Map.c--;
4048 pVM->pgm.s.cUnmappedChunks++;
4049
4050 /*
4051 * Flush dangling PGM pointers (R3 & R0 ptrs to GC physical addresses).
4052 */
4053 /** @todo We should not flush chunks which include cr3 mappings. */
4054 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
4055 {
4056 PPGMCPU pPGM = &pVM->aCpus[idCpu].pgm.s;
4057
4058 pPGM->pGst32BitPdR3 = NULL;
4059 pPGM->pGstPaePdptR3 = NULL;
4060 pPGM->pGstAmd64Pml4R3 = NULL;
4061#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
4062 pPGM->pGst32BitPdR0 = NIL_RTR0PTR;
4063 pPGM->pGstPaePdptR0 = NIL_RTR0PTR;
4064 pPGM->pGstAmd64Pml4R0 = NIL_RTR0PTR;
4065#endif
4066 for (unsigned i = 0; i < RT_ELEMENTS(pPGM->apGstPaePDsR3); i++)
4067 {
4068 pPGM->apGstPaePDsR3[i] = NULL;
4069#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
4070 pPGM->apGstPaePDsR0[i] = NIL_RTR0PTR;
4071#endif
4072 }
4073
4074 /* Flush REM TLBs. */
4075 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
4076 }
4077#ifdef VBOX_WITH_REM
4078 /* Flush REM translation blocks. */
4079 REMFlushTBs(pVM);
4080#endif
4081 }
4082 }
4083 }
4084 pgmUnlock(pVM);
4085 return rc;
4086}
4087
4088/**
4089 * Unmap a chunk to free up virtual address space (request packet handler for pgmR3PhysChunkMap)
4090 *
4091 * @returns VBox status code.
4092 * @param pVM Pointer to the VM.
4093 */
4094void pgmR3PhysUnmapChunk(PVM pVM)
4095{
4096 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysUnmapChunkRendezvous, NULL);
4097 AssertRC(rc);
4098}
4099
4100
4101/**
4102 * Maps the given chunk into the ring-3 mapping cache.
4103 *
4104 * This will call ring-0.
4105 *
4106 * @returns VBox status code.
4107 * @param pVM Pointer to the VM.
4108 * @param idChunk The chunk in question.
4109 * @param ppChunk Where to store the chunk tracking structure.
4110 *
4111 * @remarks Called from within the PGM critical section.
4112 * @remarks Can be called from any thread!
4113 */
4114int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
4115{
4116 int rc;
4117
4118 PGM_LOCK_ASSERT_OWNER(pVM);
4119
4120 /*
4121 * Move the chunk time forward.
4122 */
4123 pVM->pgm.s.ChunkR3Map.iNow++;
4124 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
4125 {
4126 pVM->pgm.s.ChunkR3Map.iNow = 4;
4127 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, NULL);
4128 }
4129
4130 /*
4131 * Allocate a new tracking structure first.
4132 */
4133#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
4134 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
4135#else
4136 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3UkHeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk), NULL);
4137#endif
4138 AssertReturn(pChunk, VERR_NO_MEMORY);
4139 pChunk->Core.Key = idChunk;
4140 pChunk->iLastUsed = pVM->pgm.s.ChunkR3Map.iNow;
4141
4142 /*
4143 * Request the ring-0 part to map the chunk in question.
4144 */
4145 GMMMAPUNMAPCHUNKREQ Req;
4146 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
4147 Req.Hdr.cbReq = sizeof(Req);
4148 Req.pvR3 = NULL;
4149 Req.idChunkMap = idChunk;
4150 Req.idChunkUnmap = NIL_GMM_CHUNKID;
4151
4152 /* Must be callable from any thread, so can't use VMMR3CallR0. */
4153 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
4154 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, NIL_VMCPUID, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
4155 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
4156 if (RT_SUCCESS(rc))
4157 {
4158 pChunk->pv = Req.pvR3;
4159
4160 /*
4161 * If we're running out of virtual address space, then we should
4162 * unmap another chunk.
4163 *
4164 * Currently, an unmap operation requires that all other virtual CPUs
4165 * are idling and not by chance making use of the memory we're
4166 * unmapping. So, we create an async unmap operation here.
4167 *
4168 * Now, when creating or restoring a saved state this wont work very
4169 * well since we may want to restore all guest RAM + a little something.
4170 * So, we have to do the unmap synchronously. Fortunately for us
4171 * though, during these operations the other virtual CPUs are inactive
4172 * and it should be safe to do this.
4173 */
4174 /** @todo Eventually we should lock all memory when used and do
4175 * map+unmap as one kernel call without any rendezvous or
4176 * other precautions. */
4177 if (pVM->pgm.s.ChunkR3Map.c + 1 >= pVM->pgm.s.ChunkR3Map.cMax)
4178 {
4179 switch (VMR3GetState(pVM))
4180 {
4181 case VMSTATE_LOADING:
4182 case VMSTATE_SAVING:
4183 {
4184 PVMCPU pVCpu = VMMGetCpu(pVM);
4185 if ( pVCpu
4186 && pVM->pgm.s.cDeprecatedPageLocks == 0)
4187 {
4188 pgmR3PhysUnmapChunkRendezvous(pVM, pVCpu, NULL);
4189 break;
4190 }
4191 /* fall thru */
4192 }
4193 default:
4194 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysUnmapChunk, 1, pVM);
4195 AssertRC(rc);
4196 break;
4197 }
4198 }
4199
4200 /*
4201 * Update the tree. We must do this after any unmapping to make sure
4202 * the chunk we're going to return isn't unmapped by accident.
4203 */
4204 AssertPtr(Req.pvR3);
4205 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
4206 AssertRelease(fRc);
4207 pVM->pgm.s.ChunkR3Map.c++;
4208 pVM->pgm.s.cMappedChunks++;
4209 }
4210 else
4211 {
4212 /** @todo this may fail because of /proc/sys/vm/max_map_count, so we
4213 * should probably restrict ourselves on linux. */
4214 AssertRC(rc);
4215#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
4216 MMR3HeapFree(pChunk);
4217#else
4218 MMR3UkHeapFree(pVM, pChunk, MM_TAG_PGM_CHUNK_MAPPING);
4219#endif
4220 pChunk = NULL;
4221 }
4222
4223 *ppChunk = pChunk;
4224 return rc;
4225}
4226
4227
4228/**
4229 * For VMMCALLRING3_PGM_MAP_CHUNK, considered internal.
4230 *
4231 * @returns see pgmR3PhysChunkMap.
4232 * @param pVM Pointer to the VM.
4233 * @param idChunk The chunk to map.
4234 */
4235VMMR3DECL(int) PGMR3PhysChunkMap(PVM pVM, uint32_t idChunk)
4236{
4237 PPGMCHUNKR3MAP pChunk;
4238 int rc;
4239
4240 pgmLock(pVM);
4241 rc = pgmR3PhysChunkMap(pVM, idChunk, &pChunk);
4242 pgmUnlock(pVM);
4243 return rc;
4244}
4245
4246
4247/**
4248 * Invalidates the TLB for the ring-3 mapping cache.
4249 *
4250 * @param pVM Pointer to the VM.
4251 */
4252VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
4253{
4254 pgmLock(pVM);
4255 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
4256 {
4257 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
4258 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
4259 }
4260 /* The page map TLB references chunks, so invalidate that one too. */
4261 pgmPhysInvalidatePageMapTLB(pVM);
4262 pgmUnlock(pVM);
4263}
4264
4265
4266/**
4267 * Response to VMMCALLRING3_PGM_ALLOCATE_LARGE_HANDY_PAGE to allocate a large
4268 * (2MB) page for use with a nested paging PDE.
4269 *
4270 * @returns The following VBox status codes.
4271 * @retval VINF_SUCCESS on success.
4272 * @retval VINF_EM_NO_MEMORY if we're out of memory.
4273 *
4274 * @param pVM Pointer to the VM.
4275 * @param GCPhys GC physical start address of the 2 MB range
4276 */
4277VMMR3DECL(int) PGMR3PhysAllocateLargeHandyPage(PVM pVM, RTGCPHYS GCPhys)
4278{
4279#ifdef PGM_WITH_LARGE_PAGES
4280 uint64_t u64TimeStamp1, u64TimeStamp2;
4281
4282 pgmLock(pVM);
4283
4284 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
4285 u64TimeStamp1 = RTTimeMilliTS();
4286 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_LARGE_HANDY_PAGE, 0, NULL);
4287 u64TimeStamp2 = RTTimeMilliTS();
4288 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
4289 if (RT_SUCCESS(rc))
4290 {
4291 Assert(pVM->pgm.s.cLargeHandyPages == 1);
4292
4293 uint32_t idPage = pVM->pgm.s.aLargeHandyPage[0].idPage;
4294 RTHCPHYS HCPhys = pVM->pgm.s.aLargeHandyPage[0].HCPhysGCPhys;
4295
4296 void *pv;
4297
4298 /* Map the large page into our address space.
4299 *
4300 * Note: assuming that within the 2 MB range:
4301 * - GCPhys + PAGE_SIZE = HCPhys + PAGE_SIZE (whole point of this exercise)
4302 * - user space mapping is continuous as well
4303 * - page id (GCPhys) + 1 = page id (GCPhys + PAGE_SIZE)
4304 */
4305 rc = pgmPhysPageMapByPageID(pVM, idPage, HCPhys, &pv);
4306 AssertLogRelMsg(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n", idPage, HCPhys, rc));
4307
4308 if (RT_SUCCESS(rc))
4309 {
4310 /*
4311 * Clear the pages.
4312 */
4313 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
4314 for (unsigned i = 0; i < _2M/PAGE_SIZE; i++)
4315 {
4316 ASMMemZeroPage(pv);
4317
4318 PPGMPAGE pPage;
4319 rc = pgmPhysGetPageEx(pVM, GCPhys, &pPage);
4320 AssertRC(rc);
4321
4322 Assert(PGM_PAGE_IS_ZERO(pPage));
4323 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatRZPageReplaceZero);
4324 pVM->pgm.s.cZeroPages--;
4325
4326 /*
4327 * Do the PGMPAGE modifications.
4328 */
4329 pVM->pgm.s.cPrivatePages++;
4330 PGM_PAGE_SET_HCPHYS(pVM, pPage, HCPhys);
4331 PGM_PAGE_SET_PAGEID(pVM, pPage, idPage);
4332 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ALLOCATED);
4333 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_PDE);
4334 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
4335 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
4336
4337 /* Somewhat dirty assumption that page ids are increasing. */
4338 idPage++;
4339
4340 HCPhys += PAGE_SIZE;
4341 GCPhys += PAGE_SIZE;
4342
4343 pv = (void *)((uintptr_t)pv + PAGE_SIZE);
4344
4345 Log3(("PGMR3PhysAllocateLargePage: idPage=%#x HCPhys=%RGp\n", idPage, HCPhys));
4346 }
4347 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
4348
4349 /* Flush all TLBs. */
4350 PGM_INVL_ALL_VCPU_TLBS(pVM);
4351 pgmPhysInvalidatePageMapTLB(pVM);
4352 }
4353 pVM->pgm.s.cLargeHandyPages = 0;
4354 }
4355
4356 if (RT_SUCCESS(rc))
4357 {
4358 static uint32_t cTimeOut = 0;
4359 uint64_t u64TimeStampDelta = u64TimeStamp2 - u64TimeStamp1;
4360
4361 if (u64TimeStampDelta > 100)
4362 {
4363 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatLargePageOverflow);
4364 if ( ++cTimeOut > 10
4365 || u64TimeStampDelta > 1000 /* more than one second forces an early retirement from allocating large pages. */)
4366 {
4367 /* If repeated attempts to allocate a large page takes more than 100 ms, then we fall back to normal 4k pages.
4368 * E.g. Vista 64 tries to move memory around, which takes a huge amount of time.
4369 */
4370 LogRel(("PGMR3PhysAllocateLargePage: allocating large pages takes too long (last attempt %d ms; nr of timeouts %d); DISABLE\n", u64TimeStampDelta, cTimeOut));
4371 PGMSetLargePageUsage(pVM, false);
4372 }
4373 }
4374 else
4375 if (cTimeOut > 0)
4376 cTimeOut--;
4377 }
4378
4379 pgmUnlock(pVM);
4380 return rc;
4381#else
4382 return VERR_NOT_IMPLEMENTED;
4383#endif /* PGM_WITH_LARGE_PAGES */
4384}
4385
4386
4387/**
4388 * Response to VM_FF_PGM_NEED_HANDY_PAGES and VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES.
4389 *
4390 * This function will also work the VM_FF_PGM_NO_MEMORY force action flag, to
4391 * signal and clear the out of memory condition. When contracted, this API is
4392 * used to try clear the condition when the user wants to resume.
4393 *
4394 * @returns The following VBox status codes.
4395 * @retval VINF_SUCCESS on success. FFs cleared.
4396 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in
4397 * this case and it gets accompanied by VM_FF_PGM_NO_MEMORY.
4398 *
4399 * @param pVM Pointer to the VM.
4400 *
4401 * @remarks The VINF_EM_NO_MEMORY status is for the benefit of the FF processing
4402 * in EM.cpp and shouldn't be propagated outside TRPM, HM, EM and
4403 * pgmPhysEnsureHandyPage. There is one exception to this in the \#PF
4404 * handler.
4405 */
4406VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
4407{
4408 pgmLock(pVM);
4409
4410 /*
4411 * Allocate more pages, noting down the index of the first new page.
4412 */
4413 uint32_t iClear = pVM->pgm.s.cHandyPages;
4414 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_PGM_HANDY_PAGE_IPE);
4415 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
4416 int rcAlloc = VINF_SUCCESS;
4417 int rcSeed = VINF_SUCCESS;
4418 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
4419 while (rc == VERR_GMM_SEED_ME)
4420 {
4421 void *pvChunk;
4422 rcAlloc = rc = SUPR3PageAlloc(GMM_CHUNK_SIZE >> PAGE_SHIFT, &pvChunk);
4423 if (RT_SUCCESS(rc))
4424 {
4425 rcSeed = rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_SEED_CHUNK, (uintptr_t)pvChunk, NULL);
4426 if (RT_FAILURE(rc))
4427 SUPR3PageFree(pvChunk, GMM_CHUNK_SIZE >> PAGE_SHIFT);
4428 }
4429 if (RT_SUCCESS(rc))
4430 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
4431 }
4432
4433 /* todo: we should split this up into an allocate and flush operation. sometimes you want to flush and not allocate more (which will trigger the vm account limit error) */
4434 if ( rc == VERR_GMM_HIT_VM_ACCOUNT_LIMIT
4435 && pVM->pgm.s.cHandyPages > 0)
4436 {
4437 /* Still handy pages left, so don't panic. */
4438 rc = VINF_SUCCESS;
4439 }
4440
4441 if (RT_SUCCESS(rc))
4442 {
4443 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
4444 Assert(pVM->pgm.s.cHandyPages > 0);
4445 VM_FF_CLEAR(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
4446 VM_FF_CLEAR(pVM, VM_FF_PGM_NO_MEMORY);
4447
4448#ifdef VBOX_STRICT
4449 uint32_t i;
4450 for (i = iClear; i < pVM->pgm.s.cHandyPages; i++)
4451 if ( pVM->pgm.s.aHandyPages[i].idPage == NIL_GMM_PAGEID
4452 || pVM->pgm.s.aHandyPages[i].idSharedPage != NIL_GMM_PAGEID
4453 || (pVM->pgm.s.aHandyPages[i].HCPhysGCPhys & PAGE_OFFSET_MASK))
4454 break;
4455 if (i != pVM->pgm.s.cHandyPages)
4456 {
4457 RTAssertMsg1Weak(NULL, __LINE__, __FILE__, __FUNCTION__);
4458 RTAssertMsg2Weak("i=%d iClear=%d cHandyPages=%d\n", i, iClear, pVM->pgm.s.cHandyPages);
4459 for (uint32_t j = iClear; j < pVM->pgm.s.cHandyPages; j++)
4460 RTAssertMsg2Add(("%03d: idPage=%d HCPhysGCPhys=%RHp idSharedPage=%d%\n", j,
4461 pVM->pgm.s.aHandyPages[j].idPage,
4462 pVM->pgm.s.aHandyPages[j].HCPhysGCPhys,
4463 pVM->pgm.s.aHandyPages[j].idSharedPage,
4464 j == i ? " <---" : ""));
4465 RTAssertPanic();
4466 }
4467#endif
4468 /*
4469 * Clear the pages.
4470 */
4471 while (iClear < pVM->pgm.s.cHandyPages)
4472 {
4473 PGMMPAGEDESC pPage = &pVM->pgm.s.aHandyPages[iClear];
4474 void *pv;
4475 rc = pgmPhysPageMapByPageID(pVM, pPage->idPage, pPage->HCPhysGCPhys, &pv);
4476 AssertLogRelMsgBreak(RT_SUCCESS(rc),
4477 ("%u/%u: idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n",
4478 iClear, pVM->pgm.s.cHandyPages, pPage->idPage, pPage->HCPhysGCPhys, rc));
4479 ASMMemZeroPage(pv);
4480 iClear++;
4481 Log3(("PGMR3PhysAllocateHandyPages: idPage=%#x HCPhys=%RGp\n", pPage->idPage, pPage->HCPhysGCPhys));
4482 }
4483 }
4484 else
4485 {
4486 uint64_t cAllocPages, cMaxPages, cBalloonPages;
4487
4488 /*
4489 * We should never get here unless there is a genuine shortage of
4490 * memory (or some internal error). Flag the error so the VM can be
4491 * suspended ASAP and the user informed. If we're totally out of
4492 * handy pages we will return failure.
4493 */
4494 /* Report the failure. */
4495 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc rcAlloc=%Rrc rcSeed=%Rrc cHandyPages=%#x\n"
4496 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
4497 rc, rcAlloc, rcSeed,
4498 pVM->pgm.s.cHandyPages,
4499 pVM->pgm.s.cAllPages,
4500 pVM->pgm.s.cPrivatePages,
4501 pVM->pgm.s.cSharedPages,
4502 pVM->pgm.s.cZeroPages));
4503
4504 if (GMMR3QueryMemoryStats(pVM, &cAllocPages, &cMaxPages, &cBalloonPages) == VINF_SUCCESS)
4505 {
4506 LogRel(("GMM: Statistics:\n"
4507 " Allocated pages: %RX64\n"
4508 " Maximum pages: %RX64\n"
4509 " Ballooned pages: %RX64\n", cAllocPages, cMaxPages, cBalloonPages));
4510 }
4511
4512 if ( rc != VERR_NO_MEMORY
4513 && rc != VERR_NO_PHYS_MEMORY
4514 && rc != VERR_LOCK_FAILED)
4515 {
4516 for (uint32_t i = 0; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
4517 {
4518 LogRel(("PGM: aHandyPages[#%#04x] = {.HCPhysGCPhys=%RHp, .idPage=%#08x, .idSharedPage=%#08x}\n",
4519 i, pVM->pgm.s.aHandyPages[i].HCPhysGCPhys, pVM->pgm.s.aHandyPages[i].idPage,
4520 pVM->pgm.s.aHandyPages[i].idSharedPage));
4521 uint32_t const idPage = pVM->pgm.s.aHandyPages[i].idPage;
4522 if (idPage != NIL_GMM_PAGEID)
4523 {
4524 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
4525 pRam;
4526 pRam = pRam->pNextR3)
4527 {
4528 uint32_t const cPages = pRam->cb >> PAGE_SHIFT;
4529 for (uint32_t iPage = 0; iPage < cPages; iPage++)
4530 if (PGM_PAGE_GET_PAGEID(&pRam->aPages[iPage]) == idPage)
4531 LogRel(("PGM: Used by %RGp %R[pgmpage] (%s)\n",
4532 pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pRam->aPages[iPage], pRam->pszDesc));
4533 }
4534 }
4535 }
4536 }
4537
4538 /* Set the FFs and adjust rc. */
4539 VM_FF_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
4540 VM_FF_SET(pVM, VM_FF_PGM_NO_MEMORY);
4541 if ( rc == VERR_NO_MEMORY
4542 || rc == VERR_NO_PHYS_MEMORY
4543 || rc == VERR_LOCK_FAILED)
4544 rc = VINF_EM_NO_MEMORY;
4545 }
4546
4547 pgmUnlock(pVM);
4548 return rc;
4549}
4550
4551
4552/**
4553 * Frees the specified RAM page and replaces it with the ZERO page.
4554 *
4555 * This is used by ballooning, remapping MMIO2, RAM reset and state loading.
4556 *
4557 * @param pVM Pointer to the VM.
4558 * @param pReq Pointer to the request.
4559 * @param pcPendingPages Where the number of pages waiting to be freed are
4560 * kept. This will normally be incremented.
4561 * @param pPage Pointer to the page structure.
4562 * @param GCPhys The guest physical address of the page, if applicable.
4563 *
4564 * @remarks The caller must own the PGM lock.
4565 */
4566int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys)
4567{
4568 /*
4569 * Assert sanity.
4570 */
4571 PGM_LOCK_ASSERT_OWNER(pVM);
4572 if (RT_UNLIKELY( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM
4573 && PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_ROM_SHADOW))
4574 {
4575 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
4576 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
4577 }
4578
4579 /** @todo What about ballooning of large pages??! */
4580 Assert( PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE
4581 && PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE_DISABLED);
4582
4583 if ( PGM_PAGE_IS_ZERO(pPage)
4584 || PGM_PAGE_IS_BALLOONED(pPage))
4585 return VINF_SUCCESS;
4586
4587 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
4588 Log3(("pgmPhysFreePage: idPage=%#x GCPhys=%RGp pPage=%R[pgmpage]\n", idPage, GCPhys, pPage));
4589 if (RT_UNLIKELY( idPage == NIL_GMM_PAGEID
4590 || idPage > GMM_PAGEID_LAST
4591 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID))
4592 {
4593 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
4594 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
4595 }
4596
4597 /* update page count stats. */
4598 if (PGM_PAGE_IS_SHARED(pPage))
4599 pVM->pgm.s.cSharedPages--;
4600 else
4601 pVM->pgm.s.cPrivatePages--;
4602 pVM->pgm.s.cZeroPages++;
4603
4604 /* Deal with write monitored pages. */
4605 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
4606 {
4607 PGM_PAGE_SET_WRITTEN_TO(pVM, pPage);
4608 pVM->pgm.s.cWrittenToPages++;
4609 }
4610
4611 /*
4612 * pPage = ZERO page.
4613 */
4614 PGM_PAGE_SET_HCPHYS(pVM, pPage, pVM->pgm.s.HCPhysZeroPg);
4615 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
4616 PGM_PAGE_SET_PAGEID(pVM, pPage, NIL_GMM_PAGEID);
4617 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4618 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
4619 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
4620
4621 /* Flush physical page map TLB entry. */
4622 pgmPhysInvalidatePageMapTLBEntry(pVM, GCPhys);
4623
4624 /*
4625 * Make sure it's not in the handy page array.
4626 */
4627 for (uint32_t i = pVM->pgm.s.cHandyPages; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
4628 {
4629 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
4630 {
4631 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
4632 break;
4633 }
4634 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
4635 {
4636 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
4637 break;
4638 }
4639 }
4640
4641 /*
4642 * Push it onto the page array.
4643 */
4644 uint32_t iPage = *pcPendingPages;
4645 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
4646 *pcPendingPages += 1;
4647
4648 pReq->aPages[iPage].idPage = idPage;
4649
4650 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
4651 return VINF_SUCCESS;
4652
4653 /*
4654 * Flush the pages.
4655 */
4656 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
4657 if (RT_SUCCESS(rc))
4658 {
4659 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
4660 *pcPendingPages = 0;
4661 }
4662 return rc;
4663}
4664
4665
4666/**
4667 * Converts a GC physical address to a HC ring-3 pointer, with some
4668 * additional checks.
4669 *
4670 * @returns VBox status code.
4671 * @retval VINF_SUCCESS on success.
4672 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
4673 * access handler of some kind.
4674 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
4675 * accesses or is odd in any way.
4676 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
4677 *
4678 * @param pVM Pointer to the VM.
4679 * @param GCPhys The GC physical address to convert. Since this is only
4680 * used for filling the REM TLB, the A20 mask must be
4681 * applied before calling this API.
4682 * @param fWritable Whether write access is required.
4683 * @param ppv Where to store the pointer corresponding to GCPhys on
4684 * success.
4685 */
4686VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
4687{
4688 pgmLock(pVM);
4689 PGM_A20_ASSERT_MASKED(VMMGetCpu(pVM), GCPhys);
4690
4691 PPGMRAMRANGE pRam;
4692 PPGMPAGE pPage;
4693 int rc = pgmPhysGetPageAndRangeEx(pVM, GCPhys, &pPage, &pRam);
4694 if (RT_SUCCESS(rc))
4695 {
4696 if (PGM_PAGE_IS_BALLOONED(pPage))
4697 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4698 else if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
4699 rc = VINF_SUCCESS;
4700 else
4701 {
4702 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
4703 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
4704 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
4705 {
4706 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
4707 * in -norawr0 mode. */
4708 if (fWritable)
4709 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4710 }
4711 else
4712 {
4713 /* Temporarily disabled physical handler(s), since the recompiler
4714 doesn't get notified when it's reset we'll have to pretend it's
4715 operating normally. */
4716 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
4717 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
4718 else
4719 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4720 }
4721 }
4722 if (RT_SUCCESS(rc))
4723 {
4724 int rc2;
4725
4726 /* Make sure what we return is writable. */
4727 if (fWritable)
4728 switch (PGM_PAGE_GET_STATE(pPage))
4729 {
4730 case PGM_PAGE_STATE_ALLOCATED:
4731 break;
4732 case PGM_PAGE_STATE_BALLOONED:
4733 AssertFailed();
4734 break;
4735 case PGM_PAGE_STATE_ZERO:
4736 case PGM_PAGE_STATE_SHARED:
4737 if (rc == VINF_PGM_PHYS_TLB_CATCH_WRITE)
4738 break;
4739 case PGM_PAGE_STATE_WRITE_MONITORED:
4740 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)PAGE_OFFSET_MASK);
4741 AssertLogRelRCReturn(rc2, rc2);
4742 break;
4743 }
4744
4745 /* Get a ring-3 mapping of the address. */
4746 PPGMPAGER3MAPTLBE pTlbe;
4747 rc2 = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
4748 AssertLogRelRCReturn(rc2, rc2);
4749 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
4750 /** @todo mapping/locking hell; this isn't horribly efficient since
4751 * pgmPhysPageLoadIntoTlb will repeat the lookup we've done here. */
4752
4753 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
4754 }
4755 else
4756 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
4757
4758 /* else: handler catching all access, no pointer returned. */
4759 }
4760 else
4761 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
4762
4763 pgmUnlock(pVM);
4764 return rc;
4765}
4766
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