VirtualBox

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

Last change on this file since 92155 was 92129, checked in by vboxsync, 3 years ago

VMM/PGM,NEM: RAM registration notification must return a u2State value too. bugref:10122

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette