VirtualBox

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

Last change on this file since 93444 was 93210, checked in by vboxsync, 3 years ago

VMM/PGMR3PhysMmio2Register: Call MMR3AdjustFixedReservation even in NEM mode. bugref:10122

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