VirtualBox

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

Last change on this file since 79345 was 78043, checked in by vboxsync, 6 years ago

pgmR3PhysMMIOExCreate: fixed mem leak.

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