VirtualBox

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

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

VMM,REM: Kicking out raw-mode. bugref:9517

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 210.3 KB
Line 
1/* $Id: PGMPhys.cpp 80161 2019-08-06 18:10:51Z 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 PGM_PAGE_CLEAR_WRITTEN_TO(pVM, pPage);
1459
1460 pgmPhysPageWriteMonitor(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1461 break;
1462
1463 case PGM_PAGE_STATE_SHARED:
1464 AssertFailed();
1465 break;
1466
1467 case PGM_PAGE_STATE_WRITE_MONITORED: /* nothing to change. */
1468 default:
1469 break;
1470 }
1471 }
1472 }
1473 }
1474 pgmR3PoolWriteProtectPages(pVM);
1475 PGM_INVL_ALL_VCPU_TLBS(pVM);
1476 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1477 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
1478
1479 pgmUnlock(pVM);
1480 return rc;
1481}
1482
1483/**
1484 * Protect all physical RAM to monitor writes
1485 *
1486 * @returns VBox status code.
1487 * @param pVM The cross context VM structure.
1488 */
1489VMMR3DECL(int) PGMR3PhysWriteProtectRAM(PVM pVM)
1490{
1491 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1492
1493 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysWriteProtectRAMRendezvous, NULL);
1494 AssertRC(rc);
1495 return rc;
1496}
1497
1498
1499/**
1500 * Gets the number of ram ranges.
1501 *
1502 * @returns Number of ram ranges. Returns UINT32_MAX if @a pVM is invalid.
1503 * @param pVM The cross context VM structure.
1504 */
1505VMMR3DECL(uint32_t) PGMR3PhysGetRamRangeCount(PVM pVM)
1506{
1507 VM_ASSERT_VALID_EXT_RETURN(pVM, UINT32_MAX);
1508
1509 pgmLock(pVM);
1510 uint32_t cRamRanges = 0;
1511 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRangesX); pCur; pCur = pCur->CTX_SUFF(pNext))
1512 cRamRanges++;
1513 pgmUnlock(pVM);
1514 return cRamRanges;
1515}
1516
1517
1518/**
1519 * Get information about a range.
1520 *
1521 * @returns VINF_SUCCESS or VERR_OUT_OF_RANGE.
1522 * @param pVM The cross context VM structure.
1523 * @param iRange The ordinal of the range.
1524 * @param pGCPhysStart Where to return the start of the range. Optional.
1525 * @param pGCPhysLast Where to return the address of the last byte in the
1526 * range. Optional.
1527 * @param ppszDesc Where to return the range description. Optional.
1528 * @param pfIsMmio Where to indicate that this is a pure MMIO range.
1529 * Optional.
1530 */
1531VMMR3DECL(int) PGMR3PhysGetRange(PVM pVM, uint32_t iRange, PRTGCPHYS pGCPhysStart, PRTGCPHYS pGCPhysLast,
1532 const char **ppszDesc, bool *pfIsMmio)
1533{
1534 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1535
1536 pgmLock(pVM);
1537 uint32_t iCurRange = 0;
1538 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRangesX); pCur; pCur = pCur->CTX_SUFF(pNext), iCurRange++)
1539 if (iCurRange == iRange)
1540 {
1541 if (pGCPhysStart)
1542 *pGCPhysStart = pCur->GCPhys;
1543 if (pGCPhysLast)
1544 *pGCPhysLast = pCur->GCPhysLast;
1545 if (ppszDesc)
1546 *ppszDesc = pCur->pszDesc;
1547 if (pfIsMmio)
1548 *pfIsMmio = !!(pCur->fFlags & PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO);
1549
1550 pgmUnlock(pVM);
1551 return VINF_SUCCESS;
1552 }
1553 pgmUnlock(pVM);
1554 return VERR_OUT_OF_RANGE;
1555}
1556
1557
1558/**
1559 * Query the amount of free memory inside VMMR0
1560 *
1561 * @returns VBox status code.
1562 * @param pUVM The user mode VM handle.
1563 * @param pcbAllocMem Where to return the amount of memory allocated
1564 * by VMs.
1565 * @param pcbFreeMem Where to return the amount of memory that is
1566 * allocated from the host but not currently used
1567 * by any VMs.
1568 * @param pcbBallonedMem Where to return the sum of memory that is
1569 * currently ballooned by the VMs.
1570 * @param pcbSharedMem Where to return the amount of memory that is
1571 * currently shared.
1572 */
1573VMMR3DECL(int) PGMR3QueryGlobalMemoryStats(PUVM pUVM, uint64_t *pcbAllocMem, uint64_t *pcbFreeMem,
1574 uint64_t *pcbBallonedMem, uint64_t *pcbSharedMem)
1575{
1576 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
1577 VM_ASSERT_VALID_EXT_RETURN(pUVM->pVM, VERR_INVALID_VM_HANDLE);
1578
1579 uint64_t cAllocPages = 0;
1580 uint64_t cFreePages = 0;
1581 uint64_t cBalloonPages = 0;
1582 uint64_t cSharedPages = 0;
1583 int rc = GMMR3QueryHypervisorMemoryStats(pUVM->pVM, &cAllocPages, &cFreePages, &cBalloonPages, &cSharedPages);
1584 AssertRCReturn(rc, rc);
1585
1586 if (pcbAllocMem)
1587 *pcbAllocMem = cAllocPages * _4K;
1588
1589 if (pcbFreeMem)
1590 *pcbFreeMem = cFreePages * _4K;
1591
1592 if (pcbBallonedMem)
1593 *pcbBallonedMem = cBalloonPages * _4K;
1594
1595 if (pcbSharedMem)
1596 *pcbSharedMem = cSharedPages * _4K;
1597
1598 Log(("PGMR3QueryVMMMemoryStats: all=%llx free=%llx ballooned=%llx shared=%llx\n",
1599 cAllocPages, cFreePages, cBalloonPages, cSharedPages));
1600 return VINF_SUCCESS;
1601}
1602
1603
1604/**
1605 * Query memory stats for the VM.
1606 *
1607 * @returns VBox status code.
1608 * @param pUVM The user mode VM handle.
1609 * @param pcbTotalMem Where to return total amount memory the VM may
1610 * possibly use.
1611 * @param pcbPrivateMem Where to return the amount of private memory
1612 * currently allocated.
1613 * @param pcbSharedMem Where to return the amount of actually shared
1614 * memory currently used by the VM.
1615 * @param pcbZeroMem Where to return the amount of memory backed by
1616 * zero pages.
1617 *
1618 * @remarks The total mem is normally larger than the sum of the three
1619 * components. There are two reasons for this, first the amount of
1620 * shared memory is what we're sure is shared instead of what could
1621 * possibly be shared with someone. Secondly, because the total may
1622 * include some pure MMIO pages that doesn't go into any of the three
1623 * sub-counts.
1624 *
1625 * @todo Why do we return reused shared pages instead of anything that could
1626 * potentially be shared? Doesn't this mean the first VM gets a much
1627 * lower number of shared pages?
1628 */
1629VMMR3DECL(int) PGMR3QueryMemoryStats(PUVM pUVM, uint64_t *pcbTotalMem, uint64_t *pcbPrivateMem,
1630 uint64_t *pcbSharedMem, uint64_t *pcbZeroMem)
1631{
1632 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
1633 PVM pVM = pUVM->pVM;
1634 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1635
1636 if (pcbTotalMem)
1637 *pcbTotalMem = (uint64_t)pVM->pgm.s.cAllPages * PAGE_SIZE;
1638
1639 if (pcbPrivateMem)
1640 *pcbPrivateMem = (uint64_t)pVM->pgm.s.cPrivatePages * PAGE_SIZE;
1641
1642 if (pcbSharedMem)
1643 *pcbSharedMem = (uint64_t)pVM->pgm.s.cReusedSharedPages * PAGE_SIZE;
1644
1645 if (pcbZeroMem)
1646 *pcbZeroMem = (uint64_t)pVM->pgm.s.cZeroPages * PAGE_SIZE;
1647
1648 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));
1649 return VINF_SUCCESS;
1650}
1651
1652
1653/**
1654 * PGMR3PhysRegisterRam worker that initializes and links a RAM range.
1655 *
1656 * @param pVM The cross context VM structure.
1657 * @param pNew The new RAM range.
1658 * @param GCPhys The address of the RAM range.
1659 * @param GCPhysLast The last address of the RAM range.
1660 * @param RCPtrNew The RC address if the range is floating. NIL_RTRCPTR
1661 * if in HMA.
1662 * @param R0PtrNew Ditto for R0.
1663 * @param pszDesc The description.
1664 * @param pPrev The previous RAM range (for linking).
1665 */
1666static void pgmR3PhysInitAndLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast,
1667 RTRCPTR RCPtrNew, RTR0PTR R0PtrNew, const char *pszDesc, PPGMRAMRANGE pPrev)
1668{
1669 /*
1670 * Initialize the range.
1671 */
1672 pNew->pSelfR0 = R0PtrNew != NIL_RTR0PTR ? R0PtrNew : MMHyperCCToR0(pVM, pNew);
1673 pNew->pSelfRC = RCPtrNew != NIL_RTRCPTR ? RCPtrNew : MMHyperCCToRC(pVM, pNew);
1674 pNew->GCPhys = GCPhys;
1675 pNew->GCPhysLast = GCPhysLast;
1676 pNew->cb = GCPhysLast - GCPhys + 1;
1677 pNew->pszDesc = pszDesc;
1678 pNew->fFlags = RCPtrNew != NIL_RTRCPTR ? PGM_RAM_RANGE_FLAGS_FLOATING : 0;
1679 pNew->pvR3 = NULL;
1680 pNew->paLSPages = NULL;
1681
1682 uint32_t const cPages = pNew->cb >> PAGE_SHIFT;
1683 RTGCPHYS iPage = cPages;
1684 while (iPage-- > 0)
1685 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_RAM);
1686
1687 /* Update the page count stats. */
1688 pVM->pgm.s.cZeroPages += cPages;
1689 pVM->pgm.s.cAllPages += cPages;
1690
1691 /*
1692 * Link it.
1693 */
1694 pgmR3PhysLinkRamRange(pVM, pNew, pPrev);
1695}
1696
1697
1698#ifndef PGM_WITHOUT_MAPPINGS
1699/**
1700 * @callback_method_impl{FNPGMRELOCATE, Relocate a floating RAM range.}
1701 * @sa pgmR3PhysMMIO2ExRangeRelocate
1702 */
1703static DECLCALLBACK(bool) pgmR3PhysRamRangeRelocate(PVM pVM, RTGCPTR GCPtrOld, RTGCPTR GCPtrNew,
1704 PGMRELOCATECALL enmMode, void *pvUser)
1705{
1706 PPGMRAMRANGE pRam = (PPGMRAMRANGE)pvUser;
1707 Assert(pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING);
1708 Assert(pRam->pSelfRC == GCPtrOld + PAGE_SIZE); RT_NOREF_PV(GCPtrOld);
1709
1710 switch (enmMode)
1711 {
1712 case PGMRELOCATECALL_SUGGEST:
1713 return true;
1714
1715 case PGMRELOCATECALL_RELOCATE:
1716 {
1717 /*
1718 * Update myself, then relink all the ranges and flush the RC TLB.
1719 */
1720 pgmLock(pVM);
1721
1722 pRam->pSelfRC = (RTRCPTR)(GCPtrNew + PAGE_SIZE);
1723
1724 pgmR3PhysRelinkRamRanges(pVM);
1725 for (unsigned i = 0; i < PGM_RAMRANGE_TLB_ENTRIES; i++)
1726 pVM->pgm.s.apRamRangesTlbRC[i] = NIL_RTRCPTR;
1727
1728 pgmUnlock(pVM);
1729 return true;
1730 }
1731
1732 default:
1733 AssertFailedReturn(false);
1734 }
1735}
1736#endif /* !PGM_WITHOUT_MAPPINGS */
1737
1738
1739/**
1740 * PGMR3PhysRegisterRam worker that registers a high chunk.
1741 *
1742 * @returns VBox status code.
1743 * @param pVM The cross context VM structure.
1744 * @param GCPhys The address of the RAM.
1745 * @param cRamPages The number of RAM pages to register.
1746 * @param cbChunk The size of the PGMRAMRANGE guest mapping.
1747 * @param iChunk The chunk number.
1748 * @param pszDesc The RAM range description.
1749 * @param ppPrev Previous RAM range pointer. In/Out.
1750 */
1751static int pgmR3PhysRegisterHighRamChunk(PVM pVM, RTGCPHYS GCPhys, uint32_t cRamPages,
1752 uint32_t cbChunk, uint32_t iChunk, const char *pszDesc,
1753 PPGMRAMRANGE *ppPrev)
1754{
1755 const char *pszDescChunk = iChunk == 0
1756 ? pszDesc
1757 : MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s (#%u)", pszDesc, iChunk + 1);
1758 AssertReturn(pszDescChunk, VERR_NO_MEMORY);
1759
1760 /*
1761 * Allocate memory for the new chunk.
1762 */
1763 size_t const cChunkPages = RT_ALIGN_Z(RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cRamPages]), PAGE_SIZE) >> PAGE_SHIFT;
1764 PSUPPAGE paChunkPages = (PSUPPAGE)RTMemTmpAllocZ(sizeof(SUPPAGE) * cChunkPages);
1765 AssertReturn(paChunkPages, VERR_NO_TMP_MEMORY);
1766 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
1767 void *pvChunk = NULL;
1768 int rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk, &R0PtrChunk, paChunkPages);
1769 if (RT_SUCCESS(rc))
1770 {
1771 Assert(R0PtrChunk != NIL_RTR0PTR);
1772 memset(pvChunk, 0, cChunkPages << PAGE_SHIFT);
1773
1774 PPGMRAMRANGE pNew = (PPGMRAMRANGE)pvChunk;
1775
1776 /*
1777 * Create a mapping and map the pages into it.
1778 * We push these in below the HMA.
1779 */
1780 RTGCPTR GCPtrChunkMap = pVM->pgm.s.GCPtrPrevRamRangeMapping - cbChunk;
1781#ifndef PGM_WITHOUT_MAPPINGS
1782 rc = PGMR3MapPT(pVM, GCPtrChunkMap, cbChunk, 0 /*fFlags*/, pgmR3PhysRamRangeRelocate, pNew, pszDescChunk);
1783 if (RT_SUCCESS(rc))
1784#endif /* !PGM_WITHOUT_MAPPINGS */
1785 {
1786 pVM->pgm.s.GCPtrPrevRamRangeMapping = GCPtrChunkMap;
1787
1788 RTGCPTR const GCPtrChunk = GCPtrChunkMap + PAGE_SIZE;
1789#ifndef PGM_WITHOUT_MAPPINGS
1790 RTGCPTR GCPtrPage = GCPtrChunk;
1791 for (uint32_t iPage = 0; iPage < cChunkPages && RT_SUCCESS(rc); iPage++, GCPtrPage += PAGE_SIZE)
1792 rc = PGMMap(pVM, GCPtrPage, paChunkPages[iPage].Phys, PAGE_SIZE, 0);
1793 if (RT_SUCCESS(rc))
1794#endif /* !PGM_WITHOUT_MAPPINGS */
1795 {
1796 /*
1797 * Ok, init and link the range.
1798 */
1799 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhys + ((RTGCPHYS)cRamPages << PAGE_SHIFT) - 1,
1800 (RTRCPTR)GCPtrChunk, R0PtrChunk, pszDescChunk, *ppPrev);
1801 *ppPrev = pNew;
1802 }
1803 }
1804
1805 if (RT_FAILURE(rc))
1806 SUPR3PageFreeEx(pvChunk, cChunkPages);
1807 }
1808
1809 RTMemTmpFree(paChunkPages);
1810 return rc;
1811}
1812
1813
1814/**
1815 * Sets up a range RAM.
1816 *
1817 * This will check for conflicting registrations, make a resource
1818 * reservation for the memory (with GMM), and setup the per-page
1819 * tracking structures (PGMPAGE).
1820 *
1821 * @returns VBox status code.
1822 * @param pVM The cross context VM structure.
1823 * @param GCPhys The physical address of the RAM.
1824 * @param cb The size of the RAM.
1825 * @param pszDesc The description - not copied, so, don't free or change it.
1826 */
1827VMMR3DECL(int) PGMR3PhysRegisterRam(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, const char *pszDesc)
1828{
1829 /*
1830 * Validate input.
1831 */
1832 Log(("PGMR3PhysRegisterRam: GCPhys=%RGp cb=%RGp pszDesc=%s\n", GCPhys, cb, pszDesc));
1833 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
1834 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
1835 AssertReturn(cb > 0, VERR_INVALID_PARAMETER);
1836 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1837 AssertMsgReturn(GCPhysLast > GCPhys, ("The range wraps! GCPhys=%RGp cb=%RGp\n", GCPhys, cb), VERR_INVALID_PARAMETER);
1838 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1839 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1840
1841 pgmLock(pVM);
1842
1843 /*
1844 * Find range location and check for conflicts.
1845 * (We don't lock here because the locking by EMT is only required on update.)
1846 */
1847 PPGMRAMRANGE pPrev = NULL;
1848 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
1849 while (pRam && GCPhysLast >= pRam->GCPhys)
1850 {
1851 if ( GCPhysLast >= pRam->GCPhys
1852 && GCPhys <= pRam->GCPhysLast)
1853 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
1854 GCPhys, GCPhysLast, pszDesc,
1855 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1856 VERR_PGM_RAM_CONFLICT);
1857
1858 /* next */
1859 pPrev = pRam;
1860 pRam = pRam->pNextR3;
1861 }
1862
1863 /*
1864 * Register it with GMM (the API bitches).
1865 */
1866 const RTGCPHYS cPages = cb >> PAGE_SHIFT;
1867 int rc = MMR3IncreaseBaseReservation(pVM, cPages);
1868 if (RT_FAILURE(rc))
1869 {
1870 pgmUnlock(pVM);
1871 return rc;
1872 }
1873
1874 if ( GCPhys >= _4G
1875 && cPages > 256)
1876 {
1877 /*
1878 * The PGMRAMRANGE structures for the high memory can get very big.
1879 * In order to avoid SUPR3PageAllocEx allocation failures due to the
1880 * allocation size limit there and also to avoid being unable to find
1881 * guest mapping space for them, we split this memory up into 4MB in
1882 * (potential) raw-mode configs and 16MB chunks in forced AMD-V/VT-x
1883 * mode.
1884 *
1885 * The first and last page of each mapping are guard pages and marked
1886 * not-present. So, we've got 4186112 and 16769024 bytes available for
1887 * the PGMRAMRANGE structure.
1888 *
1889 * Note! The sizes used here will influence the saved state.
1890 */
1891 uint32_t cbChunk;
1892 uint32_t cPagesPerChunk;
1893 if (!VM_IS_RAW_MODE_ENABLED(pVM))
1894 {
1895 cbChunk = 16U*_1M;
1896 cPagesPerChunk = 1048048; /* max ~1048059 */
1897 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 1048048 < 16U*_1M - PAGE_SIZE * 2);
1898 }
1899 else
1900 {
1901 cbChunk = 4U*_1M;
1902 cPagesPerChunk = 261616; /* max ~261627 */
1903 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 261616 < 4U*_1M - PAGE_SIZE * 2);
1904 }
1905 AssertRelease(RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPagesPerChunk]) + PAGE_SIZE * 2 <= cbChunk);
1906
1907 RTGCPHYS cPagesLeft = cPages;
1908 RTGCPHYS GCPhysChunk = GCPhys;
1909 uint32_t iChunk = 0;
1910 while (cPagesLeft > 0)
1911 {
1912 uint32_t cPagesInChunk = cPagesLeft;
1913 if (cPagesInChunk > cPagesPerChunk)
1914 cPagesInChunk = cPagesPerChunk;
1915
1916 rc = pgmR3PhysRegisterHighRamChunk(pVM, GCPhysChunk, cPagesInChunk, cbChunk, iChunk, pszDesc, &pPrev);
1917 AssertRCReturn(rc, rc);
1918
1919 /* advance */
1920 GCPhysChunk += (RTGCPHYS)cPagesInChunk << PAGE_SHIFT;
1921 cPagesLeft -= cPagesInChunk;
1922 iChunk++;
1923 }
1924 }
1925 else
1926 {
1927 /*
1928 * Allocate, initialize and link the new RAM range.
1929 */
1930 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
1931 PPGMRAMRANGE pNew;
1932 rc = MMR3HyperAllocOnceNoRel(pVM, cbRamRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
1933 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
1934
1935 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhysLast, NIL_RTRCPTR, NIL_RTR0PTR, pszDesc, pPrev);
1936 }
1937 pgmPhysInvalidatePageMapTLB(pVM);
1938
1939 /*
1940 * Notify NEM while holding the lock (experimental) and REM without (like always).
1941 */
1942 rc = NEMR3NotifyPhysRamRegister(pVM, GCPhys, cb);
1943 pgmUnlock(pVM);
1944#ifdef VBOX_WITH_REM
1945 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_RAM);
1946#endif
1947 return rc;
1948}
1949
1950
1951/**
1952 * Worker called by PGMR3InitFinalize if we're configured to pre-allocate RAM.
1953 *
1954 * We do this late in the init process so that all the ROM and MMIO ranges have
1955 * been registered already and we don't go wasting memory on them.
1956 *
1957 * @returns VBox status code.
1958 *
1959 * @param pVM The cross context VM structure.
1960 */
1961int pgmR3PhysRamPreAllocate(PVM pVM)
1962{
1963 Assert(pVM->pgm.s.fRamPreAlloc);
1964 Log(("pgmR3PhysRamPreAllocate: enter\n"));
1965
1966 /*
1967 * Walk the RAM ranges and allocate all RAM pages, halt at
1968 * the first allocation error.
1969 */
1970 uint64_t cPages = 0;
1971 uint64_t NanoTS = RTTimeNanoTS();
1972 pgmLock(pVM);
1973 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1974 {
1975 PPGMPAGE pPage = &pRam->aPages[0];
1976 RTGCPHYS GCPhys = pRam->GCPhys;
1977 uint32_t cLeft = pRam->cb >> PAGE_SHIFT;
1978 while (cLeft-- > 0)
1979 {
1980 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM)
1981 {
1982 switch (PGM_PAGE_GET_STATE(pPage))
1983 {
1984 case PGM_PAGE_STATE_ZERO:
1985 {
1986 int rc = pgmPhysAllocPage(pVM, pPage, GCPhys);
1987 if (RT_FAILURE(rc))
1988 {
1989 LogRel(("PGM: RAM Pre-allocation failed at %RGp (in %s) with rc=%Rrc\n", GCPhys, pRam->pszDesc, rc));
1990 pgmUnlock(pVM);
1991 return rc;
1992 }
1993 cPages++;
1994 break;
1995 }
1996
1997 case PGM_PAGE_STATE_BALLOONED:
1998 case PGM_PAGE_STATE_ALLOCATED:
1999 case PGM_PAGE_STATE_WRITE_MONITORED:
2000 case PGM_PAGE_STATE_SHARED:
2001 /* nothing to do here. */
2002 break;
2003 }
2004 }
2005
2006 /* next */
2007 pPage++;
2008 GCPhys += PAGE_SIZE;
2009 }
2010 }
2011 pgmUnlock(pVM);
2012 NanoTS = RTTimeNanoTS() - NanoTS;
2013
2014 LogRel(("PGM: Pre-allocated %llu pages in %llu ms\n", cPages, NanoTS / 1000000));
2015 Log(("pgmR3PhysRamPreAllocate: returns VINF_SUCCESS\n"));
2016 return VINF_SUCCESS;
2017}
2018
2019
2020/**
2021 * Checks shared page checksums.
2022 *
2023 * @param pVM The cross context VM structure.
2024 */
2025void pgmR3PhysAssertSharedPageChecksums(PVM pVM)
2026{
2027#ifdef VBOX_STRICT
2028 pgmLock(pVM);
2029
2030 if (pVM->pgm.s.cSharedPages > 0)
2031 {
2032 /*
2033 * Walk the ram ranges.
2034 */
2035 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2036 {
2037 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
2038 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
2039
2040 while (iPage-- > 0)
2041 {
2042 PPGMPAGE pPage = &pRam->aPages[iPage];
2043 if (PGM_PAGE_IS_SHARED(pPage))
2044 {
2045 uint32_t u32Checksum = pPage->s.u2Unused0/* | ((uint32_t)pPage->s.u2Unused1 << 8)*/;
2046 if (!u32Checksum)
2047 {
2048 RTGCPHYS GCPhysPage = pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT);
2049 void const *pvPage;
2050 int rc = pgmPhysPageMapReadOnly(pVM, pPage, GCPhysPage, &pvPage);
2051 if (RT_SUCCESS(rc))
2052 {
2053 uint32_t u32Checksum2 = RTCrc32(pvPage, PAGE_SIZE);
2054# if 0
2055 AssertMsg((u32Checksum2 & /*UINT32_C(0x00000303)*/ 0x3) == u32Checksum, ("GCPhysPage=%RGp\n", GCPhysPage));
2056# else
2057 if ((u32Checksum2 & /*UINT32_C(0x00000303)*/ 0x3) == u32Checksum)
2058 LogFlow(("shpg %#x @ %RGp %#x [OK]\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
2059 else
2060 AssertMsgFailed(("shpg %#x @ %RGp %#x\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
2061# endif
2062 }
2063 else
2064 AssertRC(rc);
2065 }
2066 }
2067
2068 } /* for each page */
2069
2070 } /* for each ram range */
2071 }
2072
2073 pgmUnlock(pVM);
2074#endif /* VBOX_STRICT */
2075 NOREF(pVM);
2076}
2077
2078
2079/**
2080 * Resets the physical memory state.
2081 *
2082 * ASSUMES that the caller owns the PGM lock.
2083 *
2084 * @returns VBox status code.
2085 * @param pVM The cross context VM structure.
2086 */
2087int pgmR3PhysRamReset(PVM pVM)
2088{
2089 PGM_LOCK_ASSERT_OWNER(pVM);
2090
2091 /* Reset the memory balloon. */
2092 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
2093 AssertRC(rc);
2094
2095#ifdef VBOX_WITH_PAGE_SHARING
2096 /* Clear all registered shared modules. */
2097 pgmR3PhysAssertSharedPageChecksums(pVM);
2098 rc = GMMR3ResetSharedModules(pVM);
2099 AssertRC(rc);
2100#endif
2101 /* Reset counters. */
2102 pVM->pgm.s.cReusedSharedPages = 0;
2103 pVM->pgm.s.cBalloonedPages = 0;
2104
2105 return VINF_SUCCESS;
2106}
2107
2108
2109/**
2110 * Resets (zeros) the RAM after all devices and components have been reset.
2111 *
2112 * ASSUMES that the caller owns the PGM lock.
2113 *
2114 * @returns VBox status code.
2115 * @param pVM The cross context VM structure.
2116 */
2117int pgmR3PhysRamZeroAll(PVM pVM)
2118{
2119 PGM_LOCK_ASSERT_OWNER(pVM);
2120
2121 /*
2122 * We batch up pages that should be freed instead of calling GMM for
2123 * each and every one of them.
2124 */
2125 uint32_t cPendingPages = 0;
2126 PGMMFREEPAGESREQ pReq;
2127 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2128 AssertLogRelRCReturn(rc, rc);
2129
2130 /*
2131 * Walk the ram ranges.
2132 */
2133 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2134 {
2135 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
2136 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
2137
2138 if ( !pVM->pgm.s.fRamPreAlloc
2139 && pVM->pgm.s.fZeroRamPagesOnReset)
2140 {
2141 /* Replace all RAM pages by ZERO pages. */
2142 while (iPage-- > 0)
2143 {
2144 PPGMPAGE pPage = &pRam->aPages[iPage];
2145 switch (PGM_PAGE_GET_TYPE(pPage))
2146 {
2147 case PGMPAGETYPE_RAM:
2148 /* Do not replace pages part of a 2 MB continuous range
2149 with zero pages, but zero them instead. */
2150 if ( PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE
2151 || PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE_DISABLED)
2152 {
2153 void *pvPage;
2154 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
2155 AssertLogRelRCReturn(rc, rc);
2156 ASMMemZeroPage(pvPage);
2157 }
2158 else if (PGM_PAGE_IS_BALLOONED(pPage))
2159 {
2160 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
2161 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
2162 }
2163 else if (!PGM_PAGE_IS_ZERO(pPage))
2164 {
2165 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
2166 PGMPAGETYPE_RAM);
2167 AssertLogRelRCReturn(rc, rc);
2168 }
2169 break;
2170
2171 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2172 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
2173 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
2174 true /*fDoAccounting*/);
2175 break;
2176
2177 case PGMPAGETYPE_MMIO2:
2178 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
2179 case PGMPAGETYPE_ROM:
2180 case PGMPAGETYPE_MMIO:
2181 break;
2182 default:
2183 AssertFailed();
2184 }
2185 } /* for each page */
2186 }
2187 else
2188 {
2189 /* Zero the memory. */
2190 while (iPage-- > 0)
2191 {
2192 PPGMPAGE pPage = &pRam->aPages[iPage];
2193 switch (PGM_PAGE_GET_TYPE(pPage))
2194 {
2195 case PGMPAGETYPE_RAM:
2196 switch (PGM_PAGE_GET_STATE(pPage))
2197 {
2198 case PGM_PAGE_STATE_ZERO:
2199 break;
2200
2201 case PGM_PAGE_STATE_BALLOONED:
2202 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
2203 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
2204 break;
2205
2206 case PGM_PAGE_STATE_SHARED:
2207 case PGM_PAGE_STATE_WRITE_MONITORED:
2208 rc = pgmPhysPageMakeWritable(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
2209 AssertLogRelRCReturn(rc, rc);
2210 RT_FALL_THRU();
2211
2212 case PGM_PAGE_STATE_ALLOCATED:
2213 if (pVM->pgm.s.fZeroRamPagesOnReset)
2214 {
2215 void *pvPage;
2216 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
2217 AssertLogRelRCReturn(rc, rc);
2218 ASMMemZeroPage(pvPage);
2219 }
2220 break;
2221 }
2222 break;
2223
2224 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2225 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
2226 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
2227 true /*fDoAccounting*/);
2228 break;
2229
2230 case PGMPAGETYPE_MMIO2:
2231 case PGMPAGETYPE_ROM_SHADOW:
2232 case PGMPAGETYPE_ROM:
2233 case PGMPAGETYPE_MMIO:
2234 break;
2235 default:
2236 AssertFailed();
2237
2238 }
2239 } /* for each page */
2240 }
2241
2242 }
2243
2244 /*
2245 * Finish off any pages pending freeing.
2246 */
2247 if (cPendingPages)
2248 {
2249 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2250 AssertLogRelRCReturn(rc, rc);
2251 }
2252 GMMR3FreePagesCleanup(pReq);
2253 return VINF_SUCCESS;
2254}
2255
2256
2257/**
2258 * Frees all RAM during VM termination
2259 *
2260 * ASSUMES that the caller owns the PGM lock.
2261 *
2262 * @returns VBox status code.
2263 * @param pVM The cross context VM structure.
2264 */
2265int pgmR3PhysRamTerm(PVM pVM)
2266{
2267 PGM_LOCK_ASSERT_OWNER(pVM);
2268
2269 /* Reset the memory balloon. */
2270 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
2271 AssertRC(rc);
2272
2273#ifdef VBOX_WITH_PAGE_SHARING
2274 /*
2275 * Clear all registered shared modules.
2276 */
2277 pgmR3PhysAssertSharedPageChecksums(pVM);
2278 rc = GMMR3ResetSharedModules(pVM);
2279 AssertRC(rc);
2280
2281 /*
2282 * Flush the handy pages updates to make sure no shared pages are hiding
2283 * in there. (No unlikely if the VM shuts down, apparently.)
2284 */
2285 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_FLUSH_HANDY_PAGES, 0, NULL);
2286#endif
2287
2288 /*
2289 * We batch up pages that should be freed instead of calling GMM for
2290 * each and every one of them.
2291 */
2292 uint32_t cPendingPages = 0;
2293 PGMMFREEPAGESREQ pReq;
2294 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2295 AssertLogRelRCReturn(rc, rc);
2296
2297 /*
2298 * Walk the ram ranges.
2299 */
2300 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2301 {
2302 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
2303 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
2304
2305 while (iPage-- > 0)
2306 {
2307 PPGMPAGE pPage = &pRam->aPages[iPage];
2308 switch (PGM_PAGE_GET_TYPE(pPage))
2309 {
2310 case PGMPAGETYPE_RAM:
2311 /* Free all shared pages. Private pages are automatically freed during GMM VM cleanup. */
2312 /** @todo change this to explicitly free private pages here. */
2313 if (PGM_PAGE_IS_SHARED(pPage))
2314 {
2315 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
2316 PGMPAGETYPE_RAM);
2317 AssertLogRelRCReturn(rc, rc);
2318 }
2319 break;
2320
2321 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2322 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO:
2323 case PGMPAGETYPE_MMIO2:
2324 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
2325 case PGMPAGETYPE_ROM:
2326 case PGMPAGETYPE_MMIO:
2327 break;
2328 default:
2329 AssertFailed();
2330 }
2331 } /* for each page */
2332 }
2333
2334 /*
2335 * Finish off any pages pending freeing.
2336 */
2337 if (cPendingPages)
2338 {
2339 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2340 AssertLogRelRCReturn(rc, rc);
2341 }
2342 GMMR3FreePagesCleanup(pReq);
2343 return VINF_SUCCESS;
2344}
2345
2346
2347/**
2348 * This is the interface IOM is using to register an MMIO region.
2349 *
2350 * It will check for conflicts and ensure that a RAM range structure
2351 * is present before calling the PGMR3HandlerPhysicalRegister API to
2352 * register the callbacks.
2353 *
2354 * @returns VBox status code.
2355 *
2356 * @param pVM The cross context VM structure.
2357 * @param GCPhys The start of the MMIO region.
2358 * @param cb The size of the MMIO region.
2359 * @param hType The physical access handler type registration.
2360 * @param pvUserR3 The user argument for R3.
2361 * @param pvUserR0 The user argument for R0.
2362 * @param pvUserRC The user argument for RC.
2363 * @param pszDesc The description of the MMIO region.
2364 */
2365VMMR3DECL(int) PGMR3PhysMMIORegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMPHYSHANDLERTYPE hType,
2366 RTR3PTR pvUserR3, RTR0PTR pvUserR0, RTRCPTR pvUserRC, const char *pszDesc)
2367{
2368 /*
2369 * Assert on some assumption.
2370 */
2371 VM_ASSERT_EMT(pVM);
2372 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2373 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2374 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2375 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
2376 Assert(((PPGMPHYSHANDLERTYPEINT)MMHyperHeapOffsetToPtr(pVM, hType))->enmKind == PGMPHYSHANDLERKIND_MMIO);
2377
2378 int rc = pgmLock(pVM);
2379 AssertRCReturn(rc, rc);
2380
2381 /*
2382 * Make sure there's a RAM range structure for the region.
2383 */
2384 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2385 bool fRamExists = false;
2386 PPGMRAMRANGE pRamPrev = NULL;
2387 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2388 while (pRam && GCPhysLast >= pRam->GCPhys)
2389 {
2390 if ( GCPhysLast >= pRam->GCPhys
2391 && GCPhys <= pRam->GCPhysLast)
2392 {
2393 /* Simplification: all within the same range. */
2394 AssertLogRelMsgReturnStmt( GCPhys >= pRam->GCPhys
2395 && GCPhysLast <= pRam->GCPhysLast,
2396 ("%RGp-%RGp (MMIO/%s) falls partly outside %RGp-%RGp (%s)\n",
2397 GCPhys, GCPhysLast, pszDesc,
2398 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2399 pgmUnlock(pVM),
2400 VERR_PGM_RAM_CONFLICT);
2401
2402 /* Check that it's all RAM or MMIO pages. */
2403 PCPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2404 uint32_t cLeft = cb >> PAGE_SHIFT;
2405 while (cLeft-- > 0)
2406 {
2407 AssertLogRelMsgReturnStmt( PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM
2408 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO,
2409 ("%RGp-%RGp (MMIO/%s): %RGp is not a RAM or MMIO page - type=%d desc=%s\n",
2410 GCPhys, GCPhysLast, pszDesc, pRam->GCPhys, PGM_PAGE_GET_TYPE(pPage), pRam->pszDesc),
2411 pgmUnlock(pVM),
2412 VERR_PGM_RAM_CONFLICT);
2413 pPage++;
2414 }
2415
2416 /* Looks good. */
2417 fRamExists = true;
2418 break;
2419 }
2420
2421 /* next */
2422 pRamPrev = pRam;
2423 pRam = pRam->pNextR3;
2424 }
2425 PPGMRAMRANGE pNew;
2426 if (fRamExists)
2427 {
2428 pNew = NULL;
2429
2430 /*
2431 * Make all the pages in the range MMIO/ZERO pages, freeing any
2432 * RAM pages currently mapped here. This might not be 100% correct
2433 * for PCI memory, but we're doing the same thing for MMIO2 pages.
2434 */
2435 rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, PGMPAGETYPE_MMIO);
2436 AssertRCReturnStmt(rc, pgmUnlock(pVM), rc);
2437
2438 /* Force a PGM pool flush as guest ram references have been changed. */
2439 /** @todo not entirely SMP safe; assuming for now the guest takes
2440 * care of this internally (not touch mapped mmio while changing the
2441 * mapping). */
2442 PVMCPU pVCpu = VMMGetCpu(pVM);
2443 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2444 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2445 }
2446 else
2447 {
2448
2449 /*
2450 * No RAM range, insert an ad hoc one.
2451 *
2452 * Note that we don't have to tell REM about this range because
2453 * PGMHandlerPhysicalRegisterEx will do that for us.
2454 */
2455 Log(("PGMR3PhysMMIORegister: Adding ad hoc MMIO range for %RGp-%RGp %s\n", GCPhys, GCPhysLast, pszDesc));
2456
2457 const uint32_t cPages = cb >> PAGE_SHIFT;
2458 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
2459 rc = MMHyperAlloc(pVM, RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]), 16, MM_TAG_PGM_PHYS, (void **)&pNew);
2460 AssertLogRelMsgRCReturnStmt(rc, ("cbRamRange=%zu\n", cbRamRange), pgmUnlock(pVM), rc);
2461
2462 /* Initialize the range. */
2463 pNew->pSelfR0 = MMHyperCCToR0(pVM, pNew);
2464 pNew->pSelfRC = MMHyperCCToRC(pVM, pNew);
2465 pNew->GCPhys = GCPhys;
2466 pNew->GCPhysLast = GCPhysLast;
2467 pNew->cb = cb;
2468 pNew->pszDesc = pszDesc;
2469 pNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO;
2470 pNew->pvR3 = NULL;
2471 pNew->paLSPages = NULL;
2472
2473 uint32_t iPage = cPages;
2474 while (iPage-- > 0)
2475 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_MMIO);
2476 Assert(PGM_PAGE_GET_TYPE(&pNew->aPages[0]) == PGMPAGETYPE_MMIO);
2477
2478 /* update the page count stats. */
2479 pVM->pgm.s.cPureMmioPages += cPages;
2480 pVM->pgm.s.cAllPages += cPages;
2481
2482 /* link it */
2483 pgmR3PhysLinkRamRange(pVM, pNew, pRamPrev);
2484 }
2485
2486 /*
2487 * Register the access handler.
2488 */
2489 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, hType, pvUserR3, pvUserR0, pvUserRC, pszDesc);
2490 if ( RT_FAILURE(rc)
2491 && !fRamExists)
2492 {
2493 pVM->pgm.s.cPureMmioPages -= cb >> PAGE_SHIFT;
2494 pVM->pgm.s.cAllPages -= cb >> PAGE_SHIFT;
2495
2496 /* remove the ad hoc range. */
2497 pgmR3PhysUnlinkRamRange2(pVM, pNew, pRamPrev);
2498 pNew->cb = pNew->GCPhys = pNew->GCPhysLast = NIL_RTGCPHYS;
2499 MMHyperFree(pVM, pRam);
2500 }
2501 pgmPhysInvalidatePageMapTLB(pVM);
2502
2503 pgmUnlock(pVM);
2504 return rc;
2505}
2506
2507
2508/**
2509 * This is the interface IOM is using to register an MMIO region.
2510 *
2511 * It will take care of calling PGMHandlerPhysicalDeregister and clean up
2512 * any ad hoc PGMRAMRANGE left behind.
2513 *
2514 * @returns VBox status code.
2515 * @param pVM The cross context VM structure.
2516 * @param GCPhys The start of the MMIO region.
2517 * @param cb The size of the MMIO region.
2518 */
2519VMMR3DECL(int) PGMR3PhysMMIODeregister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb)
2520{
2521 VM_ASSERT_EMT(pVM);
2522
2523 int rc = pgmLock(pVM);
2524 AssertRCReturn(rc, rc);
2525
2526 /*
2527 * First deregister the handler, then check if we should remove the ram range.
2528 */
2529 rc = PGMHandlerPhysicalDeregister(pVM, GCPhys);
2530 if (RT_SUCCESS(rc))
2531 {
2532 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2533 PPGMRAMRANGE pRamPrev = NULL;
2534 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2535 while (pRam && GCPhysLast >= pRam->GCPhys)
2536 {
2537 /** @todo We're being a bit too careful here. rewrite. */
2538 if ( GCPhysLast == pRam->GCPhysLast
2539 && GCPhys == pRam->GCPhys)
2540 {
2541 Assert(pRam->cb == cb);
2542
2543 /*
2544 * See if all the pages are dead MMIO pages.
2545 */
2546 uint32_t const cPages = cb >> PAGE_SHIFT;
2547 bool fAllMMIO = true;
2548 uint32_t iPage = 0;
2549 uint32_t cLeft = cPages;
2550 while (cLeft-- > 0)
2551 {
2552 PPGMPAGE pPage = &pRam->aPages[iPage];
2553 if ( !PGM_PAGE_IS_MMIO_OR_ALIAS(pPage)
2554 /*|| not-out-of-action later */)
2555 {
2556 fAllMMIO = false;
2557 AssertMsgFailed(("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
2558 break;
2559 }
2560 Assert( PGM_PAGE_IS_ZERO(pPage)
2561 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2_ALIAS_MMIO
2562 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_SPECIAL_ALIAS_MMIO);
2563 pPage++;
2564 }
2565 if (fAllMMIO)
2566 {
2567 /*
2568 * Ad-hoc range, unlink and free it.
2569 */
2570 Log(("PGMR3PhysMMIODeregister: Freeing ad hoc MMIO range for %RGp-%RGp %s\n",
2571 GCPhys, GCPhysLast, pRam->pszDesc));
2572
2573 pVM->pgm.s.cAllPages -= cPages;
2574 pVM->pgm.s.cPureMmioPages -= cPages;
2575
2576 pgmR3PhysUnlinkRamRange2(pVM, pRam, pRamPrev);
2577 pRam->cb = pRam->GCPhys = pRam->GCPhysLast = NIL_RTGCPHYS;
2578 MMHyperFree(pVM, pRam);
2579 break;
2580 }
2581 }
2582
2583 /*
2584 * Range match? It will all be within one range (see PGMAllHandler.cpp).
2585 */
2586 if ( GCPhysLast >= pRam->GCPhys
2587 && GCPhys <= pRam->GCPhysLast)
2588 {
2589 Assert(GCPhys >= pRam->GCPhys);
2590 Assert(GCPhysLast <= pRam->GCPhysLast);
2591
2592 /*
2593 * Turn the pages back into RAM pages.
2594 */
2595 uint32_t iPage = (GCPhys - pRam->GCPhys) >> PAGE_SHIFT;
2596 uint32_t cLeft = cb >> PAGE_SHIFT;
2597 while (cLeft--)
2598 {
2599 PPGMPAGE pPage = &pRam->aPages[iPage];
2600 AssertMsg( (PGM_PAGE_IS_MMIO(pPage) && PGM_PAGE_IS_ZERO(pPage))
2601 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2_ALIAS_MMIO
2602 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_SPECIAL_ALIAS_MMIO,
2603 ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
2604 if (PGM_PAGE_IS_MMIO_OR_ALIAS(pPage))
2605 PGM_PAGE_SET_TYPE(pVM, pPage, PGMPAGETYPE_RAM);
2606 }
2607 break;
2608 }
2609
2610 /* next */
2611 pRamPrev = pRam;
2612 pRam = pRam->pNextR3;
2613 }
2614 }
2615
2616 /* Force a PGM pool flush as guest ram references have been changed. */
2617 /** @todo Not entirely SMP safe; assuming for now the guest takes care of
2618 * this internally (not touch mapped mmio while changing the mapping). */
2619 PVMCPU pVCpu = VMMGetCpu(pVM);
2620 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2621 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2622
2623 pgmPhysInvalidatePageMapTLB(pVM);
2624 pgmPhysInvalidRamRangeTlbs(pVM);
2625 pgmUnlock(pVM);
2626 return rc;
2627}
2628
2629
2630/**
2631 * Locate a MMIO2 range.
2632 *
2633 * @returns Pointer to the MMIO2 range.
2634 * @param pVM The cross context VM structure.
2635 * @param pDevIns The device instance owning the region.
2636 * @param iSubDev The sub-device number.
2637 * @param iRegion The region.
2638 */
2639DECLINLINE(PPGMREGMMIORANGE) pgmR3PhysMMIOExFind(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion)
2640{
2641 /*
2642 * Search the list. There shouldn't be many entries.
2643 */
2644 /** @todo Optimize this lookup! There may now be many entries and it'll
2645 * become really slow when doing MMR3HyperMapMMIO2 and similar. */
2646 for (PPGMREGMMIORANGE pCur = pVM->pgm.s.pRegMmioRangesR3; pCur; pCur = pCur->pNextR3)
2647 if ( pCur->pDevInsR3 == pDevIns
2648 && pCur->iRegion == iRegion
2649 && pCur->iSubDev == iSubDev)
2650 return pCur;
2651 return NULL;
2652}
2653
2654
2655#ifndef PGM_WITHOUT_MAPPINGS
2656/**
2657 * @callback_method_impl{FNPGMRELOCATE, Relocate a floating MMIO/MMIO2 range.}
2658 * @sa pgmR3PhysRamRangeRelocate
2659 */
2660static DECLCALLBACK(bool) pgmR3PhysMMIOExRangeRelocate(PVM pVM, RTGCPTR GCPtrOld, RTGCPTR GCPtrNew,
2661 PGMRELOCATECALL enmMode, void *pvUser)
2662{
2663 PPGMREGMMIORANGE pMmio = (PPGMREGMMIORANGE)pvUser;
2664 Assert(pMmio->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING);
2665 Assert(pMmio->RamRange.pSelfRC == GCPtrOld + PAGE_SIZE + RT_UOFFSETOF(PGMREGMMIORANGE, RamRange)); RT_NOREF_PV(GCPtrOld);
2666
2667 switch (enmMode)
2668 {
2669 case PGMRELOCATECALL_SUGGEST:
2670 return true;
2671
2672 case PGMRELOCATECALL_RELOCATE:
2673 {
2674 /*
2675 * Update myself, then relink all the ranges and flush the RC TLB.
2676 */
2677 pgmLock(pVM);
2678
2679 pMmio->RamRange.pSelfRC = (RTRCPTR)(GCPtrNew + PAGE_SIZE + RT_UOFFSETOF(PGMREGMMIORANGE, RamRange));
2680
2681 pgmR3PhysRelinkRamRanges(pVM);
2682 for (unsigned i = 0; i < PGM_RAMRANGE_TLB_ENTRIES; i++)
2683 pVM->pgm.s.apRamRangesTlbRC[i] = NIL_RTRCPTR;
2684
2685 pgmUnlock(pVM);
2686 return true;
2687 }
2688
2689 default:
2690 AssertFailedReturn(false);
2691 }
2692}
2693#endif /* !PGM_WITHOUT_MAPPINGS */
2694
2695
2696/**
2697 * Calculates the number of chunks
2698 *
2699 * @returns Number of registration chunk needed.
2700 * @param pVM The cross context VM structure.
2701 * @param cb The size of the MMIO/MMIO2 range.
2702 * @param pcPagesPerChunk Where to return the number of pages tracked by each
2703 * chunk. Optional.
2704 * @param pcbChunk Where to return the guest mapping size for a chunk.
2705 */
2706static uint16_t pgmR3PhysMMIOExCalcChunkCount(PVM pVM, RTGCPHYS cb, uint32_t *pcPagesPerChunk, uint32_t *pcbChunk)
2707{
2708 RT_NOREF_PV(pVM); /* without raw mode */
2709
2710 /*
2711 * This is the same calculation as PGMR3PhysRegisterRam does, except we'll be
2712 * needing a few bytes extra the PGMREGMMIORANGE structure.
2713 *
2714 * Note! In additions, we've got a 24 bit sub-page range for MMIO2 ranges, leaving
2715 * us with an absolute maximum of 16777215 pages per chunk (close to 64 GB).
2716 */
2717 uint32_t cbChunk;
2718 uint32_t cPagesPerChunk;
2719 if (!VM_IS_RAW_MODE_ENABLED(pVM))
2720 {
2721 cbChunk = 16U*_1M;
2722 cPagesPerChunk = 1048048; /* max ~1048059 */
2723 AssertCompile(sizeof(PGMREGMMIORANGE) + sizeof(PGMPAGE) * 1048048 < 16U*_1M - PAGE_SIZE * 2);
2724 }
2725 else
2726 {
2727 cbChunk = 4U*_1M;
2728 cPagesPerChunk = 261616; /* max ~261627 */
2729 AssertCompile(sizeof(PGMREGMMIORANGE) + sizeof(PGMPAGE) * 261616 < 4U*_1M - PAGE_SIZE * 2);
2730 }
2731 AssertRelease(cPagesPerChunk <= PGM_MMIO2_MAX_PAGE_COUNT); /* See above note. */
2732 AssertRelease(RT_UOFFSETOF_DYN(PGMREGMMIORANGE, RamRange.aPages[cPagesPerChunk]) + PAGE_SIZE * 2 <= cbChunk);
2733 if (pcbChunk)
2734 *pcbChunk = cbChunk;
2735 if (pcPagesPerChunk)
2736 *pcPagesPerChunk = cPagesPerChunk;
2737
2738 /* Calc the number of chunks we need. */
2739 RTGCPHYS const cPages = cb >> X86_PAGE_SHIFT;
2740 uint16_t cChunks = (uint16_t)((cPages + cPagesPerChunk - 1) / cPagesPerChunk);
2741 AssertRelease((RTGCPHYS)cChunks * cPagesPerChunk >= cPages);
2742 return cChunks;
2743}
2744
2745
2746/**
2747 * Worker for PGMR3PhysMMIOExPreRegister & PGMR3PhysMMIO2Register that allocates
2748 * and the PGMREGMMIORANGE structures and does basic initialization.
2749 *
2750 * Caller must set type specfic members and initialize the PGMPAGE structures.
2751 *
2752 * @returns VBox status code.
2753 * @param pVM The cross context VM structure.
2754 * @param pDevIns The device instance owning the region.
2755 * @param iSubDev The sub-device number (internal PCI config number).
2756 * @param iRegion The region number. If the MMIO2 memory is a PCI
2757 * I/O region this number has to be the number of that
2758 * region. Otherwise it can be any number safe
2759 * UINT8_MAX.
2760 * @param cb The size of the region. Must be page aligned.
2761 * @param pszDesc The description.
2762 * @param ppHeadRet Where to return the pointer to the first
2763 * registration chunk.
2764 *
2765 * @thread EMT
2766 */
2767static int pgmR3PhysMMIOExCreate(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cb,
2768 const char *pszDesc, PPGMREGMMIORANGE *ppHeadRet)
2769{
2770 /*
2771 * Figure out how many chunks we need and of which size.
2772 */
2773 uint32_t cPagesPerChunk;
2774 uint16_t cChunks = pgmR3PhysMMIOExCalcChunkCount(pVM, cb, &cPagesPerChunk, NULL);
2775 AssertReturn(cChunks, VERR_PGM_PHYS_MMIO_EX_IPE);
2776
2777 /*
2778 * Allocate the chunks.
2779 */
2780 PPGMREGMMIORANGE *ppNext = ppHeadRet;
2781 *ppNext = NULL;
2782
2783 int rc = VINF_SUCCESS;
2784 uint32_t cPagesLeft = cb >> X86_PAGE_SHIFT;
2785 for (uint16_t iChunk = 0; iChunk < cChunks && RT_SUCCESS(rc); iChunk++)
2786 {
2787 /*
2788 * We currently do a single RAM range for the whole thing. This will
2789 * probably have to change once someone needs really large MMIO regions,
2790 * as we will be running into SUPR3PageAllocEx limitations and such.
2791 */
2792 const uint32_t cPagesTrackedByChunk = RT_MIN(cPagesLeft, cPagesPerChunk);
2793 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIORANGE, RamRange.aPages[cPagesTrackedByChunk]);
2794 PPGMREGMMIORANGE pNew = NULL;
2795 if ( iChunk + 1 < cChunks
2796 || cbRange >= _1M)
2797 {
2798 /*
2799 * Allocate memory for the registration structure.
2800 */
2801 size_t const cChunkPages = RT_ALIGN_Z(cbRange, PAGE_SIZE) >> PAGE_SHIFT;
2802 size_t const cbChunk = (1 + cChunkPages + 1) << PAGE_SHIFT;
2803 AssertLogRelBreakStmt(cbChunk == (uint32_t)cbChunk, rc = VERR_OUT_OF_RANGE);
2804 PSUPPAGE paChunkPages = (PSUPPAGE)RTMemTmpAllocZ(sizeof(SUPPAGE) * cChunkPages);
2805 AssertBreakStmt(paChunkPages, rc = VERR_NO_TMP_MEMORY);
2806 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
2807 void *pvChunk = NULL;
2808 rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk, &R0PtrChunk, paChunkPages);
2809 AssertLogRelMsgRCBreakStmt(rc, ("rc=%Rrc, cChunkPages=%#zx\n", rc, cChunkPages), RTMemTmpFree(paChunkPages));
2810
2811 Assert(R0PtrChunk != NIL_RTR0PTR);
2812 memset(pvChunk, 0, cChunkPages << PAGE_SHIFT);
2813
2814 pNew = (PPGMREGMMIORANGE)pvChunk;
2815 pNew->RamRange.fFlags = PGM_RAM_RANGE_FLAGS_FLOATING;
2816 pNew->RamRange.pSelfR0 = R0PtrChunk + RT_UOFFSETOF(PGMREGMMIORANGE, RamRange);
2817
2818 /*
2819 * If we might end up in raw-mode, make a HMA mapping of the range,
2820 * just like we do for memory above 4GB.
2821 */
2822 if (!VM_IS_RAW_MODE_ENABLED(pVM))
2823 pNew->RamRange.pSelfRC = NIL_RTRCPTR;
2824 else
2825 {
2826 RTGCPTR GCPtrChunkMap = pVM->pgm.s.GCPtrPrevRamRangeMapping - RT_ALIGN_Z(cbChunk, _4M);
2827 RTGCPTR const GCPtrChunk = GCPtrChunkMap + PAGE_SIZE;
2828#ifndef PGM_WITHOUT_MAPPINGS
2829 rc = PGMR3MapPT(pVM, GCPtrChunkMap, (uint32_t)cbChunk, 0 /*fFlags*/, pgmR3PhysMMIOExRangeRelocate, pNew, pszDesc);
2830 if (RT_SUCCESS(rc))
2831 {
2832#endif /* !PGM_WITHOUT_MAPPINGS */
2833 pVM->pgm.s.GCPtrPrevRamRangeMapping = GCPtrChunkMap;
2834#ifndef PGM_WITHOUT_MAPPINGS
2835 RTGCPTR GCPtrPage = GCPtrChunk;
2836 for (uint32_t iPage = 0; iPage < cChunkPages && RT_SUCCESS(rc); iPage++, GCPtrPage += PAGE_SIZE)
2837 rc = PGMMap(pVM, GCPtrPage, paChunkPages[iPage].Phys, PAGE_SIZE, 0);
2838 }
2839 if (RT_FAILURE(rc))
2840 {
2841 SUPR3PageFreeEx(pvChunk, cChunkPages);
2842 RTMemTmpFree(paChunkPages);
2843 break;
2844 }
2845#endif /* !PGM_WITHOUT_MAPPINGS */
2846 pNew->RamRange.pSelfRC = GCPtrChunk + RT_UOFFSETOF(PGMREGMMIORANGE, RamRange);
2847 }
2848 RTMemTmpFree(paChunkPages);
2849 }
2850 /*
2851 * Not so big, do a one time hyper allocation.
2852 */
2853 else
2854 {
2855 rc = MMR3HyperAllocOnceNoRel(pVM, cbRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
2856 AssertLogRelMsgRCBreak(rc, ("cbRange=%zu\n", cbRange));
2857
2858 /*
2859 * Initialize allocation specific items.
2860 */
2861 //pNew->RamRange.fFlags = 0;
2862 pNew->RamRange.pSelfR0 = MMHyperCCToR0(pVM, &pNew->RamRange);
2863 pNew->RamRange.pSelfRC = MMHyperCCToRC(pVM, &pNew->RamRange);
2864 }
2865
2866 /*
2867 * Initialize the registration structure (caller does specific bits).
2868 */
2869 pNew->pDevInsR3 = pDevIns;
2870 //pNew->pvR3 = NULL;
2871 //pNew->pNext = NULL;
2872 //pNew->fFlags = 0;
2873 if (iChunk == 0)
2874 pNew->fFlags |= PGMREGMMIORANGE_F_FIRST_CHUNK;
2875 if (iChunk + 1 == cChunks)
2876 pNew->fFlags |= PGMREGMMIORANGE_F_LAST_CHUNK;
2877 pNew->iSubDev = iSubDev;
2878 pNew->iRegion = iRegion;
2879 pNew->idSavedState = UINT8_MAX;
2880 pNew->idMmio2 = UINT8_MAX;
2881 //pNew->pPhysHandlerR3 = NULL;
2882 //pNew->paLSPages = NULL;
2883 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
2884 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
2885 pNew->RamRange.pszDesc = pszDesc;
2886 pNew->RamRange.cb = pNew->cbReal = (RTGCPHYS)cPagesTrackedByChunk << X86_PAGE_SHIFT;
2887 pNew->RamRange.fFlags |= PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO_EX;
2888 //pNew->RamRange.pvR3 = NULL;
2889 //pNew->RamRange.paLSPages = NULL;
2890
2891 *ppNext = pNew;
2892 ASMCompilerBarrier();
2893 cPagesLeft -= cPagesTrackedByChunk;
2894 ppNext = &pNew->pNextR3;
2895 }
2896 Assert(cPagesLeft == 0);
2897
2898 if (RT_SUCCESS(rc))
2899 {
2900 Assert((*ppHeadRet)->fFlags & PGMREGMMIORANGE_F_FIRST_CHUNK);
2901 return VINF_SUCCESS;
2902 }
2903
2904 /*
2905 * Free floating ranges.
2906 */
2907 while (*ppHeadRet)
2908 {
2909 PPGMREGMMIORANGE pFree = *ppHeadRet;
2910 *ppHeadRet = pFree->pNextR3;
2911
2912 if (pFree->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
2913 {
2914 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIORANGE, RamRange.aPages[pFree->RamRange.cb >> X86_PAGE_SHIFT]);
2915 size_t const cChunkPages = RT_ALIGN_Z(cbRange, PAGE_SIZE) >> PAGE_SHIFT;
2916 SUPR3PageFreeEx(pFree, cChunkPages);
2917 }
2918 }
2919
2920 return rc;
2921}
2922
2923
2924/**
2925 * Common worker PGMR3PhysMMIOExPreRegister & PGMR3PhysMMIO2Register that links
2926 * a complete registration entry into the lists and lookup tables.
2927 *
2928 * @param pVM The cross context VM structure.
2929 * @param pNew The new MMIO / MMIO2 registration to link.
2930 */
2931static void pgmR3PhysMMIOExLink(PVM pVM, PPGMREGMMIORANGE pNew)
2932{
2933 /*
2934 * Link it into the list (order doesn't matter, so insert it at the head).
2935 *
2936 * Note! The range we're link may consist of multiple chunks, so we have to
2937 * find the last one.
2938 */
2939 PPGMREGMMIORANGE pLast = pNew;
2940 for (pLast = pNew; ; pLast = pLast->pNextR3)
2941 {
2942 if (pLast->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
2943 break;
2944 Assert(pLast->pNextR3);
2945 Assert(pLast->pNextR3->pDevInsR3 == pNew->pDevInsR3);
2946 Assert(pLast->pNextR3->iSubDev == pNew->iSubDev);
2947 Assert(pLast->pNextR3->iRegion == pNew->iRegion);
2948 Assert((pLast->pNextR3->fFlags & PGMREGMMIORANGE_F_MMIO2) == (pNew->fFlags & PGMREGMMIORANGE_F_MMIO2));
2949 Assert(pLast->pNextR3->idMmio2 == (pLast->fFlags & PGMREGMMIORANGE_F_MMIO2 ? pNew->idMmio2 + 1 : UINT8_MAX));
2950 }
2951
2952 pgmLock(pVM);
2953
2954 /* Link in the chain of ranges at the head of the list. */
2955 pLast->pNextR3 = pVM->pgm.s.pRegMmioRangesR3;
2956 pVM->pgm.s.pRegMmioRangesR3 = pNew;
2957
2958 /* If MMIO, insert the MMIO2 range/page IDs. */
2959 uint8_t idMmio2 = pNew->idMmio2;
2960 if (idMmio2 != UINT8_MAX)
2961 {
2962 for (;;)
2963 {
2964 Assert(pNew->fFlags & PGMREGMMIORANGE_F_MMIO2);
2965 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == NULL);
2966 Assert(pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] == NIL_RTR0PTR);
2967 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = pNew;
2968 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = pNew->RamRange.pSelfR0 - RT_UOFFSETOF(PGMREGMMIORANGE, RamRange);
2969 if (pNew->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
2970 break;
2971 pNew = pNew->pNextR3;
2972 }
2973 }
2974 else
2975 Assert(!(pNew->fFlags & PGMREGMMIORANGE_F_MMIO2));
2976
2977 pgmPhysInvalidatePageMapTLB(pVM);
2978 pgmUnlock(pVM);
2979}
2980
2981
2982/**
2983 * Allocate and pre-register an MMIO region.
2984 *
2985 * This is currently the way to deal with large MMIO regions. It may in the
2986 * future be extended to be the way we deal with all MMIO regions, but that
2987 * means we'll have to do something about the simple list based approach we take
2988 * to tracking the registrations.
2989 *
2990 * @returns VBox status code.
2991 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
2992 * memory.
2993 * @retval VERR_ALREADY_EXISTS if the region already exists.
2994 *
2995 * @param pVM The cross context VM structure.
2996 * @param pDevIns The device instance owning the region.
2997 * @param iSubDev The sub-device number.
2998 * @param iRegion The region number. If the MMIO2 memory is a PCI
2999 * I/O region this number has to be the number of that
3000 * region. Otherwise it can be any number safe
3001 * UINT8_MAX.
3002 * @param cbRegion The size of the region. Must be page aligned.
3003 * @param hType The physical handler callback type.
3004 * @param pvUserR3 User parameter for ring-3 context callbacks.
3005 * @param pvUserR0 User parameter for ring-0 context callbacks.
3006 * @param pvUserRC User parameter for raw-mode context callbacks.
3007 * @param pszDesc The description.
3008 *
3009 * @thread EMT
3010 *
3011 * @sa PGMR3PhysMMIORegister, PGMR3PhysMMIO2Register,
3012 * PGMR3PhysMMIOExMap, PGMR3PhysMMIOExUnmap, PGMR3PhysMMIOExDeregister.
3013 */
3014VMMR3DECL(int) PGMR3PhysMMIOExPreRegister(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cbRegion,
3015 PGMPHYSHANDLERTYPE hType, RTR3PTR pvUserR3, RTR0PTR pvUserR0, RTRCPTR pvUserRC,
3016 const char *pszDesc)
3017{
3018 /*
3019 * Validate input.
3020 */
3021 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3022 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3023 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3024 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3025 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
3026 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
3027 AssertReturn(pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion) == NULL, VERR_ALREADY_EXISTS);
3028 AssertReturn(!(cbRegion & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3029 AssertReturn(cbRegion, VERR_INVALID_PARAMETER);
3030
3031 const uint32_t cPages = cbRegion >> PAGE_SHIFT;
3032 AssertLogRelReturn(((RTGCPHYS)cPages << PAGE_SHIFT) == cbRegion, VERR_INVALID_PARAMETER);
3033 AssertLogRelReturn(cPages <= (MM_MMIO_64_MAX >> X86_PAGE_SHIFT), VERR_OUT_OF_RANGE);
3034
3035 /*
3036 * For the 2nd+ instance, mangle the description string so it's unique.
3037 */
3038 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
3039 {
3040 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
3041 if (!pszDesc)
3042 return VERR_NO_MEMORY;
3043 }
3044
3045 /*
3046 * Register the MMIO callbacks.
3047 */
3048 PPGMPHYSHANDLER pPhysHandler;
3049 int rc = pgmHandlerPhysicalExCreate(pVM, hType, pvUserR3, pvUserR0, pvUserRC, pszDesc, &pPhysHandler);
3050 if (RT_SUCCESS(rc))
3051 {
3052 /*
3053 * Create the registered MMIO range record for it.
3054 */
3055 PPGMREGMMIORANGE pNew;
3056 rc = pgmR3PhysMMIOExCreate(pVM, pDevIns, iSubDev, iRegion, cbRegion, pszDesc, &pNew);
3057 if (RT_SUCCESS(rc))
3058 {
3059 Assert(!(pNew->fFlags & PGMREGMMIORANGE_F_MMIO2));
3060
3061 /*
3062 * Intialize the page structures and set up physical handlers (one for each chunk).
3063 */
3064 for (PPGMREGMMIORANGE pCur = pNew; pCur != NULL && RT_SUCCESS(rc); pCur = pCur->pNextR3)
3065 {
3066 if (pCur == pNew)
3067 pCur->pPhysHandlerR3 = pPhysHandler;
3068 else
3069 rc = pgmHandlerPhysicalExDup(pVM, pPhysHandler, &pCur->pPhysHandlerR3);
3070
3071 uint32_t iPage = pCur->RamRange.cb >> X86_PAGE_SHIFT;
3072 while (iPage-- > 0)
3073 PGM_PAGE_INIT_ZERO(&pCur->RamRange.aPages[iPage], pVM, PGMPAGETYPE_MMIO);
3074 }
3075 if (RT_SUCCESS(rc))
3076 {
3077 /*
3078 * Update the page count stats, link the registration and we're done.
3079 */
3080 pVM->pgm.s.cAllPages += cPages;
3081 pVM->pgm.s.cPureMmioPages += cPages;
3082
3083 pgmR3PhysMMIOExLink(pVM, pNew);
3084 return VINF_SUCCESS;
3085 }
3086
3087 /*
3088 * Clean up in case we're out of memory for extra access handlers.
3089 */
3090 while (pNew != NULL)
3091 {
3092 PPGMREGMMIORANGE pFree = pNew;
3093 pNew = pFree->pNextR3;
3094
3095 if (pFree->pPhysHandlerR3)
3096 {
3097 pgmHandlerPhysicalExDestroy(pVM, pFree->pPhysHandlerR3);
3098 pFree->pPhysHandlerR3 = NULL;
3099 }
3100
3101 if (pFree->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
3102 {
3103 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIORANGE, RamRange.aPages[pFree->RamRange.cb >> X86_PAGE_SHIFT]);
3104 size_t const cChunkPages = RT_ALIGN_Z(cbRange, PAGE_SIZE) >> PAGE_SHIFT;
3105 SUPR3PageFreeEx(pFree, cChunkPages);
3106 }
3107 }
3108 }
3109 else
3110 pgmHandlerPhysicalExDestroy(pVM, pPhysHandler);
3111 }
3112 return rc;
3113}
3114
3115
3116/**
3117 * Allocate and register an MMIO2 region.
3118 *
3119 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's RAM
3120 * associated with a device. It is also non-shared memory with a permanent
3121 * ring-3 mapping and page backing (presently).
3122 *
3123 * A MMIO2 range may overlap with base memory if a lot of RAM is configured for
3124 * the VM, in which case we'll drop the base memory pages. Presently we will
3125 * make no attempt to preserve anything that happens to be present in the base
3126 * memory that is replaced, this is of course incorrect but it's too much
3127 * effort.
3128 *
3129 * @returns VBox status code.
3130 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
3131 * memory.
3132 * @retval VERR_ALREADY_EXISTS if the region already exists.
3133 *
3134 * @param pVM The cross context VM structure.
3135 * @param pDevIns The device instance owning the region.
3136 * @param iSubDev The sub-device number.
3137 * @param iRegion The region number. If the MMIO2 memory is a PCI
3138 * I/O region this number has to be the number of that
3139 * region. Otherwise it can be any number safe
3140 * UINT8_MAX.
3141 * @param cb The size of the region. Must be page aligned.
3142 * @param fFlags Reserved for future use, must be zero.
3143 * @param ppv Where to store the pointer to the ring-3 mapping of
3144 * the memory.
3145 * @param pszDesc The description.
3146 * @thread EMT
3147 */
3148VMMR3DECL(int) PGMR3PhysMMIO2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cb,
3149 uint32_t fFlags, void **ppv, const char *pszDesc)
3150{
3151 /*
3152 * Validate input.
3153 */
3154 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3155 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3156 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3157 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3158 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
3159 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
3160 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
3161 AssertReturn(pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion) == NULL, VERR_ALREADY_EXISTS);
3162 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3163 AssertReturn(cb, VERR_INVALID_PARAMETER);
3164 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3165
3166 const uint32_t cPages = cb >> PAGE_SHIFT;
3167 AssertLogRelReturn(((RTGCPHYS)cPages << PAGE_SHIFT) == cb, VERR_INVALID_PARAMETER);
3168 AssertLogRelReturn(cPages <= (MM_MMIO_64_MAX >> X86_PAGE_SHIFT), VERR_OUT_OF_RANGE);
3169
3170 /*
3171 * For the 2nd+ instance, mangle the description string so it's unique.
3172 */
3173 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
3174 {
3175 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
3176 if (!pszDesc)
3177 return VERR_NO_MEMORY;
3178 }
3179
3180 /*
3181 * Allocate an MMIO2 range ID (not freed on failure).
3182 *
3183 * The zero ID is not used as it could be confused with NIL_GMM_PAGEID, so
3184 * the IDs goes from 1 thru PGM_MMIO2_MAX_RANGES.
3185 */
3186 unsigned cChunks = pgmR3PhysMMIOExCalcChunkCount(pVM, cb, NULL, NULL);
3187 pgmLock(pVM);
3188 uint8_t idMmio2 = pVM->pgm.s.cMmio2Regions + 1;
3189 unsigned cNewMmio2Regions = pVM->pgm.s.cMmio2Regions + cChunks;
3190 if (cNewMmio2Regions > PGM_MMIO2_MAX_RANGES)
3191 {
3192 pgmUnlock(pVM);
3193 AssertLogRelFailedReturn(VERR_PGM_TOO_MANY_MMIO2_RANGES);
3194 }
3195 pVM->pgm.s.cMmio2Regions = cNewMmio2Regions;
3196 pgmUnlock(pVM);
3197
3198 /*
3199 * Try reserve and allocate the backing memory first as this is what is
3200 * most likely to fail.
3201 */
3202 int rc = MMR3AdjustFixedReservation(pVM, cPages, pszDesc);
3203 if (RT_SUCCESS(rc))
3204 {
3205 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cPages * sizeof(SUPPAGE));
3206 if (RT_SUCCESS(rc))
3207 {
3208 void *pvPages;
3209 rc = SUPR3PageAllocEx(cPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
3210 if (RT_SUCCESS(rc))
3211 {
3212 memset(pvPages, 0, cPages * PAGE_SIZE);
3213
3214 /*
3215 * Create the registered MMIO range record for it.
3216 */
3217 PPGMREGMMIORANGE pNew;
3218 rc = pgmR3PhysMMIOExCreate(pVM, pDevIns, iSubDev, iRegion, cb, pszDesc, &pNew);
3219 if (RT_SUCCESS(rc))
3220 {
3221 uint32_t iSrcPage = 0;
3222 uint8_t *pbCurPages = (uint8_t *)pvPages;
3223 for (PPGMREGMMIORANGE pCur = pNew; pCur; pCur = pCur->pNextR3)
3224 {
3225 pCur->pvR3 = pbCurPages;
3226 pCur->RamRange.pvR3 = pbCurPages;
3227 pCur->idMmio2 = idMmio2;
3228 pCur->fFlags |= PGMREGMMIORANGE_F_MMIO2;
3229
3230 uint32_t iDstPage = pCur->RamRange.cb >> X86_PAGE_SHIFT;
3231 while (iDstPage-- > 0)
3232 {
3233 PGM_PAGE_INIT(&pNew->RamRange.aPages[iDstPage],
3234 paPages[iDstPage + iSrcPage].Phys,
3235 PGM_MMIO2_PAGEID_MAKE(idMmio2, iDstPage),
3236 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
3237 }
3238
3239 /* advance. */
3240 iSrcPage += pCur->RamRange.cb >> X86_PAGE_SHIFT;
3241 pbCurPages += pCur->RamRange.cb;
3242 idMmio2++;
3243 }
3244
3245 RTMemTmpFree(paPages);
3246
3247 /*
3248 * Update the page count stats, link the registration and we're done.
3249 */
3250 pVM->pgm.s.cAllPages += cPages;
3251 pVM->pgm.s.cPrivatePages += cPages;
3252
3253 pgmR3PhysMMIOExLink(pVM, pNew);
3254
3255 *ppv = pvPages;
3256 return VINF_SUCCESS;
3257 }
3258
3259 SUPR3PageFreeEx(pvPages, cPages);
3260 }
3261 }
3262 RTMemTmpFree(paPages);
3263 MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pszDesc);
3264 }
3265 if (pDevIns->iInstance > 0)
3266 MMR3HeapFree((void *)pszDesc);
3267 return rc;
3268}
3269
3270
3271/**
3272 * Deregisters and frees an MMIO2 region or a pre-registered MMIO region
3273 *
3274 * Any physical (and virtual) access handlers registered for the region must
3275 * be deregistered before calling this function.
3276 *
3277 * @returns VBox status code.
3278 * @param pVM The cross context VM structure.
3279 * @param pDevIns The device instance owning the region.
3280 * @param iSubDev The sub-device number. Pass UINT32_MAX for wildcard
3281 * matching.
3282 * @param iRegion The region. Pass UINT32_MAX for wildcard matching.
3283 */
3284VMMR3DECL(int) PGMR3PhysMMIOExDeregister(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion)
3285{
3286 /*
3287 * Validate input.
3288 */
3289 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3290 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3291 AssertReturn(iSubDev <= UINT8_MAX || iSubDev == UINT32_MAX, VERR_INVALID_PARAMETER);
3292 AssertReturn(iRegion <= UINT8_MAX || iRegion == UINT32_MAX, VERR_INVALID_PARAMETER);
3293
3294 /*
3295 * The loop here scanning all registrations will make sure that multi-chunk ranges
3296 * get properly deregistered, though it's original purpose was the wildcard iRegion.
3297 */
3298 pgmLock(pVM);
3299 int rc = VINF_SUCCESS;
3300 unsigned cFound = 0;
3301 PPGMREGMMIORANGE pPrev = NULL;
3302 PPGMREGMMIORANGE pCur = pVM->pgm.s.pRegMmioRangesR3;
3303 while (pCur)
3304 {
3305 if ( pCur->pDevInsR3 == pDevIns
3306 && ( iRegion == UINT32_MAX
3307 || pCur->iRegion == iRegion)
3308 && ( iSubDev == UINT32_MAX
3309 || pCur->iSubDev == iSubDev) )
3310 {
3311 cFound++;
3312
3313 /*
3314 * Unmap it if it's mapped.
3315 */
3316 if (pCur->fFlags & PGMREGMMIORANGE_F_MAPPED)
3317 {
3318 int rc2 = PGMR3PhysMMIOExUnmap(pVM, pCur->pDevInsR3, pCur->iSubDev, pCur->iRegion, pCur->RamRange.GCPhys);
3319 AssertRC(rc2);
3320 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3321 rc = rc2;
3322 }
3323
3324 /*
3325 * Must tell IOM about MMIO (first one only).
3326 */
3327 if ((pCur->fFlags & (PGMREGMMIORANGE_F_MMIO2 | PGMREGMMIORANGE_F_FIRST_CHUNK)) == PGMREGMMIORANGE_F_MMIO2)
3328 IOMR3MmioExNotifyDeregistered(pVM, pCur->pPhysHandlerR3->pvUserR3);
3329
3330 /*
3331 * Unlink it
3332 */
3333 PPGMREGMMIORANGE pNext = pCur->pNextR3;
3334 if (pPrev)
3335 pPrev->pNextR3 = pNext;
3336 else
3337 pVM->pgm.s.pRegMmioRangesR3 = pNext;
3338 pCur->pNextR3 = NULL;
3339
3340 uint8_t idMmio2 = pCur->idMmio2;
3341 if (idMmio2 != UINT8_MAX)
3342 {
3343 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == pCur);
3344 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = NULL;
3345 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = NIL_RTR0PTR;
3346 }
3347
3348 /*
3349 * Free the memory.
3350 */
3351 uint32_t const cPages = pCur->cbReal >> PAGE_SHIFT;
3352 if (pCur->fFlags & PGMREGMMIORANGE_F_MMIO2)
3353 {
3354 int rc2 = SUPR3PageFreeEx(pCur->pvR3, cPages);
3355 AssertRC(rc2);
3356 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3357 rc = rc2;
3358
3359 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pCur->RamRange.pszDesc);
3360 AssertRC(rc2);
3361 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3362 rc = rc2;
3363 }
3364
3365 /* we're leaking hyper memory here if done at runtime. */
3366#ifdef VBOX_STRICT
3367 VMSTATE const enmState = VMR3GetState(pVM);
3368 AssertMsg( enmState == VMSTATE_POWERING_OFF
3369 || enmState == VMSTATE_POWERING_OFF_LS
3370 || enmState == VMSTATE_OFF
3371 || enmState == VMSTATE_OFF_LS
3372 || enmState == VMSTATE_DESTROYING
3373 || enmState == VMSTATE_TERMINATED
3374 || enmState == VMSTATE_CREATING
3375 , ("%s\n", VMR3GetStateName(enmState)));
3376#endif
3377
3378 const bool fIsMmio2 = RT_BOOL(pCur->fFlags & PGMREGMMIORANGE_F_MMIO2);
3379 if (pCur->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
3380 {
3381 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIORANGE, RamRange.aPages[cPages]);
3382 size_t const cChunkPages = RT_ALIGN_Z(cbRange, PAGE_SIZE) >> PAGE_SHIFT;
3383 SUPR3PageFreeEx(pCur, cChunkPages);
3384 }
3385 /*else
3386 {
3387 rc = MMHyperFree(pVM, pCur); - does not work, see the alloc call.
3388 AssertRCReturn(rc, rc);
3389 } */
3390
3391
3392 /* update page count stats */
3393 pVM->pgm.s.cAllPages -= cPages;
3394 if (fIsMmio2)
3395 pVM->pgm.s.cPrivatePages -= cPages;
3396 else
3397 pVM->pgm.s.cPureMmioPages -= cPages;
3398
3399 /* next */
3400 pCur = pNext;
3401 }
3402 else
3403 {
3404 pPrev = pCur;
3405 pCur = pCur->pNextR3;
3406 }
3407 }
3408 pgmPhysInvalidatePageMapTLB(pVM);
3409 pgmUnlock(pVM);
3410 return !cFound && iRegion != UINT32_MAX && iSubDev != UINT32_MAX ? VERR_NOT_FOUND : rc;
3411}
3412
3413
3414/**
3415 * Maps a MMIO2 region or a pre-registered MMIO region.
3416 *
3417 * This is done when a guest / the bios / state loading changes the
3418 * PCI config. The replacing of base memory has the same restrictions
3419 * as during registration, of course.
3420 *
3421 * @returns VBox status code.
3422 *
3423 * @param pVM The cross context VM structure.
3424 * @param pDevIns The device instance owning the region.
3425 * @param iSubDev The sub-device number of the registered region.
3426 * @param iRegion The index of the registered region.
3427 * @param GCPhys The guest-physical address to be remapped.
3428 */
3429VMMR3DECL(int) PGMR3PhysMMIOExMap(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS GCPhys)
3430{
3431 /*
3432 * Validate input.
3433 *
3434 * Note! It's safe to walk the MMIO/MMIO2 list since registrations only
3435 * happens during VM construction.
3436 */
3437 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3438 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3439 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3440 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3441 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
3442 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
3443 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3444
3445 PPGMREGMMIORANGE pFirstMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
3446 AssertReturn(pFirstMmio, VERR_NOT_FOUND);
3447 Assert(pFirstMmio->fFlags & PGMREGMMIORANGE_F_FIRST_CHUNK);
3448
3449 PPGMREGMMIORANGE pLastMmio = pFirstMmio;
3450 RTGCPHYS cbRange = 0;
3451 for (;;)
3452 {
3453 AssertReturn(!(pLastMmio->fFlags & PGMREGMMIORANGE_F_MAPPED), VERR_WRONG_ORDER);
3454 Assert(pLastMmio->RamRange.GCPhys == NIL_RTGCPHYS);
3455 Assert(pLastMmio->RamRange.GCPhysLast == NIL_RTGCPHYS);
3456 Assert(pLastMmio->pDevInsR3 == pFirstMmio->pDevInsR3);
3457 Assert(pLastMmio->iSubDev == pFirstMmio->iSubDev);
3458 Assert(pLastMmio->iRegion == pFirstMmio->iRegion);
3459 cbRange += pLastMmio->RamRange.cb;
3460 if (pLastMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3461 break;
3462 pLastMmio = pLastMmio->pNextR3;
3463 }
3464
3465 RTGCPHYS GCPhysLast = GCPhys + cbRange - 1;
3466 AssertLogRelReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3467
3468 /*
3469 * Find our location in the ram range list, checking for restriction
3470 * we don't bother implementing yet (partially overlapping, multiple
3471 * ram ranges).
3472 */
3473 pgmLock(pVM);
3474
3475 AssertReturnStmt(!(pFirstMmio->fFlags & PGMREGMMIORANGE_F_MAPPED), pgmUnlock(pVM), VERR_WRONG_ORDER);
3476
3477 bool fRamExists = false;
3478 PPGMRAMRANGE pRamPrev = NULL;
3479 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3480 while (pRam && GCPhysLast >= pRam->GCPhys)
3481 {
3482 if ( GCPhys <= pRam->GCPhysLast
3483 && GCPhysLast >= pRam->GCPhys)
3484 {
3485 /* Completely within? */
3486 AssertLogRelMsgReturnStmt( GCPhys >= pRam->GCPhys
3487 && GCPhysLast <= pRam->GCPhysLast,
3488 ("%RGp-%RGp (MMIOEx/%s) falls partly outside %RGp-%RGp (%s)\n",
3489 GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc,
3490 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
3491 pgmUnlock(pVM),
3492 VERR_PGM_RAM_CONFLICT);
3493
3494 /* Check that all the pages are RAM pages. */
3495 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3496 uint32_t cPagesLeft = cbRange >> PAGE_SHIFT;
3497 while (cPagesLeft-- > 0)
3498 {
3499 AssertLogRelMsgReturnStmt(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
3500 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
3501 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc),
3502 pgmUnlock(pVM),
3503 VERR_PGM_RAM_CONFLICT);
3504 pPage++;
3505 }
3506
3507 /* There can only be one MMIO/MMIO2 chunk matching here! */
3508 AssertLogRelMsgReturnStmt(pFirstMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK,
3509 ("%RGp-%RGp (MMIOEx/%s, flags %#X) consists of multiple chunks whereas the RAM somehow doesn't!\n",
3510 GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc, pFirstMmio->fFlags),
3511 pgmUnlock(pVM),
3512 VERR_PGM_PHYS_MMIO_EX_IPE);
3513
3514 fRamExists = true;
3515 break;
3516 }
3517
3518 /* next */
3519 pRamPrev = pRam;
3520 pRam = pRam->pNextR3;
3521 }
3522 Log(("PGMR3PhysMMIOExMap: %RGp-%RGp fRamExists=%RTbool %s\n", GCPhys, GCPhysLast, fRamExists, pFirstMmio->RamRange.pszDesc));
3523
3524
3525 /*
3526 * Make the changes.
3527 */
3528 RTGCPHYS GCPhysCur = GCPhys;
3529 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3530 {
3531 pCurMmio->RamRange.GCPhys = GCPhysCur;
3532 pCurMmio->RamRange.GCPhysLast = GCPhysCur + pCurMmio->RamRange.cb - 1;
3533 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3534 {
3535 Assert(pCurMmio->RamRange.GCPhysLast == GCPhysLast);
3536 break;
3537 }
3538 GCPhysCur += pCurMmio->RamRange.cb;
3539 }
3540
3541 if (fRamExists)
3542 {
3543 /*
3544 * Make all the pages in the range MMIO/ZERO pages, freeing any
3545 * RAM pages currently mapped here. This might not be 100% correct
3546 * for PCI memory, but we're doing the same thing for MMIO2 pages.
3547 *
3548 * We replace this MMIO/ZERO pages with real pages in the MMIO2 case.
3549 */
3550 Assert(pFirstMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK); /* Only one chunk */
3551
3552 int rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, PGMPAGETYPE_MMIO);
3553 AssertRCReturnStmt(rc, pgmUnlock(pVM), rc);
3554
3555 if (pFirstMmio->fFlags & PGMREGMMIORANGE_F_MMIO2)
3556 {
3557 /* replace the pages, freeing all present RAM pages. */
3558 PPGMPAGE pPageSrc = &pFirstMmio->RamRange.aPages[0];
3559 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3560 uint32_t cPagesLeft = pFirstMmio->RamRange.cb >> PAGE_SHIFT;
3561 while (cPagesLeft-- > 0)
3562 {
3563 Assert(PGM_PAGE_IS_MMIO(pPageDst));
3564
3565 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
3566 uint32_t const idPage = PGM_PAGE_GET_PAGEID(pPageSrc);
3567 PGM_PAGE_SET_PAGEID(pVM, pPageDst, idPage);
3568 PGM_PAGE_SET_HCPHYS(pVM, pPageDst, HCPhys);
3569 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO2);
3570 PGM_PAGE_SET_STATE(pVM, pPageDst, PGM_PAGE_STATE_ALLOCATED);
3571 PGM_PAGE_SET_PDE_TYPE(pVM, pPageDst, PGM_PAGE_PDE_TYPE_DONTCARE);
3572 PGM_PAGE_SET_PTE_INDEX(pVM, pPageDst, 0);
3573 PGM_PAGE_SET_TRACKING(pVM, pPageDst, 0);
3574 /* (We tell NEM at the end of the function.) */
3575
3576 pVM->pgm.s.cZeroPages--;
3577 GCPhys += PAGE_SIZE;
3578 pPageSrc++;
3579 pPageDst++;
3580 }
3581 }
3582
3583 /* Flush physical page map TLB. */
3584 pgmPhysInvalidatePageMapTLB(pVM);
3585
3586 /* Force a PGM pool flush as guest ram references have been changed. */
3587 /** @todo not entirely SMP safe; assuming for now the guest takes care of
3588 * this internally (not touch mapped mmio while changing the mapping). */
3589 PVMCPU pVCpu = VMMGetCpu(pVM);
3590 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
3591 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3592 }
3593 else
3594 {
3595 /*
3596 * No RAM range, insert the ones prepared during registration.
3597 */
3598 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3599 {
3600 /* Clear the tracking data of pages we're going to reactivate. */
3601 PPGMPAGE pPageSrc = &pCurMmio->RamRange.aPages[0];
3602 uint32_t cPagesLeft = pCurMmio->RamRange.cb >> PAGE_SHIFT;
3603 while (cPagesLeft-- > 0)
3604 {
3605 PGM_PAGE_SET_TRACKING(pVM, pPageSrc, 0);
3606 PGM_PAGE_SET_PTE_INDEX(pVM, pPageSrc, 0);
3607 pPageSrc++;
3608 }
3609
3610 /* link in the ram range */
3611 pgmR3PhysLinkRamRange(pVM, &pCurMmio->RamRange, pRamPrev);
3612
3613 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3614 {
3615 Assert(pCurMmio->RamRange.GCPhysLast == GCPhysLast);
3616 break;
3617 }
3618 pRamPrev = &pCurMmio->RamRange;
3619 }
3620 }
3621
3622 /*
3623 * Register the access handler if plain MMIO.
3624 *
3625 * We must register access handlers for each range since the access handler
3626 * code refuses to deal with multiple ranges (and we can).
3627 */
3628 if (!(pFirstMmio->fFlags & PGMREGMMIORANGE_F_MMIO2))
3629 {
3630 int rc = VINF_SUCCESS;
3631 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3632 {
3633 Assert(!(pCurMmio->fFlags & PGMREGMMIORANGE_F_MAPPED));
3634 rc = pgmHandlerPhysicalExRegister(pVM, pCurMmio->pPhysHandlerR3, pCurMmio->RamRange.GCPhys,
3635 pCurMmio->RamRange.GCPhysLast);
3636 if (RT_FAILURE(rc))
3637 break;
3638 pCurMmio->fFlags |= PGMREGMMIORANGE_F_MAPPED; /* Use this to mark that the handler is registered. */
3639 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3640 {
3641 rc = IOMR3MmioExNotifyMapped(pVM, pFirstMmio->pPhysHandlerR3->pvUserR3, GCPhys);
3642 break;
3643 }
3644 }
3645 if (RT_FAILURE(rc))
3646 {
3647 /* Almost impossible, but try clean up properly and get out of here. */
3648 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3649 {
3650 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_MAPPED)
3651 {
3652 pCurMmio->fFlags &= ~PGMREGMMIORANGE_F_MAPPED;
3653 pgmHandlerPhysicalExDeregister(pVM, pCurMmio->pPhysHandlerR3, fRamExists);
3654 }
3655
3656 if (!fRamExists)
3657 pgmR3PhysUnlinkRamRange(pVM, &pCurMmio->RamRange);
3658 else
3659 {
3660 Assert(pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK); /* Only one chunk */
3661
3662 uint32_t cPagesLeft = pCurMmio->RamRange.cb >> PAGE_SHIFT;
3663 PPGMPAGE pPageDst = &pRam->aPages[(pCurMmio->RamRange.GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3664 while (cPagesLeft-- > 0)
3665 {
3666 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
3667 pPageDst++;
3668 }
3669 }
3670
3671 pCurMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3672 pCurMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3673 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3674 break;
3675 }
3676
3677 pgmUnlock(pVM);
3678 return rc;
3679 }
3680 }
3681
3682 /*
3683 * We're good, set the flags and invalid the mapping TLB.
3684 */
3685 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3686 {
3687 pCurMmio->fFlags |= PGMREGMMIORANGE_F_MAPPED;
3688 if (fRamExists)
3689 pCurMmio->fFlags |= PGMREGMMIORANGE_F_OVERLAPPING;
3690 else
3691 pCurMmio->fFlags &= ~PGMREGMMIORANGE_F_OVERLAPPING;
3692 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3693 break;
3694 }
3695 pgmPhysInvalidatePageMapTLB(pVM);
3696
3697 /*
3698 * Notify NEM while holding the lock (experimental) and REM without (like always).
3699 */
3700 uint32_t const fNemNotify = (pFirstMmio->fFlags & PGMREGMMIORANGE_F_MMIO2 ? NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2 : 0)
3701 | (pFirstMmio->fFlags & PGMREGMMIORANGE_F_OVERLAPPING ? NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE : 0);
3702 int rc = NEMR3NotifyPhysMmioExMap(pVM, GCPhys, cbRange, fNemNotify, pFirstMmio->pvR3);
3703
3704 pgmUnlock(pVM);
3705
3706#ifdef VBOX_WITH_REM
3707 if (!fRamExists && (pFirstMmio->fFlags & PGMREGMMIORANGE_F_MMIO2)) /** @todo this doesn't look right. */
3708 REMR3NotifyPhysRamRegister(pVM, GCPhys, cbRange, REM_NOTIFY_PHYS_RAM_FLAGS_MMIO2);
3709#endif
3710 return rc;
3711}
3712
3713
3714/**
3715 * Unmaps a MMIO2 or a pre-registered MMIO region.
3716 *
3717 * This is done when a guest / the bios / state loading changes the
3718 * PCI config. The replacing of base memory has the same restrictions
3719 * as during registration, of course.
3720 */
3721VMMR3DECL(int) PGMR3PhysMMIOExUnmap(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS GCPhys)
3722{
3723 /*
3724 * Validate input
3725 */
3726 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3727 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3728 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3729 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3730 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
3731 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
3732 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3733
3734 PPGMREGMMIORANGE pFirstMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
3735 AssertReturn(pFirstMmio, VERR_NOT_FOUND);
3736 Assert(pFirstMmio->fFlags & PGMREGMMIORANGE_F_FIRST_CHUNK);
3737
3738 PPGMREGMMIORANGE pLastMmio = pFirstMmio;
3739 RTGCPHYS cbRange = 0;
3740 for (;;)
3741 {
3742 AssertReturn(pLastMmio->fFlags & PGMREGMMIORANGE_F_MAPPED, VERR_WRONG_ORDER);
3743 AssertReturn(pLastMmio->RamRange.GCPhys == GCPhys + cbRange, VERR_INVALID_PARAMETER);
3744 Assert(pLastMmio->pDevInsR3 == pFirstMmio->pDevInsR3);
3745 Assert(pLastMmio->iSubDev == pFirstMmio->iSubDev);
3746 Assert(pLastMmio->iRegion == pFirstMmio->iRegion);
3747 cbRange += pLastMmio->RamRange.cb;
3748 if (pLastMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3749 break;
3750 pLastMmio = pLastMmio->pNextR3;
3751 }
3752
3753 Log(("PGMR3PhysMMIOExUnmap: %RGp-%RGp %s\n",
3754 pFirstMmio->RamRange.GCPhys, pLastMmio->RamRange.GCPhysLast, pFirstMmio->RamRange.pszDesc));
3755
3756 int rc = pgmLock(pVM);
3757 AssertRCReturn(rc, rc);
3758 uint16_t const fOldFlags = pFirstMmio->fFlags;
3759 AssertReturnStmt(fOldFlags & PGMREGMMIORANGE_F_MAPPED, pgmUnlock(pVM), VERR_WRONG_ORDER);
3760
3761 /*
3762 * If plain MMIO, we must deregister the handlers first.
3763 */
3764 if (!(fOldFlags & PGMREGMMIORANGE_F_MMIO2))
3765 {
3766 PPGMREGMMIORANGE pCurMmio = pFirstMmio;
3767 rc = pgmHandlerPhysicalExDeregister(pVM, pFirstMmio->pPhysHandlerR3, RT_BOOL(fOldFlags & PGMREGMMIORANGE_F_OVERLAPPING));
3768 AssertRCReturnStmt(rc, pgmUnlock(pVM), rc);
3769 while (!(pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK))
3770 {
3771 pCurMmio = pCurMmio->pNextR3;
3772 rc = pgmHandlerPhysicalExDeregister(pVM, pCurMmio->pPhysHandlerR3, RT_BOOL(fOldFlags & PGMREGMMIORANGE_F_OVERLAPPING));
3773 AssertRCReturnStmt(rc, pgmUnlock(pVM), VERR_PGM_PHYS_MMIO_EX_IPE);
3774 }
3775
3776 IOMR3MmioExNotifyUnmapped(pVM, pFirstMmio->pPhysHandlerR3->pvUserR3, GCPhys);
3777 }
3778
3779 /*
3780 * Unmap it.
3781 */
3782 RTGCPHYS const GCPhysRangeNotify = pFirstMmio->RamRange.GCPhys;
3783 if (fOldFlags & PGMREGMMIORANGE_F_OVERLAPPING)
3784 {
3785 /*
3786 * We've replaced RAM, replace with zero pages.
3787 *
3788 * Note! This is where we might differ a little from a real system, because
3789 * it's likely to just show the RAM pages as they were before the
3790 * MMIO/MMIO2 region was mapped here.
3791 */
3792 /* Only one chunk allowed when overlapping! */
3793 Assert(fOldFlags & PGMREGMMIORANGE_F_LAST_CHUNK);
3794
3795 /* Restore the RAM pages we've replaced. */
3796 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3797 while (pRam->GCPhys > pFirstMmio->RamRange.GCPhysLast)
3798 pRam = pRam->pNextR3;
3799
3800 uint32_t cPagesLeft = pFirstMmio->RamRange.cb >> PAGE_SHIFT;
3801 if (fOldFlags & PGMREGMMIORANGE_F_MMIO2)
3802 pVM->pgm.s.cZeroPages += cPagesLeft;
3803
3804 PPGMPAGE pPageDst = &pRam->aPages[(pFirstMmio->RamRange.GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3805 while (cPagesLeft-- > 0)
3806 {
3807 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
3808 pPageDst++;
3809 }
3810
3811 /* Flush physical page map TLB. */
3812 pgmPhysInvalidatePageMapTLB(pVM);
3813
3814 /* Update range state. */
3815 pFirstMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3816 pFirstMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3817 pFirstMmio->fFlags &= ~(PGMREGMMIORANGE_F_OVERLAPPING | PGMREGMMIORANGE_F_MAPPED);
3818 }
3819 else
3820 {
3821 /*
3822 * Unlink the chunks related to the MMIO/MMIO2 region.
3823 */
3824 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3825 {
3826 pgmR3PhysUnlinkRamRange(pVM, &pCurMmio->RamRange);
3827 pCurMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3828 pCurMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3829 pCurMmio->fFlags &= ~(PGMREGMMIORANGE_F_OVERLAPPING | PGMREGMMIORANGE_F_MAPPED);
3830 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3831 break;
3832 }
3833 }
3834
3835 /* Force a PGM pool flush as guest ram references have been changed. */
3836 /** @todo not entirely SMP safe; assuming for now the guest takes care
3837 * of this internally (not touch mapped mmio while changing the
3838 * mapping). */
3839 PVMCPU pVCpu = VMMGetCpu(pVM);
3840 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
3841 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3842
3843 pgmPhysInvalidatePageMapTLB(pVM);
3844 pgmPhysInvalidRamRangeTlbs(pVM);
3845
3846 /*
3847 * Notify NEM while holding the lock (experimental) and REM without (like always).
3848 */
3849 uint32_t const fNemFlags = (fOldFlags & PGMREGMMIORANGE_F_MMIO2 ? NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2 : 0)
3850 | (fOldFlags & PGMREGMMIORANGE_F_OVERLAPPING ? NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE : 0);
3851 rc = NEMR3NotifyPhysMmioExUnmap(pVM, GCPhysRangeNotify, cbRange, fNemFlags);
3852 pgmUnlock(pVM);
3853#ifdef VBOX_WITH_REM
3854 if ((fOldFlags & (PGMREGMMIORANGE_F_OVERLAPPING | PGMREGMMIORANGE_F_MMIO2)) == PGMREGMMIORANGE_F_MMIO2)
3855 REMR3NotifyPhysRamDeregister(pVM, GCPhysRangeNotify, cbRange);
3856#endif
3857 return rc;
3858}
3859
3860
3861/**
3862 * Reduces the mapping size of a MMIO2 or pre-registered MMIO region.
3863 *
3864 * This is mainly for dealing with old saved states after changing the default
3865 * size of a mapping region. See PGMDevHlpMMIOExReduce and
3866 * PDMPCIDEV::pfnRegionLoadChangeHookR3.
3867 *
3868 * The region must not currently be mapped when making this call. The VM state
3869 * must be state restore or VM construction.
3870 *
3871 * @returns VBox status code.
3872 * @param pVM The cross context VM structure.
3873 * @param pDevIns The device instance owning the region.
3874 * @param iSubDev The sub-device number of the registered region.
3875 * @param iRegion The index of the registered region.
3876 * @param cbRegion The new mapping size.
3877 */
3878VMMR3_INT_DECL(int) PGMR3PhysMMIOExReduce(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cbRegion)
3879{
3880 /*
3881 * Validate input
3882 */
3883 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3884 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3885 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3886 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3887 AssertReturn(cbRegion >= X86_PAGE_SIZE, VERR_INVALID_PARAMETER);
3888 AssertReturn(!(cbRegion & X86_PAGE_OFFSET_MASK), VERR_UNSUPPORTED_ALIGNMENT);
3889 VMSTATE enmVmState = VMR3GetState(pVM);
3890 AssertLogRelMsgReturn( enmVmState == VMSTATE_CREATING
3891 || enmVmState == VMSTATE_LOADING,
3892 ("enmVmState=%d (%s)\n", enmVmState, VMR3GetStateName(enmVmState)),
3893 VERR_VM_INVALID_VM_STATE);
3894
3895 int rc = pgmLock(pVM);
3896 AssertRCReturn(rc, rc);
3897
3898 PPGMREGMMIORANGE pFirstMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
3899 if (pFirstMmio)
3900 {
3901 Assert(pFirstMmio->fFlags & PGMREGMMIORANGE_F_FIRST_CHUNK);
3902 if (!(pFirstMmio->fFlags & PGMREGMMIORANGE_F_MAPPED))
3903 {
3904 /*
3905 * NOTE! Current implementation does not support multiple ranges.
3906 * Implement when there is a real world need and thus a testcase.
3907 */
3908 AssertLogRelMsgStmt(pFirstMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK,
3909 ("%s: %#x\n", pFirstMmio->RamRange.pszDesc, pFirstMmio->fFlags),
3910 rc = VERR_NOT_SUPPORTED);
3911 if (RT_SUCCESS(rc))
3912 {
3913 /*
3914 * Make the change.
3915 */
3916 Log(("PGMR3PhysMMIOExReduce: %s changes from %RGp bytes (%RGp) to %RGp bytes.\n",
3917 pFirstMmio->RamRange.pszDesc, pFirstMmio->RamRange.cb, pFirstMmio->cbReal, cbRegion));
3918
3919 AssertLogRelMsgStmt(cbRegion <= pFirstMmio->cbReal,
3920 ("%s: cbRegion=%#RGp cbReal=%#RGp\n", pFirstMmio->RamRange.pszDesc, cbRegion, pFirstMmio->cbReal),
3921 rc = VERR_OUT_OF_RANGE);
3922 if (RT_SUCCESS(rc))
3923 {
3924 pFirstMmio->RamRange.cb = cbRegion;
3925 }
3926 }
3927 }
3928 else
3929 rc = VERR_WRONG_ORDER;
3930 }
3931 else
3932 rc = VERR_NOT_FOUND;
3933
3934 pgmUnlock(pVM);
3935 return rc;
3936}
3937
3938
3939/**
3940 * Checks if the given address is an MMIO2 or pre-registered MMIO base address
3941 * or not.
3942 *
3943 * @returns true/false accordingly.
3944 * @param pVM The cross context VM structure.
3945 * @param pDevIns The owner of the memory, optional.
3946 * @param GCPhys The address to check.
3947 */
3948VMMR3DECL(bool) PGMR3PhysMMIOExIsBase(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys)
3949{
3950 /*
3951 * Validate input
3952 */
3953 VM_ASSERT_EMT_RETURN(pVM, false);
3954 AssertPtrReturn(pDevIns, false);
3955 AssertReturn(GCPhys != NIL_RTGCPHYS, false);
3956 AssertReturn(GCPhys != 0, false);
3957 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), false);
3958
3959 /*
3960 * Search the list.
3961 */
3962 pgmLock(pVM);
3963 for (PPGMREGMMIORANGE pCurMmio = pVM->pgm.s.pRegMmioRangesR3; pCurMmio; pCurMmio = pCurMmio->pNextR3)
3964 if (pCurMmio->RamRange.GCPhys == GCPhys)
3965 {
3966 Assert(pCurMmio->fFlags & PGMREGMMIORANGE_F_MAPPED);
3967 bool fRet = RT_BOOL(pCurMmio->fFlags & PGMREGMMIORANGE_F_FIRST_CHUNK);
3968 pgmUnlock(pVM);
3969 return fRet;
3970 }
3971 pgmUnlock(pVM);
3972 return false;
3973}
3974
3975
3976/**
3977 * Gets the HC physical address of a page in the MMIO2 region.
3978 *
3979 * This is API is intended for MMHyper and shouldn't be called
3980 * by anyone else...
3981 *
3982 * @returns VBox status code.
3983 * @param pVM The cross context VM structure.
3984 * @param pDevIns The owner of the memory, optional.
3985 * @param iSubDev Sub-device number.
3986 * @param iRegion The region.
3987 * @param off The page expressed an offset into the MMIO2 region.
3988 * @param pHCPhys Where to store the result.
3989 */
3990VMMR3_INT_DECL(int) PGMR3PhysMMIO2GetHCPhys(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion,
3991 RTGCPHYS off, PRTHCPHYS pHCPhys)
3992{
3993 /*
3994 * Validate input
3995 */
3996 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3997 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3998 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3999 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4000
4001 pgmLock(pVM);
4002 PPGMREGMMIORANGE pCurMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
4003 AssertReturn(pCurMmio, VERR_NOT_FOUND);
4004 AssertReturn(pCurMmio->fFlags & (PGMREGMMIORANGE_F_MMIO2 | PGMREGMMIORANGE_F_FIRST_CHUNK), VERR_WRONG_TYPE);
4005
4006 while ( off >= pCurMmio->RamRange.cb
4007 && !(pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK))
4008 {
4009 off -= pCurMmio->RamRange.cb;
4010 pCurMmio = pCurMmio->pNextR3;
4011 }
4012 AssertReturn(off < pCurMmio->RamRange.cb, VERR_INVALID_PARAMETER);
4013
4014 PCPGMPAGE pPage = &pCurMmio->RamRange.aPages[off >> PAGE_SHIFT];
4015 *pHCPhys = PGM_PAGE_GET_HCPHYS(pPage);
4016 pgmUnlock(pVM);
4017 return VINF_SUCCESS;
4018}
4019
4020
4021/**
4022 * Maps a portion of an MMIO2 region into kernel space (host).
4023 *
4024 * The kernel mapping will become invalid when the MMIO2 memory is deregistered
4025 * or the VM is terminated.
4026 *
4027 * @return VBox status code.
4028 *
4029 * @param pVM The cross context VM structure.
4030 * @param pDevIns The device owning the MMIO2 memory.
4031 * @param iSubDev The sub-device number.
4032 * @param iRegion The region.
4033 * @param off The offset into the region. Must be page aligned.
4034 * @param cb The number of bytes to map. Must be page aligned.
4035 * @param pszDesc Mapping description.
4036 * @param pR0Ptr Where to store the R0 address.
4037 */
4038VMMR3_INT_DECL(int) PGMR3PhysMMIO2MapKernel(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion,
4039 RTGCPHYS off, RTGCPHYS cb, const char *pszDesc, PRTR0PTR pR0Ptr)
4040{
4041 /*
4042 * Validate input.
4043 */
4044 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
4045 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4046 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
4047 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4048
4049 PPGMREGMMIORANGE pFirstRegMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
4050 AssertReturn(pFirstRegMmio, VERR_NOT_FOUND);
4051 AssertReturn(pFirstRegMmio->fFlags & (PGMREGMMIORANGE_F_MMIO2 | PGMREGMMIORANGE_F_FIRST_CHUNK), VERR_WRONG_TYPE);
4052 AssertReturn(off < pFirstRegMmio->RamRange.cb, VERR_INVALID_PARAMETER);
4053 AssertReturn(cb <= pFirstRegMmio->RamRange.cb, VERR_INVALID_PARAMETER);
4054 AssertReturn(off + cb <= pFirstRegMmio->RamRange.cb, VERR_INVALID_PARAMETER);
4055 NOREF(pszDesc);
4056
4057 /*
4058 * Pass the request on to the support library/driver.
4059 */
4060#if defined(RT_OS_WINDOWS) || defined(RT_OS_LINUX) || defined(RT_OS_OS2) /** @todo Fully implement RTR0MemObjMapKernelEx everywhere. */
4061 AssertLogRelReturn(off == 0, VERR_NOT_SUPPORTED);
4062 AssertLogRelReturn(pFirstRegMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK, VERR_NOT_SUPPORTED);
4063 int rc = SUPR3PageMapKernel(pFirstRegMmio->pvR3, 0 /*off*/, pFirstRegMmio->RamRange.cb, 0 /*fFlags*/, pR0Ptr);
4064#else
4065 int rc = SUPR3PageMapKernel(pFirstRegMmio->pvR3, off, cb, 0 /*fFlags*/, pR0Ptr);
4066#endif
4067
4068 return rc;
4069}
4070
4071
4072/**
4073 * Changes the region number of an MMIO2 or pre-registered MMIO region.
4074 *
4075 * This is only for dealing with save state issues, nothing else.
4076 *
4077 * @return VBox status code.
4078 *
4079 * @param pVM The cross context VM structure.
4080 * @param pDevIns The device owning the MMIO2 memory.
4081 * @param iSubDev The sub-device number.
4082 * @param iRegion The region.
4083 * @param iNewRegion The new region index.
4084 *
4085 * @sa @bugref{9359}
4086 */
4087VMMR3_INT_DECL(int) PGMR3PhysMMIOExChangeRegionNo(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion,
4088 uint32_t iNewRegion)
4089{
4090 /*
4091 * Validate input.
4092 */
4093 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
4094 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4095 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
4096 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4097 AssertReturn(iNewRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4098
4099 AssertReturn(pVM->enmVMState == VMSTATE_LOADING, VERR_INVALID_STATE);
4100
4101 PPGMREGMMIORANGE pFirstRegMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
4102 AssertReturn(pFirstRegMmio, VERR_NOT_FOUND);
4103 AssertReturn(pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iNewRegion) == NULL, VERR_RESOURCE_IN_USE);
4104
4105 /*
4106 * Make the change.
4107 */
4108 pFirstRegMmio->iRegion = (uint8_t)iNewRegion;
4109
4110 return VINF_SUCCESS;
4111}
4112
4113
4114/**
4115 * Worker for PGMR3PhysRomRegister.
4116 *
4117 * This is here to simplify lock management, i.e. the caller does all the
4118 * locking and we can simply return without needing to remember to unlock
4119 * anything first.
4120 *
4121 * @returns VBox status code.
4122 * @param pVM The cross context VM structure.
4123 * @param pDevIns The device instance owning the ROM.
4124 * @param GCPhys First physical address in the range.
4125 * Must be page aligned!
4126 * @param cb The size of the range (in bytes).
4127 * Must be page aligned!
4128 * @param pvBinary Pointer to the binary data backing the ROM image.
4129 * @param cbBinary The size of the binary data pvBinary points to.
4130 * This must be less or equal to @a cb.
4131 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
4132 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
4133 * @param pszDesc Pointer to description string. This must not be freed.
4134 */
4135static int pgmR3PhysRomRegisterLocked(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
4136 const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
4137{
4138 /*
4139 * Validate input.
4140 */
4141 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4142 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
4143 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
4144 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
4145 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
4146 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
4147 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
4148 AssertReturn(!(fFlags & ~(PGMPHYS_ROM_FLAGS_SHADOWED | PGMPHYS_ROM_FLAGS_PERMANENT_BINARY)), VERR_INVALID_PARAMETER);
4149 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
4150
4151 const uint32_t cPages = cb >> PAGE_SHIFT;
4152
4153 /*
4154 * Find the ROM location in the ROM list first.
4155 */
4156 PPGMROMRANGE pRomPrev = NULL;
4157 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
4158 while (pRom && GCPhysLast >= pRom->GCPhys)
4159 {
4160 if ( GCPhys <= pRom->GCPhysLast
4161 && GCPhysLast >= pRom->GCPhys)
4162 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
4163 GCPhys, GCPhysLast, pszDesc,
4164 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
4165 VERR_PGM_RAM_CONFLICT);
4166 /* next */
4167 pRomPrev = pRom;
4168 pRom = pRom->pNextR3;
4169 }
4170
4171 /*
4172 * Find the RAM location and check for conflicts.
4173 *
4174 * Conflict detection is a bit different than for RAM
4175 * registration since a ROM can be located within a RAM
4176 * range. So, what we have to check for is other memory
4177 * types (other than RAM that is) and that we don't span
4178 * more than one RAM range (layz).
4179 */
4180 bool fRamExists = false;
4181 PPGMRAMRANGE pRamPrev = NULL;
4182 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
4183 while (pRam && GCPhysLast >= pRam->GCPhys)
4184 {
4185 if ( GCPhys <= pRam->GCPhysLast
4186 && GCPhysLast >= pRam->GCPhys)
4187 {
4188 /* completely within? */
4189 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
4190 && GCPhysLast <= pRam->GCPhysLast,
4191 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
4192 GCPhys, GCPhysLast, pszDesc,
4193 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
4194 VERR_PGM_RAM_CONFLICT);
4195 fRamExists = true;
4196 break;
4197 }
4198
4199 /* next */
4200 pRamPrev = pRam;
4201 pRam = pRam->pNextR3;
4202 }
4203 if (fRamExists)
4204 {
4205 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
4206 uint32_t cPagesLeft = cPages;
4207 while (cPagesLeft-- > 0)
4208 {
4209 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
4210 ("%RGp (%R[pgmpage]) isn't a RAM page - registering %RGp-%RGp (%s).\n",
4211 pRam->GCPhys + ((RTGCPHYS)(uintptr_t)(pPage - &pRam->aPages[0]) << PAGE_SHIFT),
4212 pPage, GCPhys, GCPhysLast, pszDesc), VERR_PGM_RAM_CONFLICT);
4213 Assert(PGM_PAGE_IS_ZERO(pPage));
4214 pPage++;
4215 }
4216 }
4217
4218 /*
4219 * Update the base memory reservation if necessary.
4220 */
4221 uint32_t cExtraBaseCost = fRamExists ? 0 : cPages;
4222 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4223 cExtraBaseCost += cPages;
4224 if (cExtraBaseCost)
4225 {
4226 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
4227 if (RT_FAILURE(rc))
4228 return rc;
4229 }
4230
4231 /*
4232 * Allocate memory for the virgin copy of the RAM.
4233 */
4234 PGMMALLOCATEPAGESREQ pReq;
4235 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cPages, GMMACCOUNT_BASE);
4236 AssertRCReturn(rc, rc);
4237
4238 for (uint32_t iPage = 0; iPage < cPages; iPage++)
4239 {
4240 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << PAGE_SHIFT);
4241 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
4242 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
4243 }
4244
4245 rc = GMMR3AllocatePagesPerform(pVM, pReq);
4246 if (RT_FAILURE(rc))
4247 {
4248 GMMR3AllocatePagesCleanup(pReq);
4249 return rc;
4250 }
4251
4252 /*
4253 * Allocate the new ROM range and RAM range (if necessary).
4254 */
4255 PPGMROMRANGE pRomNew;
4256 rc = MMHyperAlloc(pVM, RT_UOFFSETOF_DYN(PGMROMRANGE, aPages[cPages]), 0, MM_TAG_PGM_PHYS, (void **)&pRomNew);
4257 if (RT_SUCCESS(rc))
4258 {
4259 PPGMRAMRANGE pRamNew = NULL;
4260 if (!fRamExists)
4261 rc = MMHyperAlloc(pVM, RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]), sizeof(PGMPAGE), MM_TAG_PGM_PHYS, (void **)&pRamNew);
4262 if (RT_SUCCESS(rc))
4263 {
4264 /*
4265 * Initialize and insert the RAM range (if required).
4266 */
4267 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
4268 if (!fRamExists)
4269 {
4270 pRamNew->pSelfR0 = MMHyperCCToR0(pVM, pRamNew);
4271 pRamNew->pSelfRC = MMHyperCCToRC(pVM, pRamNew);
4272 pRamNew->GCPhys = GCPhys;
4273 pRamNew->GCPhysLast = GCPhysLast;
4274 pRamNew->cb = cb;
4275 pRamNew->pszDesc = pszDesc;
4276 pRamNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_ROM;
4277 pRamNew->pvR3 = NULL;
4278 pRamNew->paLSPages = NULL;
4279
4280 PPGMPAGE pPage = &pRamNew->aPages[0];
4281 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
4282 {
4283 PGM_PAGE_INIT(pPage,
4284 pReq->aPages[iPage].HCPhysGCPhys,
4285 pReq->aPages[iPage].idPage,
4286 PGMPAGETYPE_ROM,
4287 PGM_PAGE_STATE_ALLOCATED);
4288
4289 pRomPage->Virgin = *pPage;
4290 }
4291
4292 pVM->pgm.s.cAllPages += cPages;
4293 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
4294 }
4295 else
4296 {
4297 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
4298 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
4299 {
4300 PGM_PAGE_SET_TYPE(pVM, pPage, PGMPAGETYPE_ROM);
4301 PGM_PAGE_SET_HCPHYS(pVM, pPage, pReq->aPages[iPage].HCPhysGCPhys);
4302 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ALLOCATED);
4303 PGM_PAGE_SET_PAGEID(pVM, pPage, pReq->aPages[iPage].idPage);
4304 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4305 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
4306 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
4307
4308 pRomPage->Virgin = *pPage;
4309 }
4310
4311 pRamNew = pRam;
4312
4313 pVM->pgm.s.cZeroPages -= cPages;
4314 }
4315 pVM->pgm.s.cPrivatePages += cPages;
4316
4317 /* Flush physical page map TLB. */
4318 pgmPhysInvalidatePageMapTLB(pVM);
4319
4320
4321 /* Notify NEM before we register handlers. */
4322 uint32_t const fNemNotify = (fRamExists ? NEM_NOTIFY_PHYS_ROM_F_REPLACE : 0)
4323 | (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED ? NEM_NOTIFY_PHYS_ROM_F_SHADOW : 0);
4324 rc = NEMR3NotifyPhysRomRegisterEarly(pVM, GCPhys, cb, fNemNotify);
4325
4326 /*
4327 * !HACK ALERT! REM + (Shadowed) ROM ==> mess.
4328 *
4329 * If it's shadowed we'll register the handler after the ROM notification
4330 * so we get the access handler callbacks that we should. If it isn't
4331 * shadowed we'll do it the other way around to make REM use the built-in
4332 * ROM behavior and not the handler behavior (which is to route all access
4333 * to PGM atm).
4334 */
4335 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4336 {
4337#ifdef VBOX_WITH_REM
4338 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, true /* fShadowed */);
4339#endif
4340 if (RT_SUCCESS(rc))
4341 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, pVM->pgm.s.hRomPhysHandlerType,
4342 pRomNew, MMHyperCCToR0(pVM, pRomNew), MMHyperCCToRC(pVM, pRomNew),
4343 pszDesc);
4344 }
4345 else
4346 {
4347 if (RT_SUCCESS(rc))
4348 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, pVM->pgm.s.hRomPhysHandlerType,
4349 pRomNew, MMHyperCCToR0(pVM, pRomNew), MMHyperCCToRC(pVM, pRomNew),
4350 pszDesc);
4351#ifdef VBOX_WITH_REM
4352 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, false /* fShadowed */);
4353#endif
4354 }
4355 if (RT_SUCCESS(rc))
4356 {
4357 /*
4358 * Copy the image over to the virgin pages.
4359 * This must be done after linking in the RAM range.
4360 */
4361 size_t cbBinaryLeft = cbBinary;
4362 PPGMPAGE pRamPage = &pRamNew->aPages[(GCPhys - pRamNew->GCPhys) >> PAGE_SHIFT];
4363 for (uint32_t iPage = 0; iPage < cPages; iPage++, pRamPage++)
4364 {
4365 void *pvDstPage;
4366 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << PAGE_SHIFT), &pvDstPage);
4367 if (RT_FAILURE(rc))
4368 {
4369 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
4370 break;
4371 }
4372 if (cbBinaryLeft >= PAGE_SIZE)
4373 {
4374 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), PAGE_SIZE);
4375 cbBinaryLeft -= PAGE_SIZE;
4376 }
4377 else
4378 {
4379 ASMMemZeroPage(pvDstPage); /* (shouldn't be necessary, but can't hurt either) */
4380 if (cbBinaryLeft > 0)
4381 {
4382 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), cbBinaryLeft);
4383 cbBinaryLeft = 0;
4384 }
4385 }
4386 }
4387 if (RT_SUCCESS(rc))
4388 {
4389 /*
4390 * Initialize the ROM range.
4391 * Note that the Virgin member of the pages has already been initialized above.
4392 */
4393 pRomNew->GCPhys = GCPhys;
4394 pRomNew->GCPhysLast = GCPhysLast;
4395 pRomNew->cb = cb;
4396 pRomNew->fFlags = fFlags;
4397 pRomNew->idSavedState = UINT8_MAX;
4398 pRomNew->cbOriginal = cbBinary;
4399 pRomNew->pszDesc = pszDesc;
4400 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY
4401 ? pvBinary : RTMemDup(pvBinary, cbBinary);
4402 if (pRomNew->pvOriginal)
4403 {
4404 for (unsigned iPage = 0; iPage < cPages; iPage++)
4405 {
4406 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
4407 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
4408 PGM_PAGE_INIT_ZERO(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
4409 }
4410
4411 /* update the page count stats for the shadow pages. */
4412 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4413 {
4414 pVM->pgm.s.cZeroPages += cPages;
4415 pVM->pgm.s.cAllPages += cPages;
4416 }
4417
4418 /*
4419 * Insert the ROM range, tell REM and return successfully.
4420 */
4421 pRomNew->pNextR3 = pRom;
4422 pRomNew->pNextR0 = pRom ? MMHyperCCToR0(pVM, pRom) : NIL_RTR0PTR;
4423 pRomNew->pNextRC = pRom ? MMHyperCCToRC(pVM, pRom) : NIL_RTRCPTR;
4424
4425 if (pRomPrev)
4426 {
4427 pRomPrev->pNextR3 = pRomNew;
4428 pRomPrev->pNextR0 = MMHyperCCToR0(pVM, pRomNew);
4429 pRomPrev->pNextRC = MMHyperCCToRC(pVM, pRomNew);
4430 }
4431 else
4432 {
4433 pVM->pgm.s.pRomRangesR3 = pRomNew;
4434 pVM->pgm.s.pRomRangesR0 = MMHyperCCToR0(pVM, pRomNew);
4435 pVM->pgm.s.pRomRangesRC = MMHyperCCToRC(pVM, pRomNew);
4436 }
4437
4438 pgmPhysInvalidatePageMapTLB(pVM);
4439 GMMR3AllocatePagesCleanup(pReq);
4440
4441 /* Notify NEM again. */
4442 return NEMR3NotifyPhysRomRegisterLate(pVM, GCPhys, cb, fNemNotify);
4443 }
4444
4445 /* bail out */
4446 rc = VERR_NO_MEMORY;
4447 }
4448
4449 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
4450 AssertRC(rc2);
4451 }
4452
4453 if (!fRamExists)
4454 {
4455 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
4456 MMHyperFree(pVM, pRamNew);
4457 }
4458 }
4459 MMHyperFree(pVM, pRomNew);
4460 }
4461
4462 /** @todo Purge the mapping cache or something... */
4463 GMMR3FreeAllocatedPages(pVM, pReq);
4464 GMMR3AllocatePagesCleanup(pReq);
4465 return rc;
4466}
4467
4468
4469/**
4470 * Registers a ROM image.
4471 *
4472 * Shadowed ROM images requires double the amount of backing memory, so,
4473 * don't use that unless you have to. Shadowing of ROM images is process
4474 * where we can select where the reads go and where the writes go. On real
4475 * hardware the chipset provides means to configure this. We provide
4476 * PGMR3PhysProtectROM() for this purpose.
4477 *
4478 * A read-only copy of the ROM image will always be kept around while we
4479 * will allocate RAM pages for the changes on demand (unless all memory
4480 * is configured to be preallocated).
4481 *
4482 * @returns VBox status code.
4483 * @param pVM The cross context VM structure.
4484 * @param pDevIns The device instance owning the ROM.
4485 * @param GCPhys First physical address in the range.
4486 * Must be page aligned!
4487 * @param cb The size of the range (in bytes).
4488 * Must be page aligned!
4489 * @param pvBinary Pointer to the binary data backing the ROM image.
4490 * @param cbBinary The size of the binary data pvBinary points to.
4491 * This must be less or equal to @a cb.
4492 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
4493 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
4494 * @param pszDesc Pointer to description string. This must not be freed.
4495 *
4496 * @remark There is no way to remove the rom, automatically on device cleanup or
4497 * manually from the device yet. This isn't difficult in any way, it's
4498 * just not something we expect to be necessary for a while.
4499 */
4500VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
4501 const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
4502{
4503 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p cbBinary=%#x fFlags=%#x pszDesc=%s\n",
4504 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, cbBinary, fFlags, pszDesc));
4505 pgmLock(pVM);
4506 int rc = pgmR3PhysRomRegisterLocked(pVM, pDevIns, GCPhys, cb, pvBinary, cbBinary, fFlags, pszDesc);
4507 pgmUnlock(pVM);
4508 return rc;
4509}
4510
4511
4512/**
4513 * Called by PGMR3MemSetup to reset the shadow, switch to the virgin, and verify
4514 * that the virgin part is untouched.
4515 *
4516 * This is done after the normal memory has been cleared.
4517 *
4518 * ASSUMES that the caller owns the PGM lock.
4519 *
4520 * @param pVM The cross context VM structure.
4521 */
4522int pgmR3PhysRomReset(PVM pVM)
4523{
4524 PGM_LOCK_ASSERT_OWNER(pVM);
4525 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4526 {
4527 const uint32_t cPages = pRom->cb >> PAGE_SHIFT;
4528
4529 if (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4530 {
4531 /*
4532 * Reset the physical handler.
4533 */
4534 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
4535 AssertRCReturn(rc, rc);
4536
4537 /*
4538 * What we do with the shadow pages depends on the memory
4539 * preallocation option. If not enabled, we'll just throw
4540 * out all the dirty pages and replace them by the zero page.
4541 */
4542 if (!pVM->pgm.s.fRamPreAlloc)
4543 {
4544 /* Free the dirty pages. */
4545 uint32_t cPendingPages = 0;
4546 PGMMFREEPAGESREQ pReq;
4547 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
4548 AssertRCReturn(rc, rc);
4549
4550 for (uint32_t iPage = 0; iPage < cPages; iPage++)
4551 if ( !PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow)
4552 && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow))
4553 {
4554 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
4555 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, &pRom->aPages[iPage].Shadow,
4556 pRom->GCPhys + (iPage << PAGE_SHIFT),
4557 (PGMPAGETYPE)PGM_PAGE_GET_TYPE(&pRom->aPages[iPage].Shadow));
4558 AssertLogRelRCReturn(rc, rc);
4559 }
4560
4561 if (cPendingPages)
4562 {
4563 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
4564 AssertLogRelRCReturn(rc, rc);
4565 }
4566 GMMR3FreePagesCleanup(pReq);
4567 }
4568 else
4569 {
4570 /* clear all the shadow pages. */
4571 for (uint32_t iPage = 0; iPage < cPages; iPage++)
4572 {
4573 if (PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow))
4574 continue;
4575 Assert(!PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow));
4576 void *pvDstPage;
4577 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
4578 rc = pgmPhysPageMakeWritableAndMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pvDstPage);
4579 if (RT_FAILURE(rc))
4580 break;
4581 ASMMemZeroPage(pvDstPage);
4582 }
4583 AssertRCReturn(rc, rc);
4584 }
4585 }
4586
4587 /*
4588 * Restore the original ROM pages after a saved state load.
4589 * Also, in strict builds check that ROM pages remain unmodified.
4590 */
4591#ifndef VBOX_STRICT
4592 if (pVM->pgm.s.fRestoreRomPagesOnReset)
4593#endif
4594 {
4595 size_t cbSrcLeft = pRom->cbOriginal;
4596 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
4597 uint32_t cRestored = 0;
4598 for (uint32_t iPage = 0; iPage < cPages && cbSrcLeft > 0; iPage++, pbSrcPage += PAGE_SIZE)
4599 {
4600 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
4601 void const *pvDstPage;
4602 int rc = pgmPhysPageMapReadOnly(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPage);
4603 if (RT_FAILURE(rc))
4604 break;
4605
4606 if (memcmp(pvDstPage, pbSrcPage, RT_MIN(cbSrcLeft, PAGE_SIZE)))
4607 {
4608 if (pVM->pgm.s.fRestoreRomPagesOnReset)
4609 {
4610 void *pvDstPageW;
4611 rc = pgmPhysPageMap(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPageW);
4612 AssertLogRelRCReturn(rc, rc);
4613 memcpy(pvDstPageW, pbSrcPage, RT_MIN(cbSrcLeft, PAGE_SIZE));
4614 cRestored++;
4615 }
4616 else
4617 LogRel(("pgmR3PhysRomReset: %RGp: ROM page changed (%s)\n", GCPhys, pRom->pszDesc));
4618 }
4619 cbSrcLeft -= RT_MIN(cbSrcLeft, PAGE_SIZE);
4620 }
4621 if (cRestored > 0)
4622 LogRel(("PGM: ROM \"%s\": Reloaded %u of %u pages.\n", pRom->pszDesc, cRestored, cPages));
4623 }
4624 }
4625
4626 /* Clear the ROM restore flag now as we only need to do this once after
4627 loading saved state. */
4628 pVM->pgm.s.fRestoreRomPagesOnReset = false;
4629
4630 return VINF_SUCCESS;
4631}
4632
4633
4634/**
4635 * Called by PGMR3Term to free resources.
4636 *
4637 * ASSUMES that the caller owns the PGM lock.
4638 *
4639 * @param pVM The cross context VM structure.
4640 */
4641void pgmR3PhysRomTerm(PVM pVM)
4642{
4643 /*
4644 * Free the heap copy of the original bits.
4645 */
4646 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4647 {
4648 if ( pRom->pvOriginal
4649 && !(pRom->fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY))
4650 {
4651 RTMemFree((void *)pRom->pvOriginal);
4652 pRom->pvOriginal = NULL;
4653 }
4654 }
4655}
4656
4657
4658/**
4659 * Change the shadowing of a range of ROM pages.
4660 *
4661 * This is intended for implementing chipset specific memory registers
4662 * and will not be very strict about the input. It will silently ignore
4663 * any pages that are not the part of a shadowed ROM.
4664 *
4665 * @returns VBox status code.
4666 * @retval VINF_PGM_SYNC_CR3
4667 *
4668 * @param pVM The cross context VM structure.
4669 * @param GCPhys Where to start. Page aligned.
4670 * @param cb How much to change. Page aligned.
4671 * @param enmProt The new ROM protection.
4672 */
4673VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
4674{
4675 /*
4676 * Check input
4677 */
4678 if (!cb)
4679 return VINF_SUCCESS;
4680 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
4681 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
4682 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
4683 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
4684 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
4685
4686 /*
4687 * Process the request.
4688 */
4689 pgmLock(pVM);
4690 int rc = VINF_SUCCESS;
4691 bool fFlushTLB = false;
4692 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4693 {
4694 if ( GCPhys <= pRom->GCPhysLast
4695 && GCPhysLast >= pRom->GCPhys
4696 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
4697 {
4698 /*
4699 * Iterate the relevant pages and make necessary the changes.
4700 */
4701 bool fChanges = false;
4702 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
4703 ? pRom->cb >> PAGE_SHIFT
4704 : (GCPhysLast - pRom->GCPhys + 1) >> PAGE_SHIFT;
4705 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
4706 iPage < cPages;
4707 iPage++)
4708 {
4709 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
4710 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
4711 {
4712 fChanges = true;
4713
4714 /* flush references to the page. */
4715 PPGMPAGE pRamPage = pgmPhysGetPage(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT));
4716 int rc2 = pgmPoolTrackUpdateGCPhys(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT), pRamPage,
4717 true /*fFlushPTEs*/, &fFlushTLB);
4718 if (rc2 != VINF_SUCCESS && (rc == VINF_SUCCESS || RT_FAILURE(rc2)))
4719 rc = rc2;
4720 uint8_t u2State = PGM_PAGE_GET_NEM_STATE(pRamPage);
4721
4722 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
4723 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
4724
4725 *pOld = *pRamPage;
4726 *pRamPage = *pNew;
4727 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
4728
4729 /* Tell NEM about the backing and protection change. */
4730 if (VM_IS_NEM_ENABLED(pVM))
4731 {
4732 PGMPAGETYPE enmType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pNew);
4733 NEMHCNotifyPhysPageChanged(pVM, GCPhys, PGM_PAGE_GET_HCPHYS(pOld), PGM_PAGE_GET_HCPHYS(pNew),
4734 pgmPhysPageCalcNemProtection(pRamPage, enmType), enmType, &u2State);
4735 PGM_PAGE_SET_NEM_STATE(pRamPage, u2State);
4736 }
4737 }
4738 pRomPage->enmProt = enmProt;
4739 }
4740
4741 /*
4742 * Reset the access handler if we made changes, no need
4743 * to optimize this.
4744 */
4745 if (fChanges)
4746 {
4747 int rc2 = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
4748 if (RT_FAILURE(rc2))
4749 {
4750 pgmUnlock(pVM);
4751 AssertRC(rc);
4752 return rc2;
4753 }
4754 }
4755
4756 /* Advance - cb isn't updated. */
4757 GCPhys = pRom->GCPhys + (cPages << PAGE_SHIFT);
4758 }
4759 }
4760 pgmUnlock(pVM);
4761 if (fFlushTLB)
4762 PGM_INVL_ALL_VCPU_TLBS(pVM);
4763
4764 return rc;
4765}
4766
4767
4768/**
4769 * Sets the Address Gate 20 state.
4770 *
4771 * @param pVCpu The cross context virtual CPU structure.
4772 * @param fEnable True if the gate should be enabled.
4773 * False if the gate should be disabled.
4774 */
4775VMMDECL(void) PGMR3PhysSetA20(PVMCPU pVCpu, bool fEnable)
4776{
4777 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVCpu->pgm.s.fA20Enabled));
4778 if (pVCpu->pgm.s.fA20Enabled != fEnable)
4779 {
4780#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4781 PCCPUMCTX pCtx = CPUMQueryGuestCtxPtr(pVCpu);
4782 if ( CPUMIsGuestInVmxRootMode(pCtx)
4783 && !fEnable)
4784 {
4785 Log(("Cannot enter A20M mode while in VMX root mode\n"));
4786 return;
4787 }
4788#endif
4789 pVCpu->pgm.s.fA20Enabled = fEnable;
4790 pVCpu->pgm.s.GCPhysA20Mask = ~((RTGCPHYS)!fEnable << 20);
4791#ifdef VBOX_WITH_REM
4792 REMR3A20Set(pVCpu->pVMR3, pVCpu, fEnable);
4793#endif
4794 NEMR3NotifySetA20(pVCpu, fEnable);
4795#ifdef PGM_WITH_A20
4796 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_UPDATE_PAGE_BIT_VIRTUAL;
4797 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
4798 pgmR3RefreshShadowModeAfterA20Change(pVCpu);
4799 HMFlushTlb(pVCpu);
4800#endif
4801 IEMTlbInvalidateAllPhysical(pVCpu);
4802 STAM_REL_COUNTER_INC(&pVCpu->pgm.s.cA20Changes);
4803 }
4804}
4805
4806
4807/**
4808 * Tree enumeration callback for dealing with age rollover.
4809 * It will perform a simple compression of the current age.
4810 */
4811static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
4812{
4813 /* Age compression - ASSUMES iNow == 4. */
4814 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
4815 if (pChunk->iLastUsed >= UINT32_C(0xffffff00))
4816 pChunk->iLastUsed = 3;
4817 else if (pChunk->iLastUsed >= UINT32_C(0xfffff000))
4818 pChunk->iLastUsed = 2;
4819 else if (pChunk->iLastUsed)
4820 pChunk->iLastUsed = 1;
4821 else /* iLastUsed = 0 */
4822 pChunk->iLastUsed = 4;
4823
4824 NOREF(pvUser);
4825 return 0;
4826}
4827
4828
4829/**
4830 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
4831 */
4832typedef struct PGMR3PHYSCHUNKUNMAPCB
4833{
4834 PVM pVM; /**< Pointer to the VM. */
4835 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
4836} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
4837
4838
4839/**
4840 * Callback used to find the mapping that's been unused for
4841 * the longest time.
4842 */
4843static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLU32NODECORE pNode, void *pvUser)
4844{
4845 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
4846 PPGMR3PHYSCHUNKUNMAPCB pArg = (PPGMR3PHYSCHUNKUNMAPCB)pvUser;
4847
4848 /*
4849 * Check for locks and compare when last used.
4850 */
4851 if (pChunk->cRefs)
4852 return 0;
4853 if (pChunk->cPermRefs)
4854 return 0;
4855 if ( pArg->pChunk
4856 && pChunk->iLastUsed >= pArg->pChunk->iLastUsed)
4857 return 0;
4858
4859 /*
4860 * Check that it's not in any of the TLBs.
4861 */
4862 PVM pVM = pArg->pVM;
4863 if ( pVM->pgm.s.ChunkR3Map.Tlb.aEntries[PGM_CHUNKR3MAPTLB_IDX(pChunk->Core.Key)].idChunk
4864 == pChunk->Core.Key)
4865 {
4866 pChunk = NULL;
4867 return 0;
4868 }
4869#ifdef VBOX_STRICT
4870 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
4871 {
4872 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk != pChunk);
4873 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk != pChunk->Core.Key);
4874 }
4875#endif
4876
4877 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbR0.aEntries); i++)
4878 if (pVM->pgm.s.PhysTlbR0.aEntries[i].pMap == pChunk)
4879 return 0;
4880 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbR3.aEntries); i++)
4881 if (pVM->pgm.s.PhysTlbR3.aEntries[i].pMap == pChunk)
4882 return 0;
4883
4884 pArg->pChunk = pChunk;
4885 return 0;
4886}
4887
4888
4889/**
4890 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
4891 *
4892 * The candidate will not be part of any TLBs, so no need to flush
4893 * anything afterwards.
4894 *
4895 * @returns Chunk id.
4896 * @param pVM The cross context VM structure.
4897 */
4898static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
4899{
4900 PGM_LOCK_ASSERT_OWNER(pVM);
4901
4902 /*
4903 * Enumerate the age tree starting with the left most node.
4904 */
4905 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
4906 PGMR3PHYSCHUNKUNMAPCB Args;
4907 Args.pVM = pVM;
4908 Args.pChunk = NULL;
4909 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, &Args);
4910 Assert(Args.pChunk);
4911 if (Args.pChunk)
4912 {
4913 Assert(Args.pChunk->cRefs == 0);
4914 Assert(Args.pChunk->cPermRefs == 0);
4915 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
4916 return Args.pChunk->Core.Key;
4917 }
4918
4919 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
4920 return INT32_MAX;
4921}
4922
4923
4924/**
4925 * Rendezvous callback used by pgmR3PhysUnmapChunk that unmaps a chunk
4926 *
4927 * This is only called on one of the EMTs while the other ones are waiting for
4928 * it to complete this function.
4929 *
4930 * @returns VINF_SUCCESS (VBox strict status code).
4931 * @param pVM The cross context VM structure.
4932 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
4933 * @param pvUser User pointer. Unused
4934 *
4935 */
4936static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysUnmapChunkRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
4937{
4938 int rc = VINF_SUCCESS;
4939 pgmLock(pVM);
4940 NOREF(pVCpu); NOREF(pvUser);
4941
4942 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
4943 {
4944 /* Flush the pgm pool cache; call the internal rendezvous handler as we're already in a rendezvous handler here. */
4945 /** @todo also not really efficient to unmap a chunk that contains PD
4946 * or PT pages. */
4947 pgmR3PoolClearAllRendezvous(pVM, &pVM->aCpus[0], NULL /* no need to flush the REM TLB as we already did that above */);
4948
4949 /*
4950 * Request the ring-0 part to unmap a chunk to make space in the mapping cache.
4951 */
4952 GMMMAPUNMAPCHUNKREQ Req;
4953 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
4954 Req.Hdr.cbReq = sizeof(Req);
4955 Req.pvR3 = NULL;
4956 Req.idChunkMap = NIL_GMM_CHUNKID;
4957 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
4958 if (Req.idChunkUnmap != INT32_MAX)
4959 {
4960 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
4961 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
4962 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
4963 if (RT_SUCCESS(rc))
4964 {
4965 /*
4966 * Remove the unmapped one.
4967 */
4968 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
4969 AssertRelease(pUnmappedChunk);
4970 AssertRelease(!pUnmappedChunk->cRefs);
4971 AssertRelease(!pUnmappedChunk->cPermRefs);
4972 pUnmappedChunk->pv = NULL;
4973 pUnmappedChunk->Core.Key = UINT32_MAX;
4974#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
4975 MMR3HeapFree(pUnmappedChunk);
4976#else
4977 MMR3UkHeapFree(pVM, pUnmappedChunk, MM_TAG_PGM_CHUNK_MAPPING);
4978#endif
4979 pVM->pgm.s.ChunkR3Map.c--;
4980 pVM->pgm.s.cUnmappedChunks++;
4981
4982 /*
4983 * Flush dangling PGM pointers (R3 & R0 ptrs to GC physical addresses).
4984 */
4985 /** @todo We should not flush chunks which include cr3 mappings. */
4986 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
4987 {
4988 PPGMCPU pPGM = &pVM->aCpus[idCpu].pgm.s;
4989
4990 pPGM->pGst32BitPdR3 = NULL;
4991 pPGM->pGstPaePdptR3 = NULL;
4992 pPGM->pGstAmd64Pml4R3 = NULL;
4993#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
4994 pPGM->pGst32BitPdR0 = NIL_RTR0PTR;
4995 pPGM->pGstPaePdptR0 = NIL_RTR0PTR;
4996 pPGM->pGstAmd64Pml4R0 = NIL_RTR0PTR;
4997#endif
4998 for (unsigned i = 0; i < RT_ELEMENTS(pPGM->apGstPaePDsR3); i++)
4999 {
5000 pPGM->apGstPaePDsR3[i] = NULL;
5001#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
5002 pPGM->apGstPaePDsR0[i] = NIL_RTR0PTR;
5003#endif
5004 }
5005
5006 /* Flush REM TLBs. */
5007 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5008 }
5009#ifdef VBOX_WITH_REM
5010 /* Flush REM translation blocks. */
5011 REMFlushTBs(pVM);
5012#endif
5013 }
5014 }
5015 }
5016 pgmUnlock(pVM);
5017 return rc;
5018}
5019
5020/**
5021 * Unmap a chunk to free up virtual address space (request packet handler for pgmR3PhysChunkMap)
5022 *
5023 * @returns VBox status code.
5024 * @param pVM The cross context VM structure.
5025 */
5026void pgmR3PhysUnmapChunk(PVM pVM)
5027{
5028 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysUnmapChunkRendezvous, NULL);
5029 AssertRC(rc);
5030}
5031
5032
5033/**
5034 * Maps the given chunk into the ring-3 mapping cache.
5035 *
5036 * This will call ring-0.
5037 *
5038 * @returns VBox status code.
5039 * @param pVM The cross context VM structure.
5040 * @param idChunk The chunk in question.
5041 * @param ppChunk Where to store the chunk tracking structure.
5042 *
5043 * @remarks Called from within the PGM critical section.
5044 * @remarks Can be called from any thread!
5045 */
5046int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
5047{
5048 int rc;
5049
5050 PGM_LOCK_ASSERT_OWNER(pVM);
5051
5052 /*
5053 * Move the chunk time forward.
5054 */
5055 pVM->pgm.s.ChunkR3Map.iNow++;
5056 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
5057 {
5058 pVM->pgm.s.ChunkR3Map.iNow = 4;
5059 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, NULL);
5060 }
5061
5062 /*
5063 * Allocate a new tracking structure first.
5064 */
5065#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
5066 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
5067#else
5068 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3UkHeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk), NULL);
5069#endif
5070 AssertReturn(pChunk, VERR_NO_MEMORY);
5071 pChunk->Core.Key = idChunk;
5072 pChunk->iLastUsed = pVM->pgm.s.ChunkR3Map.iNow;
5073
5074 /*
5075 * Request the ring-0 part to map the chunk in question.
5076 */
5077 GMMMAPUNMAPCHUNKREQ Req;
5078 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
5079 Req.Hdr.cbReq = sizeof(Req);
5080 Req.pvR3 = NULL;
5081 Req.idChunkMap = idChunk;
5082 Req.idChunkUnmap = NIL_GMM_CHUNKID;
5083
5084 /* Must be callable from any thread, so can't use VMMR3CallR0. */
5085 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
5086 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, NIL_VMCPUID, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
5087 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
5088 if (RT_SUCCESS(rc))
5089 {
5090 pChunk->pv = Req.pvR3;
5091
5092 /*
5093 * If we're running out of virtual address space, then we should
5094 * unmap another chunk.
5095 *
5096 * Currently, an unmap operation requires that all other virtual CPUs
5097 * are idling and not by chance making use of the memory we're
5098 * unmapping. So, we create an async unmap operation here.
5099 *
5100 * Now, when creating or restoring a saved state this wont work very
5101 * well since we may want to restore all guest RAM + a little something.
5102 * So, we have to do the unmap synchronously. Fortunately for us
5103 * though, during these operations the other virtual CPUs are inactive
5104 * and it should be safe to do this.
5105 */
5106 /** @todo Eventually we should lock all memory when used and do
5107 * map+unmap as one kernel call without any rendezvous or
5108 * other precautions. */
5109 if (pVM->pgm.s.ChunkR3Map.c + 1 >= pVM->pgm.s.ChunkR3Map.cMax)
5110 {
5111 switch (VMR3GetState(pVM))
5112 {
5113 case VMSTATE_LOADING:
5114 case VMSTATE_SAVING:
5115 {
5116 PVMCPU pVCpu = VMMGetCpu(pVM);
5117 if ( pVCpu
5118 && pVM->pgm.s.cDeprecatedPageLocks == 0)
5119 {
5120 pgmR3PhysUnmapChunkRendezvous(pVM, pVCpu, NULL);
5121 break;
5122 }
5123 }
5124 RT_FALL_THRU();
5125 default:
5126 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysUnmapChunk, 1, pVM);
5127 AssertRC(rc);
5128 break;
5129 }
5130 }
5131
5132 /*
5133 * Update the tree. We must do this after any unmapping to make sure
5134 * the chunk we're going to return isn't unmapped by accident.
5135 */
5136 AssertPtr(Req.pvR3);
5137 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
5138 AssertRelease(fRc);
5139 pVM->pgm.s.ChunkR3Map.c++;
5140 pVM->pgm.s.cMappedChunks++;
5141 }
5142 else
5143 {
5144 /** @todo this may fail because of /proc/sys/vm/max_map_count, so we
5145 * should probably restrict ourselves on linux. */
5146 AssertRC(rc);
5147#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
5148 MMR3HeapFree(pChunk);
5149#else
5150 MMR3UkHeapFree(pVM, pChunk, MM_TAG_PGM_CHUNK_MAPPING);
5151#endif
5152 pChunk = NULL;
5153 }
5154
5155 *ppChunk = pChunk;
5156 return rc;
5157}
5158
5159
5160/**
5161 * For VMMCALLRING3_PGM_MAP_CHUNK, considered internal.
5162 *
5163 * @returns see pgmR3PhysChunkMap.
5164 * @param pVM The cross context VM structure.
5165 * @param idChunk The chunk to map.
5166 */
5167VMMR3DECL(int) PGMR3PhysChunkMap(PVM pVM, uint32_t idChunk)
5168{
5169 PPGMCHUNKR3MAP pChunk;
5170 int rc;
5171
5172 pgmLock(pVM);
5173 rc = pgmR3PhysChunkMap(pVM, idChunk, &pChunk);
5174 pgmUnlock(pVM);
5175 return rc;
5176}
5177
5178
5179/**
5180 * Invalidates the TLB for the ring-3 mapping cache.
5181 *
5182 * @param pVM The cross context VM structure.
5183 */
5184VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
5185{
5186 pgmLock(pVM);
5187 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
5188 {
5189 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
5190 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
5191 }
5192 /* The page map TLB references chunks, so invalidate that one too. */
5193 pgmPhysInvalidatePageMapTLB(pVM);
5194 pgmUnlock(pVM);
5195}
5196
5197
5198/**
5199 * Response to VMMCALLRING3_PGM_ALLOCATE_LARGE_HANDY_PAGE to allocate a large
5200 * (2MB) page for use with a nested paging PDE.
5201 *
5202 * @returns The following VBox status codes.
5203 * @retval VINF_SUCCESS on success.
5204 * @retval VINF_EM_NO_MEMORY if we're out of memory.
5205 *
5206 * @param pVM The cross context VM structure.
5207 * @param GCPhys GC physical start address of the 2 MB range
5208 */
5209VMMR3DECL(int) PGMR3PhysAllocateLargeHandyPage(PVM pVM, RTGCPHYS GCPhys)
5210{
5211#ifdef PGM_WITH_LARGE_PAGES
5212 uint64_t u64TimeStamp1, u64TimeStamp2;
5213
5214 pgmLock(pVM);
5215
5216 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
5217 u64TimeStamp1 = RTTimeMilliTS();
5218 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_LARGE_HANDY_PAGE, 0, NULL);
5219 u64TimeStamp2 = RTTimeMilliTS();
5220 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
5221 if (RT_SUCCESS(rc))
5222 {
5223 Assert(pVM->pgm.s.cLargeHandyPages == 1);
5224
5225 uint32_t idPage = pVM->pgm.s.aLargeHandyPage[0].idPage;
5226 RTHCPHYS HCPhys = pVM->pgm.s.aLargeHandyPage[0].HCPhysGCPhys;
5227
5228 void *pv;
5229
5230 /* Map the large page into our address space.
5231 *
5232 * Note: assuming that within the 2 MB range:
5233 * - GCPhys + PAGE_SIZE = HCPhys + PAGE_SIZE (whole point of this exercise)
5234 * - user space mapping is continuous as well
5235 * - page id (GCPhys) + 1 = page id (GCPhys + PAGE_SIZE)
5236 */
5237 rc = pgmPhysPageMapByPageID(pVM, idPage, HCPhys, &pv);
5238 AssertLogRelMsg(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n", idPage, HCPhys, rc));
5239
5240 if (RT_SUCCESS(rc))
5241 {
5242 /*
5243 * Clear the pages.
5244 */
5245 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
5246 for (unsigned i = 0; i < _2M/PAGE_SIZE; i++)
5247 {
5248 ASMMemZeroPage(pv);
5249
5250 PPGMPAGE pPage;
5251 rc = pgmPhysGetPageEx(pVM, GCPhys, &pPage);
5252 AssertRC(rc);
5253
5254 Assert(PGM_PAGE_IS_ZERO(pPage));
5255 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatRZPageReplaceZero);
5256 pVM->pgm.s.cZeroPages--;
5257
5258 /*
5259 * Do the PGMPAGE modifications.
5260 */
5261 pVM->pgm.s.cPrivatePages++;
5262 PGM_PAGE_SET_HCPHYS(pVM, pPage, HCPhys);
5263 PGM_PAGE_SET_PAGEID(pVM, pPage, idPage);
5264 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ALLOCATED);
5265 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_PDE);
5266 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
5267 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
5268
5269 /* Somewhat dirty assumption that page ids are increasing. */
5270 idPage++;
5271
5272 HCPhys += PAGE_SIZE;
5273 GCPhys += PAGE_SIZE;
5274
5275 pv = (void *)((uintptr_t)pv + PAGE_SIZE);
5276
5277 Log3(("PGMR3PhysAllocateLargePage: idPage=%#x HCPhys=%RGp\n", idPage, HCPhys));
5278 }
5279 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
5280
5281 /* Flush all TLBs. */
5282 PGM_INVL_ALL_VCPU_TLBS(pVM);
5283 pgmPhysInvalidatePageMapTLB(pVM);
5284 }
5285 pVM->pgm.s.cLargeHandyPages = 0;
5286 }
5287
5288 if (RT_SUCCESS(rc))
5289 {
5290 static uint32_t cTimeOut = 0;
5291 uint64_t u64TimeStampDelta = u64TimeStamp2 - u64TimeStamp1;
5292
5293 if (u64TimeStampDelta > 100)
5294 {
5295 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatLargePageOverflow);
5296 if ( ++cTimeOut > 10
5297 || u64TimeStampDelta > 1000 /* more than one second forces an early retirement from allocating large pages. */)
5298 {
5299 /* If repeated attempts to allocate a large page takes more than 100 ms, then we fall back to normal 4k pages.
5300 * E.g. Vista 64 tries to move memory around, which takes a huge amount of time.
5301 */
5302 LogRel(("PGMR3PhysAllocateLargePage: allocating large pages takes too long (last attempt %d ms; nr of timeouts %d); DISABLE\n", u64TimeStampDelta, cTimeOut));
5303 PGMSetLargePageUsage(pVM, false);
5304 }
5305 }
5306 else
5307 if (cTimeOut > 0)
5308 cTimeOut--;
5309 }
5310
5311 pgmUnlock(pVM);
5312 return rc;
5313#else
5314 RT_NOREF(pVM, GCPhys);
5315 return VERR_NOT_IMPLEMENTED;
5316#endif /* PGM_WITH_LARGE_PAGES */
5317}
5318
5319
5320/**
5321 * Response to VM_FF_PGM_NEED_HANDY_PAGES and VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES.
5322 *
5323 * This function will also work the VM_FF_PGM_NO_MEMORY force action flag, to
5324 * signal and clear the out of memory condition. When contracted, this API is
5325 * used to try clear the condition when the user wants to resume.
5326 *
5327 * @returns The following VBox status codes.
5328 * @retval VINF_SUCCESS on success. FFs cleared.
5329 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in
5330 * this case and it gets accompanied by VM_FF_PGM_NO_MEMORY.
5331 *
5332 * @param pVM The cross context VM structure.
5333 *
5334 * @remarks The VINF_EM_NO_MEMORY status is for the benefit of the FF processing
5335 * in EM.cpp and shouldn't be propagated outside TRPM, HM, EM and
5336 * pgmPhysEnsureHandyPage. There is one exception to this in the \#PF
5337 * handler.
5338 */
5339VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
5340{
5341 pgmLock(pVM);
5342
5343 /*
5344 * Allocate more pages, noting down the index of the first new page.
5345 */
5346 uint32_t iClear = pVM->pgm.s.cHandyPages;
5347 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_PGM_HANDY_PAGE_IPE);
5348 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
5349 int rcAlloc = VINF_SUCCESS;
5350 int rcSeed = VINF_SUCCESS;
5351 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
5352 while (rc == VERR_GMM_SEED_ME)
5353 {
5354 void *pvChunk;
5355 rcAlloc = rc = SUPR3PageAlloc(GMM_CHUNK_SIZE >> PAGE_SHIFT, &pvChunk);
5356 if (RT_SUCCESS(rc))
5357 {
5358 rcSeed = rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_SEED_CHUNK, (uintptr_t)pvChunk, NULL);
5359 if (RT_FAILURE(rc))
5360 SUPR3PageFree(pvChunk, GMM_CHUNK_SIZE >> PAGE_SHIFT);
5361 }
5362 if (RT_SUCCESS(rc))
5363 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
5364 }
5365
5366 /** @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) */
5367 if ( rc == VERR_GMM_HIT_VM_ACCOUNT_LIMIT
5368 && pVM->pgm.s.cHandyPages > 0)
5369 {
5370 /* Still handy pages left, so don't panic. */
5371 rc = VINF_SUCCESS;
5372 }
5373
5374 if (RT_SUCCESS(rc))
5375 {
5376 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
5377 Assert(pVM->pgm.s.cHandyPages > 0);
5378 VM_FF_CLEAR(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
5379 VM_FF_CLEAR(pVM, VM_FF_PGM_NO_MEMORY);
5380
5381#ifdef VBOX_STRICT
5382 uint32_t i;
5383 for (i = iClear; i < pVM->pgm.s.cHandyPages; i++)
5384 if ( pVM->pgm.s.aHandyPages[i].idPage == NIL_GMM_PAGEID
5385 || pVM->pgm.s.aHandyPages[i].idSharedPage != NIL_GMM_PAGEID
5386 || (pVM->pgm.s.aHandyPages[i].HCPhysGCPhys & PAGE_OFFSET_MASK))
5387 break;
5388 if (i != pVM->pgm.s.cHandyPages)
5389 {
5390 RTAssertMsg1Weak(NULL, __LINE__, __FILE__, __FUNCTION__);
5391 RTAssertMsg2Weak("i=%d iClear=%d cHandyPages=%d\n", i, iClear, pVM->pgm.s.cHandyPages);
5392 for (uint32_t j = iClear; j < pVM->pgm.s.cHandyPages; j++)
5393 RTAssertMsg2Add("%03d: idPage=%d HCPhysGCPhys=%RHp idSharedPage=%d%\n", j,
5394 pVM->pgm.s.aHandyPages[j].idPage,
5395 pVM->pgm.s.aHandyPages[j].HCPhysGCPhys,
5396 pVM->pgm.s.aHandyPages[j].idSharedPage,
5397 j == i ? " <---" : "");
5398 RTAssertPanic();
5399 }
5400#endif
5401 /*
5402 * Clear the pages.
5403 */
5404 while (iClear < pVM->pgm.s.cHandyPages)
5405 {
5406 PGMMPAGEDESC pPage = &pVM->pgm.s.aHandyPages[iClear];
5407 void *pv;
5408 rc = pgmPhysPageMapByPageID(pVM, pPage->idPage, pPage->HCPhysGCPhys, &pv);
5409 AssertLogRelMsgBreak(RT_SUCCESS(rc),
5410 ("%u/%u: idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n",
5411 iClear, pVM->pgm.s.cHandyPages, pPage->idPage, pPage->HCPhysGCPhys, rc));
5412 ASMMemZeroPage(pv);
5413 iClear++;
5414 Log3(("PGMR3PhysAllocateHandyPages: idPage=%#x HCPhys=%RGp\n", pPage->idPage, pPage->HCPhysGCPhys));
5415 }
5416 }
5417 else
5418 {
5419 uint64_t cAllocPages, cMaxPages, cBalloonPages;
5420
5421 /*
5422 * We should never get here unless there is a genuine shortage of
5423 * memory (or some internal error). Flag the error so the VM can be
5424 * suspended ASAP and the user informed. If we're totally out of
5425 * handy pages we will return failure.
5426 */
5427 /* Report the failure. */
5428 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc rcAlloc=%Rrc rcSeed=%Rrc cHandyPages=%#x\n"
5429 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
5430 rc, rcAlloc, rcSeed,
5431 pVM->pgm.s.cHandyPages,
5432 pVM->pgm.s.cAllPages,
5433 pVM->pgm.s.cPrivatePages,
5434 pVM->pgm.s.cSharedPages,
5435 pVM->pgm.s.cZeroPages));
5436
5437 if (GMMR3QueryMemoryStats(pVM, &cAllocPages, &cMaxPages, &cBalloonPages) == VINF_SUCCESS)
5438 {
5439 LogRel(("GMM: Statistics:\n"
5440 " Allocated pages: %RX64\n"
5441 " Maximum pages: %RX64\n"
5442 " Ballooned pages: %RX64\n", cAllocPages, cMaxPages, cBalloonPages));
5443 }
5444
5445 if ( rc != VERR_NO_MEMORY
5446 && rc != VERR_NO_PHYS_MEMORY
5447 && rc != VERR_LOCK_FAILED)
5448 {
5449 for (uint32_t i = 0; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
5450 {
5451 LogRel(("PGM: aHandyPages[#%#04x] = {.HCPhysGCPhys=%RHp, .idPage=%#08x, .idSharedPage=%#08x}\n",
5452 i, pVM->pgm.s.aHandyPages[i].HCPhysGCPhys, pVM->pgm.s.aHandyPages[i].idPage,
5453 pVM->pgm.s.aHandyPages[i].idSharedPage));
5454 uint32_t const idPage = pVM->pgm.s.aHandyPages[i].idPage;
5455 if (idPage != NIL_GMM_PAGEID)
5456 {
5457 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
5458 pRam;
5459 pRam = pRam->pNextR3)
5460 {
5461 uint32_t const cPages = pRam->cb >> PAGE_SHIFT;
5462 for (uint32_t iPage = 0; iPage < cPages; iPage++)
5463 if (PGM_PAGE_GET_PAGEID(&pRam->aPages[iPage]) == idPage)
5464 LogRel(("PGM: Used by %RGp %R[pgmpage] (%s)\n",
5465 pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pRam->aPages[iPage], pRam->pszDesc));
5466 }
5467 }
5468 }
5469 }
5470
5471 if (rc == VERR_NO_MEMORY)
5472 {
5473 uint64_t cbHostRamAvail = 0;
5474 int rc2 = RTSystemQueryAvailableRam(&cbHostRamAvail);
5475 if (RT_SUCCESS(rc2))
5476 LogRel(("Host RAM: %RU64MB available\n", cbHostRamAvail / _1M));
5477 else
5478 LogRel(("Cannot determine the amount of available host memory\n"));
5479 }
5480
5481 /* Set the FFs and adjust rc. */
5482 VM_FF_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
5483 VM_FF_SET(pVM, VM_FF_PGM_NO_MEMORY);
5484 if ( rc == VERR_NO_MEMORY
5485 || rc == VERR_NO_PHYS_MEMORY
5486 || rc == VERR_LOCK_FAILED)
5487 rc = VINF_EM_NO_MEMORY;
5488 }
5489
5490 pgmUnlock(pVM);
5491 return rc;
5492}
5493
5494
5495/**
5496 * Frees the specified RAM page and replaces it with the ZERO page.
5497 *
5498 * This is used by ballooning, remapping MMIO2, RAM reset and state loading.
5499 *
5500 * @param pVM The cross context VM structure.
5501 * @param pReq Pointer to the request.
5502 * @param pcPendingPages Where the number of pages waiting to be freed are
5503 * kept. This will normally be incremented.
5504 * @param pPage Pointer to the page structure.
5505 * @param GCPhys The guest physical address of the page, if applicable.
5506 * @param enmNewType New page type for NEM notification, since several
5507 * callers will change the type upon successful return.
5508 *
5509 * @remarks The caller must own the PGM lock.
5510 */
5511int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys,
5512 PGMPAGETYPE enmNewType)
5513{
5514 /*
5515 * Assert sanity.
5516 */
5517 PGM_LOCK_ASSERT_OWNER(pVM);
5518 if (RT_UNLIKELY( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM
5519 && PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_ROM_SHADOW))
5520 {
5521 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
5522 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
5523 }
5524
5525 /** @todo What about ballooning of large pages??! */
5526 Assert( PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE
5527 && PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE_DISABLED);
5528
5529 if ( PGM_PAGE_IS_ZERO(pPage)
5530 || PGM_PAGE_IS_BALLOONED(pPage))
5531 return VINF_SUCCESS;
5532
5533 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
5534 Log3(("pgmPhysFreePage: idPage=%#x GCPhys=%RGp pPage=%R[pgmpage]\n", idPage, GCPhys, pPage));
5535 if (RT_UNLIKELY( idPage == NIL_GMM_PAGEID
5536 || idPage > GMM_PAGEID_LAST
5537 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID))
5538 {
5539 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
5540 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
5541 }
5542 const RTHCPHYS HCPhysPrev = PGM_PAGE_GET_HCPHYS(pPage);
5543
5544 /* update page count stats. */
5545 if (PGM_PAGE_IS_SHARED(pPage))
5546 pVM->pgm.s.cSharedPages--;
5547 else
5548 pVM->pgm.s.cPrivatePages--;
5549 pVM->pgm.s.cZeroPages++;
5550
5551 /* Deal with write monitored pages. */
5552 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
5553 {
5554 PGM_PAGE_SET_WRITTEN_TO(pVM, pPage);
5555 pVM->pgm.s.cWrittenToPages++;
5556 }
5557
5558 /*
5559 * pPage = ZERO page.
5560 */
5561 PGM_PAGE_SET_HCPHYS(pVM, pPage, pVM->pgm.s.HCPhysZeroPg);
5562 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
5563 PGM_PAGE_SET_PAGEID(pVM, pPage, NIL_GMM_PAGEID);
5564 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
5565 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
5566 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
5567
5568 /* Flush physical page map TLB entry. */
5569 pgmPhysInvalidatePageMapTLBEntry(pVM, GCPhys);
5570
5571 /* Notify NEM. */
5572 /** @todo consider doing batch NEM notifications. */
5573 if (VM_IS_NEM_ENABLED(pVM))
5574 {
5575 uint8_t u2State = PGM_PAGE_GET_NEM_STATE(pPage);
5576 NEMHCNotifyPhysPageChanged(pVM, GCPhys, HCPhysPrev, pVM->pgm.s.HCPhysZeroPg,
5577 pgmPhysPageCalcNemProtection(pPage, enmNewType), enmNewType, &u2State);
5578 PGM_PAGE_SET_NEM_STATE(pPage, u2State);
5579 }
5580
5581 /*
5582 * Make sure it's not in the handy page array.
5583 */
5584 for (uint32_t i = pVM->pgm.s.cHandyPages; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
5585 {
5586 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
5587 {
5588 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
5589 break;
5590 }
5591 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
5592 {
5593 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
5594 break;
5595 }
5596 }
5597
5598 /*
5599 * Push it onto the page array.
5600 */
5601 uint32_t iPage = *pcPendingPages;
5602 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
5603 *pcPendingPages += 1;
5604
5605 pReq->aPages[iPage].idPage = idPage;
5606
5607 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
5608 return VINF_SUCCESS;
5609
5610 /*
5611 * Flush the pages.
5612 */
5613 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
5614 if (RT_SUCCESS(rc))
5615 {
5616 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
5617 *pcPendingPages = 0;
5618 }
5619 return rc;
5620}
5621
5622
5623/**
5624 * Converts a GC physical address to a HC ring-3 pointer, with some
5625 * additional checks.
5626 *
5627 * @returns VBox status code.
5628 * @retval VINF_SUCCESS on success.
5629 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
5630 * access handler of some kind.
5631 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
5632 * accesses or is odd in any way.
5633 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
5634 *
5635 * @param pVM The cross context VM structure.
5636 * @param GCPhys The GC physical address to convert. Since this is only
5637 * used for filling the REM TLB, the A20 mask must be
5638 * applied before calling this API.
5639 * @param fWritable Whether write access is required.
5640 * @param ppv Where to store the pointer corresponding to GCPhys on
5641 * success.
5642 */
5643VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
5644{
5645 pgmLock(pVM);
5646 PGM_A20_ASSERT_MASKED(VMMGetCpu(pVM), GCPhys);
5647
5648 PPGMRAMRANGE pRam;
5649 PPGMPAGE pPage;
5650 int rc = pgmPhysGetPageAndRangeEx(pVM, GCPhys, &pPage, &pRam);
5651 if (RT_SUCCESS(rc))
5652 {
5653 if (PGM_PAGE_IS_BALLOONED(pPage))
5654 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
5655 else if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
5656 rc = VINF_SUCCESS;
5657 else
5658 {
5659 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
5660 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
5661 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
5662 {
5663 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
5664 * in -norawr0 mode. */
5665 if (fWritable)
5666 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
5667 }
5668 else
5669 {
5670 /* Temporarily disabled physical handler(s), since the recompiler
5671 doesn't get notified when it's reset we'll have to pretend it's
5672 operating normally. */
5673 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
5674 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
5675 else
5676 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
5677 }
5678 }
5679 if (RT_SUCCESS(rc))
5680 {
5681 int rc2;
5682
5683 /* Make sure what we return is writable. */
5684 if (fWritable)
5685 switch (PGM_PAGE_GET_STATE(pPage))
5686 {
5687 case PGM_PAGE_STATE_ALLOCATED:
5688 break;
5689 case PGM_PAGE_STATE_BALLOONED:
5690 AssertFailed();
5691 break;
5692 case PGM_PAGE_STATE_ZERO:
5693 case PGM_PAGE_STATE_SHARED:
5694 if (rc == VINF_PGM_PHYS_TLB_CATCH_WRITE)
5695 break;
5696 RT_FALL_THRU();
5697 case PGM_PAGE_STATE_WRITE_MONITORED:
5698 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)PAGE_OFFSET_MASK);
5699 AssertLogRelRCReturn(rc2, rc2);
5700 break;
5701 }
5702
5703 /* Get a ring-3 mapping of the address. */
5704 PPGMPAGER3MAPTLBE pTlbe;
5705 rc2 = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
5706 AssertLogRelRCReturn(rc2, rc2);
5707 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
5708 /** @todo mapping/locking hell; this isn't horribly efficient since
5709 * pgmPhysPageLoadIntoTlb will repeat the lookup we've done here. */
5710
5711 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
5712 }
5713 else
5714 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
5715
5716 /* else: handler catching all access, no pointer returned. */
5717 }
5718 else
5719 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
5720
5721 pgmUnlock(pVM);
5722 return rc;
5723}
5724
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