VirtualBox

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

Last change on this file since 45618 was 45618, checked in by vboxsync, 12 years ago

Do HMR3Init first in vmR3InitRing3 so the other components can skip raw-mode bits during init.

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