VirtualBox

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

Last change on this file since 80135 was 80135, checked in by vboxsync, 5 years ago

PGM: Split the phys guest->host TLB into separate ring-0 and ring-3 entities and align it properly. bugref:9511 bugref:9517

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 210.8 KB
Line 
1/* $Id: PGMPhys.cpp 80135 2019-08-05 15:05:33Z 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,
2809#if defined(VBOX_WITH_MORE_RING0_MEM_MAPPINGS)
2810 &R0PtrChunk,
2811#elif defined(VBOX_WITH_2X_4GB_ADDR_SPACE)
2812 VM_IS_HM_OR_NEM_ENABLED(pVM) ? &R0PtrChunk : NULL,
2813#else
2814 NULL,
2815#endif
2816 paChunkPages);
2817 AssertLogRelMsgRCBreakStmt(rc, ("rc=%Rrc, cChunkPages=%#zx\n", rc, cChunkPages), RTMemTmpFree(paChunkPages));
2818
2819#if defined(VBOX_WITH_MORE_RING0_MEM_MAPPINGS)
2820 Assert(R0PtrChunk != NIL_RTR0PTR);
2821#elif defined(VBOX_WITH_2X_4GB_ADDR_SPACE)
2822 if (!VM_IS_HM_OR_NEM_ENABLED(pVM))
2823 R0PtrChunk = NIL_RTR0PTR;
2824#else
2825 R0PtrChunk = (uintptr_t)pvChunk;
2826#endif
2827 memset(pvChunk, 0, cChunkPages << PAGE_SHIFT);
2828
2829 pNew = (PPGMREGMMIORANGE)pvChunk;
2830 pNew->RamRange.fFlags = PGM_RAM_RANGE_FLAGS_FLOATING;
2831 pNew->RamRange.pSelfR0 = R0PtrChunk + RT_UOFFSETOF(PGMREGMMIORANGE, RamRange);
2832
2833 /*
2834 * If we might end up in raw-mode, make a HMA mapping of the range,
2835 * just like we do for memory above 4GB.
2836 */
2837 if (!VM_IS_RAW_MODE_ENABLED(pVM))
2838 pNew->RamRange.pSelfRC = NIL_RTRCPTR;
2839 else
2840 {
2841 RTGCPTR GCPtrChunkMap = pVM->pgm.s.GCPtrPrevRamRangeMapping - RT_ALIGN_Z(cbChunk, _4M);
2842 RTGCPTR const GCPtrChunk = GCPtrChunkMap + PAGE_SIZE;
2843#ifndef PGM_WITHOUT_MAPPINGS
2844 rc = PGMR3MapPT(pVM, GCPtrChunkMap, (uint32_t)cbChunk, 0 /*fFlags*/, pgmR3PhysMMIOExRangeRelocate, pNew, pszDesc);
2845 if (RT_SUCCESS(rc))
2846 {
2847#endif /* !PGM_WITHOUT_MAPPINGS */
2848 pVM->pgm.s.GCPtrPrevRamRangeMapping = GCPtrChunkMap;
2849#ifndef PGM_WITHOUT_MAPPINGS
2850 RTGCPTR GCPtrPage = GCPtrChunk;
2851 for (uint32_t iPage = 0; iPage < cChunkPages && RT_SUCCESS(rc); iPage++, GCPtrPage += PAGE_SIZE)
2852 rc = PGMMap(pVM, GCPtrPage, paChunkPages[iPage].Phys, PAGE_SIZE, 0);
2853 }
2854 if (RT_FAILURE(rc))
2855 {
2856 SUPR3PageFreeEx(pvChunk, cChunkPages);
2857 RTMemTmpFree(paChunkPages);
2858 break;
2859 }
2860#endif /* !PGM_WITHOUT_MAPPINGS */
2861 pNew->RamRange.pSelfRC = GCPtrChunk + RT_UOFFSETOF(PGMREGMMIORANGE, RamRange);
2862 }
2863 RTMemTmpFree(paChunkPages);
2864 }
2865 /*
2866 * Not so big, do a one time hyper allocation.
2867 */
2868 else
2869 {
2870 rc = MMR3HyperAllocOnceNoRel(pVM, cbRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
2871 AssertLogRelMsgRCBreak(rc, ("cbRange=%zu\n", cbRange));
2872
2873 /*
2874 * Initialize allocation specific items.
2875 */
2876 //pNew->RamRange.fFlags = 0;
2877 pNew->RamRange.pSelfR0 = MMHyperCCToR0(pVM, &pNew->RamRange);
2878 pNew->RamRange.pSelfRC = MMHyperCCToRC(pVM, &pNew->RamRange);
2879 }
2880
2881 /*
2882 * Initialize the registration structure (caller does specific bits).
2883 */
2884 pNew->pDevInsR3 = pDevIns;
2885 //pNew->pvR3 = NULL;
2886 //pNew->pNext = NULL;
2887 //pNew->fFlags = 0;
2888 if (iChunk == 0)
2889 pNew->fFlags |= PGMREGMMIORANGE_F_FIRST_CHUNK;
2890 if (iChunk + 1 == cChunks)
2891 pNew->fFlags |= PGMREGMMIORANGE_F_LAST_CHUNK;
2892 pNew->iSubDev = iSubDev;
2893 pNew->iRegion = iRegion;
2894 pNew->idSavedState = UINT8_MAX;
2895 pNew->idMmio2 = UINT8_MAX;
2896 //pNew->pPhysHandlerR3 = NULL;
2897 //pNew->paLSPages = NULL;
2898 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
2899 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
2900 pNew->RamRange.pszDesc = pszDesc;
2901 pNew->RamRange.cb = pNew->cbReal = (RTGCPHYS)cPagesTrackedByChunk << X86_PAGE_SHIFT;
2902 pNew->RamRange.fFlags |= PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO_EX;
2903 //pNew->RamRange.pvR3 = NULL;
2904 //pNew->RamRange.paLSPages = NULL;
2905
2906 *ppNext = pNew;
2907 ASMCompilerBarrier();
2908 cPagesLeft -= cPagesTrackedByChunk;
2909 ppNext = &pNew->pNextR3;
2910 }
2911 Assert(cPagesLeft == 0);
2912
2913 if (RT_SUCCESS(rc))
2914 {
2915 Assert((*ppHeadRet)->fFlags & PGMREGMMIORANGE_F_FIRST_CHUNK);
2916 return VINF_SUCCESS;
2917 }
2918
2919 /*
2920 * Free floating ranges.
2921 */
2922 while (*ppHeadRet)
2923 {
2924 PPGMREGMMIORANGE pFree = *ppHeadRet;
2925 *ppHeadRet = pFree->pNextR3;
2926
2927 if (pFree->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
2928 {
2929 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIORANGE, RamRange.aPages[pFree->RamRange.cb >> X86_PAGE_SHIFT]);
2930 size_t const cChunkPages = RT_ALIGN_Z(cbRange, PAGE_SIZE) >> PAGE_SHIFT;
2931 SUPR3PageFreeEx(pFree, cChunkPages);
2932 }
2933 }
2934
2935 return rc;
2936}
2937
2938
2939/**
2940 * Common worker PGMR3PhysMMIOExPreRegister & PGMR3PhysMMIO2Register that links
2941 * a complete registration entry into the lists and lookup tables.
2942 *
2943 * @param pVM The cross context VM structure.
2944 * @param pNew The new MMIO / MMIO2 registration to link.
2945 */
2946static void pgmR3PhysMMIOExLink(PVM pVM, PPGMREGMMIORANGE pNew)
2947{
2948 /*
2949 * Link it into the list (order doesn't matter, so insert it at the head).
2950 *
2951 * Note! The range we're link may consist of multiple chunks, so we have to
2952 * find the last one.
2953 */
2954 PPGMREGMMIORANGE pLast = pNew;
2955 for (pLast = pNew; ; pLast = pLast->pNextR3)
2956 {
2957 if (pLast->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
2958 break;
2959 Assert(pLast->pNextR3);
2960 Assert(pLast->pNextR3->pDevInsR3 == pNew->pDevInsR3);
2961 Assert(pLast->pNextR3->iSubDev == pNew->iSubDev);
2962 Assert(pLast->pNextR3->iRegion == pNew->iRegion);
2963 Assert((pLast->pNextR3->fFlags & PGMREGMMIORANGE_F_MMIO2) == (pNew->fFlags & PGMREGMMIORANGE_F_MMIO2));
2964 Assert(pLast->pNextR3->idMmio2 == (pLast->fFlags & PGMREGMMIORANGE_F_MMIO2 ? pNew->idMmio2 + 1 : UINT8_MAX));
2965 }
2966
2967 pgmLock(pVM);
2968
2969 /* Link in the chain of ranges at the head of the list. */
2970 pLast->pNextR3 = pVM->pgm.s.pRegMmioRangesR3;
2971 pVM->pgm.s.pRegMmioRangesR3 = pNew;
2972
2973 /* If MMIO, insert the MMIO2 range/page IDs. */
2974 uint8_t idMmio2 = pNew->idMmio2;
2975 if (idMmio2 != UINT8_MAX)
2976 {
2977 for (;;)
2978 {
2979 Assert(pNew->fFlags & PGMREGMMIORANGE_F_MMIO2);
2980 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == NULL);
2981 Assert(pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] == NIL_RTR0PTR);
2982 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = pNew;
2983 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = pNew->RamRange.pSelfR0 - RT_UOFFSETOF(PGMREGMMIORANGE, RamRange);
2984 if (pNew->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
2985 break;
2986 pNew = pNew->pNextR3;
2987 }
2988 }
2989 else
2990 Assert(!(pNew->fFlags & PGMREGMMIORANGE_F_MMIO2));
2991
2992 pgmPhysInvalidatePageMapTLB(pVM);
2993 pgmUnlock(pVM);
2994}
2995
2996
2997/**
2998 * Allocate and pre-register an MMIO region.
2999 *
3000 * This is currently the way to deal with large MMIO regions. It may in the
3001 * future be extended to be the way we deal with all MMIO regions, but that
3002 * means we'll have to do something about the simple list based approach we take
3003 * to tracking the registrations.
3004 *
3005 * @returns VBox status code.
3006 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
3007 * memory.
3008 * @retval VERR_ALREADY_EXISTS if the region already exists.
3009 *
3010 * @param pVM The cross context VM structure.
3011 * @param pDevIns The device instance owning the region.
3012 * @param iSubDev The sub-device number.
3013 * @param iRegion The region number. If the MMIO2 memory is a PCI
3014 * I/O region this number has to be the number of that
3015 * region. Otherwise it can be any number safe
3016 * UINT8_MAX.
3017 * @param cbRegion The size of the region. Must be page aligned.
3018 * @param hType The physical handler callback type.
3019 * @param pvUserR3 User parameter for ring-3 context callbacks.
3020 * @param pvUserR0 User parameter for ring-0 context callbacks.
3021 * @param pvUserRC User parameter for raw-mode context callbacks.
3022 * @param pszDesc The description.
3023 *
3024 * @thread EMT
3025 *
3026 * @sa PGMR3PhysMMIORegister, PGMR3PhysMMIO2Register,
3027 * PGMR3PhysMMIOExMap, PGMR3PhysMMIOExUnmap, PGMR3PhysMMIOExDeregister.
3028 */
3029VMMR3DECL(int) PGMR3PhysMMIOExPreRegister(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cbRegion,
3030 PGMPHYSHANDLERTYPE hType, RTR3PTR pvUserR3, RTR0PTR pvUserR0, RTRCPTR pvUserRC,
3031 const char *pszDesc)
3032{
3033 /*
3034 * Validate input.
3035 */
3036 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3037 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3038 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3039 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3040 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
3041 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
3042 AssertReturn(pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion) == NULL, VERR_ALREADY_EXISTS);
3043 AssertReturn(!(cbRegion & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3044 AssertReturn(cbRegion, VERR_INVALID_PARAMETER);
3045
3046 const uint32_t cPages = cbRegion >> PAGE_SHIFT;
3047 AssertLogRelReturn(((RTGCPHYS)cPages << PAGE_SHIFT) == cbRegion, VERR_INVALID_PARAMETER);
3048 AssertLogRelReturn(cPages <= (MM_MMIO_64_MAX >> X86_PAGE_SHIFT), VERR_OUT_OF_RANGE);
3049
3050 /*
3051 * For the 2nd+ instance, mangle the description string so it's unique.
3052 */
3053 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
3054 {
3055 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
3056 if (!pszDesc)
3057 return VERR_NO_MEMORY;
3058 }
3059
3060 /*
3061 * Register the MMIO callbacks.
3062 */
3063 PPGMPHYSHANDLER pPhysHandler;
3064 int rc = pgmHandlerPhysicalExCreate(pVM, hType, pvUserR3, pvUserR0, pvUserRC, pszDesc, &pPhysHandler);
3065 if (RT_SUCCESS(rc))
3066 {
3067 /*
3068 * Create the registered MMIO range record for it.
3069 */
3070 PPGMREGMMIORANGE pNew;
3071 rc = pgmR3PhysMMIOExCreate(pVM, pDevIns, iSubDev, iRegion, cbRegion, pszDesc, &pNew);
3072 if (RT_SUCCESS(rc))
3073 {
3074 Assert(!(pNew->fFlags & PGMREGMMIORANGE_F_MMIO2));
3075
3076 /*
3077 * Intialize the page structures and set up physical handlers (one for each chunk).
3078 */
3079 for (PPGMREGMMIORANGE pCur = pNew; pCur != NULL && RT_SUCCESS(rc); pCur = pCur->pNextR3)
3080 {
3081 if (pCur == pNew)
3082 pCur->pPhysHandlerR3 = pPhysHandler;
3083 else
3084 rc = pgmHandlerPhysicalExDup(pVM, pPhysHandler, &pCur->pPhysHandlerR3);
3085
3086 uint32_t iPage = pCur->RamRange.cb >> X86_PAGE_SHIFT;
3087 while (iPage-- > 0)
3088 PGM_PAGE_INIT_ZERO(&pCur->RamRange.aPages[iPage], pVM, PGMPAGETYPE_MMIO);
3089 }
3090 if (RT_SUCCESS(rc))
3091 {
3092 /*
3093 * Update the page count stats, link the registration and we're done.
3094 */
3095 pVM->pgm.s.cAllPages += cPages;
3096 pVM->pgm.s.cPureMmioPages += cPages;
3097
3098 pgmR3PhysMMIOExLink(pVM, pNew);
3099 return VINF_SUCCESS;
3100 }
3101
3102 /*
3103 * Clean up in case we're out of memory for extra access handlers.
3104 */
3105 while (pNew != NULL)
3106 {
3107 PPGMREGMMIORANGE pFree = pNew;
3108 pNew = pFree->pNextR3;
3109
3110 if (pFree->pPhysHandlerR3)
3111 {
3112 pgmHandlerPhysicalExDestroy(pVM, pFree->pPhysHandlerR3);
3113 pFree->pPhysHandlerR3 = NULL;
3114 }
3115
3116 if (pFree->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
3117 {
3118 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIORANGE, RamRange.aPages[pFree->RamRange.cb >> X86_PAGE_SHIFT]);
3119 size_t const cChunkPages = RT_ALIGN_Z(cbRange, PAGE_SIZE) >> PAGE_SHIFT;
3120 SUPR3PageFreeEx(pFree, cChunkPages);
3121 }
3122 }
3123 }
3124 else
3125 pgmHandlerPhysicalExDestroy(pVM, pPhysHandler);
3126 }
3127 return rc;
3128}
3129
3130
3131/**
3132 * Allocate and register an MMIO2 region.
3133 *
3134 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's RAM
3135 * associated with a device. It is also non-shared memory with a permanent
3136 * ring-3 mapping and page backing (presently).
3137 *
3138 * A MMIO2 range may overlap with base memory if a lot of RAM is configured for
3139 * the VM, in which case we'll drop the base memory pages. Presently we will
3140 * make no attempt to preserve anything that happens to be present in the base
3141 * memory that is replaced, this is of course incorrect but it's too much
3142 * effort.
3143 *
3144 * @returns VBox status code.
3145 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
3146 * memory.
3147 * @retval VERR_ALREADY_EXISTS if the region already exists.
3148 *
3149 * @param pVM The cross context VM structure.
3150 * @param pDevIns The device instance owning the region.
3151 * @param iSubDev The sub-device number.
3152 * @param iRegion The region number. If the MMIO2 memory is a PCI
3153 * I/O region this number has to be the number of that
3154 * region. Otherwise it can be any number safe
3155 * UINT8_MAX.
3156 * @param cb The size of the region. Must be page aligned.
3157 * @param fFlags Reserved for future use, must be zero.
3158 * @param ppv Where to store the pointer to the ring-3 mapping of
3159 * the memory.
3160 * @param pszDesc The description.
3161 * @thread EMT
3162 */
3163VMMR3DECL(int) PGMR3PhysMMIO2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cb,
3164 uint32_t fFlags, void **ppv, const char *pszDesc)
3165{
3166 /*
3167 * Validate input.
3168 */
3169 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3170 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3171 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3172 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3173 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
3174 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
3175 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
3176 AssertReturn(pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion) == NULL, VERR_ALREADY_EXISTS);
3177 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3178 AssertReturn(cb, VERR_INVALID_PARAMETER);
3179 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3180
3181 const uint32_t cPages = cb >> PAGE_SHIFT;
3182 AssertLogRelReturn(((RTGCPHYS)cPages << PAGE_SHIFT) == cb, VERR_INVALID_PARAMETER);
3183 AssertLogRelReturn(cPages <= (MM_MMIO_64_MAX >> X86_PAGE_SHIFT), VERR_OUT_OF_RANGE);
3184
3185 /*
3186 * For the 2nd+ instance, mangle the description string so it's unique.
3187 */
3188 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
3189 {
3190 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
3191 if (!pszDesc)
3192 return VERR_NO_MEMORY;
3193 }
3194
3195 /*
3196 * Allocate an MMIO2 range ID (not freed on failure).
3197 *
3198 * The zero ID is not used as it could be confused with NIL_GMM_PAGEID, so
3199 * the IDs goes from 1 thru PGM_MMIO2_MAX_RANGES.
3200 */
3201 unsigned cChunks = pgmR3PhysMMIOExCalcChunkCount(pVM, cb, NULL, NULL);
3202 pgmLock(pVM);
3203 uint8_t idMmio2 = pVM->pgm.s.cMmio2Regions + 1;
3204 unsigned cNewMmio2Regions = pVM->pgm.s.cMmio2Regions + cChunks;
3205 if (cNewMmio2Regions > PGM_MMIO2_MAX_RANGES)
3206 {
3207 pgmUnlock(pVM);
3208 AssertLogRelFailedReturn(VERR_PGM_TOO_MANY_MMIO2_RANGES);
3209 }
3210 pVM->pgm.s.cMmio2Regions = cNewMmio2Regions;
3211 pgmUnlock(pVM);
3212
3213 /*
3214 * Try reserve and allocate the backing memory first as this is what is
3215 * most likely to fail.
3216 */
3217 int rc = MMR3AdjustFixedReservation(pVM, cPages, pszDesc);
3218 if (RT_SUCCESS(rc))
3219 {
3220 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cPages * sizeof(SUPPAGE));
3221 if (RT_SUCCESS(rc))
3222 {
3223 void *pvPages;
3224 rc = SUPR3PageAllocEx(cPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
3225 if (RT_SUCCESS(rc))
3226 {
3227 memset(pvPages, 0, cPages * PAGE_SIZE);
3228
3229 /*
3230 * Create the registered MMIO range record for it.
3231 */
3232 PPGMREGMMIORANGE pNew;
3233 rc = pgmR3PhysMMIOExCreate(pVM, pDevIns, iSubDev, iRegion, cb, pszDesc, &pNew);
3234 if (RT_SUCCESS(rc))
3235 {
3236 uint32_t iSrcPage = 0;
3237 uint8_t *pbCurPages = (uint8_t *)pvPages;
3238 for (PPGMREGMMIORANGE pCur = pNew; pCur; pCur = pCur->pNextR3)
3239 {
3240 pCur->pvR3 = pbCurPages;
3241 pCur->RamRange.pvR3 = pbCurPages;
3242 pCur->idMmio2 = idMmio2;
3243 pCur->fFlags |= PGMREGMMIORANGE_F_MMIO2;
3244
3245 uint32_t iDstPage = pCur->RamRange.cb >> X86_PAGE_SHIFT;
3246 while (iDstPage-- > 0)
3247 {
3248 PGM_PAGE_INIT(&pNew->RamRange.aPages[iDstPage],
3249 paPages[iDstPage + iSrcPage].Phys,
3250 PGM_MMIO2_PAGEID_MAKE(idMmio2, iDstPage),
3251 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
3252 }
3253
3254 /* advance. */
3255 iSrcPage += pCur->RamRange.cb >> X86_PAGE_SHIFT;
3256 pbCurPages += pCur->RamRange.cb;
3257 idMmio2++;
3258 }
3259
3260 RTMemTmpFree(paPages);
3261
3262 /*
3263 * Update the page count stats, link the registration and we're done.
3264 */
3265 pVM->pgm.s.cAllPages += cPages;
3266 pVM->pgm.s.cPrivatePages += cPages;
3267
3268 pgmR3PhysMMIOExLink(pVM, pNew);
3269
3270 *ppv = pvPages;
3271 return VINF_SUCCESS;
3272 }
3273
3274 SUPR3PageFreeEx(pvPages, cPages);
3275 }
3276 }
3277 RTMemTmpFree(paPages);
3278 MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pszDesc);
3279 }
3280 if (pDevIns->iInstance > 0)
3281 MMR3HeapFree((void *)pszDesc);
3282 return rc;
3283}
3284
3285
3286/**
3287 * Deregisters and frees an MMIO2 region or a pre-registered MMIO region
3288 *
3289 * Any physical (and virtual) access handlers registered for the region must
3290 * be deregistered before calling this function.
3291 *
3292 * @returns VBox status code.
3293 * @param pVM The cross context VM structure.
3294 * @param pDevIns The device instance owning the region.
3295 * @param iSubDev The sub-device number. Pass UINT32_MAX for wildcard
3296 * matching.
3297 * @param iRegion The region. Pass UINT32_MAX for wildcard matching.
3298 */
3299VMMR3DECL(int) PGMR3PhysMMIOExDeregister(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion)
3300{
3301 /*
3302 * Validate input.
3303 */
3304 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3305 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3306 AssertReturn(iSubDev <= UINT8_MAX || iSubDev == UINT32_MAX, VERR_INVALID_PARAMETER);
3307 AssertReturn(iRegion <= UINT8_MAX || iRegion == UINT32_MAX, VERR_INVALID_PARAMETER);
3308
3309 /*
3310 * The loop here scanning all registrations will make sure that multi-chunk ranges
3311 * get properly deregistered, though it's original purpose was the wildcard iRegion.
3312 */
3313 pgmLock(pVM);
3314 int rc = VINF_SUCCESS;
3315 unsigned cFound = 0;
3316 PPGMREGMMIORANGE pPrev = NULL;
3317 PPGMREGMMIORANGE pCur = pVM->pgm.s.pRegMmioRangesR3;
3318 while (pCur)
3319 {
3320 if ( pCur->pDevInsR3 == pDevIns
3321 && ( iRegion == UINT32_MAX
3322 || pCur->iRegion == iRegion)
3323 && ( iSubDev == UINT32_MAX
3324 || pCur->iSubDev == iSubDev) )
3325 {
3326 cFound++;
3327
3328 /*
3329 * Unmap it if it's mapped.
3330 */
3331 if (pCur->fFlags & PGMREGMMIORANGE_F_MAPPED)
3332 {
3333 int rc2 = PGMR3PhysMMIOExUnmap(pVM, pCur->pDevInsR3, pCur->iSubDev, pCur->iRegion, pCur->RamRange.GCPhys);
3334 AssertRC(rc2);
3335 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3336 rc = rc2;
3337 }
3338
3339 /*
3340 * Must tell IOM about MMIO (first one only).
3341 */
3342 if ((pCur->fFlags & (PGMREGMMIORANGE_F_MMIO2 | PGMREGMMIORANGE_F_FIRST_CHUNK)) == PGMREGMMIORANGE_F_MMIO2)
3343 IOMR3MmioExNotifyDeregistered(pVM, pCur->pPhysHandlerR3->pvUserR3);
3344
3345 /*
3346 * Unlink it
3347 */
3348 PPGMREGMMIORANGE pNext = pCur->pNextR3;
3349 if (pPrev)
3350 pPrev->pNextR3 = pNext;
3351 else
3352 pVM->pgm.s.pRegMmioRangesR3 = pNext;
3353 pCur->pNextR3 = NULL;
3354
3355 uint8_t idMmio2 = pCur->idMmio2;
3356 if (idMmio2 != UINT8_MAX)
3357 {
3358 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == pCur);
3359 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = NULL;
3360 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = NIL_RTR0PTR;
3361 }
3362
3363 /*
3364 * Free the memory.
3365 */
3366 uint32_t const cPages = pCur->cbReal >> PAGE_SHIFT;
3367 if (pCur->fFlags & PGMREGMMIORANGE_F_MMIO2)
3368 {
3369 int rc2 = SUPR3PageFreeEx(pCur->pvR3, cPages);
3370 AssertRC(rc2);
3371 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3372 rc = rc2;
3373
3374 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pCur->RamRange.pszDesc);
3375 AssertRC(rc2);
3376 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3377 rc = rc2;
3378 }
3379
3380 /* we're leaking hyper memory here if done at runtime. */
3381#ifdef VBOX_STRICT
3382 VMSTATE const enmState = VMR3GetState(pVM);
3383 AssertMsg( enmState == VMSTATE_POWERING_OFF
3384 || enmState == VMSTATE_POWERING_OFF_LS
3385 || enmState == VMSTATE_OFF
3386 || enmState == VMSTATE_OFF_LS
3387 || enmState == VMSTATE_DESTROYING
3388 || enmState == VMSTATE_TERMINATED
3389 || enmState == VMSTATE_CREATING
3390 , ("%s\n", VMR3GetStateName(enmState)));
3391#endif
3392
3393 const bool fIsMmio2 = RT_BOOL(pCur->fFlags & PGMREGMMIORANGE_F_MMIO2);
3394 if (pCur->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
3395 {
3396 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIORANGE, RamRange.aPages[cPages]);
3397 size_t const cChunkPages = RT_ALIGN_Z(cbRange, PAGE_SIZE) >> PAGE_SHIFT;
3398 SUPR3PageFreeEx(pCur, cChunkPages);
3399 }
3400 /*else
3401 {
3402 rc = MMHyperFree(pVM, pCur); - does not work, see the alloc call.
3403 AssertRCReturn(rc, rc);
3404 } */
3405
3406
3407 /* update page count stats */
3408 pVM->pgm.s.cAllPages -= cPages;
3409 if (fIsMmio2)
3410 pVM->pgm.s.cPrivatePages -= cPages;
3411 else
3412 pVM->pgm.s.cPureMmioPages -= cPages;
3413
3414 /* next */
3415 pCur = pNext;
3416 }
3417 else
3418 {
3419 pPrev = pCur;
3420 pCur = pCur->pNextR3;
3421 }
3422 }
3423 pgmPhysInvalidatePageMapTLB(pVM);
3424 pgmUnlock(pVM);
3425 return !cFound && iRegion != UINT32_MAX && iSubDev != UINT32_MAX ? VERR_NOT_FOUND : rc;
3426}
3427
3428
3429/**
3430 * Maps a MMIO2 region or a pre-registered MMIO region.
3431 *
3432 * This is done when a guest / the bios / state loading changes the
3433 * PCI config. The replacing of base memory has the same restrictions
3434 * as during registration, of course.
3435 *
3436 * @returns VBox status code.
3437 *
3438 * @param pVM The cross context VM structure.
3439 * @param pDevIns The device instance owning the region.
3440 * @param iSubDev The sub-device number of the registered region.
3441 * @param iRegion The index of the registered region.
3442 * @param GCPhys The guest-physical address to be remapped.
3443 */
3444VMMR3DECL(int) PGMR3PhysMMIOExMap(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS GCPhys)
3445{
3446 /*
3447 * Validate input.
3448 *
3449 * Note! It's safe to walk the MMIO/MMIO2 list since registrations only
3450 * happens during VM construction.
3451 */
3452 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3453 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3454 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3455 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3456 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
3457 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
3458 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3459
3460 PPGMREGMMIORANGE pFirstMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
3461 AssertReturn(pFirstMmio, VERR_NOT_FOUND);
3462 Assert(pFirstMmio->fFlags & PGMREGMMIORANGE_F_FIRST_CHUNK);
3463
3464 PPGMREGMMIORANGE pLastMmio = pFirstMmio;
3465 RTGCPHYS cbRange = 0;
3466 for (;;)
3467 {
3468 AssertReturn(!(pLastMmio->fFlags & PGMREGMMIORANGE_F_MAPPED), VERR_WRONG_ORDER);
3469 Assert(pLastMmio->RamRange.GCPhys == NIL_RTGCPHYS);
3470 Assert(pLastMmio->RamRange.GCPhysLast == NIL_RTGCPHYS);
3471 Assert(pLastMmio->pDevInsR3 == pFirstMmio->pDevInsR3);
3472 Assert(pLastMmio->iSubDev == pFirstMmio->iSubDev);
3473 Assert(pLastMmio->iRegion == pFirstMmio->iRegion);
3474 cbRange += pLastMmio->RamRange.cb;
3475 if (pLastMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3476 break;
3477 pLastMmio = pLastMmio->pNextR3;
3478 }
3479
3480 RTGCPHYS GCPhysLast = GCPhys + cbRange - 1;
3481 AssertLogRelReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3482
3483 /*
3484 * Find our location in the ram range list, checking for restriction
3485 * we don't bother implementing yet (partially overlapping, multiple
3486 * ram ranges).
3487 */
3488 pgmLock(pVM);
3489
3490 AssertReturnStmt(!(pFirstMmio->fFlags & PGMREGMMIORANGE_F_MAPPED), pgmUnlock(pVM), VERR_WRONG_ORDER);
3491
3492 bool fRamExists = false;
3493 PPGMRAMRANGE pRamPrev = NULL;
3494 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3495 while (pRam && GCPhysLast >= pRam->GCPhys)
3496 {
3497 if ( GCPhys <= pRam->GCPhysLast
3498 && GCPhysLast >= pRam->GCPhys)
3499 {
3500 /* Completely within? */
3501 AssertLogRelMsgReturnStmt( GCPhys >= pRam->GCPhys
3502 && GCPhysLast <= pRam->GCPhysLast,
3503 ("%RGp-%RGp (MMIOEx/%s) falls partly outside %RGp-%RGp (%s)\n",
3504 GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc,
3505 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
3506 pgmUnlock(pVM),
3507 VERR_PGM_RAM_CONFLICT);
3508
3509 /* Check that all the pages are RAM pages. */
3510 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3511 uint32_t cPagesLeft = cbRange >> PAGE_SHIFT;
3512 while (cPagesLeft-- > 0)
3513 {
3514 AssertLogRelMsgReturnStmt(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
3515 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
3516 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc),
3517 pgmUnlock(pVM),
3518 VERR_PGM_RAM_CONFLICT);
3519 pPage++;
3520 }
3521
3522 /* There can only be one MMIO/MMIO2 chunk matching here! */
3523 AssertLogRelMsgReturnStmt(pFirstMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK,
3524 ("%RGp-%RGp (MMIOEx/%s, flags %#X) consists of multiple chunks whereas the RAM somehow doesn't!\n",
3525 GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc, pFirstMmio->fFlags),
3526 pgmUnlock(pVM),
3527 VERR_PGM_PHYS_MMIO_EX_IPE);
3528
3529 fRamExists = true;
3530 break;
3531 }
3532
3533 /* next */
3534 pRamPrev = pRam;
3535 pRam = pRam->pNextR3;
3536 }
3537 Log(("PGMR3PhysMMIOExMap: %RGp-%RGp fRamExists=%RTbool %s\n", GCPhys, GCPhysLast, fRamExists, pFirstMmio->RamRange.pszDesc));
3538
3539
3540 /*
3541 * Make the changes.
3542 */
3543 RTGCPHYS GCPhysCur = GCPhys;
3544 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3545 {
3546 pCurMmio->RamRange.GCPhys = GCPhysCur;
3547 pCurMmio->RamRange.GCPhysLast = GCPhysCur + pCurMmio->RamRange.cb - 1;
3548 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3549 {
3550 Assert(pCurMmio->RamRange.GCPhysLast == GCPhysLast);
3551 break;
3552 }
3553 GCPhysCur += pCurMmio->RamRange.cb;
3554 }
3555
3556 if (fRamExists)
3557 {
3558 /*
3559 * Make all the pages in the range MMIO/ZERO pages, freeing any
3560 * RAM pages currently mapped here. This might not be 100% correct
3561 * for PCI memory, but we're doing the same thing for MMIO2 pages.
3562 *
3563 * We replace this MMIO/ZERO pages with real pages in the MMIO2 case.
3564 */
3565 Assert(pFirstMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK); /* Only one chunk */
3566
3567 int rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, PGMPAGETYPE_MMIO);
3568 AssertRCReturnStmt(rc, pgmUnlock(pVM), rc);
3569
3570 if (pFirstMmio->fFlags & PGMREGMMIORANGE_F_MMIO2)
3571 {
3572 /* replace the pages, freeing all present RAM pages. */
3573 PPGMPAGE pPageSrc = &pFirstMmio->RamRange.aPages[0];
3574 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3575 uint32_t cPagesLeft = pFirstMmio->RamRange.cb >> PAGE_SHIFT;
3576 while (cPagesLeft-- > 0)
3577 {
3578 Assert(PGM_PAGE_IS_MMIO(pPageDst));
3579
3580 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
3581 uint32_t const idPage = PGM_PAGE_GET_PAGEID(pPageSrc);
3582 PGM_PAGE_SET_PAGEID(pVM, pPageDst, idPage);
3583 PGM_PAGE_SET_HCPHYS(pVM, pPageDst, HCPhys);
3584 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO2);
3585 PGM_PAGE_SET_STATE(pVM, pPageDst, PGM_PAGE_STATE_ALLOCATED);
3586 PGM_PAGE_SET_PDE_TYPE(pVM, pPageDst, PGM_PAGE_PDE_TYPE_DONTCARE);
3587 PGM_PAGE_SET_PTE_INDEX(pVM, pPageDst, 0);
3588 PGM_PAGE_SET_TRACKING(pVM, pPageDst, 0);
3589 /* (We tell NEM at the end of the function.) */
3590
3591 pVM->pgm.s.cZeroPages--;
3592 GCPhys += PAGE_SIZE;
3593 pPageSrc++;
3594 pPageDst++;
3595 }
3596 }
3597
3598 /* Flush physical page map TLB. */
3599 pgmPhysInvalidatePageMapTLB(pVM);
3600
3601 /* Force a PGM pool flush as guest ram references have been changed. */
3602 /** @todo not entirely SMP safe; assuming for now the guest takes care of
3603 * this internally (not touch mapped mmio while changing the mapping). */
3604 PVMCPU pVCpu = VMMGetCpu(pVM);
3605 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
3606 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3607 }
3608 else
3609 {
3610 /*
3611 * No RAM range, insert the ones prepared during registration.
3612 */
3613 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3614 {
3615 /* Clear the tracking data of pages we're going to reactivate. */
3616 PPGMPAGE pPageSrc = &pCurMmio->RamRange.aPages[0];
3617 uint32_t cPagesLeft = pCurMmio->RamRange.cb >> PAGE_SHIFT;
3618 while (cPagesLeft-- > 0)
3619 {
3620 PGM_PAGE_SET_TRACKING(pVM, pPageSrc, 0);
3621 PGM_PAGE_SET_PTE_INDEX(pVM, pPageSrc, 0);
3622 pPageSrc++;
3623 }
3624
3625 /* link in the ram range */
3626 pgmR3PhysLinkRamRange(pVM, &pCurMmio->RamRange, pRamPrev);
3627
3628 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3629 {
3630 Assert(pCurMmio->RamRange.GCPhysLast == GCPhysLast);
3631 break;
3632 }
3633 pRamPrev = &pCurMmio->RamRange;
3634 }
3635 }
3636
3637 /*
3638 * Register the access handler if plain MMIO.
3639 *
3640 * We must register access handlers for each range since the access handler
3641 * code refuses to deal with multiple ranges (and we can).
3642 */
3643 if (!(pFirstMmio->fFlags & PGMREGMMIORANGE_F_MMIO2))
3644 {
3645 int rc = VINF_SUCCESS;
3646 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3647 {
3648 Assert(!(pCurMmio->fFlags & PGMREGMMIORANGE_F_MAPPED));
3649 rc = pgmHandlerPhysicalExRegister(pVM, pCurMmio->pPhysHandlerR3, pCurMmio->RamRange.GCPhys,
3650 pCurMmio->RamRange.GCPhysLast);
3651 if (RT_FAILURE(rc))
3652 break;
3653 pCurMmio->fFlags |= PGMREGMMIORANGE_F_MAPPED; /* Use this to mark that the handler is registered. */
3654 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3655 {
3656 rc = IOMR3MmioExNotifyMapped(pVM, pFirstMmio->pPhysHandlerR3->pvUserR3, GCPhys);
3657 break;
3658 }
3659 }
3660 if (RT_FAILURE(rc))
3661 {
3662 /* Almost impossible, but try clean up properly and get out of here. */
3663 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3664 {
3665 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_MAPPED)
3666 {
3667 pCurMmio->fFlags &= ~PGMREGMMIORANGE_F_MAPPED;
3668 pgmHandlerPhysicalExDeregister(pVM, pCurMmio->pPhysHandlerR3, fRamExists);
3669 }
3670
3671 if (!fRamExists)
3672 pgmR3PhysUnlinkRamRange(pVM, &pCurMmio->RamRange);
3673 else
3674 {
3675 Assert(pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK); /* Only one chunk */
3676
3677 uint32_t cPagesLeft = pCurMmio->RamRange.cb >> PAGE_SHIFT;
3678 PPGMPAGE pPageDst = &pRam->aPages[(pCurMmio->RamRange.GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3679 while (cPagesLeft-- > 0)
3680 {
3681 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
3682 pPageDst++;
3683 }
3684 }
3685
3686 pCurMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3687 pCurMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3688 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3689 break;
3690 }
3691
3692 pgmUnlock(pVM);
3693 return rc;
3694 }
3695 }
3696
3697 /*
3698 * We're good, set the flags and invalid the mapping TLB.
3699 */
3700 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3701 {
3702 pCurMmio->fFlags |= PGMREGMMIORANGE_F_MAPPED;
3703 if (fRamExists)
3704 pCurMmio->fFlags |= PGMREGMMIORANGE_F_OVERLAPPING;
3705 else
3706 pCurMmio->fFlags &= ~PGMREGMMIORANGE_F_OVERLAPPING;
3707 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3708 break;
3709 }
3710 pgmPhysInvalidatePageMapTLB(pVM);
3711
3712 /*
3713 * Notify NEM while holding the lock (experimental) and REM without (like always).
3714 */
3715 uint32_t const fNemNotify = (pFirstMmio->fFlags & PGMREGMMIORANGE_F_MMIO2 ? NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2 : 0)
3716 | (pFirstMmio->fFlags & PGMREGMMIORANGE_F_OVERLAPPING ? NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE : 0);
3717 int rc = NEMR3NotifyPhysMmioExMap(pVM, GCPhys, cbRange, fNemNotify, pFirstMmio->pvR3);
3718
3719 pgmUnlock(pVM);
3720
3721#ifdef VBOX_WITH_REM
3722 if (!fRamExists && (pFirstMmio->fFlags & PGMREGMMIORANGE_F_MMIO2)) /** @todo this doesn't look right. */
3723 REMR3NotifyPhysRamRegister(pVM, GCPhys, cbRange, REM_NOTIFY_PHYS_RAM_FLAGS_MMIO2);
3724#endif
3725 return rc;
3726}
3727
3728
3729/**
3730 * Unmaps a MMIO2 or a pre-registered MMIO region.
3731 *
3732 * This is done when a guest / the bios / state loading changes the
3733 * PCI config. The replacing of base memory has the same restrictions
3734 * as during registration, of course.
3735 */
3736VMMR3DECL(int) PGMR3PhysMMIOExUnmap(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS GCPhys)
3737{
3738 /*
3739 * Validate input
3740 */
3741 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3742 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3743 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3744 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3745 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
3746 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
3747 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3748
3749 PPGMREGMMIORANGE pFirstMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
3750 AssertReturn(pFirstMmio, VERR_NOT_FOUND);
3751 Assert(pFirstMmio->fFlags & PGMREGMMIORANGE_F_FIRST_CHUNK);
3752
3753 PPGMREGMMIORANGE pLastMmio = pFirstMmio;
3754 RTGCPHYS cbRange = 0;
3755 for (;;)
3756 {
3757 AssertReturn(pLastMmio->fFlags & PGMREGMMIORANGE_F_MAPPED, VERR_WRONG_ORDER);
3758 AssertReturn(pLastMmio->RamRange.GCPhys == GCPhys + cbRange, VERR_INVALID_PARAMETER);
3759 Assert(pLastMmio->pDevInsR3 == pFirstMmio->pDevInsR3);
3760 Assert(pLastMmio->iSubDev == pFirstMmio->iSubDev);
3761 Assert(pLastMmio->iRegion == pFirstMmio->iRegion);
3762 cbRange += pLastMmio->RamRange.cb;
3763 if (pLastMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3764 break;
3765 pLastMmio = pLastMmio->pNextR3;
3766 }
3767
3768 Log(("PGMR3PhysMMIOExUnmap: %RGp-%RGp %s\n",
3769 pFirstMmio->RamRange.GCPhys, pLastMmio->RamRange.GCPhysLast, pFirstMmio->RamRange.pszDesc));
3770
3771 int rc = pgmLock(pVM);
3772 AssertRCReturn(rc, rc);
3773 uint16_t const fOldFlags = pFirstMmio->fFlags;
3774 AssertReturnStmt(fOldFlags & PGMREGMMIORANGE_F_MAPPED, pgmUnlock(pVM), VERR_WRONG_ORDER);
3775
3776 /*
3777 * If plain MMIO, we must deregister the handlers first.
3778 */
3779 if (!(fOldFlags & PGMREGMMIORANGE_F_MMIO2))
3780 {
3781 PPGMREGMMIORANGE pCurMmio = pFirstMmio;
3782 rc = pgmHandlerPhysicalExDeregister(pVM, pFirstMmio->pPhysHandlerR3, RT_BOOL(fOldFlags & PGMREGMMIORANGE_F_OVERLAPPING));
3783 AssertRCReturnStmt(rc, pgmUnlock(pVM), rc);
3784 while (!(pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK))
3785 {
3786 pCurMmio = pCurMmio->pNextR3;
3787 rc = pgmHandlerPhysicalExDeregister(pVM, pCurMmio->pPhysHandlerR3, RT_BOOL(fOldFlags & PGMREGMMIORANGE_F_OVERLAPPING));
3788 AssertRCReturnStmt(rc, pgmUnlock(pVM), VERR_PGM_PHYS_MMIO_EX_IPE);
3789 }
3790
3791 IOMR3MmioExNotifyUnmapped(pVM, pFirstMmio->pPhysHandlerR3->pvUserR3, GCPhys);
3792 }
3793
3794 /*
3795 * Unmap it.
3796 */
3797 RTGCPHYS const GCPhysRangeNotify = pFirstMmio->RamRange.GCPhys;
3798 if (fOldFlags & PGMREGMMIORANGE_F_OVERLAPPING)
3799 {
3800 /*
3801 * We've replaced RAM, replace with zero pages.
3802 *
3803 * Note! This is where we might differ a little from a real system, because
3804 * it's likely to just show the RAM pages as they were before the
3805 * MMIO/MMIO2 region was mapped here.
3806 */
3807 /* Only one chunk allowed when overlapping! */
3808 Assert(fOldFlags & PGMREGMMIORANGE_F_LAST_CHUNK);
3809
3810 /* Restore the RAM pages we've replaced. */
3811 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3812 while (pRam->GCPhys > pFirstMmio->RamRange.GCPhysLast)
3813 pRam = pRam->pNextR3;
3814
3815 uint32_t cPagesLeft = pFirstMmio->RamRange.cb >> PAGE_SHIFT;
3816 if (fOldFlags & PGMREGMMIORANGE_F_MMIO2)
3817 pVM->pgm.s.cZeroPages += cPagesLeft;
3818
3819 PPGMPAGE pPageDst = &pRam->aPages[(pFirstMmio->RamRange.GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3820 while (cPagesLeft-- > 0)
3821 {
3822 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
3823 pPageDst++;
3824 }
3825
3826 /* Flush physical page map TLB. */
3827 pgmPhysInvalidatePageMapTLB(pVM);
3828
3829 /* Update range state. */
3830 pFirstMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3831 pFirstMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3832 pFirstMmio->fFlags &= ~(PGMREGMMIORANGE_F_OVERLAPPING | PGMREGMMIORANGE_F_MAPPED);
3833 }
3834 else
3835 {
3836 /*
3837 * Unlink the chunks related to the MMIO/MMIO2 region.
3838 */
3839 for (PPGMREGMMIORANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3840 {
3841 pgmR3PhysUnlinkRamRange(pVM, &pCurMmio->RamRange);
3842 pCurMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3843 pCurMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3844 pCurMmio->fFlags &= ~(PGMREGMMIORANGE_F_OVERLAPPING | PGMREGMMIORANGE_F_MAPPED);
3845 if (pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK)
3846 break;
3847 }
3848 }
3849
3850 /* Force a PGM pool flush as guest ram references have been changed. */
3851 /** @todo not entirely SMP safe; assuming for now the guest takes care
3852 * of this internally (not touch mapped mmio while changing the
3853 * mapping). */
3854 PVMCPU pVCpu = VMMGetCpu(pVM);
3855 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
3856 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3857
3858 pgmPhysInvalidatePageMapTLB(pVM);
3859 pgmPhysInvalidRamRangeTlbs(pVM);
3860
3861 /*
3862 * Notify NEM while holding the lock (experimental) and REM without (like always).
3863 */
3864 uint32_t const fNemFlags = (fOldFlags & PGMREGMMIORANGE_F_MMIO2 ? NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2 : 0)
3865 | (fOldFlags & PGMREGMMIORANGE_F_OVERLAPPING ? NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE : 0);
3866 rc = NEMR3NotifyPhysMmioExUnmap(pVM, GCPhysRangeNotify, cbRange, fNemFlags);
3867 pgmUnlock(pVM);
3868#ifdef VBOX_WITH_REM
3869 if ((fOldFlags & (PGMREGMMIORANGE_F_OVERLAPPING | PGMREGMMIORANGE_F_MMIO2)) == PGMREGMMIORANGE_F_MMIO2)
3870 REMR3NotifyPhysRamDeregister(pVM, GCPhysRangeNotify, cbRange);
3871#endif
3872 return rc;
3873}
3874
3875
3876/**
3877 * Reduces the mapping size of a MMIO2 or pre-registered MMIO region.
3878 *
3879 * This is mainly for dealing with old saved states after changing the default
3880 * size of a mapping region. See PGMDevHlpMMIOExReduce and
3881 * PDMPCIDEV::pfnRegionLoadChangeHookR3.
3882 *
3883 * The region must not currently be mapped when making this call. The VM state
3884 * must be state restore or VM construction.
3885 *
3886 * @returns VBox status code.
3887 * @param pVM The cross context VM structure.
3888 * @param pDevIns The device instance owning the region.
3889 * @param iSubDev The sub-device number of the registered region.
3890 * @param iRegion The index of the registered region.
3891 * @param cbRegion The new mapping size.
3892 */
3893VMMR3_INT_DECL(int) PGMR3PhysMMIOExReduce(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cbRegion)
3894{
3895 /*
3896 * Validate input
3897 */
3898 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3899 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3900 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
3901 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3902 AssertReturn(cbRegion >= X86_PAGE_SIZE, VERR_INVALID_PARAMETER);
3903 AssertReturn(!(cbRegion & X86_PAGE_OFFSET_MASK), VERR_UNSUPPORTED_ALIGNMENT);
3904 VMSTATE enmVmState = VMR3GetState(pVM);
3905 AssertLogRelMsgReturn( enmVmState == VMSTATE_CREATING
3906 || enmVmState == VMSTATE_LOADING,
3907 ("enmVmState=%d (%s)\n", enmVmState, VMR3GetStateName(enmVmState)),
3908 VERR_VM_INVALID_VM_STATE);
3909
3910 int rc = pgmLock(pVM);
3911 AssertRCReturn(rc, rc);
3912
3913 PPGMREGMMIORANGE pFirstMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
3914 if (pFirstMmio)
3915 {
3916 Assert(pFirstMmio->fFlags & PGMREGMMIORANGE_F_FIRST_CHUNK);
3917 if (!(pFirstMmio->fFlags & PGMREGMMIORANGE_F_MAPPED))
3918 {
3919 /*
3920 * NOTE! Current implementation does not support multiple ranges.
3921 * Implement when there is a real world need and thus a testcase.
3922 */
3923 AssertLogRelMsgStmt(pFirstMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK,
3924 ("%s: %#x\n", pFirstMmio->RamRange.pszDesc, pFirstMmio->fFlags),
3925 rc = VERR_NOT_SUPPORTED);
3926 if (RT_SUCCESS(rc))
3927 {
3928 /*
3929 * Make the change.
3930 */
3931 Log(("PGMR3PhysMMIOExReduce: %s changes from %RGp bytes (%RGp) to %RGp bytes.\n",
3932 pFirstMmio->RamRange.pszDesc, pFirstMmio->RamRange.cb, pFirstMmio->cbReal, cbRegion));
3933
3934 AssertLogRelMsgStmt(cbRegion <= pFirstMmio->cbReal,
3935 ("%s: cbRegion=%#RGp cbReal=%#RGp\n", pFirstMmio->RamRange.pszDesc, cbRegion, pFirstMmio->cbReal),
3936 rc = VERR_OUT_OF_RANGE);
3937 if (RT_SUCCESS(rc))
3938 {
3939 pFirstMmio->RamRange.cb = cbRegion;
3940 }
3941 }
3942 }
3943 else
3944 rc = VERR_WRONG_ORDER;
3945 }
3946 else
3947 rc = VERR_NOT_FOUND;
3948
3949 pgmUnlock(pVM);
3950 return rc;
3951}
3952
3953
3954/**
3955 * Checks if the given address is an MMIO2 or pre-registered MMIO base address
3956 * or not.
3957 *
3958 * @returns true/false accordingly.
3959 * @param pVM The cross context VM structure.
3960 * @param pDevIns The owner of the memory, optional.
3961 * @param GCPhys The address to check.
3962 */
3963VMMR3DECL(bool) PGMR3PhysMMIOExIsBase(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys)
3964{
3965 /*
3966 * Validate input
3967 */
3968 VM_ASSERT_EMT_RETURN(pVM, false);
3969 AssertPtrReturn(pDevIns, false);
3970 AssertReturn(GCPhys != NIL_RTGCPHYS, false);
3971 AssertReturn(GCPhys != 0, false);
3972 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), false);
3973
3974 /*
3975 * Search the list.
3976 */
3977 pgmLock(pVM);
3978 for (PPGMREGMMIORANGE pCurMmio = pVM->pgm.s.pRegMmioRangesR3; pCurMmio; pCurMmio = pCurMmio->pNextR3)
3979 if (pCurMmio->RamRange.GCPhys == GCPhys)
3980 {
3981 Assert(pCurMmio->fFlags & PGMREGMMIORANGE_F_MAPPED);
3982 bool fRet = RT_BOOL(pCurMmio->fFlags & PGMREGMMIORANGE_F_FIRST_CHUNK);
3983 pgmUnlock(pVM);
3984 return fRet;
3985 }
3986 pgmUnlock(pVM);
3987 return false;
3988}
3989
3990
3991/**
3992 * Gets the HC physical address of a page in the MMIO2 region.
3993 *
3994 * This is API is intended for MMHyper and shouldn't be called
3995 * by anyone else...
3996 *
3997 * @returns VBox status code.
3998 * @param pVM The cross context VM structure.
3999 * @param pDevIns The owner of the memory, optional.
4000 * @param iSubDev Sub-device number.
4001 * @param iRegion The region.
4002 * @param off The page expressed an offset into the MMIO2 region.
4003 * @param pHCPhys Where to store the result.
4004 */
4005VMMR3_INT_DECL(int) PGMR3PhysMMIO2GetHCPhys(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion,
4006 RTGCPHYS off, PRTHCPHYS pHCPhys)
4007{
4008 /*
4009 * Validate input
4010 */
4011 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
4012 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4013 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
4014 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4015
4016 pgmLock(pVM);
4017 PPGMREGMMIORANGE pCurMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
4018 AssertReturn(pCurMmio, VERR_NOT_FOUND);
4019 AssertReturn(pCurMmio->fFlags & (PGMREGMMIORANGE_F_MMIO2 | PGMREGMMIORANGE_F_FIRST_CHUNK), VERR_WRONG_TYPE);
4020
4021 while ( off >= pCurMmio->RamRange.cb
4022 && !(pCurMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK))
4023 {
4024 off -= pCurMmio->RamRange.cb;
4025 pCurMmio = pCurMmio->pNextR3;
4026 }
4027 AssertReturn(off < pCurMmio->RamRange.cb, VERR_INVALID_PARAMETER);
4028
4029 PCPGMPAGE pPage = &pCurMmio->RamRange.aPages[off >> PAGE_SHIFT];
4030 *pHCPhys = PGM_PAGE_GET_HCPHYS(pPage);
4031 pgmUnlock(pVM);
4032 return VINF_SUCCESS;
4033}
4034
4035
4036/**
4037 * Maps a portion of an MMIO2 region into kernel space (host).
4038 *
4039 * The kernel mapping will become invalid when the MMIO2 memory is deregistered
4040 * or the VM is terminated.
4041 *
4042 * @return VBox status code.
4043 *
4044 * @param pVM The cross context VM structure.
4045 * @param pDevIns The device owning the MMIO2 memory.
4046 * @param iSubDev The sub-device number.
4047 * @param iRegion The region.
4048 * @param off The offset into the region. Must be page aligned.
4049 * @param cb The number of bytes to map. Must be page aligned.
4050 * @param pszDesc Mapping description.
4051 * @param pR0Ptr Where to store the R0 address.
4052 */
4053VMMR3_INT_DECL(int) PGMR3PhysMMIO2MapKernel(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion,
4054 RTGCPHYS off, RTGCPHYS cb, const char *pszDesc, PRTR0PTR pR0Ptr)
4055{
4056 /*
4057 * Validate input.
4058 */
4059 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
4060 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4061 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
4062 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4063
4064 PPGMREGMMIORANGE pFirstRegMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
4065 AssertReturn(pFirstRegMmio, VERR_NOT_FOUND);
4066 AssertReturn(pFirstRegMmio->fFlags & (PGMREGMMIORANGE_F_MMIO2 | PGMREGMMIORANGE_F_FIRST_CHUNK), VERR_WRONG_TYPE);
4067 AssertReturn(off < pFirstRegMmio->RamRange.cb, VERR_INVALID_PARAMETER);
4068 AssertReturn(cb <= pFirstRegMmio->RamRange.cb, VERR_INVALID_PARAMETER);
4069 AssertReturn(off + cb <= pFirstRegMmio->RamRange.cb, VERR_INVALID_PARAMETER);
4070 NOREF(pszDesc);
4071
4072 /*
4073 * Pass the request on to the support library/driver.
4074 */
4075#if defined(RT_OS_WINDOWS) || defined(RT_OS_LINUX) || defined(RT_OS_OS2) /** @todo Fully implement RTR0MemObjMapKernelEx everywhere. */
4076 AssertLogRelReturn(off == 0, VERR_NOT_SUPPORTED);
4077 AssertLogRelReturn(pFirstRegMmio->fFlags & PGMREGMMIORANGE_F_LAST_CHUNK, VERR_NOT_SUPPORTED);
4078 int rc = SUPR3PageMapKernel(pFirstRegMmio->pvR3, 0 /*off*/, pFirstRegMmio->RamRange.cb, 0 /*fFlags*/, pR0Ptr);
4079#else
4080 int rc = SUPR3PageMapKernel(pFirstRegMmio->pvR3, off, cb, 0 /*fFlags*/, pR0Ptr);
4081#endif
4082
4083 return rc;
4084}
4085
4086
4087/**
4088 * Changes the region number of an MMIO2 or pre-registered MMIO region.
4089 *
4090 * This is only for dealing with save state issues, nothing else.
4091 *
4092 * @return VBox status code.
4093 *
4094 * @param pVM The cross context VM structure.
4095 * @param pDevIns The device owning the MMIO2 memory.
4096 * @param iSubDev The sub-device number.
4097 * @param iRegion The region.
4098 * @param iNewRegion The new region index.
4099 *
4100 * @sa @bugref{9359}
4101 */
4102VMMR3_INT_DECL(int) PGMR3PhysMMIOExChangeRegionNo(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion,
4103 uint32_t iNewRegion)
4104{
4105 /*
4106 * Validate input.
4107 */
4108 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
4109 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4110 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
4111 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4112 AssertReturn(iNewRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4113
4114 AssertReturn(pVM->enmVMState == VMSTATE_LOADING, VERR_INVALID_STATE);
4115
4116 PPGMREGMMIORANGE pFirstRegMmio = pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iRegion);
4117 AssertReturn(pFirstRegMmio, VERR_NOT_FOUND);
4118 AssertReturn(pgmR3PhysMMIOExFind(pVM, pDevIns, iSubDev, iNewRegion) == NULL, VERR_RESOURCE_IN_USE);
4119
4120 /*
4121 * Make the change.
4122 */
4123 pFirstRegMmio->iRegion = (uint8_t)iNewRegion;
4124
4125 return VINF_SUCCESS;
4126}
4127
4128
4129/**
4130 * Worker for PGMR3PhysRomRegister.
4131 *
4132 * This is here to simplify lock management, i.e. the caller does all the
4133 * locking and we can simply return without needing to remember to unlock
4134 * anything first.
4135 *
4136 * @returns VBox status code.
4137 * @param pVM The cross context VM structure.
4138 * @param pDevIns The device instance owning the ROM.
4139 * @param GCPhys First physical address in the range.
4140 * Must be page aligned!
4141 * @param cb The size of the range (in bytes).
4142 * Must be page aligned!
4143 * @param pvBinary Pointer to the binary data backing the ROM image.
4144 * @param cbBinary The size of the binary data pvBinary points to.
4145 * This must be less or equal to @a cb.
4146 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
4147 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
4148 * @param pszDesc Pointer to description string. This must not be freed.
4149 */
4150static int pgmR3PhysRomRegisterLocked(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
4151 const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
4152{
4153 /*
4154 * Validate input.
4155 */
4156 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4157 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
4158 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
4159 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
4160 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
4161 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
4162 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
4163 AssertReturn(!(fFlags & ~(PGMPHYS_ROM_FLAGS_SHADOWED | PGMPHYS_ROM_FLAGS_PERMANENT_BINARY)), VERR_INVALID_PARAMETER);
4164 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
4165
4166 const uint32_t cPages = cb >> PAGE_SHIFT;
4167
4168 /*
4169 * Find the ROM location in the ROM list first.
4170 */
4171 PPGMROMRANGE pRomPrev = NULL;
4172 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
4173 while (pRom && GCPhysLast >= pRom->GCPhys)
4174 {
4175 if ( GCPhys <= pRom->GCPhysLast
4176 && GCPhysLast >= pRom->GCPhys)
4177 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
4178 GCPhys, GCPhysLast, pszDesc,
4179 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
4180 VERR_PGM_RAM_CONFLICT);
4181 /* next */
4182 pRomPrev = pRom;
4183 pRom = pRom->pNextR3;
4184 }
4185
4186 /*
4187 * Find the RAM location and check for conflicts.
4188 *
4189 * Conflict detection is a bit different than for RAM
4190 * registration since a ROM can be located within a RAM
4191 * range. So, what we have to check for is other memory
4192 * types (other than RAM that is) and that we don't span
4193 * more than one RAM range (layz).
4194 */
4195 bool fRamExists = false;
4196 PPGMRAMRANGE pRamPrev = NULL;
4197 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
4198 while (pRam && GCPhysLast >= pRam->GCPhys)
4199 {
4200 if ( GCPhys <= pRam->GCPhysLast
4201 && GCPhysLast >= pRam->GCPhys)
4202 {
4203 /* completely within? */
4204 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
4205 && GCPhysLast <= pRam->GCPhysLast,
4206 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
4207 GCPhys, GCPhysLast, pszDesc,
4208 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
4209 VERR_PGM_RAM_CONFLICT);
4210 fRamExists = true;
4211 break;
4212 }
4213
4214 /* next */
4215 pRamPrev = pRam;
4216 pRam = pRam->pNextR3;
4217 }
4218 if (fRamExists)
4219 {
4220 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
4221 uint32_t cPagesLeft = cPages;
4222 while (cPagesLeft-- > 0)
4223 {
4224 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
4225 ("%RGp (%R[pgmpage]) isn't a RAM page - registering %RGp-%RGp (%s).\n",
4226 pRam->GCPhys + ((RTGCPHYS)(uintptr_t)(pPage - &pRam->aPages[0]) << PAGE_SHIFT),
4227 pPage, GCPhys, GCPhysLast, pszDesc), VERR_PGM_RAM_CONFLICT);
4228 Assert(PGM_PAGE_IS_ZERO(pPage));
4229 pPage++;
4230 }
4231 }
4232
4233 /*
4234 * Update the base memory reservation if necessary.
4235 */
4236 uint32_t cExtraBaseCost = fRamExists ? 0 : cPages;
4237 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4238 cExtraBaseCost += cPages;
4239 if (cExtraBaseCost)
4240 {
4241 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
4242 if (RT_FAILURE(rc))
4243 return rc;
4244 }
4245
4246 /*
4247 * Allocate memory for the virgin copy of the RAM.
4248 */
4249 PGMMALLOCATEPAGESREQ pReq;
4250 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cPages, GMMACCOUNT_BASE);
4251 AssertRCReturn(rc, rc);
4252
4253 for (uint32_t iPage = 0; iPage < cPages; iPage++)
4254 {
4255 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << PAGE_SHIFT);
4256 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
4257 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
4258 }
4259
4260 rc = GMMR3AllocatePagesPerform(pVM, pReq);
4261 if (RT_FAILURE(rc))
4262 {
4263 GMMR3AllocatePagesCleanup(pReq);
4264 return rc;
4265 }
4266
4267 /*
4268 * Allocate the new ROM range and RAM range (if necessary).
4269 */
4270 PPGMROMRANGE pRomNew;
4271 rc = MMHyperAlloc(pVM, RT_UOFFSETOF_DYN(PGMROMRANGE, aPages[cPages]), 0, MM_TAG_PGM_PHYS, (void **)&pRomNew);
4272 if (RT_SUCCESS(rc))
4273 {
4274 PPGMRAMRANGE pRamNew = NULL;
4275 if (!fRamExists)
4276 rc = MMHyperAlloc(pVM, RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]), sizeof(PGMPAGE), MM_TAG_PGM_PHYS, (void **)&pRamNew);
4277 if (RT_SUCCESS(rc))
4278 {
4279 /*
4280 * Initialize and insert the RAM range (if required).
4281 */
4282 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
4283 if (!fRamExists)
4284 {
4285 pRamNew->pSelfR0 = MMHyperCCToR0(pVM, pRamNew);
4286 pRamNew->pSelfRC = MMHyperCCToRC(pVM, pRamNew);
4287 pRamNew->GCPhys = GCPhys;
4288 pRamNew->GCPhysLast = GCPhysLast;
4289 pRamNew->cb = cb;
4290 pRamNew->pszDesc = pszDesc;
4291 pRamNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_ROM;
4292 pRamNew->pvR3 = NULL;
4293 pRamNew->paLSPages = NULL;
4294
4295 PPGMPAGE pPage = &pRamNew->aPages[0];
4296 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
4297 {
4298 PGM_PAGE_INIT(pPage,
4299 pReq->aPages[iPage].HCPhysGCPhys,
4300 pReq->aPages[iPage].idPage,
4301 PGMPAGETYPE_ROM,
4302 PGM_PAGE_STATE_ALLOCATED);
4303
4304 pRomPage->Virgin = *pPage;
4305 }
4306
4307 pVM->pgm.s.cAllPages += cPages;
4308 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
4309 }
4310 else
4311 {
4312 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
4313 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
4314 {
4315 PGM_PAGE_SET_TYPE(pVM, pPage, PGMPAGETYPE_ROM);
4316 PGM_PAGE_SET_HCPHYS(pVM, pPage, pReq->aPages[iPage].HCPhysGCPhys);
4317 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ALLOCATED);
4318 PGM_PAGE_SET_PAGEID(pVM, pPage, pReq->aPages[iPage].idPage);
4319 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4320 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
4321 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
4322
4323 pRomPage->Virgin = *pPage;
4324 }
4325
4326 pRamNew = pRam;
4327
4328 pVM->pgm.s.cZeroPages -= cPages;
4329 }
4330 pVM->pgm.s.cPrivatePages += cPages;
4331
4332 /* Flush physical page map TLB. */
4333 pgmPhysInvalidatePageMapTLB(pVM);
4334
4335
4336 /* Notify NEM before we register handlers. */
4337 uint32_t const fNemNotify = (fRamExists ? NEM_NOTIFY_PHYS_ROM_F_REPLACE : 0)
4338 | (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED ? NEM_NOTIFY_PHYS_ROM_F_SHADOW : 0);
4339 rc = NEMR3NotifyPhysRomRegisterEarly(pVM, GCPhys, cb, fNemNotify);
4340
4341 /*
4342 * !HACK ALERT! REM + (Shadowed) ROM ==> mess.
4343 *
4344 * If it's shadowed we'll register the handler after the ROM notification
4345 * so we get the access handler callbacks that we should. If it isn't
4346 * shadowed we'll do it the other way around to make REM use the built-in
4347 * ROM behavior and not the handler behavior (which is to route all access
4348 * to PGM atm).
4349 */
4350 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4351 {
4352#ifdef VBOX_WITH_REM
4353 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, true /* fShadowed */);
4354#endif
4355 if (RT_SUCCESS(rc))
4356 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, pVM->pgm.s.hRomPhysHandlerType,
4357 pRomNew, MMHyperCCToR0(pVM, pRomNew), MMHyperCCToRC(pVM, pRomNew),
4358 pszDesc);
4359 }
4360 else
4361 {
4362 if (RT_SUCCESS(rc))
4363 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, pVM->pgm.s.hRomPhysHandlerType,
4364 pRomNew, MMHyperCCToR0(pVM, pRomNew), MMHyperCCToRC(pVM, pRomNew),
4365 pszDesc);
4366#ifdef VBOX_WITH_REM
4367 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, false /* fShadowed */);
4368#endif
4369 }
4370 if (RT_SUCCESS(rc))
4371 {
4372 /*
4373 * Copy the image over to the virgin pages.
4374 * This must be done after linking in the RAM range.
4375 */
4376 size_t cbBinaryLeft = cbBinary;
4377 PPGMPAGE pRamPage = &pRamNew->aPages[(GCPhys - pRamNew->GCPhys) >> PAGE_SHIFT];
4378 for (uint32_t iPage = 0; iPage < cPages; iPage++, pRamPage++)
4379 {
4380 void *pvDstPage;
4381 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << PAGE_SHIFT), &pvDstPage);
4382 if (RT_FAILURE(rc))
4383 {
4384 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
4385 break;
4386 }
4387 if (cbBinaryLeft >= PAGE_SIZE)
4388 {
4389 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), PAGE_SIZE);
4390 cbBinaryLeft -= PAGE_SIZE;
4391 }
4392 else
4393 {
4394 ASMMemZeroPage(pvDstPage); /* (shouldn't be necessary, but can't hurt either) */
4395 if (cbBinaryLeft > 0)
4396 {
4397 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), cbBinaryLeft);
4398 cbBinaryLeft = 0;
4399 }
4400 }
4401 }
4402 if (RT_SUCCESS(rc))
4403 {
4404 /*
4405 * Initialize the ROM range.
4406 * Note that the Virgin member of the pages has already been initialized above.
4407 */
4408 pRomNew->GCPhys = GCPhys;
4409 pRomNew->GCPhysLast = GCPhysLast;
4410 pRomNew->cb = cb;
4411 pRomNew->fFlags = fFlags;
4412 pRomNew->idSavedState = UINT8_MAX;
4413 pRomNew->cbOriginal = cbBinary;
4414 pRomNew->pszDesc = pszDesc;
4415 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY
4416 ? pvBinary : RTMemDup(pvBinary, cbBinary);
4417 if (pRomNew->pvOriginal)
4418 {
4419 for (unsigned iPage = 0; iPage < cPages; iPage++)
4420 {
4421 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
4422 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
4423 PGM_PAGE_INIT_ZERO(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
4424 }
4425
4426 /* update the page count stats for the shadow pages. */
4427 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4428 {
4429 pVM->pgm.s.cZeroPages += cPages;
4430 pVM->pgm.s.cAllPages += cPages;
4431 }
4432
4433 /*
4434 * Insert the ROM range, tell REM and return successfully.
4435 */
4436 pRomNew->pNextR3 = pRom;
4437 pRomNew->pNextR0 = pRom ? MMHyperCCToR0(pVM, pRom) : NIL_RTR0PTR;
4438 pRomNew->pNextRC = pRom ? MMHyperCCToRC(pVM, pRom) : NIL_RTRCPTR;
4439
4440 if (pRomPrev)
4441 {
4442 pRomPrev->pNextR3 = pRomNew;
4443 pRomPrev->pNextR0 = MMHyperCCToR0(pVM, pRomNew);
4444 pRomPrev->pNextRC = MMHyperCCToRC(pVM, pRomNew);
4445 }
4446 else
4447 {
4448 pVM->pgm.s.pRomRangesR3 = pRomNew;
4449 pVM->pgm.s.pRomRangesR0 = MMHyperCCToR0(pVM, pRomNew);
4450 pVM->pgm.s.pRomRangesRC = MMHyperCCToRC(pVM, pRomNew);
4451 }
4452
4453 pgmPhysInvalidatePageMapTLB(pVM);
4454 GMMR3AllocatePagesCleanup(pReq);
4455
4456 /* Notify NEM again. */
4457 return NEMR3NotifyPhysRomRegisterLate(pVM, GCPhys, cb, fNemNotify);
4458 }
4459
4460 /* bail out */
4461 rc = VERR_NO_MEMORY;
4462 }
4463
4464 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
4465 AssertRC(rc2);
4466 }
4467
4468 if (!fRamExists)
4469 {
4470 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
4471 MMHyperFree(pVM, pRamNew);
4472 }
4473 }
4474 MMHyperFree(pVM, pRomNew);
4475 }
4476
4477 /** @todo Purge the mapping cache or something... */
4478 GMMR3FreeAllocatedPages(pVM, pReq);
4479 GMMR3AllocatePagesCleanup(pReq);
4480 return rc;
4481}
4482
4483
4484/**
4485 * Registers a ROM image.
4486 *
4487 * Shadowed ROM images requires double the amount of backing memory, so,
4488 * don't use that unless you have to. Shadowing of ROM images is process
4489 * where we can select where the reads go and where the writes go. On real
4490 * hardware the chipset provides means to configure this. We provide
4491 * PGMR3PhysProtectROM() for this purpose.
4492 *
4493 * A read-only copy of the ROM image will always be kept around while we
4494 * will allocate RAM pages for the changes on demand (unless all memory
4495 * is configured to be preallocated).
4496 *
4497 * @returns VBox status code.
4498 * @param pVM The cross context VM structure.
4499 * @param pDevIns The device instance owning the ROM.
4500 * @param GCPhys First physical address in the range.
4501 * Must be page aligned!
4502 * @param cb The size of the range (in bytes).
4503 * Must be page aligned!
4504 * @param pvBinary Pointer to the binary data backing the ROM image.
4505 * @param cbBinary The size of the binary data pvBinary points to.
4506 * This must be less or equal to @a cb.
4507 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
4508 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
4509 * @param pszDesc Pointer to description string. This must not be freed.
4510 *
4511 * @remark There is no way to remove the rom, automatically on device cleanup or
4512 * manually from the device yet. This isn't difficult in any way, it's
4513 * just not something we expect to be necessary for a while.
4514 */
4515VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
4516 const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
4517{
4518 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p cbBinary=%#x fFlags=%#x pszDesc=%s\n",
4519 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, cbBinary, fFlags, pszDesc));
4520 pgmLock(pVM);
4521 int rc = pgmR3PhysRomRegisterLocked(pVM, pDevIns, GCPhys, cb, pvBinary, cbBinary, fFlags, pszDesc);
4522 pgmUnlock(pVM);
4523 return rc;
4524}
4525
4526
4527/**
4528 * Called by PGMR3MemSetup to reset the shadow, switch to the virgin, and verify
4529 * that the virgin part is untouched.
4530 *
4531 * This is done after the normal memory has been cleared.
4532 *
4533 * ASSUMES that the caller owns the PGM lock.
4534 *
4535 * @param pVM The cross context VM structure.
4536 */
4537int pgmR3PhysRomReset(PVM pVM)
4538{
4539 PGM_LOCK_ASSERT_OWNER(pVM);
4540 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4541 {
4542 const uint32_t cPages = pRom->cb >> PAGE_SHIFT;
4543
4544 if (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4545 {
4546 /*
4547 * Reset the physical handler.
4548 */
4549 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
4550 AssertRCReturn(rc, rc);
4551
4552 /*
4553 * What we do with the shadow pages depends on the memory
4554 * preallocation option. If not enabled, we'll just throw
4555 * out all the dirty pages and replace them by the zero page.
4556 */
4557 if (!pVM->pgm.s.fRamPreAlloc)
4558 {
4559 /* Free the dirty pages. */
4560 uint32_t cPendingPages = 0;
4561 PGMMFREEPAGESREQ pReq;
4562 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
4563 AssertRCReturn(rc, rc);
4564
4565 for (uint32_t iPage = 0; iPage < cPages; iPage++)
4566 if ( !PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow)
4567 && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow))
4568 {
4569 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
4570 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, &pRom->aPages[iPage].Shadow,
4571 pRom->GCPhys + (iPage << PAGE_SHIFT),
4572 (PGMPAGETYPE)PGM_PAGE_GET_TYPE(&pRom->aPages[iPage].Shadow));
4573 AssertLogRelRCReturn(rc, rc);
4574 }
4575
4576 if (cPendingPages)
4577 {
4578 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
4579 AssertLogRelRCReturn(rc, rc);
4580 }
4581 GMMR3FreePagesCleanup(pReq);
4582 }
4583 else
4584 {
4585 /* clear all the shadow pages. */
4586 for (uint32_t iPage = 0; iPage < cPages; iPage++)
4587 {
4588 if (PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow))
4589 continue;
4590 Assert(!PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow));
4591 void *pvDstPage;
4592 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
4593 rc = pgmPhysPageMakeWritableAndMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pvDstPage);
4594 if (RT_FAILURE(rc))
4595 break;
4596 ASMMemZeroPage(pvDstPage);
4597 }
4598 AssertRCReturn(rc, rc);
4599 }
4600 }
4601
4602 /*
4603 * Restore the original ROM pages after a saved state load.
4604 * Also, in strict builds check that ROM pages remain unmodified.
4605 */
4606#ifndef VBOX_STRICT
4607 if (pVM->pgm.s.fRestoreRomPagesOnReset)
4608#endif
4609 {
4610 size_t cbSrcLeft = pRom->cbOriginal;
4611 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
4612 uint32_t cRestored = 0;
4613 for (uint32_t iPage = 0; iPage < cPages && cbSrcLeft > 0; iPage++, pbSrcPage += PAGE_SIZE)
4614 {
4615 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
4616 void const *pvDstPage;
4617 int rc = pgmPhysPageMapReadOnly(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPage);
4618 if (RT_FAILURE(rc))
4619 break;
4620
4621 if (memcmp(pvDstPage, pbSrcPage, RT_MIN(cbSrcLeft, PAGE_SIZE)))
4622 {
4623 if (pVM->pgm.s.fRestoreRomPagesOnReset)
4624 {
4625 void *pvDstPageW;
4626 rc = pgmPhysPageMap(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPageW);
4627 AssertLogRelRCReturn(rc, rc);
4628 memcpy(pvDstPageW, pbSrcPage, RT_MIN(cbSrcLeft, PAGE_SIZE));
4629 cRestored++;
4630 }
4631 else
4632 LogRel(("pgmR3PhysRomReset: %RGp: ROM page changed (%s)\n", GCPhys, pRom->pszDesc));
4633 }
4634 cbSrcLeft -= RT_MIN(cbSrcLeft, PAGE_SIZE);
4635 }
4636 if (cRestored > 0)
4637 LogRel(("PGM: ROM \"%s\": Reloaded %u of %u pages.\n", pRom->pszDesc, cRestored, cPages));
4638 }
4639 }
4640
4641 /* Clear the ROM restore flag now as we only need to do this once after
4642 loading saved state. */
4643 pVM->pgm.s.fRestoreRomPagesOnReset = false;
4644
4645 return VINF_SUCCESS;
4646}
4647
4648
4649/**
4650 * Called by PGMR3Term to free resources.
4651 *
4652 * ASSUMES that the caller owns the PGM lock.
4653 *
4654 * @param pVM The cross context VM structure.
4655 */
4656void pgmR3PhysRomTerm(PVM pVM)
4657{
4658 /*
4659 * Free the heap copy of the original bits.
4660 */
4661 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4662 {
4663 if ( pRom->pvOriginal
4664 && !(pRom->fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY))
4665 {
4666 RTMemFree((void *)pRom->pvOriginal);
4667 pRom->pvOriginal = NULL;
4668 }
4669 }
4670}
4671
4672
4673/**
4674 * Change the shadowing of a range of ROM pages.
4675 *
4676 * This is intended for implementing chipset specific memory registers
4677 * and will not be very strict about the input. It will silently ignore
4678 * any pages that are not the part of a shadowed ROM.
4679 *
4680 * @returns VBox status code.
4681 * @retval VINF_PGM_SYNC_CR3
4682 *
4683 * @param pVM The cross context VM structure.
4684 * @param GCPhys Where to start. Page aligned.
4685 * @param cb How much to change. Page aligned.
4686 * @param enmProt The new ROM protection.
4687 */
4688VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
4689{
4690 /*
4691 * Check input
4692 */
4693 if (!cb)
4694 return VINF_SUCCESS;
4695 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
4696 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
4697 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
4698 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
4699 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
4700
4701 /*
4702 * Process the request.
4703 */
4704 pgmLock(pVM);
4705 int rc = VINF_SUCCESS;
4706 bool fFlushTLB = false;
4707 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4708 {
4709 if ( GCPhys <= pRom->GCPhysLast
4710 && GCPhysLast >= pRom->GCPhys
4711 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
4712 {
4713 /*
4714 * Iterate the relevant pages and make necessary the changes.
4715 */
4716 bool fChanges = false;
4717 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
4718 ? pRom->cb >> PAGE_SHIFT
4719 : (GCPhysLast - pRom->GCPhys + 1) >> PAGE_SHIFT;
4720 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
4721 iPage < cPages;
4722 iPage++)
4723 {
4724 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
4725 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
4726 {
4727 fChanges = true;
4728
4729 /* flush references to the page. */
4730 PPGMPAGE pRamPage = pgmPhysGetPage(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT));
4731 int rc2 = pgmPoolTrackUpdateGCPhys(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT), pRamPage,
4732 true /*fFlushPTEs*/, &fFlushTLB);
4733 if (rc2 != VINF_SUCCESS && (rc == VINF_SUCCESS || RT_FAILURE(rc2)))
4734 rc = rc2;
4735 uint8_t u2State = PGM_PAGE_GET_NEM_STATE(pRamPage);
4736
4737 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
4738 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
4739
4740 *pOld = *pRamPage;
4741 *pRamPage = *pNew;
4742 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
4743
4744 /* Tell NEM about the backing and protection change. */
4745 if (VM_IS_NEM_ENABLED(pVM))
4746 {
4747 PGMPAGETYPE enmType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pNew);
4748 NEMHCNotifyPhysPageChanged(pVM, GCPhys, PGM_PAGE_GET_HCPHYS(pOld), PGM_PAGE_GET_HCPHYS(pNew),
4749 pgmPhysPageCalcNemProtection(pRamPage, enmType), enmType, &u2State);
4750 PGM_PAGE_SET_NEM_STATE(pRamPage, u2State);
4751 }
4752 }
4753 pRomPage->enmProt = enmProt;
4754 }
4755
4756 /*
4757 * Reset the access handler if we made changes, no need
4758 * to optimize this.
4759 */
4760 if (fChanges)
4761 {
4762 int rc2 = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
4763 if (RT_FAILURE(rc2))
4764 {
4765 pgmUnlock(pVM);
4766 AssertRC(rc);
4767 return rc2;
4768 }
4769 }
4770
4771 /* Advance - cb isn't updated. */
4772 GCPhys = pRom->GCPhys + (cPages << PAGE_SHIFT);
4773 }
4774 }
4775 pgmUnlock(pVM);
4776 if (fFlushTLB)
4777 PGM_INVL_ALL_VCPU_TLBS(pVM);
4778
4779 return rc;
4780}
4781
4782
4783/**
4784 * Sets the Address Gate 20 state.
4785 *
4786 * @param pVCpu The cross context virtual CPU structure.
4787 * @param fEnable True if the gate should be enabled.
4788 * False if the gate should be disabled.
4789 */
4790VMMDECL(void) PGMR3PhysSetA20(PVMCPU pVCpu, bool fEnable)
4791{
4792 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVCpu->pgm.s.fA20Enabled));
4793 if (pVCpu->pgm.s.fA20Enabled != fEnable)
4794 {
4795#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4796 PCCPUMCTX pCtx = CPUMQueryGuestCtxPtr(pVCpu);
4797 if ( CPUMIsGuestInVmxRootMode(pCtx)
4798 && !fEnable)
4799 {
4800 Log(("Cannot enter A20M mode while in VMX root mode\n"));
4801 return;
4802 }
4803#endif
4804 pVCpu->pgm.s.fA20Enabled = fEnable;
4805 pVCpu->pgm.s.GCPhysA20Mask = ~((RTGCPHYS)!fEnable << 20);
4806#ifdef VBOX_WITH_REM
4807 REMR3A20Set(pVCpu->pVMR3, pVCpu, fEnable);
4808#endif
4809 NEMR3NotifySetA20(pVCpu, fEnable);
4810#ifdef PGM_WITH_A20
4811 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_UPDATE_PAGE_BIT_VIRTUAL;
4812 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
4813 pgmR3RefreshShadowModeAfterA20Change(pVCpu);
4814 HMFlushTlb(pVCpu);
4815#endif
4816 IEMTlbInvalidateAllPhysical(pVCpu);
4817 STAM_REL_COUNTER_INC(&pVCpu->pgm.s.cA20Changes);
4818 }
4819}
4820
4821
4822/**
4823 * Tree enumeration callback for dealing with age rollover.
4824 * It will perform a simple compression of the current age.
4825 */
4826static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
4827{
4828 /* Age compression - ASSUMES iNow == 4. */
4829 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
4830 if (pChunk->iLastUsed >= UINT32_C(0xffffff00))
4831 pChunk->iLastUsed = 3;
4832 else if (pChunk->iLastUsed >= UINT32_C(0xfffff000))
4833 pChunk->iLastUsed = 2;
4834 else if (pChunk->iLastUsed)
4835 pChunk->iLastUsed = 1;
4836 else /* iLastUsed = 0 */
4837 pChunk->iLastUsed = 4;
4838
4839 NOREF(pvUser);
4840 return 0;
4841}
4842
4843
4844/**
4845 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
4846 */
4847typedef struct PGMR3PHYSCHUNKUNMAPCB
4848{
4849 PVM pVM; /**< Pointer to the VM. */
4850 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
4851} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
4852
4853
4854/**
4855 * Callback used to find the mapping that's been unused for
4856 * the longest time.
4857 */
4858static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLU32NODECORE pNode, void *pvUser)
4859{
4860 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
4861 PPGMR3PHYSCHUNKUNMAPCB pArg = (PPGMR3PHYSCHUNKUNMAPCB)pvUser;
4862
4863 /*
4864 * Check for locks and compare when last used.
4865 */
4866 if (pChunk->cRefs)
4867 return 0;
4868 if (pChunk->cPermRefs)
4869 return 0;
4870 if ( pArg->pChunk
4871 && pChunk->iLastUsed >= pArg->pChunk->iLastUsed)
4872 return 0;
4873
4874 /*
4875 * Check that it's not in any of the TLBs.
4876 */
4877 PVM pVM = pArg->pVM;
4878 if ( pVM->pgm.s.ChunkR3Map.Tlb.aEntries[PGM_CHUNKR3MAPTLB_IDX(pChunk->Core.Key)].idChunk
4879 == pChunk->Core.Key)
4880 {
4881 pChunk = NULL;
4882 return 0;
4883 }
4884#ifdef VBOX_STRICT
4885 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
4886 {
4887 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk != pChunk);
4888 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk != pChunk->Core.Key);
4889 }
4890#endif
4891
4892 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbR0.aEntries); i++)
4893 if (pVM->pgm.s.PhysTlbR0.aEntries[i].pMap == pChunk)
4894 return 0;
4895 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbR3.aEntries); i++)
4896 if (pVM->pgm.s.PhysTlbR3.aEntries[i].pMap == pChunk)
4897 return 0;
4898
4899 pArg->pChunk = pChunk;
4900 return 0;
4901}
4902
4903
4904/**
4905 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
4906 *
4907 * The candidate will not be part of any TLBs, so no need to flush
4908 * anything afterwards.
4909 *
4910 * @returns Chunk id.
4911 * @param pVM The cross context VM structure.
4912 */
4913static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
4914{
4915 PGM_LOCK_ASSERT_OWNER(pVM);
4916
4917 /*
4918 * Enumerate the age tree starting with the left most node.
4919 */
4920 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
4921 PGMR3PHYSCHUNKUNMAPCB Args;
4922 Args.pVM = pVM;
4923 Args.pChunk = NULL;
4924 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, &Args);
4925 Assert(Args.pChunk);
4926 if (Args.pChunk)
4927 {
4928 Assert(Args.pChunk->cRefs == 0);
4929 Assert(Args.pChunk->cPermRefs == 0);
4930 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
4931 return Args.pChunk->Core.Key;
4932 }
4933
4934 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
4935 return INT32_MAX;
4936}
4937
4938
4939/**
4940 * Rendezvous callback used by pgmR3PhysUnmapChunk that unmaps a chunk
4941 *
4942 * This is only called on one of the EMTs while the other ones are waiting for
4943 * it to complete this function.
4944 *
4945 * @returns VINF_SUCCESS (VBox strict status code).
4946 * @param pVM The cross context VM structure.
4947 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
4948 * @param pvUser User pointer. Unused
4949 *
4950 */
4951static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysUnmapChunkRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
4952{
4953 int rc = VINF_SUCCESS;
4954 pgmLock(pVM);
4955 NOREF(pVCpu); NOREF(pvUser);
4956
4957 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
4958 {
4959 /* Flush the pgm pool cache; call the internal rendezvous handler as we're already in a rendezvous handler here. */
4960 /** @todo also not really efficient to unmap a chunk that contains PD
4961 * or PT pages. */
4962 pgmR3PoolClearAllRendezvous(pVM, &pVM->aCpus[0], NULL /* no need to flush the REM TLB as we already did that above */);
4963
4964 /*
4965 * Request the ring-0 part to unmap a chunk to make space in the mapping cache.
4966 */
4967 GMMMAPUNMAPCHUNKREQ Req;
4968 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
4969 Req.Hdr.cbReq = sizeof(Req);
4970 Req.pvR3 = NULL;
4971 Req.idChunkMap = NIL_GMM_CHUNKID;
4972 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
4973 if (Req.idChunkUnmap != INT32_MAX)
4974 {
4975 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
4976 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
4977 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
4978 if (RT_SUCCESS(rc))
4979 {
4980 /*
4981 * Remove the unmapped one.
4982 */
4983 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
4984 AssertRelease(pUnmappedChunk);
4985 AssertRelease(!pUnmappedChunk->cRefs);
4986 AssertRelease(!pUnmappedChunk->cPermRefs);
4987 pUnmappedChunk->pv = NULL;
4988 pUnmappedChunk->Core.Key = UINT32_MAX;
4989#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
4990 MMR3HeapFree(pUnmappedChunk);
4991#else
4992 MMR3UkHeapFree(pVM, pUnmappedChunk, MM_TAG_PGM_CHUNK_MAPPING);
4993#endif
4994 pVM->pgm.s.ChunkR3Map.c--;
4995 pVM->pgm.s.cUnmappedChunks++;
4996
4997 /*
4998 * Flush dangling PGM pointers (R3 & R0 ptrs to GC physical addresses).
4999 */
5000 /** @todo We should not flush chunks which include cr3 mappings. */
5001 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
5002 {
5003 PPGMCPU pPGM = &pVM->aCpus[idCpu].pgm.s;
5004
5005 pPGM->pGst32BitPdR3 = NULL;
5006 pPGM->pGstPaePdptR3 = NULL;
5007 pPGM->pGstAmd64Pml4R3 = NULL;
5008#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
5009 pPGM->pGst32BitPdR0 = NIL_RTR0PTR;
5010 pPGM->pGstPaePdptR0 = NIL_RTR0PTR;
5011 pPGM->pGstAmd64Pml4R0 = NIL_RTR0PTR;
5012#endif
5013 for (unsigned i = 0; i < RT_ELEMENTS(pPGM->apGstPaePDsR3); i++)
5014 {
5015 pPGM->apGstPaePDsR3[i] = NULL;
5016#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
5017 pPGM->apGstPaePDsR0[i] = NIL_RTR0PTR;
5018#endif
5019 }
5020
5021 /* Flush REM TLBs. */
5022 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5023 }
5024#ifdef VBOX_WITH_REM
5025 /* Flush REM translation blocks. */
5026 REMFlushTBs(pVM);
5027#endif
5028 }
5029 }
5030 }
5031 pgmUnlock(pVM);
5032 return rc;
5033}
5034
5035/**
5036 * Unmap a chunk to free up virtual address space (request packet handler for pgmR3PhysChunkMap)
5037 *
5038 * @returns VBox status code.
5039 * @param pVM The cross context VM structure.
5040 */
5041void pgmR3PhysUnmapChunk(PVM pVM)
5042{
5043 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysUnmapChunkRendezvous, NULL);
5044 AssertRC(rc);
5045}
5046
5047
5048/**
5049 * Maps the given chunk into the ring-3 mapping cache.
5050 *
5051 * This will call ring-0.
5052 *
5053 * @returns VBox status code.
5054 * @param pVM The cross context VM structure.
5055 * @param idChunk The chunk in question.
5056 * @param ppChunk Where to store the chunk tracking structure.
5057 *
5058 * @remarks Called from within the PGM critical section.
5059 * @remarks Can be called from any thread!
5060 */
5061int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
5062{
5063 int rc;
5064
5065 PGM_LOCK_ASSERT_OWNER(pVM);
5066
5067 /*
5068 * Move the chunk time forward.
5069 */
5070 pVM->pgm.s.ChunkR3Map.iNow++;
5071 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
5072 {
5073 pVM->pgm.s.ChunkR3Map.iNow = 4;
5074 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, NULL);
5075 }
5076
5077 /*
5078 * Allocate a new tracking structure first.
5079 */
5080#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
5081 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
5082#else
5083 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3UkHeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk), NULL);
5084#endif
5085 AssertReturn(pChunk, VERR_NO_MEMORY);
5086 pChunk->Core.Key = idChunk;
5087 pChunk->iLastUsed = pVM->pgm.s.ChunkR3Map.iNow;
5088
5089 /*
5090 * Request the ring-0 part to map the chunk in question.
5091 */
5092 GMMMAPUNMAPCHUNKREQ Req;
5093 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
5094 Req.Hdr.cbReq = sizeof(Req);
5095 Req.pvR3 = NULL;
5096 Req.idChunkMap = idChunk;
5097 Req.idChunkUnmap = NIL_GMM_CHUNKID;
5098
5099 /* Must be callable from any thread, so can't use VMMR3CallR0. */
5100 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
5101 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, NIL_VMCPUID, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
5102 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
5103 if (RT_SUCCESS(rc))
5104 {
5105 pChunk->pv = Req.pvR3;
5106
5107 /*
5108 * If we're running out of virtual address space, then we should
5109 * unmap another chunk.
5110 *
5111 * Currently, an unmap operation requires that all other virtual CPUs
5112 * are idling and not by chance making use of the memory we're
5113 * unmapping. So, we create an async unmap operation here.
5114 *
5115 * Now, when creating or restoring a saved state this wont work very
5116 * well since we may want to restore all guest RAM + a little something.
5117 * So, we have to do the unmap synchronously. Fortunately for us
5118 * though, during these operations the other virtual CPUs are inactive
5119 * and it should be safe to do this.
5120 */
5121 /** @todo Eventually we should lock all memory when used and do
5122 * map+unmap as one kernel call without any rendezvous or
5123 * other precautions. */
5124 if (pVM->pgm.s.ChunkR3Map.c + 1 >= pVM->pgm.s.ChunkR3Map.cMax)
5125 {
5126 switch (VMR3GetState(pVM))
5127 {
5128 case VMSTATE_LOADING:
5129 case VMSTATE_SAVING:
5130 {
5131 PVMCPU pVCpu = VMMGetCpu(pVM);
5132 if ( pVCpu
5133 && pVM->pgm.s.cDeprecatedPageLocks == 0)
5134 {
5135 pgmR3PhysUnmapChunkRendezvous(pVM, pVCpu, NULL);
5136 break;
5137 }
5138 }
5139 RT_FALL_THRU();
5140 default:
5141 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysUnmapChunk, 1, pVM);
5142 AssertRC(rc);
5143 break;
5144 }
5145 }
5146
5147 /*
5148 * Update the tree. We must do this after any unmapping to make sure
5149 * the chunk we're going to return isn't unmapped by accident.
5150 */
5151 AssertPtr(Req.pvR3);
5152 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
5153 AssertRelease(fRc);
5154 pVM->pgm.s.ChunkR3Map.c++;
5155 pVM->pgm.s.cMappedChunks++;
5156 }
5157 else
5158 {
5159 /** @todo this may fail because of /proc/sys/vm/max_map_count, so we
5160 * should probably restrict ourselves on linux. */
5161 AssertRC(rc);
5162#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
5163 MMR3HeapFree(pChunk);
5164#else
5165 MMR3UkHeapFree(pVM, pChunk, MM_TAG_PGM_CHUNK_MAPPING);
5166#endif
5167 pChunk = NULL;
5168 }
5169
5170 *ppChunk = pChunk;
5171 return rc;
5172}
5173
5174
5175/**
5176 * For VMMCALLRING3_PGM_MAP_CHUNK, considered internal.
5177 *
5178 * @returns see pgmR3PhysChunkMap.
5179 * @param pVM The cross context VM structure.
5180 * @param idChunk The chunk to map.
5181 */
5182VMMR3DECL(int) PGMR3PhysChunkMap(PVM pVM, uint32_t idChunk)
5183{
5184 PPGMCHUNKR3MAP pChunk;
5185 int rc;
5186
5187 pgmLock(pVM);
5188 rc = pgmR3PhysChunkMap(pVM, idChunk, &pChunk);
5189 pgmUnlock(pVM);
5190 return rc;
5191}
5192
5193
5194/**
5195 * Invalidates the TLB for the ring-3 mapping cache.
5196 *
5197 * @param pVM The cross context VM structure.
5198 */
5199VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
5200{
5201 pgmLock(pVM);
5202 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
5203 {
5204 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
5205 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
5206 }
5207 /* The page map TLB references chunks, so invalidate that one too. */
5208 pgmPhysInvalidatePageMapTLB(pVM);
5209 pgmUnlock(pVM);
5210}
5211
5212
5213/**
5214 * Response to VMMCALLRING3_PGM_ALLOCATE_LARGE_HANDY_PAGE to allocate a large
5215 * (2MB) page for use with a nested paging PDE.
5216 *
5217 * @returns The following VBox status codes.
5218 * @retval VINF_SUCCESS on success.
5219 * @retval VINF_EM_NO_MEMORY if we're out of memory.
5220 *
5221 * @param pVM The cross context VM structure.
5222 * @param GCPhys GC physical start address of the 2 MB range
5223 */
5224VMMR3DECL(int) PGMR3PhysAllocateLargeHandyPage(PVM pVM, RTGCPHYS GCPhys)
5225{
5226#ifdef PGM_WITH_LARGE_PAGES
5227 uint64_t u64TimeStamp1, u64TimeStamp2;
5228
5229 pgmLock(pVM);
5230
5231 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
5232 u64TimeStamp1 = RTTimeMilliTS();
5233 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_LARGE_HANDY_PAGE, 0, NULL);
5234 u64TimeStamp2 = RTTimeMilliTS();
5235 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
5236 if (RT_SUCCESS(rc))
5237 {
5238 Assert(pVM->pgm.s.cLargeHandyPages == 1);
5239
5240 uint32_t idPage = pVM->pgm.s.aLargeHandyPage[0].idPage;
5241 RTHCPHYS HCPhys = pVM->pgm.s.aLargeHandyPage[0].HCPhysGCPhys;
5242
5243 void *pv;
5244
5245 /* Map the large page into our address space.
5246 *
5247 * Note: assuming that within the 2 MB range:
5248 * - GCPhys + PAGE_SIZE = HCPhys + PAGE_SIZE (whole point of this exercise)
5249 * - user space mapping is continuous as well
5250 * - page id (GCPhys) + 1 = page id (GCPhys + PAGE_SIZE)
5251 */
5252 rc = pgmPhysPageMapByPageID(pVM, idPage, HCPhys, &pv);
5253 AssertLogRelMsg(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n", idPage, HCPhys, rc));
5254
5255 if (RT_SUCCESS(rc))
5256 {
5257 /*
5258 * Clear the pages.
5259 */
5260 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
5261 for (unsigned i = 0; i < _2M/PAGE_SIZE; i++)
5262 {
5263 ASMMemZeroPage(pv);
5264
5265 PPGMPAGE pPage;
5266 rc = pgmPhysGetPageEx(pVM, GCPhys, &pPage);
5267 AssertRC(rc);
5268
5269 Assert(PGM_PAGE_IS_ZERO(pPage));
5270 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatRZPageReplaceZero);
5271 pVM->pgm.s.cZeroPages--;
5272
5273 /*
5274 * Do the PGMPAGE modifications.
5275 */
5276 pVM->pgm.s.cPrivatePages++;
5277 PGM_PAGE_SET_HCPHYS(pVM, pPage, HCPhys);
5278 PGM_PAGE_SET_PAGEID(pVM, pPage, idPage);
5279 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ALLOCATED);
5280 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_PDE);
5281 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
5282 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
5283
5284 /* Somewhat dirty assumption that page ids are increasing. */
5285 idPage++;
5286
5287 HCPhys += PAGE_SIZE;
5288 GCPhys += PAGE_SIZE;
5289
5290 pv = (void *)((uintptr_t)pv + PAGE_SIZE);
5291
5292 Log3(("PGMR3PhysAllocateLargePage: idPage=%#x HCPhys=%RGp\n", idPage, HCPhys));
5293 }
5294 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
5295
5296 /* Flush all TLBs. */
5297 PGM_INVL_ALL_VCPU_TLBS(pVM);
5298 pgmPhysInvalidatePageMapTLB(pVM);
5299 }
5300 pVM->pgm.s.cLargeHandyPages = 0;
5301 }
5302
5303 if (RT_SUCCESS(rc))
5304 {
5305 static uint32_t cTimeOut = 0;
5306 uint64_t u64TimeStampDelta = u64TimeStamp2 - u64TimeStamp1;
5307
5308 if (u64TimeStampDelta > 100)
5309 {
5310 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatLargePageOverflow);
5311 if ( ++cTimeOut > 10
5312 || u64TimeStampDelta > 1000 /* more than one second forces an early retirement from allocating large pages. */)
5313 {
5314 /* If repeated attempts to allocate a large page takes more than 100 ms, then we fall back to normal 4k pages.
5315 * E.g. Vista 64 tries to move memory around, which takes a huge amount of time.
5316 */
5317 LogRel(("PGMR3PhysAllocateLargePage: allocating large pages takes too long (last attempt %d ms; nr of timeouts %d); DISABLE\n", u64TimeStampDelta, cTimeOut));
5318 PGMSetLargePageUsage(pVM, false);
5319 }
5320 }
5321 else
5322 if (cTimeOut > 0)
5323 cTimeOut--;
5324 }
5325
5326 pgmUnlock(pVM);
5327 return rc;
5328#else
5329 RT_NOREF(pVM, GCPhys);
5330 return VERR_NOT_IMPLEMENTED;
5331#endif /* PGM_WITH_LARGE_PAGES */
5332}
5333
5334
5335/**
5336 * Response to VM_FF_PGM_NEED_HANDY_PAGES and VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES.
5337 *
5338 * This function will also work the VM_FF_PGM_NO_MEMORY force action flag, to
5339 * signal and clear the out of memory condition. When contracted, this API is
5340 * used to try clear the condition when the user wants to resume.
5341 *
5342 * @returns The following VBox status codes.
5343 * @retval VINF_SUCCESS on success. FFs cleared.
5344 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in
5345 * this case and it gets accompanied by VM_FF_PGM_NO_MEMORY.
5346 *
5347 * @param pVM The cross context VM structure.
5348 *
5349 * @remarks The VINF_EM_NO_MEMORY status is for the benefit of the FF processing
5350 * in EM.cpp and shouldn't be propagated outside TRPM, HM, EM and
5351 * pgmPhysEnsureHandyPage. There is one exception to this in the \#PF
5352 * handler.
5353 */
5354VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
5355{
5356 pgmLock(pVM);
5357
5358 /*
5359 * Allocate more pages, noting down the index of the first new page.
5360 */
5361 uint32_t iClear = pVM->pgm.s.cHandyPages;
5362 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_PGM_HANDY_PAGE_IPE);
5363 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
5364 int rcAlloc = VINF_SUCCESS;
5365 int rcSeed = VINF_SUCCESS;
5366 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
5367 while (rc == VERR_GMM_SEED_ME)
5368 {
5369 void *pvChunk;
5370 rcAlloc = rc = SUPR3PageAlloc(GMM_CHUNK_SIZE >> PAGE_SHIFT, &pvChunk);
5371 if (RT_SUCCESS(rc))
5372 {
5373 rcSeed = rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_SEED_CHUNK, (uintptr_t)pvChunk, NULL);
5374 if (RT_FAILURE(rc))
5375 SUPR3PageFree(pvChunk, GMM_CHUNK_SIZE >> PAGE_SHIFT);
5376 }
5377 if (RT_SUCCESS(rc))
5378 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
5379 }
5380
5381 /** @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) */
5382 if ( rc == VERR_GMM_HIT_VM_ACCOUNT_LIMIT
5383 && pVM->pgm.s.cHandyPages > 0)
5384 {
5385 /* Still handy pages left, so don't panic. */
5386 rc = VINF_SUCCESS;
5387 }
5388
5389 if (RT_SUCCESS(rc))
5390 {
5391 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
5392 Assert(pVM->pgm.s.cHandyPages > 0);
5393 VM_FF_CLEAR(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
5394 VM_FF_CLEAR(pVM, VM_FF_PGM_NO_MEMORY);
5395
5396#ifdef VBOX_STRICT
5397 uint32_t i;
5398 for (i = iClear; i < pVM->pgm.s.cHandyPages; i++)
5399 if ( pVM->pgm.s.aHandyPages[i].idPage == NIL_GMM_PAGEID
5400 || pVM->pgm.s.aHandyPages[i].idSharedPage != NIL_GMM_PAGEID
5401 || (pVM->pgm.s.aHandyPages[i].HCPhysGCPhys & PAGE_OFFSET_MASK))
5402 break;
5403 if (i != pVM->pgm.s.cHandyPages)
5404 {
5405 RTAssertMsg1Weak(NULL, __LINE__, __FILE__, __FUNCTION__);
5406 RTAssertMsg2Weak("i=%d iClear=%d cHandyPages=%d\n", i, iClear, pVM->pgm.s.cHandyPages);
5407 for (uint32_t j = iClear; j < pVM->pgm.s.cHandyPages; j++)
5408 RTAssertMsg2Add("%03d: idPage=%d HCPhysGCPhys=%RHp idSharedPage=%d%\n", j,
5409 pVM->pgm.s.aHandyPages[j].idPage,
5410 pVM->pgm.s.aHandyPages[j].HCPhysGCPhys,
5411 pVM->pgm.s.aHandyPages[j].idSharedPage,
5412 j == i ? " <---" : "");
5413 RTAssertPanic();
5414 }
5415#endif
5416 /*
5417 * Clear the pages.
5418 */
5419 while (iClear < pVM->pgm.s.cHandyPages)
5420 {
5421 PGMMPAGEDESC pPage = &pVM->pgm.s.aHandyPages[iClear];
5422 void *pv;
5423 rc = pgmPhysPageMapByPageID(pVM, pPage->idPage, pPage->HCPhysGCPhys, &pv);
5424 AssertLogRelMsgBreak(RT_SUCCESS(rc),
5425 ("%u/%u: idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n",
5426 iClear, pVM->pgm.s.cHandyPages, pPage->idPage, pPage->HCPhysGCPhys, rc));
5427 ASMMemZeroPage(pv);
5428 iClear++;
5429 Log3(("PGMR3PhysAllocateHandyPages: idPage=%#x HCPhys=%RGp\n", pPage->idPage, pPage->HCPhysGCPhys));
5430 }
5431 }
5432 else
5433 {
5434 uint64_t cAllocPages, cMaxPages, cBalloonPages;
5435
5436 /*
5437 * We should never get here unless there is a genuine shortage of
5438 * memory (or some internal error). Flag the error so the VM can be
5439 * suspended ASAP and the user informed. If we're totally out of
5440 * handy pages we will return failure.
5441 */
5442 /* Report the failure. */
5443 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc rcAlloc=%Rrc rcSeed=%Rrc cHandyPages=%#x\n"
5444 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
5445 rc, rcAlloc, rcSeed,
5446 pVM->pgm.s.cHandyPages,
5447 pVM->pgm.s.cAllPages,
5448 pVM->pgm.s.cPrivatePages,
5449 pVM->pgm.s.cSharedPages,
5450 pVM->pgm.s.cZeroPages));
5451
5452 if (GMMR3QueryMemoryStats(pVM, &cAllocPages, &cMaxPages, &cBalloonPages) == VINF_SUCCESS)
5453 {
5454 LogRel(("GMM: Statistics:\n"
5455 " Allocated pages: %RX64\n"
5456 " Maximum pages: %RX64\n"
5457 " Ballooned pages: %RX64\n", cAllocPages, cMaxPages, cBalloonPages));
5458 }
5459
5460 if ( rc != VERR_NO_MEMORY
5461 && rc != VERR_NO_PHYS_MEMORY
5462 && rc != VERR_LOCK_FAILED)
5463 {
5464 for (uint32_t i = 0; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
5465 {
5466 LogRel(("PGM: aHandyPages[#%#04x] = {.HCPhysGCPhys=%RHp, .idPage=%#08x, .idSharedPage=%#08x}\n",
5467 i, pVM->pgm.s.aHandyPages[i].HCPhysGCPhys, pVM->pgm.s.aHandyPages[i].idPage,
5468 pVM->pgm.s.aHandyPages[i].idSharedPage));
5469 uint32_t const idPage = pVM->pgm.s.aHandyPages[i].idPage;
5470 if (idPage != NIL_GMM_PAGEID)
5471 {
5472 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
5473 pRam;
5474 pRam = pRam->pNextR3)
5475 {
5476 uint32_t const cPages = pRam->cb >> PAGE_SHIFT;
5477 for (uint32_t iPage = 0; iPage < cPages; iPage++)
5478 if (PGM_PAGE_GET_PAGEID(&pRam->aPages[iPage]) == idPage)
5479 LogRel(("PGM: Used by %RGp %R[pgmpage] (%s)\n",
5480 pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pRam->aPages[iPage], pRam->pszDesc));
5481 }
5482 }
5483 }
5484 }
5485
5486 if (rc == VERR_NO_MEMORY)
5487 {
5488 uint64_t cbHostRamAvail = 0;
5489 int rc2 = RTSystemQueryAvailableRam(&cbHostRamAvail);
5490 if (RT_SUCCESS(rc2))
5491 LogRel(("Host RAM: %RU64MB available\n", cbHostRamAvail / _1M));
5492 else
5493 LogRel(("Cannot determine the amount of available host memory\n"));
5494 }
5495
5496 /* Set the FFs and adjust rc. */
5497 VM_FF_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
5498 VM_FF_SET(pVM, VM_FF_PGM_NO_MEMORY);
5499 if ( rc == VERR_NO_MEMORY
5500 || rc == VERR_NO_PHYS_MEMORY
5501 || rc == VERR_LOCK_FAILED)
5502 rc = VINF_EM_NO_MEMORY;
5503 }
5504
5505 pgmUnlock(pVM);
5506 return rc;
5507}
5508
5509
5510/**
5511 * Frees the specified RAM page and replaces it with the ZERO page.
5512 *
5513 * This is used by ballooning, remapping MMIO2, RAM reset and state loading.
5514 *
5515 * @param pVM The cross context VM structure.
5516 * @param pReq Pointer to the request.
5517 * @param pcPendingPages Where the number of pages waiting to be freed are
5518 * kept. This will normally be incremented.
5519 * @param pPage Pointer to the page structure.
5520 * @param GCPhys The guest physical address of the page, if applicable.
5521 * @param enmNewType New page type for NEM notification, since several
5522 * callers will change the type upon successful return.
5523 *
5524 * @remarks The caller must own the PGM lock.
5525 */
5526int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys,
5527 PGMPAGETYPE enmNewType)
5528{
5529 /*
5530 * Assert sanity.
5531 */
5532 PGM_LOCK_ASSERT_OWNER(pVM);
5533 if (RT_UNLIKELY( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM
5534 && PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_ROM_SHADOW))
5535 {
5536 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
5537 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
5538 }
5539
5540 /** @todo What about ballooning of large pages??! */
5541 Assert( PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE
5542 && PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE_DISABLED);
5543
5544 if ( PGM_PAGE_IS_ZERO(pPage)
5545 || PGM_PAGE_IS_BALLOONED(pPage))
5546 return VINF_SUCCESS;
5547
5548 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
5549 Log3(("pgmPhysFreePage: idPage=%#x GCPhys=%RGp pPage=%R[pgmpage]\n", idPage, GCPhys, pPage));
5550 if (RT_UNLIKELY( idPage == NIL_GMM_PAGEID
5551 || idPage > GMM_PAGEID_LAST
5552 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID))
5553 {
5554 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
5555 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
5556 }
5557 const RTHCPHYS HCPhysPrev = PGM_PAGE_GET_HCPHYS(pPage);
5558
5559 /* update page count stats. */
5560 if (PGM_PAGE_IS_SHARED(pPage))
5561 pVM->pgm.s.cSharedPages--;
5562 else
5563 pVM->pgm.s.cPrivatePages--;
5564 pVM->pgm.s.cZeroPages++;
5565
5566 /* Deal with write monitored pages. */
5567 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
5568 {
5569 PGM_PAGE_SET_WRITTEN_TO(pVM, pPage);
5570 pVM->pgm.s.cWrittenToPages++;
5571 }
5572
5573 /*
5574 * pPage = ZERO page.
5575 */
5576 PGM_PAGE_SET_HCPHYS(pVM, pPage, pVM->pgm.s.HCPhysZeroPg);
5577 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
5578 PGM_PAGE_SET_PAGEID(pVM, pPage, NIL_GMM_PAGEID);
5579 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
5580 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
5581 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
5582
5583 /* Flush physical page map TLB entry. */
5584 pgmPhysInvalidatePageMapTLBEntry(pVM, GCPhys);
5585
5586 /* Notify NEM. */
5587 /** @todo consider doing batch NEM notifications. */
5588 if (VM_IS_NEM_ENABLED(pVM))
5589 {
5590 uint8_t u2State = PGM_PAGE_GET_NEM_STATE(pPage);
5591 NEMHCNotifyPhysPageChanged(pVM, GCPhys, HCPhysPrev, pVM->pgm.s.HCPhysZeroPg,
5592 pgmPhysPageCalcNemProtection(pPage, enmNewType), enmNewType, &u2State);
5593 PGM_PAGE_SET_NEM_STATE(pPage, u2State);
5594 }
5595
5596 /*
5597 * Make sure it's not in the handy page array.
5598 */
5599 for (uint32_t i = pVM->pgm.s.cHandyPages; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
5600 {
5601 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
5602 {
5603 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
5604 break;
5605 }
5606 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
5607 {
5608 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
5609 break;
5610 }
5611 }
5612
5613 /*
5614 * Push it onto the page array.
5615 */
5616 uint32_t iPage = *pcPendingPages;
5617 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
5618 *pcPendingPages += 1;
5619
5620 pReq->aPages[iPage].idPage = idPage;
5621
5622 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
5623 return VINF_SUCCESS;
5624
5625 /*
5626 * Flush the pages.
5627 */
5628 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
5629 if (RT_SUCCESS(rc))
5630 {
5631 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
5632 *pcPendingPages = 0;
5633 }
5634 return rc;
5635}
5636
5637
5638/**
5639 * Converts a GC physical address to a HC ring-3 pointer, with some
5640 * additional checks.
5641 *
5642 * @returns VBox status code.
5643 * @retval VINF_SUCCESS on success.
5644 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
5645 * access handler of some kind.
5646 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
5647 * accesses or is odd in any way.
5648 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
5649 *
5650 * @param pVM The cross context VM structure.
5651 * @param GCPhys The GC physical address to convert. Since this is only
5652 * used for filling the REM TLB, the A20 mask must be
5653 * applied before calling this API.
5654 * @param fWritable Whether write access is required.
5655 * @param ppv Where to store the pointer corresponding to GCPhys on
5656 * success.
5657 */
5658VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
5659{
5660 pgmLock(pVM);
5661 PGM_A20_ASSERT_MASKED(VMMGetCpu(pVM), GCPhys);
5662
5663 PPGMRAMRANGE pRam;
5664 PPGMPAGE pPage;
5665 int rc = pgmPhysGetPageAndRangeEx(pVM, GCPhys, &pPage, &pRam);
5666 if (RT_SUCCESS(rc))
5667 {
5668 if (PGM_PAGE_IS_BALLOONED(pPage))
5669 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
5670 else if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
5671 rc = VINF_SUCCESS;
5672 else
5673 {
5674 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
5675 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
5676 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
5677 {
5678 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
5679 * in -norawr0 mode. */
5680 if (fWritable)
5681 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
5682 }
5683 else
5684 {
5685 /* Temporarily disabled physical handler(s), since the recompiler
5686 doesn't get notified when it's reset we'll have to pretend it's
5687 operating normally. */
5688 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
5689 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
5690 else
5691 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
5692 }
5693 }
5694 if (RT_SUCCESS(rc))
5695 {
5696 int rc2;
5697
5698 /* Make sure what we return is writable. */
5699 if (fWritable)
5700 switch (PGM_PAGE_GET_STATE(pPage))
5701 {
5702 case PGM_PAGE_STATE_ALLOCATED:
5703 break;
5704 case PGM_PAGE_STATE_BALLOONED:
5705 AssertFailed();
5706 break;
5707 case PGM_PAGE_STATE_ZERO:
5708 case PGM_PAGE_STATE_SHARED:
5709 if (rc == VINF_PGM_PHYS_TLB_CATCH_WRITE)
5710 break;
5711 RT_FALL_THRU();
5712 case PGM_PAGE_STATE_WRITE_MONITORED:
5713 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)PAGE_OFFSET_MASK);
5714 AssertLogRelRCReturn(rc2, rc2);
5715 break;
5716 }
5717
5718 /* Get a ring-3 mapping of the address. */
5719 PPGMPAGER3MAPTLBE pTlbe;
5720 rc2 = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
5721 AssertLogRelRCReturn(rc2, rc2);
5722 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
5723 /** @todo mapping/locking hell; this isn't horribly efficient since
5724 * pgmPhysPageLoadIntoTlb will repeat the lookup we've done here. */
5725
5726 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
5727 }
5728 else
5729 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
5730
5731 /* else: handler catching all access, no pointer returned. */
5732 }
5733 else
5734 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
5735
5736 pgmUnlock(pVM);
5737 return rc;
5738}
5739
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