VirtualBox

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

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

PGMR3PhysBulkGCPhys2CCPtrExternal: Fixed pgmR3PhysGCPhys2CCPtrDelegated call. bugref:9172

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

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