VirtualBox

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

Last change on this file since 72358 was 70977, checked in by vboxsync, 7 years ago

NEM: Working on PGM notifications. bugref:9044

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