VirtualBox

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

Last change on this file since 56046 was 55909, checked in by vboxsync, 10 years ago

PGM,++: Made the ring-3 physical access handler callbacks present in all contexts, where applicable. They are not yet registered or used. Taking things slowly.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 165.0 KB
Line 
1/* $Id: PGMPhys.cpp 55909 2015-05-18 13:09:16Z vboxsync $ */
2/** @file
3 * PGM - Page Manager and Monitor, Physical Memory Addressing.
4 */
5
6/*
7 * Copyright (C) 2006-2014 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/iom.h>
25#include <VBox/vmm/mm.h>
26#include <VBox/vmm/stam.h>
27#ifdef VBOX_WITH_REM
28# include <VBox/vmm/rem.h>
29#endif
30#include <VBox/vmm/pdmdev.h>
31#include "PGMInternal.h"
32#include <VBox/vmm/vm.h>
33#include <VBox/vmm/uvm.h>
34#include "PGMInline.h"
35#include <VBox/sup.h>
36#include <VBox/param.h>
37#include <VBox/err.h>
38#include <VBox/log.h>
39#include <iprt/assert.h>
40#include <iprt/alloc.h>
41#include <iprt/asm.h>
42#ifdef VBOX_STRICT
43# include <iprt/crc.h>
44#endif
45#include <iprt/thread.h>
46#include <iprt/string.h>
47#include <iprt/system.h>
48
49
50/*******************************************************************************
51* Defined Constants And Macros *
52*******************************************************************************/
53/** The number of pages to free in one batch. */
54#define PGMPHYS_FREE_PAGE_BATCH_SIZE 128
55
56
57/*
58 * PGMR3PhysReadU8-64
59 * PGMR3PhysWriteU8-64
60 */
61#define PGMPHYSFN_READNAME PGMR3PhysReadU8
62#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU8
63#define PGMPHYS_DATASIZE 1
64#define PGMPHYS_DATATYPE uint8_t
65#include "PGMPhysRWTmpl.h"
66
67#define PGMPHYSFN_READNAME PGMR3PhysReadU16
68#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU16
69#define PGMPHYS_DATASIZE 2
70#define PGMPHYS_DATATYPE uint16_t
71#include "PGMPhysRWTmpl.h"
72
73#define PGMPHYSFN_READNAME PGMR3PhysReadU32
74#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU32
75#define PGMPHYS_DATASIZE 4
76#define PGMPHYS_DATATYPE uint32_t
77#include "PGMPhysRWTmpl.h"
78
79#define PGMPHYSFN_READNAME PGMR3PhysReadU64
80#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU64
81#define PGMPHYS_DATASIZE 8
82#define PGMPHYS_DATATYPE uint64_t
83#include "PGMPhysRWTmpl.h"
84
85
86/**
87 * EMT worker for PGMR3PhysReadExternal.
88 */
89static DECLCALLBACK(int) pgmR3PhysReadExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, void *pvBuf, size_t cbRead,
90 PGMACCESSORIGIN enmOrigin)
91{
92 PGMPhysRead(pVM, *pGCPhys, pvBuf, cbRead, enmOrigin);
93 return VINF_SUCCESS;
94}
95
96
97/**
98 * Read from physical memory, external users.
99 *
100 * @returns VBox status code.
101 * @retval VINF_SUCCESS.
102 *
103 * @param pVM Pointer to the VM.
104 * @param GCPhys Physical address to read from.
105 * @param pvBuf Where to read into.
106 * @param cbRead How many bytes to read.
107 * @param enmOrigin Who is calling.
108 *
109 * @thread Any but EMTs.
110 */
111VMMR3DECL(int) PGMR3PhysReadExternal(PVM pVM, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead, PGMACCESSORIGIN enmOrigin)
112{
113 VM_ASSERT_OTHER_THREAD(pVM);
114
115 AssertMsgReturn(cbRead > 0, ("don't even think about reading zero bytes!\n"), VINF_SUCCESS);
116 LogFlow(("PGMR3PhysReadExternal: %RGp %d\n", GCPhys, cbRead));
117
118 pgmLock(pVM);
119
120 /*
121 * Copy loop on ram ranges.
122 */
123 PPGMRAMRANGE pRam = pgmPhysGetRangeAtOrAbove(pVM, GCPhys);
124 for (;;)
125 {
126 /* Inside range or not? */
127 if (pRam && GCPhys >= pRam->GCPhys)
128 {
129 /*
130 * Must work our way thru this page by page.
131 */
132 RTGCPHYS off = GCPhys - pRam->GCPhys;
133 while (off < pRam->cb)
134 {
135 unsigned iPage = off >> PAGE_SHIFT;
136 PPGMPAGE pPage = &pRam->aPages[iPage];
137
138 /*
139 * If the page has an ALL access handler, we'll have to
140 * delegate the job to EMT.
141 */
142 if ( PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)
143 || PGM_PAGE_IS_SPECIAL_ALIAS_MMIO(pPage))
144 {
145 pgmUnlock(pVM);
146
147 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysReadExternalEMT, 5,
148 pVM, &GCPhys, pvBuf, cbRead, enmOrigin);
149 }
150 Assert(!PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage));
151
152 /*
153 * Simple stuff, go ahead.
154 */
155 size_t cb = PAGE_SIZE - (off & PAGE_OFFSET_MASK);
156 if (cb > cbRead)
157 cb = cbRead;
158 PGMPAGEMAPLOCK PgMpLck;
159 const void *pvSrc;
160 int rc = pgmPhysGCPhys2CCPtrInternalReadOnly(pVM, pPage, pRam->GCPhys + off, &pvSrc, &PgMpLck);
161 if (RT_SUCCESS(rc))
162 {
163 memcpy(pvBuf, pvSrc, cb);
164 pgmPhysReleaseInternalPageMappingLock(pVM, &PgMpLck);
165 }
166 else
167 {
168 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternalReadOnly failed on %RGp / %R[pgmpage] -> %Rrc\n",
169 pRam->GCPhys + off, pPage, rc));
170 memset(pvBuf, 0xff, cb);
171 }
172
173 /* next page */
174 if (cb >= cbRead)
175 {
176 pgmUnlock(pVM);
177 return VINF_SUCCESS;
178 }
179 cbRead -= cb;
180 off += cb;
181 GCPhys += cb;
182 pvBuf = (char *)pvBuf + cb;
183 } /* walk pages in ram range. */
184 }
185 else
186 {
187 LogFlow(("PGMPhysRead: Unassigned %RGp size=%u\n", GCPhys, cbRead));
188
189 /*
190 * Unassigned address space.
191 */
192 size_t cb = pRam ? pRam->GCPhys - GCPhys : ~(size_t)0;
193 if (cb >= cbRead)
194 {
195 memset(pvBuf, 0xff, cbRead);
196 break;
197 }
198 memset(pvBuf, 0xff, cb);
199
200 cbRead -= cb;
201 pvBuf = (char *)pvBuf + cb;
202 GCPhys += cb;
203 }
204
205 /* Advance range if necessary. */
206 while (pRam && GCPhys > pRam->GCPhysLast)
207 pRam = pRam->CTX_SUFF(pNext);
208 } /* Ram range walk */
209
210 pgmUnlock(pVM);
211
212 return VINF_SUCCESS;
213}
214
215
216/**
217 * EMT worker for PGMR3PhysWriteExternal.
218 */
219static DECLCALLBACK(int) pgmR3PhysWriteExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, const void *pvBuf, size_t cbWrite,
220 PGMACCESSORIGIN enmOrigin)
221{
222 /** @todo VERR_EM_NO_MEMORY */
223 PGMPhysWrite(pVM, *pGCPhys, pvBuf, cbWrite, enmOrigin);
224 return VINF_SUCCESS;
225}
226
227
228/**
229 * Write to physical memory, external users.
230 *
231 * @returns VBox status code.
232 * @retval VINF_SUCCESS.
233 * @retval VERR_EM_NO_MEMORY.
234 *
235 * @param pVM Pointer to the VM.
236 * @param GCPhys Physical address to write to.
237 * @param pvBuf What to write.
238 * @param cbWrite How many bytes to write.
239 * @param enmOrigin Who is calling.
240 *
241 * @thread Any but EMTs.
242 */
243VMMDECL(int) PGMR3PhysWriteExternal(PVM pVM, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite, PGMACCESSORIGIN enmOrigin)
244{
245 VM_ASSERT_OTHER_THREAD(pVM);
246
247 AssertMsg(!pVM->pgm.s.fNoMorePhysWrites,
248 ("Calling PGMR3PhysWriteExternal after pgmR3Save()! GCPhys=%RGp cbWrite=%#x enmOrigin=%d\n",
249 GCPhys, cbWrite, enmOrigin));
250 AssertMsgReturn(cbWrite > 0, ("don't even think about writing zero bytes!\n"), VINF_SUCCESS);
251 LogFlow(("PGMR3PhysWriteExternal: %RGp %d\n", GCPhys, cbWrite));
252
253 pgmLock(pVM);
254
255 /*
256 * Copy loop on ram ranges, stop when we hit something difficult.
257 */
258 PPGMRAMRANGE pRam = pgmPhysGetRangeAtOrAbove(pVM, GCPhys);
259 for (;;)
260 {
261 /* Inside range or not? */
262 if (pRam && GCPhys >= pRam->GCPhys)
263 {
264 /*
265 * Must work our way thru this page by page.
266 */
267 RTGCPTR off = GCPhys - pRam->GCPhys;
268 while (off < pRam->cb)
269 {
270 RTGCPTR iPage = off >> PAGE_SHIFT;
271 PPGMPAGE pPage = &pRam->aPages[iPage];
272
273 /*
274 * Is the page problematic, we have to do the work on the EMT.
275 *
276 * Allocating writable pages and access handlers are
277 * problematic, write monitored pages are simple and can be
278 * dealt with here.
279 */
280 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
281 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED
282 || PGM_PAGE_IS_SPECIAL_ALIAS_MMIO(pPage))
283 {
284 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
285 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
286 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage);
287 else
288 {
289 pgmUnlock(pVM);
290
291 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysWriteExternalEMT, 5,
292 pVM, &GCPhys, pvBuf, cbWrite, enmOrigin);
293 }
294 }
295 Assert(!PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage));
296
297 /*
298 * Simple stuff, go ahead.
299 */
300 size_t cb = PAGE_SIZE - (off & PAGE_OFFSET_MASK);
301 if (cb > cbWrite)
302 cb = cbWrite;
303 PGMPAGEMAPLOCK PgMpLck;
304 void *pvDst;
305 int rc = pgmPhysGCPhys2CCPtrInternal(pVM, pPage, pRam->GCPhys + off, &pvDst, &PgMpLck);
306 if (RT_SUCCESS(rc))
307 {
308 memcpy(pvDst, pvBuf, cb);
309 pgmPhysReleaseInternalPageMappingLock(pVM, &PgMpLck);
310 }
311 else
312 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternal failed on %RGp / %R[pgmpage] -> %Rrc\n",
313 pRam->GCPhys + off, pPage, rc));
314
315 /* next page */
316 if (cb >= cbWrite)
317 {
318 pgmUnlock(pVM);
319 return VINF_SUCCESS;
320 }
321
322 cbWrite -= cb;
323 off += cb;
324 GCPhys += cb;
325 pvBuf = (const char *)pvBuf + cb;
326 } /* walk pages in ram range */
327 }
328 else
329 {
330 /*
331 * Unassigned address space, skip it.
332 */
333 if (!pRam)
334 break;
335 size_t cb = pRam->GCPhys - GCPhys;
336 if (cb >= cbWrite)
337 break;
338 cbWrite -= cb;
339 pvBuf = (const char *)pvBuf + cb;
340 GCPhys += cb;
341 }
342
343 /* Advance range if necessary. */
344 while (pRam && GCPhys > pRam->GCPhysLast)
345 pRam = pRam->CTX_SUFF(pNext);
346 } /* Ram range walk */
347
348 pgmUnlock(pVM);
349 return VINF_SUCCESS;
350}
351
352
353/**
354 * VMR3ReqCall worker for PGMR3PhysGCPhys2CCPtrExternal to make pages writable.
355 *
356 * @returns see PGMR3PhysGCPhys2CCPtrExternal
357 * @param pVM Pointer to the VM.
358 * @param pGCPhys Pointer to the guest physical address.
359 * @param ppv Where to store the mapping address.
360 * @param pLock Where to store the lock.
361 */
362static DECLCALLBACK(int) pgmR3PhysGCPhys2CCPtrDelegated(PVM pVM, PRTGCPHYS pGCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
363{
364 /*
365 * Just hand it to PGMPhysGCPhys2CCPtr and check that it's not a page with
366 * an access handler after it succeeds.
367 */
368 int rc = pgmLock(pVM);
369 AssertRCReturn(rc, rc);
370
371 rc = PGMPhysGCPhys2CCPtr(pVM, *pGCPhys, ppv, pLock);
372 if (RT_SUCCESS(rc))
373 {
374 PPGMPAGEMAPTLBE pTlbe;
375 int rc2 = pgmPhysPageQueryTlbe(pVM, *pGCPhys, &pTlbe);
376 AssertFatalRC(rc2);
377 PPGMPAGE pPage = pTlbe->pPage;
378 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
379 {
380 PGMPhysReleasePageMappingLock(pVM, pLock);
381 rc = VERR_PGM_PHYS_PAGE_RESERVED;
382 }
383 else if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
384#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
385 || pgmPoolIsDirtyPage(pVM, *pGCPhys)
386#endif
387 )
388 {
389 /* We *must* flush any corresponding pgm pool page here, otherwise we'll
390 * not be informed about writes and keep bogus gst->shw mappings around.
391 */
392 pgmPoolFlushPageByGCPhys(pVM, *pGCPhys);
393 Assert(!PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage));
394 /** @todo r=bird: return VERR_PGM_PHYS_PAGE_RESERVED here if it still has
395 * active handlers, see the PGMR3PhysGCPhys2CCPtrExternal docs. */
396 }
397 }
398
399 pgmUnlock(pVM);
400 return rc;
401}
402
403
404/**
405 * Requests the mapping of a guest page into ring-3, external threads.
406 *
407 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
408 * release it.
409 *
410 * This API will assume your intention is to write to the page, and will
411 * therefore replace shared and zero pages. If you do not intend to modify the
412 * page, use the PGMR3PhysGCPhys2CCPtrReadOnlyExternal() API.
413 *
414 * @returns VBox status code.
415 * @retval VINF_SUCCESS on success.
416 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
417 * backing or if the page has any active access handlers. The caller
418 * must fall back on using PGMR3PhysWriteExternal.
419 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
420 *
421 * @param pVM Pointer to the VM.
422 * @param GCPhys The guest physical address of the page that should be mapped.
423 * @param ppv Where to store the address corresponding to GCPhys.
424 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
425 *
426 * @remark Avoid calling this API from within critical sections (other than the
427 * PGM one) because of the deadlock risk when we have to delegating the
428 * task to an EMT.
429 * @thread Any.
430 */
431VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrExternal(PVM pVM, RTGCPHYS GCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
432{
433 AssertPtr(ppv);
434 AssertPtr(pLock);
435
436 Assert(VM_IS_EMT(pVM) || !PGMIsLockOwner(pVM));
437
438 int rc = pgmLock(pVM);
439 AssertRCReturn(rc, rc);
440
441 /*
442 * Query the Physical TLB entry for the page (may fail).
443 */
444 PPGMPAGEMAPTLBE pTlbe;
445 rc = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
446 if (RT_SUCCESS(rc))
447 {
448 PPGMPAGE pPage = pTlbe->pPage;
449 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
450 rc = VERR_PGM_PHYS_PAGE_RESERVED;
451 else
452 {
453 /*
454 * If the page is shared, the zero page, or being write monitored
455 * it must be converted to an page that's writable if possible.
456 * We can only deal with write monitored pages here, the rest have
457 * to be on an EMT.
458 */
459 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
460 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED
461#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
462 || pgmPoolIsDirtyPage(pVM, GCPhys)
463#endif
464 )
465 {
466 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
467 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
468#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
469 && !pgmPoolIsDirtyPage(pVM, GCPhys)
470#endif
471 )
472 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage);
473 else
474 {
475 pgmUnlock(pVM);
476
477 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysGCPhys2CCPtrDelegated, 4,
478 pVM, &GCPhys, ppv, pLock);
479 }
480 }
481
482 /*
483 * Now, just perform the locking and calculate the return address.
484 */
485 PPGMPAGEMAP pMap = pTlbe->pMap;
486 if (pMap)
487 pMap->cRefs++;
488
489 unsigned cLocks = PGM_PAGE_GET_WRITE_LOCKS(pPage);
490 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
491 {
492 if (cLocks == 0)
493 pVM->pgm.s.cWriteLockedPages++;
494 PGM_PAGE_INC_WRITE_LOCKS(pPage);
495 }
496 else if (cLocks != PGM_PAGE_GET_WRITE_LOCKS(pPage))
497 {
498 PGM_PAGE_INC_WRITE_LOCKS(pPage);
499 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent write locked state!\n", GCPhys, pPage));
500 if (pMap)
501 pMap->cRefs++; /* Extra ref to prevent it from going away. */
502 }
503
504 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
505 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_WRITE;
506 pLock->pvMap = pMap;
507 }
508 }
509
510 pgmUnlock(pVM);
511 return rc;
512}
513
514
515/**
516 * Requests the mapping of a guest page into ring-3, external threads.
517 *
518 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
519 * release it.
520 *
521 * @returns VBox status code.
522 * @retval VINF_SUCCESS on success.
523 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
524 * backing or if the page as an active ALL access handler. The caller
525 * must fall back on using PGMPhysRead.
526 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
527 *
528 * @param pVM Pointer to the VM.
529 * @param GCPhys The guest physical address of the page that should be mapped.
530 * @param ppv Where to store the address corresponding to GCPhys.
531 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
532 *
533 * @remark Avoid calling this API from within critical sections (other than
534 * the PGM one) because of the deadlock risk.
535 * @thread Any.
536 */
537VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrReadOnlyExternal(PVM pVM, RTGCPHYS GCPhys, void const **ppv, PPGMPAGEMAPLOCK pLock)
538{
539 int rc = pgmLock(pVM);
540 AssertRCReturn(rc, rc);
541
542 /*
543 * Query the Physical TLB entry for the page (may fail).
544 */
545 PPGMPAGEMAPTLBE pTlbe;
546 rc = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
547 if (RT_SUCCESS(rc))
548 {
549 PPGMPAGE pPage = pTlbe->pPage;
550#if 1
551 /* MMIO pages doesn't have any readable backing. */
552 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
553 rc = VERR_PGM_PHYS_PAGE_RESERVED;
554#else
555 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
556 rc = VERR_PGM_PHYS_PAGE_RESERVED;
557#endif
558 else
559 {
560 /*
561 * Now, just perform the locking and calculate the return address.
562 */
563 PPGMPAGEMAP pMap = pTlbe->pMap;
564 if (pMap)
565 pMap->cRefs++;
566
567 unsigned cLocks = PGM_PAGE_GET_READ_LOCKS(pPage);
568 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
569 {
570 if (cLocks == 0)
571 pVM->pgm.s.cReadLockedPages++;
572 PGM_PAGE_INC_READ_LOCKS(pPage);
573 }
574 else if (cLocks != PGM_PAGE_GET_READ_LOCKS(pPage))
575 {
576 PGM_PAGE_INC_READ_LOCKS(pPage);
577 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent readonly locked state!\n", GCPhys, pPage));
578 if (pMap)
579 pMap->cRefs++; /* Extra ref to prevent it from going away. */
580 }
581
582 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
583 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_READ;
584 pLock->pvMap = pMap;
585 }
586 }
587
588 pgmUnlock(pVM);
589 return rc;
590}
591
592
593#define MAKE_LEAF(a_pNode) \
594 do { \
595 (a_pNode)->pLeftR3 = NIL_RTR3PTR; \
596 (a_pNode)->pRightR3 = NIL_RTR3PTR; \
597 (a_pNode)->pLeftR0 = NIL_RTR0PTR; \
598 (a_pNode)->pRightR0 = NIL_RTR0PTR; \
599 (a_pNode)->pLeftRC = NIL_RTRCPTR; \
600 (a_pNode)->pRightRC = NIL_RTRCPTR; \
601 } while (0)
602
603#define INSERT_LEFT(a_pParent, a_pNode) \
604 do { \
605 (a_pParent)->pLeftR3 = (a_pNode); \
606 (a_pParent)->pLeftR0 = (a_pNode)->pSelfR0; \
607 (a_pParent)->pLeftRC = (a_pNode)->pSelfRC; \
608 } while (0)
609#define INSERT_RIGHT(a_pParent, a_pNode) \
610 do { \
611 (a_pParent)->pRightR3 = (a_pNode); \
612 (a_pParent)->pRightR0 = (a_pNode)->pSelfR0; \
613 (a_pParent)->pRightRC = (a_pNode)->pSelfRC; \
614 } while (0)
615
616
617/**
618 * Recursive tree builder.
619 *
620 * @param ppRam Pointer to the iterator variable.
621 * @param iHeight The hight about normal leaf nodes. Inserts a leaf
622 * node if 0.
623 */
624static PPGMRAMRANGE pgmR3PhysRebuildRamRangeSearchTreesRecursively(PPGMRAMRANGE *ppRam, int iDepth)
625{
626 PPGMRAMRANGE pRam;
627 if (iDepth <= 0)
628 {
629 /*
630 * Leaf node.
631 */
632 pRam = *ppRam;
633 if (pRam)
634 {
635 *ppRam = pRam->pNextR3;
636 MAKE_LEAF(pRam);
637 }
638 }
639 else
640 {
641
642 /*
643 * Intermediate node.
644 */
645 PPGMRAMRANGE pLeft = pgmR3PhysRebuildRamRangeSearchTreesRecursively(ppRam, iDepth - 1);
646
647 pRam = *ppRam;
648 if (!pRam)
649 return pLeft;
650 *ppRam = pRam->pNextR3;
651 MAKE_LEAF(pRam);
652 INSERT_LEFT(pRam, pLeft);
653
654 PPGMRAMRANGE pRight = pgmR3PhysRebuildRamRangeSearchTreesRecursively(ppRam, iDepth - 1);
655 if (pRight)
656 INSERT_RIGHT(pRam, pRight);
657 }
658 return pRam;
659}
660
661
662/**
663 * Rebuilds the RAM range search trees.
664 *
665 * @param pVM Pointer to the VM.
666 */
667static void pgmR3PhysRebuildRamRangeSearchTrees(PVM pVM)
668{
669
670 /*
671 * Create the reasonably balanced tree in a sequential fashion.
672 * For simplicity (laziness) we use standard recursion here.
673 */
674 int iDepth = 0;
675 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
676 PPGMRAMRANGE pRoot = pgmR3PhysRebuildRamRangeSearchTreesRecursively(&pRam, 0);
677 while (pRam)
678 {
679 PPGMRAMRANGE pLeft = pRoot;
680
681 pRoot = pRam;
682 pRam = pRam->pNextR3;
683 MAKE_LEAF(pRoot);
684 INSERT_LEFT(pRoot, pLeft);
685
686 PPGMRAMRANGE pRight = pgmR3PhysRebuildRamRangeSearchTreesRecursively(&pRam, iDepth);
687 if (pRight)
688 INSERT_RIGHT(pRoot, pRight);
689 /** @todo else: rotate the tree. */
690
691 iDepth++;
692 }
693
694 pVM->pgm.s.pRamRangeTreeR3 = pRoot;
695 pVM->pgm.s.pRamRangeTreeR0 = pRoot ? pRoot->pSelfR0 : NIL_RTR0PTR;
696 pVM->pgm.s.pRamRangeTreeRC = pRoot ? pRoot->pSelfRC : NIL_RTRCPTR;
697
698#ifdef VBOX_STRICT
699 /*
700 * Verify that the above code works.
701 */
702 unsigned cRanges = 0;
703 for (pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
704 cRanges++;
705 Assert(cRanges > 0);
706
707 unsigned cMaxDepth = ASMBitLastSetU32(cRanges);
708 if ((1U << cMaxDepth) < cRanges)
709 cMaxDepth++;
710
711 for (pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
712 {
713 unsigned cDepth = 0;
714 PPGMRAMRANGE pRam2 = pVM->pgm.s.pRamRangeTreeR3;
715 for (;;)
716 {
717 if (pRam == pRam2)
718 break;
719 Assert(pRam2);
720 if (pRam->GCPhys < pRam2->GCPhys)
721 pRam2 = pRam2->pLeftR3;
722 else
723 pRam2 = pRam2->pRightR3;
724 }
725 AssertMsg(cDepth <= cMaxDepth, ("cDepth=%d cMaxDepth=%d\n", cDepth, cMaxDepth));
726 }
727#endif /* VBOX_STRICT */
728}
729
730#undef MAKE_LEAF
731#undef INSERT_LEFT
732#undef INSERT_RIGHT
733
734/**
735 * Relinks the RAM ranges using the pSelfRC and pSelfR0 pointers.
736 *
737 * Called when anything was relocated.
738 *
739 * @param pVM Pointer to the VM.
740 */
741void pgmR3PhysRelinkRamRanges(PVM pVM)
742{
743 PPGMRAMRANGE pCur;
744
745#ifdef VBOX_STRICT
746 for (pCur = pVM->pgm.s.pRamRangesXR3; pCur; pCur = pCur->pNextR3)
747 {
748 Assert((pCur->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pCur->pSelfR0 == MMHyperCCToR0(pVM, pCur));
749 Assert((pCur->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pCur->pSelfRC == MMHyperCCToRC(pVM, pCur));
750 Assert((pCur->GCPhys & PAGE_OFFSET_MASK) == 0);
751 Assert((pCur->GCPhysLast & PAGE_OFFSET_MASK) == PAGE_OFFSET_MASK);
752 Assert((pCur->cb & PAGE_OFFSET_MASK) == 0);
753 Assert(pCur->cb == pCur->GCPhysLast - pCur->GCPhys + 1);
754 for (PPGMRAMRANGE pCur2 = pVM->pgm.s.pRamRangesXR3; pCur2; pCur2 = pCur2->pNextR3)
755 Assert( pCur2 == pCur
756 || strcmp(pCur2->pszDesc, pCur->pszDesc)); /** @todo fix MMIO ranges!! */
757 }
758#endif
759
760 pCur = pVM->pgm.s.pRamRangesXR3;
761 if (pCur)
762 {
763 pVM->pgm.s.pRamRangesXR0 = pCur->pSelfR0;
764 pVM->pgm.s.pRamRangesXRC = pCur->pSelfRC;
765
766 for (; pCur->pNextR3; pCur = pCur->pNextR3)
767 {
768 pCur->pNextR0 = pCur->pNextR3->pSelfR0;
769 pCur->pNextRC = pCur->pNextR3->pSelfRC;
770 }
771
772 Assert(pCur->pNextR0 == NIL_RTR0PTR);
773 Assert(pCur->pNextRC == NIL_RTRCPTR);
774 }
775 else
776 {
777 Assert(pVM->pgm.s.pRamRangesXR0 == NIL_RTR0PTR);
778 Assert(pVM->pgm.s.pRamRangesXRC == NIL_RTRCPTR);
779 }
780 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
781
782 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
783}
784
785
786/**
787 * Links a new RAM range into the list.
788 *
789 * @param pVM Pointer to the VM.
790 * @param pNew Pointer to the new list entry.
791 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
792 */
793static void pgmR3PhysLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, PPGMRAMRANGE pPrev)
794{
795 AssertMsg(pNew->pszDesc, ("%RGp-%RGp\n", pNew->GCPhys, pNew->GCPhysLast));
796 Assert((pNew->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pNew->pSelfR0 == MMHyperCCToR0(pVM, pNew));
797 Assert((pNew->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pNew->pSelfRC == MMHyperCCToRC(pVM, pNew));
798
799 pgmLock(pVM);
800
801 PPGMRAMRANGE pRam = pPrev ? pPrev->pNextR3 : pVM->pgm.s.pRamRangesXR3;
802 pNew->pNextR3 = pRam;
803 pNew->pNextR0 = pRam ? pRam->pSelfR0 : NIL_RTR0PTR;
804 pNew->pNextRC = pRam ? pRam->pSelfRC : NIL_RTRCPTR;
805
806 if (pPrev)
807 {
808 pPrev->pNextR3 = pNew;
809 pPrev->pNextR0 = pNew->pSelfR0;
810 pPrev->pNextRC = pNew->pSelfRC;
811 }
812 else
813 {
814 pVM->pgm.s.pRamRangesXR3 = pNew;
815 pVM->pgm.s.pRamRangesXR0 = pNew->pSelfR0;
816 pVM->pgm.s.pRamRangesXRC = pNew->pSelfRC;
817 }
818 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
819
820 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
821 pgmUnlock(pVM);
822}
823
824
825/**
826 * Unlink an existing RAM range from the list.
827 *
828 * @param pVM Pointer to the VM.
829 * @param pRam Pointer to the new list entry.
830 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
831 */
832static void pgmR3PhysUnlinkRamRange2(PVM pVM, PPGMRAMRANGE pRam, PPGMRAMRANGE pPrev)
833{
834 Assert(pPrev ? pPrev->pNextR3 == pRam : pVM->pgm.s.pRamRangesXR3 == pRam);
835 Assert((pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pRam->pSelfR0 == MMHyperCCToR0(pVM, pRam));
836 Assert((pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pRam->pSelfRC == MMHyperCCToRC(pVM, pRam));
837
838 pgmLock(pVM);
839
840 PPGMRAMRANGE pNext = pRam->pNextR3;
841 if (pPrev)
842 {
843 pPrev->pNextR3 = pNext;
844 pPrev->pNextR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
845 pPrev->pNextRC = pNext ? pNext->pSelfRC : NIL_RTRCPTR;
846 }
847 else
848 {
849 Assert(pVM->pgm.s.pRamRangesXR3 == pRam);
850 pVM->pgm.s.pRamRangesXR3 = pNext;
851 pVM->pgm.s.pRamRangesXR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
852 pVM->pgm.s.pRamRangesXRC = pNext ? pNext->pSelfRC : NIL_RTRCPTR;
853 }
854 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
855
856 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
857 pgmUnlock(pVM);
858}
859
860
861/**
862 * Unlink an existing RAM range from the list.
863 *
864 * @param pVM Pointer to the VM.
865 * @param pRam Pointer to the new list entry.
866 */
867static void pgmR3PhysUnlinkRamRange(PVM pVM, PPGMRAMRANGE pRam)
868{
869 pgmLock(pVM);
870
871 /* find prev. */
872 PPGMRAMRANGE pPrev = NULL;
873 PPGMRAMRANGE pCur = pVM->pgm.s.pRamRangesXR3;
874 while (pCur != pRam)
875 {
876 pPrev = pCur;
877 pCur = pCur->pNextR3;
878 }
879 AssertFatal(pCur);
880
881 pgmR3PhysUnlinkRamRange2(pVM, pRam, pPrev);
882 pgmUnlock(pVM);
883}
884
885
886/**
887 * Frees a range of pages, replacing them with ZERO pages of the specified type.
888 *
889 * @returns VBox status code.
890 * @param pVM Pointer to the VM.
891 * @param pRam The RAM range in which the pages resides.
892 * @param GCPhys The address of the first page.
893 * @param GCPhysLast The address of the last page.
894 * @param uType The page type to replace then with.
895 */
896static int pgmR3PhysFreePageRange(PVM pVM, PPGMRAMRANGE pRam, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast, uint8_t uType)
897{
898 PGM_LOCK_ASSERT_OWNER(pVM);
899 uint32_t cPendingPages = 0;
900 PGMMFREEPAGESREQ pReq;
901 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
902 AssertLogRelRCReturn(rc, rc);
903
904 /* Iterate the pages. */
905 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
906 uint32_t cPagesLeft = ((GCPhysLast - GCPhys) >> PAGE_SHIFT) + 1;
907 while (cPagesLeft-- > 0)
908 {
909 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys);
910 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
911
912 PGM_PAGE_SET_TYPE(pVM, pPageDst, uType);
913
914 GCPhys += PAGE_SIZE;
915 pPageDst++;
916 }
917
918 if (cPendingPages)
919 {
920 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
921 AssertLogRelRCReturn(rc, rc);
922 }
923 GMMR3FreePagesCleanup(pReq);
924
925 return rc;
926}
927
928#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
929
930/**
931 * Rendezvous callback used by PGMR3ChangeMemBalloon that changes the memory balloon size
932 *
933 * This is only called on one of the EMTs while the other ones are waiting for
934 * it to complete this function.
935 *
936 * @returns VINF_SUCCESS (VBox strict status code).
937 * @param pVM Pointer to the VM.
938 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
939 * @param pvUser User parameter
940 */
941static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysChangeMemBalloonRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
942{
943 uintptr_t *paUser = (uintptr_t *)pvUser;
944 bool fInflate = !!paUser[0];
945 unsigned cPages = paUser[1];
946 RTGCPHYS *paPhysPage = (RTGCPHYS *)paUser[2];
947 uint32_t cPendingPages = 0;
948 PGMMFREEPAGESREQ pReq;
949 int rc;
950
951 Log(("pgmR3PhysChangeMemBalloonRendezvous: %s %x pages\n", (fInflate) ? "inflate" : "deflate", cPages));
952 pgmLock(pVM);
953
954 if (fInflate)
955 {
956 /* Flush the PGM pool cache as we might have stale references to pages that we just freed. */
957 pgmR3PoolClearAllRendezvous(pVM, pVCpu, NULL);
958
959 /* Replace pages with ZERO pages. */
960 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
961 if (RT_FAILURE(rc))
962 {
963 pgmUnlock(pVM);
964 AssertLogRelRC(rc);
965 return rc;
966 }
967
968 /* Iterate the pages. */
969 for (unsigned i = 0; i < cPages; i++)
970 {
971 PPGMPAGE pPage = pgmPhysGetPage(pVM, paPhysPage[i]);
972 if ( pPage == NULL
973 || PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM)
974 {
975 Log(("pgmR3PhysChangeMemBalloonRendezvous: invalid physical page %RGp pPage->u3Type=%d\n", paPhysPage[i], pPage ? PGM_PAGE_GET_TYPE(pPage) : 0));
976 break;
977 }
978
979 LogFlow(("balloon page: %RGp\n", paPhysPage[i]));
980
981 /* Flush the shadow PT if this page was previously used as a guest page table. */
982 pgmPoolFlushPageByGCPhys(pVM, paPhysPage[i]);
983
984 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, paPhysPage[i]);
985 if (RT_FAILURE(rc))
986 {
987 pgmUnlock(pVM);
988 AssertLogRelRC(rc);
989 return rc;
990 }
991 Assert(PGM_PAGE_IS_ZERO(pPage));
992 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_BALLOONED);
993 }
994
995 if (cPendingPages)
996 {
997 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
998 if (RT_FAILURE(rc))
999 {
1000 pgmUnlock(pVM);
1001 AssertLogRelRC(rc);
1002 return rc;
1003 }
1004 }
1005 GMMR3FreePagesCleanup(pReq);
1006 }
1007 else
1008 {
1009 /* Iterate the pages. */
1010 for (unsigned i = 0; i < cPages; i++)
1011 {
1012 PPGMPAGE pPage = pgmPhysGetPage(pVM, paPhysPage[i]);
1013 AssertBreak(pPage && PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM);
1014
1015 LogFlow(("Free ballooned page: %RGp\n", paPhysPage[i]));
1016
1017 Assert(PGM_PAGE_IS_BALLOONED(pPage));
1018
1019 /* Change back to zero page. */
1020 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
1021 }
1022
1023 /* Note that we currently do not map any ballooned pages in our shadow page tables, so no need to flush the pgm pool. */
1024 }
1025
1026 /* Notify GMM about the balloon change. */
1027 rc = GMMR3BalloonedPages(pVM, (fInflate) ? GMMBALLOONACTION_INFLATE : GMMBALLOONACTION_DEFLATE, cPages);
1028 if (RT_SUCCESS(rc))
1029 {
1030 if (!fInflate)
1031 {
1032 Assert(pVM->pgm.s.cBalloonedPages >= cPages);
1033 pVM->pgm.s.cBalloonedPages -= cPages;
1034 }
1035 else
1036 pVM->pgm.s.cBalloonedPages += cPages;
1037 }
1038
1039 pgmUnlock(pVM);
1040
1041 /* Flush the recompiler's TLB as well. */
1042 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1043 CPUMSetChangedFlags(&pVM->aCpus[i], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
1044
1045 AssertLogRelRC(rc);
1046 return rc;
1047}
1048
1049
1050/**
1051 * Frees a range of ram pages, replacing them with ZERO pages; helper for PGMR3PhysFreeRamPages
1052 *
1053 * @returns VBox status code.
1054 * @param pVM Pointer to the VM.
1055 * @param fInflate Inflate or deflate memory balloon
1056 * @param cPages Number of pages to free
1057 * @param paPhysPage Array of guest physical addresses
1058 */
1059static DECLCALLBACK(void) pgmR3PhysChangeMemBalloonHelper(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
1060{
1061 uintptr_t paUser[3];
1062
1063 paUser[0] = fInflate;
1064 paUser[1] = cPages;
1065 paUser[2] = (uintptr_t)paPhysPage;
1066 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
1067 AssertRC(rc);
1068
1069 /* Made a copy in PGMR3PhysFreeRamPages; free it here. */
1070 RTMemFree(paPhysPage);
1071}
1072
1073#endif /* 64-bit host && (Windows || Solaris || Linux || FreeBSD) */
1074
1075/**
1076 * Inflate or deflate a memory balloon
1077 *
1078 * @returns VBox status code.
1079 * @param pVM Pointer to the VM.
1080 * @param fInflate Inflate or deflate memory balloon
1081 * @param cPages Number of pages to free
1082 * @param paPhysPage Array of guest physical addresses
1083 */
1084VMMR3DECL(int) PGMR3PhysChangeMemBalloon(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
1085{
1086 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
1087#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
1088 int rc;
1089
1090 /* Older additions (ancient non-functioning balloon code) pass wrong physical addresses. */
1091 AssertReturn(!(paPhysPage[0] & 0xfff), VERR_INVALID_PARAMETER);
1092
1093 /* We own the IOM lock here and could cause a deadlock by waiting for another VCPU that is blocking on the IOM lock.
1094 * In the SMP case we post a request packet to postpone the job.
1095 */
1096 if (pVM->cCpus > 1)
1097 {
1098 unsigned cbPhysPage = cPages * sizeof(paPhysPage[0]);
1099 RTGCPHYS *paPhysPageCopy = (RTGCPHYS *)RTMemAlloc(cbPhysPage);
1100 AssertReturn(paPhysPageCopy, VERR_NO_MEMORY);
1101
1102 memcpy(paPhysPageCopy, paPhysPage, cbPhysPage);
1103
1104 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysChangeMemBalloonHelper, 4, pVM, fInflate, cPages, paPhysPageCopy);
1105 AssertRC(rc);
1106 }
1107 else
1108 {
1109 uintptr_t paUser[3];
1110
1111 paUser[0] = fInflate;
1112 paUser[1] = cPages;
1113 paUser[2] = (uintptr_t)paPhysPage;
1114 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
1115 AssertRC(rc);
1116 }
1117 return rc;
1118
1119#else
1120 NOREF(pVM); NOREF(fInflate); NOREF(cPages); NOREF(paPhysPage);
1121 return VERR_NOT_IMPLEMENTED;
1122#endif
1123}
1124
1125
1126/**
1127 * Rendezvous callback used by PGMR3WriteProtectRAM that write protects all
1128 * physical RAM.
1129 *
1130 * This is only called on one of the EMTs while the other ones are waiting for
1131 * it to complete this function.
1132 *
1133 * @returns VINF_SUCCESS (VBox strict status code).
1134 * @param pVM Pointer to the VM.
1135 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
1136 * @param pvUser User parameter, unused.
1137 */
1138static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysWriteProtectRAMRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
1139{
1140 int rc = VINF_SUCCESS;
1141 NOREF(pvUser); NOREF(pVCpu);
1142
1143 pgmLock(pVM);
1144#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
1145 pgmPoolResetDirtyPages(pVM);
1146#endif
1147
1148 /** @todo pointless to write protect the physical page pointed to by RSP. */
1149
1150 for (PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRangesX);
1151 pRam;
1152 pRam = pRam->CTX_SUFF(pNext))
1153 {
1154 uint32_t cPages = pRam->cb >> PAGE_SHIFT;
1155 for (uint32_t iPage = 0; iPage < cPages; iPage++)
1156 {
1157 PPGMPAGE pPage = &pRam->aPages[iPage];
1158 PGMPAGETYPE enmPageType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage);
1159
1160 if ( RT_LIKELY(enmPageType == PGMPAGETYPE_RAM)
1161 || enmPageType == PGMPAGETYPE_MMIO2)
1162 {
1163 /*
1164 * A RAM page.
1165 */
1166 switch (PGM_PAGE_GET_STATE(pPage))
1167 {
1168 case PGM_PAGE_STATE_ALLOCATED:
1169 /** @todo Optimize this: Don't always re-enable write
1170 * monitoring if the page is known to be very busy. */
1171 if (PGM_PAGE_IS_WRITTEN_TO(pPage))
1172 {
1173 PGM_PAGE_CLEAR_WRITTEN_TO(pVM, pPage);
1174 /* Remember this dirty page for the next (memory) sync. */
1175 PGM_PAGE_SET_FT_DIRTY(pPage);
1176 }
1177
1178 pgmPhysPageWriteMonitor(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1179 break;
1180
1181 case PGM_PAGE_STATE_SHARED:
1182 AssertFailed();
1183 break;
1184
1185 case PGM_PAGE_STATE_WRITE_MONITORED: /* nothing to change. */
1186 default:
1187 break;
1188 }
1189 }
1190 }
1191 }
1192 pgmR3PoolWriteProtectPages(pVM);
1193 PGM_INVL_ALL_VCPU_TLBS(pVM);
1194 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1195 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
1196
1197 pgmUnlock(pVM);
1198 return rc;
1199}
1200
1201/**
1202 * Protect all physical RAM to monitor writes
1203 *
1204 * @returns VBox status code.
1205 * @param pVM Pointer to the VM.
1206 */
1207VMMR3DECL(int) PGMR3PhysWriteProtectRAM(PVM pVM)
1208{
1209 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1210
1211 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysWriteProtectRAMRendezvous, NULL);
1212 AssertRC(rc);
1213 return rc;
1214}
1215
1216/**
1217 * Enumerate all dirty FT pages.
1218 *
1219 * @returns VBox status code.
1220 * @param pVM Pointer to the VM.
1221 * @param pfnEnum Enumerate callback handler.
1222 * @param pvUser Enumerate callback handler parameter.
1223 */
1224VMMR3DECL(int) PGMR3PhysEnumDirtyFTPages(PVM pVM, PFNPGMENUMDIRTYFTPAGES pfnEnum, void *pvUser)
1225{
1226 int rc = VINF_SUCCESS;
1227
1228 pgmLock(pVM);
1229 for (PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRangesX);
1230 pRam;
1231 pRam = pRam->CTX_SUFF(pNext))
1232 {
1233 uint32_t cPages = pRam->cb >> PAGE_SHIFT;
1234 for (uint32_t iPage = 0; iPage < cPages; iPage++)
1235 {
1236 PPGMPAGE pPage = &pRam->aPages[iPage];
1237 PGMPAGETYPE enmPageType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage);
1238
1239 if ( RT_LIKELY(enmPageType == PGMPAGETYPE_RAM)
1240 || enmPageType == PGMPAGETYPE_MMIO2)
1241 {
1242 /*
1243 * A RAM page.
1244 */
1245 switch (PGM_PAGE_GET_STATE(pPage))
1246 {
1247 case PGM_PAGE_STATE_ALLOCATED:
1248 case PGM_PAGE_STATE_WRITE_MONITORED:
1249 if ( !PGM_PAGE_IS_WRITTEN_TO(pPage) /* not very recently updated? */
1250 && PGM_PAGE_IS_FT_DIRTY(pPage))
1251 {
1252 unsigned cbPageRange = PAGE_SIZE;
1253 unsigned iPageClean = iPage + 1;
1254 RTGCPHYS GCPhysPage = pRam->GCPhys + iPage * PAGE_SIZE;
1255 uint8_t *pu8Page = NULL;
1256 PGMPAGEMAPLOCK Lock;
1257
1258 /* Find the next clean page, so we can merge adjacent dirty pages. */
1259 for (; iPageClean < cPages; iPageClean++)
1260 {
1261 PPGMPAGE pPageNext = &pRam->aPages[iPageClean];
1262 if ( RT_UNLIKELY(PGM_PAGE_GET_TYPE(pPageNext) != PGMPAGETYPE_RAM)
1263 || PGM_PAGE_GET_STATE(pPageNext) != PGM_PAGE_STATE_ALLOCATED
1264 || PGM_PAGE_IS_WRITTEN_TO(pPageNext)
1265 || !PGM_PAGE_IS_FT_DIRTY(pPageNext)
1266 /* Crossing a chunk boundary? */
1267 || (GCPhysPage & GMM_PAGEID_IDX_MASK) != ((GCPhysPage + cbPageRange) & GMM_PAGEID_IDX_MASK)
1268 )
1269 break;
1270
1271 cbPageRange += PAGE_SIZE;
1272 }
1273
1274 rc = PGMPhysGCPhys2CCPtrReadOnly(pVM, GCPhysPage, (const void **)&pu8Page, &Lock);
1275 if (RT_SUCCESS(rc))
1276 {
1277 /** @todo this is risky; the range might be changed, but little choice as the sync
1278 * costs a lot of time. */
1279 pgmUnlock(pVM);
1280 pfnEnum(pVM, GCPhysPage, pu8Page, cbPageRange, pvUser);
1281 pgmLock(pVM);
1282 PGMPhysReleasePageMappingLock(pVM, &Lock);
1283 }
1284
1285 for (iPage; iPage < iPageClean; iPage++)
1286 PGM_PAGE_CLEAR_FT_DIRTY(&pRam->aPages[iPage]);
1287
1288 iPage = iPageClean - 1;
1289 }
1290 break;
1291 }
1292 }
1293 }
1294 }
1295 pgmUnlock(pVM);
1296 return rc;
1297}
1298
1299
1300/**
1301 * Gets the number of ram ranges.
1302 *
1303 * @returns Number of ram ranges. Returns UINT32_MAX if @a pVM is invalid.
1304 * @param pVM Pointer to the VM.
1305 */
1306VMMR3DECL(uint32_t) PGMR3PhysGetRamRangeCount(PVM pVM)
1307{
1308 VM_ASSERT_VALID_EXT_RETURN(pVM, UINT32_MAX);
1309
1310 pgmLock(pVM);
1311 uint32_t cRamRanges = 0;
1312 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRangesX); pCur; pCur = pCur->CTX_SUFF(pNext))
1313 cRamRanges++;
1314 pgmUnlock(pVM);
1315 return cRamRanges;
1316}
1317
1318
1319/**
1320 * Get information about a range.
1321 *
1322 * @returns VINF_SUCCESS or VERR_OUT_OF_RANGE.
1323 * @param pVM Pointer to the VM.
1324 * @param iRange The ordinal of the range.
1325 * @param pGCPhysStart Where to return the start of the range. Optional.
1326 * @param pGCPhysLast Where to return the address of the last byte in the
1327 * range. Optional.
1328 * @param pfIsMmio Where to indicate that this is a pure MMIO range.
1329 * Optional.
1330 */
1331VMMR3DECL(int) PGMR3PhysGetRange(PVM pVM, uint32_t iRange, PRTGCPHYS pGCPhysStart, PRTGCPHYS pGCPhysLast,
1332 const char **ppszDesc, bool *pfIsMmio)
1333{
1334 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1335
1336 pgmLock(pVM);
1337 uint32_t iCurRange = 0;
1338 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRangesX); pCur; pCur = pCur->CTX_SUFF(pNext), iCurRange++)
1339 if (iCurRange == iRange)
1340 {
1341 if (pGCPhysStart)
1342 *pGCPhysStart = pCur->GCPhys;
1343 if (pGCPhysLast)
1344 *pGCPhysLast = pCur->GCPhysLast;
1345 if (ppszDesc)
1346 *ppszDesc = pCur->pszDesc;
1347 if (pfIsMmio)
1348 *pfIsMmio = !!(pCur->fFlags & PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO);
1349
1350 pgmUnlock(pVM);
1351 return VINF_SUCCESS;
1352 }
1353 pgmUnlock(pVM);
1354 return VERR_OUT_OF_RANGE;
1355}
1356
1357
1358/**
1359 * Query the amount of free memory inside VMMR0
1360 *
1361 * @returns VBox status code.
1362 * @param pUVM The user mode VM handle.
1363 * @param pcbAllocMem Where to return the amount of memory allocated
1364 * by VMs.
1365 * @param pcbFreeMem Where to return the amount of memory that is
1366 * allocated from the host but not currently used
1367 * by any VMs.
1368 * @param pcbBallonedMem Where to return the sum of memory that is
1369 * currently ballooned by the VMs.
1370 * @param pcbSharedMem Where to return the amount of memory that is
1371 * currently shared.
1372 */
1373VMMR3DECL(int) PGMR3QueryGlobalMemoryStats(PUVM pUVM, uint64_t *pcbAllocMem, uint64_t *pcbFreeMem,
1374 uint64_t *pcbBallonedMem, uint64_t *pcbSharedMem)
1375{
1376 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
1377 VM_ASSERT_VALID_EXT_RETURN(pUVM->pVM, VERR_INVALID_VM_HANDLE);
1378
1379 uint64_t cAllocPages = 0;
1380 uint64_t cFreePages = 0;
1381 uint64_t cBalloonPages = 0;
1382 uint64_t cSharedPages = 0;
1383 int rc = GMMR3QueryHypervisorMemoryStats(pUVM->pVM, &cAllocPages, &cFreePages, &cBalloonPages, &cSharedPages);
1384 AssertRCReturn(rc, rc);
1385
1386 if (pcbAllocMem)
1387 *pcbAllocMem = cAllocPages * _4K;
1388
1389 if (pcbFreeMem)
1390 *pcbFreeMem = cFreePages * _4K;
1391
1392 if (pcbBallonedMem)
1393 *pcbBallonedMem = cBalloonPages * _4K;
1394
1395 if (pcbSharedMem)
1396 *pcbSharedMem = cSharedPages * _4K;
1397
1398 Log(("PGMR3QueryVMMMemoryStats: all=%llx free=%llx ballooned=%llx shared=%llx\n",
1399 cAllocPages, cFreePages, cBalloonPages, cSharedPages));
1400 return VINF_SUCCESS;
1401}
1402
1403
1404/**
1405 * Query memory stats for the VM.
1406 *
1407 * @returns VBox status code.
1408 * @param pUVM The user mode VM handle.
1409 * @param pcbTotalMem Where to return total amount memory the VM may
1410 * possibly use.
1411 * @param pcbPrivateMem Where to return the amount of private memory
1412 * currently allocated.
1413 * @param pcbSharedMem Where to return the amount of actually shared
1414 * memory currently used by the VM.
1415 * @param pcbZeroMem Where to return the amount of memory backed by
1416 * zero pages.
1417 *
1418 * @remarks The total mem is normally larger than the sum of the three
1419 * components. There are two reasons for this, first the amount of
1420 * shared memory is what we're sure is shared instead of what could
1421 * possibly be shared with someone. Secondly, because the total may
1422 * include some pure MMIO pages that doesn't go into any of the three
1423 * sub-counts.
1424 *
1425 * @todo Why do we return reused shared pages instead of anything that could
1426 * potentially be shared? Doesn't this mean the first VM gets a much
1427 * lower number of shared pages?
1428 */
1429VMMR3DECL(int) PGMR3QueryMemoryStats(PUVM pUVM, uint64_t *pcbTotalMem, uint64_t *pcbPrivateMem,
1430 uint64_t *pcbSharedMem, uint64_t *pcbZeroMem)
1431{
1432 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
1433 PVM pVM = pUVM->pVM;
1434 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1435
1436 if (pcbTotalMem)
1437 *pcbTotalMem = (uint64_t)pVM->pgm.s.cAllPages * PAGE_SIZE;
1438
1439 if (pcbPrivateMem)
1440 *pcbPrivateMem = (uint64_t)pVM->pgm.s.cPrivatePages * PAGE_SIZE;
1441
1442 if (pcbSharedMem)
1443 *pcbSharedMem = (uint64_t)pVM->pgm.s.cReusedSharedPages * PAGE_SIZE;
1444
1445 if (pcbZeroMem)
1446 *pcbZeroMem = (uint64_t)pVM->pgm.s.cZeroPages * PAGE_SIZE;
1447
1448 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));
1449 return VINF_SUCCESS;
1450}
1451
1452
1453/**
1454 * PGMR3PhysRegisterRam worker that initializes and links a RAM range.
1455 *
1456 * @param pVM Pointer to the VM.
1457 * @param pNew The new RAM range.
1458 * @param GCPhys The address of the RAM range.
1459 * @param GCPhysLast The last address of the RAM range.
1460 * @param RCPtrNew The RC address if the range is floating. NIL_RTRCPTR
1461 * if in HMA.
1462 * @param R0PtrNew Ditto for R0.
1463 * @param pszDesc The description.
1464 * @param pPrev The previous RAM range (for linking).
1465 */
1466static void pgmR3PhysInitAndLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast,
1467 RTRCPTR RCPtrNew, RTR0PTR R0PtrNew, const char *pszDesc, PPGMRAMRANGE pPrev)
1468{
1469 /*
1470 * Initialize the range.
1471 */
1472 pNew->pSelfR0 = R0PtrNew != NIL_RTR0PTR ? R0PtrNew : MMHyperCCToR0(pVM, pNew);
1473 pNew->pSelfRC = RCPtrNew != NIL_RTRCPTR ? RCPtrNew : MMHyperCCToRC(pVM, pNew);
1474 pNew->GCPhys = GCPhys;
1475 pNew->GCPhysLast = GCPhysLast;
1476 pNew->cb = GCPhysLast - GCPhys + 1;
1477 pNew->pszDesc = pszDesc;
1478 pNew->fFlags = RCPtrNew != NIL_RTRCPTR ? PGM_RAM_RANGE_FLAGS_FLOATING : 0;
1479 pNew->pvR3 = NULL;
1480 pNew->paLSPages = NULL;
1481
1482 uint32_t const cPages = pNew->cb >> PAGE_SHIFT;
1483 RTGCPHYS iPage = cPages;
1484 while (iPage-- > 0)
1485 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_RAM);
1486
1487 /* Update the page count stats. */
1488 pVM->pgm.s.cZeroPages += cPages;
1489 pVM->pgm.s.cAllPages += cPages;
1490
1491 /*
1492 * Link it.
1493 */
1494 pgmR3PhysLinkRamRange(pVM, pNew, pPrev);
1495}
1496
1497
1498/**
1499 * Relocate a floating RAM range.
1500 *
1501 * @copydoc FNPGMRELOCATE.
1502 */
1503static DECLCALLBACK(bool) pgmR3PhysRamRangeRelocate(PVM pVM, RTGCPTR GCPtrOld, RTGCPTR GCPtrNew, PGMRELOCATECALL enmMode, void *pvUser)
1504{
1505 PPGMRAMRANGE pRam = (PPGMRAMRANGE)pvUser;
1506 Assert(pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING);
1507 Assert(pRam->pSelfRC == GCPtrOld + PAGE_SIZE);
1508
1509 switch (enmMode)
1510 {
1511 case PGMRELOCATECALL_SUGGEST:
1512 return true;
1513
1514 case PGMRELOCATECALL_RELOCATE:
1515 {
1516 /*
1517 * Update myself, then relink all the ranges and flush the RC TLB.
1518 */
1519 pgmLock(pVM);
1520
1521 pRam->pSelfRC = (RTRCPTR)(GCPtrNew + PAGE_SIZE);
1522
1523 pgmR3PhysRelinkRamRanges(pVM);
1524 for (unsigned i = 0; i < PGM_RAMRANGE_TLB_ENTRIES; i++)
1525 pVM->pgm.s.apRamRangesTlbRC[i] = NIL_RTRCPTR;
1526
1527 pgmUnlock(pVM);
1528 return true;
1529 }
1530
1531 default:
1532 AssertFailedReturn(false);
1533 }
1534}
1535
1536
1537/**
1538 * PGMR3PhysRegisterRam worker that registers a high chunk.
1539 *
1540 * @returns VBox status code.
1541 * @param pVM Pointer to the VM.
1542 * @param GCPhys The address of the RAM.
1543 * @param cRamPages The number of RAM pages to register.
1544 * @param cbChunk The size of the PGMRAMRANGE guest mapping.
1545 * @param iChunk The chunk number.
1546 * @param pszDesc The RAM range description.
1547 * @param ppPrev Previous RAM range pointer. In/Out.
1548 */
1549static int pgmR3PhysRegisterHighRamChunk(PVM pVM, RTGCPHYS GCPhys, uint32_t cRamPages,
1550 uint32_t cbChunk, uint32_t iChunk, const char *pszDesc,
1551 PPGMRAMRANGE *ppPrev)
1552{
1553 const char *pszDescChunk = iChunk == 0
1554 ? pszDesc
1555 : MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s (#%u)", pszDesc, iChunk + 1);
1556 AssertReturn(pszDescChunk, VERR_NO_MEMORY);
1557
1558 /*
1559 * Allocate memory for the new chunk.
1560 */
1561 size_t const cChunkPages = RT_ALIGN_Z(RT_UOFFSETOF(PGMRAMRANGE, aPages[cRamPages]), PAGE_SIZE) >> PAGE_SHIFT;
1562 PSUPPAGE paChunkPages = (PSUPPAGE)RTMemTmpAllocZ(sizeof(SUPPAGE) * cChunkPages);
1563 AssertReturn(paChunkPages, VERR_NO_TMP_MEMORY);
1564 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
1565 void *pvChunk = NULL;
1566 int rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk,
1567#if defined(VBOX_WITH_MORE_RING0_MEM_MAPPINGS)
1568 &R0PtrChunk,
1569#elif defined(VBOX_WITH_2X_4GB_ADDR_SPACE)
1570 HMIsEnabled(pVM) ? &R0PtrChunk : NULL,
1571#else
1572 NULL,
1573#endif
1574 paChunkPages);
1575 if (RT_SUCCESS(rc))
1576 {
1577#if defined(VBOX_WITH_MORE_RING0_MEM_MAPPINGS)
1578 Assert(R0PtrChunk != NIL_RTR0PTR);
1579#elif defined(VBOX_WITH_2X_4GB_ADDR_SPACE)
1580 if (!HMIsEnabled(pVM))
1581 R0PtrChunk = NIL_RTR0PTR;
1582#else
1583 R0PtrChunk = (uintptr_t)pvChunk;
1584#endif
1585 memset(pvChunk, 0, cChunkPages << PAGE_SHIFT);
1586
1587 PPGMRAMRANGE pNew = (PPGMRAMRANGE)pvChunk;
1588
1589 /*
1590 * Create a mapping and map the pages into it.
1591 * We push these in below the HMA.
1592 */
1593 RTGCPTR GCPtrChunkMap = pVM->pgm.s.GCPtrPrevRamRangeMapping - cbChunk;
1594 rc = PGMR3MapPT(pVM, GCPtrChunkMap, cbChunk, 0 /*fFlags*/, pgmR3PhysRamRangeRelocate, pNew, pszDescChunk);
1595 if (RT_SUCCESS(rc))
1596 {
1597 pVM->pgm.s.GCPtrPrevRamRangeMapping = GCPtrChunkMap;
1598
1599 RTGCPTR const GCPtrChunk = GCPtrChunkMap + PAGE_SIZE;
1600 RTGCPTR GCPtrPage = GCPtrChunk;
1601 for (uint32_t iPage = 0; iPage < cChunkPages && RT_SUCCESS(rc); iPage++, GCPtrPage += PAGE_SIZE)
1602 rc = PGMMap(pVM, GCPtrPage, paChunkPages[iPage].Phys, PAGE_SIZE, 0);
1603 if (RT_SUCCESS(rc))
1604 {
1605 /*
1606 * Ok, init and link the range.
1607 */
1608 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhys + ((RTGCPHYS)cRamPages << PAGE_SHIFT) - 1,
1609 (RTRCPTR)GCPtrChunk, R0PtrChunk, pszDescChunk, *ppPrev);
1610 *ppPrev = pNew;
1611 }
1612 }
1613
1614 if (RT_FAILURE(rc))
1615 SUPR3PageFreeEx(pvChunk, cChunkPages);
1616 }
1617
1618 RTMemTmpFree(paChunkPages);
1619 return rc;
1620}
1621
1622
1623/**
1624 * Sets up a range RAM.
1625 *
1626 * This will check for conflicting registrations, make a resource
1627 * reservation for the memory (with GMM), and setup the per-page
1628 * tracking structures (PGMPAGE).
1629 *
1630 * @returns VBox status code.
1631 * @param pVM Pointer to the VM.
1632 * @param GCPhys The physical address of the RAM.
1633 * @param cb The size of the RAM.
1634 * @param pszDesc The description - not copied, so, don't free or change it.
1635 */
1636VMMR3DECL(int) PGMR3PhysRegisterRam(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, const char *pszDesc)
1637{
1638 /*
1639 * Validate input.
1640 */
1641 Log(("PGMR3PhysRegisterRam: GCPhys=%RGp cb=%RGp pszDesc=%s\n", GCPhys, cb, pszDesc));
1642 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
1643 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
1644 AssertReturn(cb > 0, VERR_INVALID_PARAMETER);
1645 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1646 AssertMsgReturn(GCPhysLast > GCPhys, ("The range wraps! GCPhys=%RGp cb=%RGp\n", GCPhys, cb), VERR_INVALID_PARAMETER);
1647 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1648 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1649
1650 pgmLock(pVM);
1651
1652 /*
1653 * Find range location and check for conflicts.
1654 * (We don't lock here because the locking by EMT is only required on update.)
1655 */
1656 PPGMRAMRANGE pPrev = NULL;
1657 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
1658 while (pRam && GCPhysLast >= pRam->GCPhys)
1659 {
1660 if ( GCPhysLast >= pRam->GCPhys
1661 && GCPhys <= pRam->GCPhysLast)
1662 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
1663 GCPhys, GCPhysLast, pszDesc,
1664 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1665 VERR_PGM_RAM_CONFLICT);
1666
1667 /* next */
1668 pPrev = pRam;
1669 pRam = pRam->pNextR3;
1670 }
1671
1672 /*
1673 * Register it with GMM (the API bitches).
1674 */
1675 const RTGCPHYS cPages = cb >> PAGE_SHIFT;
1676 int rc = MMR3IncreaseBaseReservation(pVM, cPages);
1677 if (RT_FAILURE(rc))
1678 {
1679 pgmUnlock(pVM);
1680 return rc;
1681 }
1682
1683 if ( GCPhys >= _4G
1684 && cPages > 256)
1685 {
1686 /*
1687 * The PGMRAMRANGE structures for the high memory can get very big.
1688 * In order to avoid SUPR3PageAllocEx allocation failures due to the
1689 * allocation size limit there and also to avoid being unable to find
1690 * guest mapping space for them, we split this memory up into 4MB in
1691 * (potential) raw-mode configs and 16MB chunks in forced AMD-V/VT-x
1692 * mode.
1693 *
1694 * The first and last page of each mapping are guard pages and marked
1695 * not-present. So, we've got 4186112 and 16769024 bytes available for
1696 * the PGMRAMRANGE structure.
1697 *
1698 * Note! The sizes used here will influence the saved state.
1699 */
1700 uint32_t cbChunk;
1701 uint32_t cPagesPerChunk;
1702 if (HMIsEnabled(pVM))
1703 {
1704 cbChunk = 16U*_1M;
1705 cPagesPerChunk = 1048048; /* max ~1048059 */
1706 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 1048048 < 16U*_1M - PAGE_SIZE * 2);
1707 }
1708 else
1709 {
1710 cbChunk = 4U*_1M;
1711 cPagesPerChunk = 261616; /* max ~261627 */
1712 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 261616 < 4U*_1M - PAGE_SIZE * 2);
1713 }
1714 AssertRelease(RT_UOFFSETOF(PGMRAMRANGE, aPages[cPagesPerChunk]) + PAGE_SIZE * 2 <= cbChunk);
1715
1716 RTGCPHYS cPagesLeft = cPages;
1717 RTGCPHYS GCPhysChunk = GCPhys;
1718 uint32_t iChunk = 0;
1719 while (cPagesLeft > 0)
1720 {
1721 uint32_t cPagesInChunk = cPagesLeft;
1722 if (cPagesInChunk > cPagesPerChunk)
1723 cPagesInChunk = cPagesPerChunk;
1724
1725 rc = pgmR3PhysRegisterHighRamChunk(pVM, GCPhysChunk, cPagesInChunk, cbChunk, iChunk, pszDesc, &pPrev);
1726 AssertRCReturn(rc, rc);
1727
1728 /* advance */
1729 GCPhysChunk += (RTGCPHYS)cPagesInChunk << PAGE_SHIFT;
1730 cPagesLeft -= cPagesInChunk;
1731 iChunk++;
1732 }
1733 }
1734 else
1735 {
1736 /*
1737 * Allocate, initialize and link the new RAM range.
1738 */
1739 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
1740 PPGMRAMRANGE pNew;
1741 rc = MMR3HyperAllocOnceNoRel(pVM, cbRamRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
1742 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
1743
1744 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhysLast, NIL_RTRCPTR, NIL_RTR0PTR, pszDesc, pPrev);
1745 }
1746 pgmPhysInvalidatePageMapTLB(pVM);
1747 pgmUnlock(pVM);
1748
1749#ifdef VBOX_WITH_REM
1750 /*
1751 * Notify REM.
1752 */
1753 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_RAM);
1754#endif
1755
1756 return VINF_SUCCESS;
1757}
1758
1759
1760/**
1761 * Worker called by PGMR3InitFinalize if we're configured to pre-allocate RAM.
1762 *
1763 * We do this late in the init process so that all the ROM and MMIO ranges have
1764 * been registered already and we don't go wasting memory on them.
1765 *
1766 * @returns VBox status code.
1767 *
1768 * @param pVM Pointer to the VM.
1769 */
1770int pgmR3PhysRamPreAllocate(PVM pVM)
1771{
1772 Assert(pVM->pgm.s.fRamPreAlloc);
1773 Log(("pgmR3PhysRamPreAllocate: enter\n"));
1774
1775 /*
1776 * Walk the RAM ranges and allocate all RAM pages, halt at
1777 * the first allocation error.
1778 */
1779 uint64_t cPages = 0;
1780 uint64_t NanoTS = RTTimeNanoTS();
1781 pgmLock(pVM);
1782 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1783 {
1784 PPGMPAGE pPage = &pRam->aPages[0];
1785 RTGCPHYS GCPhys = pRam->GCPhys;
1786 uint32_t cLeft = pRam->cb >> PAGE_SHIFT;
1787 while (cLeft-- > 0)
1788 {
1789 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM)
1790 {
1791 switch (PGM_PAGE_GET_STATE(pPage))
1792 {
1793 case PGM_PAGE_STATE_ZERO:
1794 {
1795 int rc = pgmPhysAllocPage(pVM, pPage, GCPhys);
1796 if (RT_FAILURE(rc))
1797 {
1798 LogRel(("PGM: RAM Pre-allocation failed at %RGp (in %s) with rc=%Rrc\n", GCPhys, pRam->pszDesc, rc));
1799 pgmUnlock(pVM);
1800 return rc;
1801 }
1802 cPages++;
1803 break;
1804 }
1805
1806 case PGM_PAGE_STATE_BALLOONED:
1807 case PGM_PAGE_STATE_ALLOCATED:
1808 case PGM_PAGE_STATE_WRITE_MONITORED:
1809 case PGM_PAGE_STATE_SHARED:
1810 /* nothing to do here. */
1811 break;
1812 }
1813 }
1814
1815 /* next */
1816 pPage++;
1817 GCPhys += PAGE_SIZE;
1818 }
1819 }
1820 pgmUnlock(pVM);
1821 NanoTS = RTTimeNanoTS() - NanoTS;
1822
1823 LogRel(("PGM: Pre-allocated %llu pages in %llu ms\n", cPages, NanoTS / 1000000));
1824 Log(("pgmR3PhysRamPreAllocate: returns VINF_SUCCESS\n"));
1825 return VINF_SUCCESS;
1826}
1827
1828
1829/**
1830 * Checks shared page checksums.
1831 *
1832 * @param pVM Pointer to the shared VM structure.
1833 */
1834void pgmR3PhysAssertSharedPageChecksums(PVM pVM)
1835{
1836#ifdef VBOX_STRICT
1837 pgmLock(pVM);
1838
1839 if (pVM->pgm.s.cSharedPages > 0)
1840 {
1841 /*
1842 * Walk the ram ranges.
1843 */
1844 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1845 {
1846 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
1847 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
1848
1849 while (iPage-- > 0)
1850 {
1851 PPGMPAGE pPage = &pRam->aPages[iPage];
1852 if (PGM_PAGE_IS_SHARED(pPage))
1853 {
1854 uint32_t u32Checksum = pPage->s.u2Unused0 | ((uint32_t)pPage->s.u2Unused1 << 8);
1855 if (!u32Checksum)
1856 {
1857 RTGCPHYS GCPhysPage = pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT);
1858 void const *pvPage;
1859 int rc = pgmPhysPageMapReadOnly(pVM, pPage, GCPhysPage, &pvPage);
1860 if (RT_SUCCESS(rc))
1861 {
1862 uint32_t u32Checksum2 = RTCrc32(pvPage, PAGE_SIZE);
1863# if 0
1864 AssertMsg((u32Checksum2 & UINT32_C(0x00000303)) == u32Checksum, ("GCPhysPage=%RGp\n", GCPhysPage));
1865# else
1866 if ((u32Checksum2 & UINT32_C(0x00000303)) == u32Checksum)
1867 LogFlow(("shpg %#x @ %RGp %#x [OK]\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
1868 else
1869 AssertMsgFailed(("shpg %#x @ %RGp %#x\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
1870# endif
1871 }
1872 else
1873 AssertRC(rc);
1874 }
1875 }
1876
1877 } /* for each page */
1878
1879 } /* for each ram range */
1880 }
1881
1882 pgmUnlock(pVM);
1883#endif /* VBOX_STRICT */
1884 NOREF(pVM);
1885}
1886
1887
1888/**
1889 * Resets the physical memory state.
1890 *
1891 * ASSUMES that the caller owns the PGM lock.
1892 *
1893 * @returns VBox status code.
1894 * @param pVM Pointer to the VM.
1895 */
1896int pgmR3PhysRamReset(PVM pVM)
1897{
1898 PGM_LOCK_ASSERT_OWNER(pVM);
1899
1900 /* Reset the memory balloon. */
1901 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
1902 AssertRC(rc);
1903
1904#ifdef VBOX_WITH_PAGE_SHARING
1905 /* Clear all registered shared modules. */
1906 pgmR3PhysAssertSharedPageChecksums(pVM);
1907 rc = GMMR3ResetSharedModules(pVM);
1908 AssertRC(rc);
1909#endif
1910 /* Reset counters. */
1911 pVM->pgm.s.cReusedSharedPages = 0;
1912 pVM->pgm.s.cBalloonedPages = 0;
1913
1914 return VINF_SUCCESS;
1915}
1916
1917
1918/**
1919 * Resets (zeros) the RAM after all devices and components have been reset.
1920 *
1921 * ASSUMES that the caller owns the PGM lock.
1922 *
1923 * @returns VBox status code.
1924 * @param pVM Pointer to the VM.
1925 */
1926int pgmR3PhysRamZeroAll(PVM pVM)
1927{
1928 PGM_LOCK_ASSERT_OWNER(pVM);
1929
1930 /*
1931 * We batch up pages that should be freed instead of calling GMM for
1932 * each and every one of them.
1933 */
1934 uint32_t cPendingPages = 0;
1935 PGMMFREEPAGESREQ pReq;
1936 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1937 AssertLogRelRCReturn(rc, rc);
1938
1939 /*
1940 * Walk the ram ranges.
1941 */
1942 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1943 {
1944 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
1945 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
1946
1947#ifndef NO_RAM_RESET
1948 if (!pVM->pgm.s.fRamPreAlloc)
1949#else
1950 if (0)
1951#endif
1952 {
1953 /* Replace all RAM pages by ZERO pages. */
1954 while (iPage-- > 0)
1955 {
1956 PPGMPAGE pPage = &pRam->aPages[iPage];
1957 switch (PGM_PAGE_GET_TYPE(pPage))
1958 {
1959 case PGMPAGETYPE_RAM:
1960 /* Do not replace pages part of a 2 MB continuous range
1961 with zero pages, but zero them instead. */
1962 if ( PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE
1963 || PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE_DISABLED)
1964 {
1965 void *pvPage;
1966 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
1967 AssertLogRelRCReturn(rc, rc);
1968 ASMMemZeroPage(pvPage);
1969 }
1970 else if (PGM_PAGE_IS_BALLOONED(pPage))
1971 {
1972 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
1973 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
1974 }
1975 else if (!PGM_PAGE_IS_ZERO(pPage))
1976 {
1977 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
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 /* no break */
2022
2023 case PGM_PAGE_STATE_ALLOCATED:
2024 {
2025 void *pvPage;
2026 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
2027 AssertLogRelRCReturn(rc, rc);
2028#ifndef NO_RAM_RESET
2029 ASMMemZeroPage(pvPage);
2030#endif
2031 break;
2032 }
2033 }
2034 break;
2035
2036 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2037 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
2038 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT),
2039 true /*fDoAccounting*/);
2040 break;
2041
2042 case PGMPAGETYPE_MMIO2:
2043 case PGMPAGETYPE_ROM_SHADOW:
2044 case PGMPAGETYPE_ROM:
2045 case PGMPAGETYPE_MMIO:
2046 break;
2047 default:
2048 AssertFailed();
2049
2050 }
2051 } /* for each page */
2052 }
2053
2054 }
2055
2056 /*
2057 * Finish off any pages pending freeing.
2058 */
2059 if (cPendingPages)
2060 {
2061 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2062 AssertLogRelRCReturn(rc, rc);
2063 }
2064 GMMR3FreePagesCleanup(pReq);
2065 return VINF_SUCCESS;
2066}
2067
2068
2069/**
2070 * Frees all RAM during VM termination
2071 *
2072 * ASSUMES that the caller owns the PGM lock.
2073 *
2074 * @returns VBox status code.
2075 * @param pVM Pointer to the VM.
2076 */
2077int pgmR3PhysRamTerm(PVM pVM)
2078{
2079 PGM_LOCK_ASSERT_OWNER(pVM);
2080
2081 /* Reset the memory balloon. */
2082 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
2083 AssertRC(rc);
2084
2085#ifdef VBOX_WITH_PAGE_SHARING
2086 /*
2087 * Clear all registered shared modules.
2088 */
2089 pgmR3PhysAssertSharedPageChecksums(pVM);
2090 rc = GMMR3ResetSharedModules(pVM);
2091 AssertRC(rc);
2092
2093 /*
2094 * Flush the handy pages updates to make sure no shared pages are hiding
2095 * in there. (No unlikely if the VM shuts down, apparently.)
2096 */
2097 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_FLUSH_HANDY_PAGES, 0, NULL);
2098#endif
2099
2100 /*
2101 * We batch up pages that should be freed instead of calling GMM for
2102 * each and every one of them.
2103 */
2104 uint32_t cPendingPages = 0;
2105 PGMMFREEPAGESREQ pReq;
2106 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2107 AssertLogRelRCReturn(rc, rc);
2108
2109 /*
2110 * Walk the ram ranges.
2111 */
2112 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2113 {
2114 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
2115 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
2116
2117 while (iPage-- > 0)
2118 {
2119 PPGMPAGE pPage = &pRam->aPages[iPage];
2120 switch (PGM_PAGE_GET_TYPE(pPage))
2121 {
2122 case PGMPAGETYPE_RAM:
2123 /* Free all shared pages. Private pages are automatically freed during GMM VM cleanup. */
2124 /** @todo change this to explicitly free private pages here. */
2125 if (PGM_PAGE_IS_SHARED(pPage))
2126 {
2127 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
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 Pointer to the VM.
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 Pointer to the VM.
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 Pointer to the VM.
2446 * @param pDevIns The device instance owning the region.
2447 * @param iRegion The region.
2448 */
2449DECLINLINE(PPGMMMIO2RANGE) pgmR3PhysMMIO2Find(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
2450{
2451 /*
2452 * Search the list.
2453 */
2454 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
2455 if ( pCur->pDevInsR3 == pDevIns
2456 && pCur->iRegion == iRegion)
2457 return pCur;
2458 return NULL;
2459}
2460
2461
2462/**
2463 * Allocate and register an MMIO2 region.
2464 *
2465 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's RAM
2466 * associated with a device. It is also non-shared memory with a permanent
2467 * ring-3 mapping and page backing (presently).
2468 *
2469 * A MMIO2 range may overlap with base memory if a lot of RAM is configured for
2470 * the VM, in which case we'll drop the base memory pages. Presently we will
2471 * make no attempt to preserve anything that happens to be present in the base
2472 * memory that is replaced, this is of course incorrect but it's too much
2473 * effort.
2474 *
2475 * @returns VBox status code.
2476 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
2477 * memory.
2478 * @retval VERR_ALREADY_EXISTS if the region already exists.
2479 *
2480 * @param pVM Pointer to the VM.
2481 * @param pDevIns The device instance owning the region.
2482 * @param iRegion The region number. If the MMIO2 memory is a PCI
2483 * I/O region this number has to be the number of that
2484 * region. Otherwise it can be any number safe
2485 * UINT8_MAX.
2486 * @param cb The size of the region. Must be page aligned.
2487 * @param fFlags Reserved for future use, must be zero.
2488 * @param ppv Where to store the pointer to the ring-3 mapping of
2489 * the memory.
2490 * @param pszDesc The description.
2491 */
2492VMMR3DECL(int) PGMR3PhysMMIO2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags,
2493 void **ppv, const char *pszDesc)
2494{
2495 /*
2496 * Validate input.
2497 */
2498 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2499 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2500 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2501 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
2502 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2503 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
2504 AssertReturn(pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion) == NULL, VERR_ALREADY_EXISTS);
2505 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2506 AssertReturn(cb, VERR_INVALID_PARAMETER);
2507 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
2508
2509 const uint32_t cPages = cb >> PAGE_SHIFT;
2510 AssertLogRelReturn(((RTGCPHYS)cPages << PAGE_SHIFT) == cb, VERR_INVALID_PARAMETER);
2511 AssertLogRelReturn(cPages <= PGM_MMIO2_MAX_PAGE_COUNT, VERR_NO_MEMORY);
2512
2513 /*
2514 * For the 2nd+ instance, mangle the description string so it's unique.
2515 */
2516 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
2517 {
2518 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
2519 if (!pszDesc)
2520 return VERR_NO_MEMORY;
2521 }
2522
2523 /*
2524 * Allocate an MMIO2 range ID (not freed on failure).
2525 * The zero ID is not used as it could be confused with NIL_GMM_PAGEID.
2526 */
2527 pgmLock(pVM);
2528 uint8_t idMmio2 = pVM->pgm.s.cMmio2Regions + 1;
2529 if (idMmio2 > PGM_MMIO2_MAX_RANGES)
2530 {
2531 pgmUnlock(pVM);
2532 AssertLogRelFailedReturn(VERR_PGM_TOO_MANY_MMIO2_RANGES);
2533 }
2534 pVM->pgm.s.cMmio2Regions = idMmio2;
2535 pgmUnlock(pVM);
2536
2537 /*
2538 * Try reserve and allocate the backing memory first as this is what is
2539 * most likely to fail.
2540 */
2541 int rc = MMR3AdjustFixedReservation(pVM, cPages, pszDesc);
2542 if (RT_SUCCESS(rc))
2543 {
2544 void *pvPages;
2545 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cPages * sizeof(SUPPAGE));
2546 if (RT_SUCCESS(rc))
2547 rc = SUPR3PageAllocEx(cPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
2548 if (RT_SUCCESS(rc))
2549 {
2550 memset(pvPages, 0, cPages * PAGE_SIZE);
2551
2552 /*
2553 * Create the MMIO2 range record for it.
2554 */
2555 const size_t cbRange = RT_OFFSETOF(PGMMMIO2RANGE, RamRange.aPages[cPages]);
2556 PPGMMMIO2RANGE pNew;
2557 rc = MMR3HyperAllocOnceNoRel(pVM, cbRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
2558 AssertLogRelMsgRC(rc, ("cbRamRange=%zu\n", cbRange));
2559 if (RT_SUCCESS(rc))
2560 {
2561 pNew->pDevInsR3 = pDevIns;
2562 pNew->pvR3 = pvPages;
2563 //pNew->pNext = NULL;
2564 //pNew->fMapped = false;
2565 //pNew->fOverlapping = false;
2566 pNew->iRegion = iRegion;
2567 pNew->idSavedState = UINT8_MAX;
2568 pNew->idMmio2 = idMmio2;
2569 pNew->RamRange.pSelfR0 = MMHyperCCToR0(pVM, &pNew->RamRange);
2570 pNew->RamRange.pSelfRC = MMHyperCCToRC(pVM, &pNew->RamRange);
2571 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
2572 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
2573 pNew->RamRange.pszDesc = pszDesc;
2574 pNew->RamRange.cb = cb;
2575 pNew->RamRange.fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO2;
2576 pNew->RamRange.pvR3 = pvPages;
2577 //pNew->RamRange.paLSPages = NULL;
2578
2579 uint32_t iPage = cPages;
2580 while (iPage-- > 0)
2581 {
2582 PGM_PAGE_INIT(&pNew->RamRange.aPages[iPage],
2583 paPages[iPage].Phys,
2584 PGM_MMIO2_PAGEID_MAKE(idMmio2, iPage),
2585 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
2586 }
2587
2588 /* update page count stats */
2589 pVM->pgm.s.cAllPages += cPages;
2590 pVM->pgm.s.cPrivatePages += cPages;
2591
2592 /*
2593 * Link it into the list.
2594 * Since there is no particular order, just push it.
2595 */
2596 /** @todo we can save us the linked list now, just search the lookup table... */
2597 pgmLock(pVM);
2598 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == NULL);
2599 Assert(pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] == NIL_RTR0PTR);
2600 pNew->pNextR3 = pVM->pgm.s.pMmio2RangesR3;
2601 pVM->pgm.s.pMmio2RangesR3 = pNew;
2602 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = pNew;
2603 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = MMHyperCCToR0(pVM, pNew);
2604 pgmUnlock(pVM);
2605
2606 *ppv = pvPages;
2607 RTMemTmpFree(paPages);
2608 pgmPhysInvalidatePageMapTLB(pVM);
2609 return VINF_SUCCESS;
2610 }
2611
2612 SUPR3PageFreeEx(pvPages, cPages);
2613 }
2614 RTMemTmpFree(paPages);
2615 MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pszDesc);
2616 }
2617 if (pDevIns->iInstance > 0)
2618 MMR3HeapFree((void *)pszDesc);
2619 return rc;
2620}
2621
2622
2623/**
2624 * Deregisters and frees an MMIO2 region.
2625 *
2626 * Any physical (and virtual) access handlers registered for the region must
2627 * be deregistered before calling this function.
2628 *
2629 * @returns VBox status code.
2630 * @param pVM Pointer to the VM.
2631 * @param pDevIns The device instance owning the region.
2632 * @param iRegion The region. If it's UINT32_MAX it'll be a wildcard match.
2633 */
2634VMMR3DECL(int) PGMR3PhysMMIO2Deregister(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
2635{
2636 /*
2637 * Validate input.
2638 */
2639 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2640 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2641 AssertReturn(iRegion <= UINT8_MAX || iRegion == UINT32_MAX, VERR_INVALID_PARAMETER);
2642
2643 pgmLock(pVM);
2644 int rc = VINF_SUCCESS;
2645 unsigned cFound = 0;
2646 PPGMMMIO2RANGE pPrev = NULL;
2647 PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3;
2648 while (pCur)
2649 {
2650 if ( pCur->pDevInsR3 == pDevIns
2651 && ( iRegion == UINT32_MAX
2652 || pCur->iRegion == iRegion))
2653 {
2654 cFound++;
2655
2656 /*
2657 * Unmap it if it's mapped.
2658 */
2659 if (pCur->fMapped)
2660 {
2661 int rc2 = PGMR3PhysMMIO2Unmap(pVM, pCur->pDevInsR3, pCur->iRegion, pCur->RamRange.GCPhys);
2662 AssertRC(rc2);
2663 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2664 rc = rc2;
2665 }
2666
2667 /*
2668 * Unlink it
2669 */
2670 PPGMMMIO2RANGE pNext = pCur->pNextR3;
2671 if (pPrev)
2672 pPrev->pNextR3 = pNext;
2673 else
2674 pVM->pgm.s.pMmio2RangesR3 = pNext;
2675 pCur->pNextR3 = NULL;
2676
2677 uint8_t idMmio2 = pCur->idMmio2;
2678 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == pCur);
2679 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = NULL;
2680 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = NIL_RTR0PTR;
2681
2682 /*
2683 * Free the memory.
2684 */
2685 int rc2 = SUPR3PageFreeEx(pCur->pvR3, pCur->RamRange.cb >> PAGE_SHIFT);
2686 AssertRC(rc2);
2687 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2688 rc = rc2;
2689
2690 uint32_t const cPages = pCur->RamRange.cb >> PAGE_SHIFT;
2691 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pCur->RamRange.pszDesc);
2692 AssertRC(rc2);
2693 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2694 rc = rc2;
2695
2696 /* we're leaking hyper memory here if done at runtime. */
2697#ifdef VBOX_STRICT
2698 VMSTATE const enmState = VMR3GetState(pVM);
2699 AssertMsg( enmState == VMSTATE_POWERING_OFF
2700 || enmState == VMSTATE_POWERING_OFF_LS
2701 || enmState == VMSTATE_OFF
2702 || enmState == VMSTATE_OFF_LS
2703 || enmState == VMSTATE_DESTROYING
2704 || enmState == VMSTATE_TERMINATED
2705 || enmState == VMSTATE_CREATING
2706 , ("%s\n", VMR3GetStateName(enmState)));
2707#endif
2708 /*rc = MMHyperFree(pVM, pCur);
2709 AssertRCReturn(rc, rc); - not safe, see the alloc call. */
2710
2711
2712 /* update page count stats */
2713 pVM->pgm.s.cAllPages -= cPages;
2714 pVM->pgm.s.cPrivatePages -= cPages;
2715
2716 /* next */
2717 pCur = pNext;
2718 }
2719 else
2720 {
2721 pPrev = pCur;
2722 pCur = pCur->pNextR3;
2723 }
2724 }
2725 pgmPhysInvalidatePageMapTLB(pVM);
2726 pgmUnlock(pVM);
2727 return !cFound && iRegion != UINT32_MAX ? VERR_NOT_FOUND : rc;
2728}
2729
2730
2731/**
2732 * Maps a MMIO2 region.
2733 *
2734 * This is done when a guest / the bios / state loading changes the
2735 * PCI config. The replacing of base memory has the same restrictions
2736 * as during registration, of course.
2737 *
2738 * @returns VBox status code.
2739 *
2740 * @param pVM Pointer to the VM.
2741 * @param pDevIns The device instance owning the region.
2742 * @param iRegion The index of the registered region.
2743 * @param GCPhys The guest-physical address to be remapped.
2744 */
2745VMMR3DECL(int) PGMR3PhysMMIO2Map(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
2746{
2747 /*
2748 * Validate input
2749 */
2750 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2751 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2752 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2753 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
2754 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
2755 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2756
2757 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2758 AssertReturn(pCur, VERR_NOT_FOUND);
2759 AssertReturn(!pCur->fMapped, VERR_WRONG_ORDER);
2760 Assert(pCur->RamRange.GCPhys == NIL_RTGCPHYS);
2761 Assert(pCur->RamRange.GCPhysLast == NIL_RTGCPHYS);
2762
2763 const RTGCPHYS GCPhysLast = GCPhys + pCur->RamRange.cb - 1;
2764 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2765
2766 /*
2767 * Find our location in the ram range list, checking for
2768 * restriction we don't bother implementing yet (partially overlapping).
2769 */
2770 bool fRamExists = false;
2771 PPGMRAMRANGE pRamPrev = NULL;
2772 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2773 while (pRam && GCPhysLast >= pRam->GCPhys)
2774 {
2775 if ( GCPhys <= pRam->GCPhysLast
2776 && GCPhysLast >= pRam->GCPhys)
2777 {
2778 /* completely within? */
2779 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
2780 && GCPhysLast <= pRam->GCPhysLast,
2781 ("%RGp-%RGp (MMIO2/%s) falls partly outside %RGp-%RGp (%s)\n",
2782 GCPhys, GCPhysLast, pCur->RamRange.pszDesc,
2783 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2784 VERR_PGM_RAM_CONFLICT);
2785 fRamExists = true;
2786 break;
2787 }
2788
2789 /* next */
2790 pRamPrev = pRam;
2791 pRam = pRam->pNextR3;
2792 }
2793 if (fRamExists)
2794 {
2795 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2796 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2797 while (cPagesLeft-- > 0)
2798 {
2799 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
2800 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
2801 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pCur->RamRange.pszDesc),
2802 VERR_PGM_RAM_CONFLICT);
2803 pPage++;
2804 }
2805 }
2806 Log(("PGMR3PhysMMIO2Map: %RGp-%RGp fRamExists=%RTbool %s\n",
2807 GCPhys, GCPhysLast, fRamExists, pCur->RamRange.pszDesc));
2808
2809 /*
2810 * Make the changes.
2811 */
2812 pgmLock(pVM);
2813
2814 pCur->RamRange.GCPhys = GCPhys;
2815 pCur->RamRange.GCPhysLast = GCPhysLast;
2816 pCur->fMapped = true;
2817 pCur->fOverlapping = fRamExists;
2818
2819 if (fRamExists)
2820 {
2821/** @todo use pgmR3PhysFreePageRange here. */
2822 uint32_t cPendingPages = 0;
2823 PGMMFREEPAGESREQ pReq;
2824 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2825 AssertLogRelRCReturn(rc, rc);
2826
2827 /* replace the pages, freeing all present RAM pages. */
2828 PPGMPAGE pPageSrc = &pCur->RamRange.aPages[0];
2829 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2830 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2831 while (cPagesLeft-- > 0)
2832 {
2833 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys);
2834 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
2835
2836 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
2837 uint32_t const idPage = PGM_PAGE_GET_PAGEID(pPageSrc);
2838 PGM_PAGE_SET_PAGEID(pVM, pPageDst, idPage);
2839 PGM_PAGE_SET_HCPHYS(pVM, pPageDst, HCPhys);
2840 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO2);
2841 PGM_PAGE_SET_STATE(pVM, pPageDst, PGM_PAGE_STATE_ALLOCATED);
2842 PGM_PAGE_SET_PDE_TYPE(pVM, pPageDst, PGM_PAGE_PDE_TYPE_DONTCARE);
2843 PGM_PAGE_SET_PTE_INDEX(pVM, pPageDst, 0);
2844 PGM_PAGE_SET_TRACKING(pVM, pPageDst, 0);
2845
2846 pVM->pgm.s.cZeroPages--;
2847 GCPhys += PAGE_SIZE;
2848 pPageSrc++;
2849 pPageDst++;
2850 }
2851
2852 /* Flush physical page map TLB. */
2853 pgmPhysInvalidatePageMapTLB(pVM);
2854
2855 if (cPendingPages)
2856 {
2857 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2858 AssertLogRelRCReturn(rc, rc);
2859 }
2860 GMMR3FreePagesCleanup(pReq);
2861
2862 /* Force a PGM pool flush as guest ram references have been changed. */
2863 /** @todo not entirely SMP safe; assuming for now the guest takes care of
2864 * this internally (not touch mapped mmio while changing the mapping). */
2865 PVMCPU pVCpu = VMMGetCpu(pVM);
2866 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2867 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2868
2869 pgmUnlock(pVM);
2870 }
2871 else
2872 {
2873 RTGCPHYS cb = pCur->RamRange.cb;
2874
2875 /* Clear the tracking data of pages we're going to reactivate. */
2876 PPGMPAGE pPageSrc = &pCur->RamRange.aPages[0];
2877 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2878 while (cPagesLeft-- > 0)
2879 {
2880 PGM_PAGE_SET_TRACKING(pVM, pPageSrc, 0);
2881 PGM_PAGE_SET_PTE_INDEX(pVM, pPageSrc, 0);
2882 pPageSrc++;
2883 }
2884
2885 /* link in the ram range */
2886 pgmR3PhysLinkRamRange(pVM, &pCur->RamRange, pRamPrev);
2887 pgmUnlock(pVM);
2888
2889#ifdef VBOX_WITH_REM
2890 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_MMIO2);
2891#endif
2892 }
2893
2894 pgmPhysInvalidatePageMapTLB(pVM);
2895 return VINF_SUCCESS;
2896}
2897
2898
2899/**
2900 * Unmaps a MMIO2 region.
2901 *
2902 * This is done when a guest / the bios / state loading changes the
2903 * PCI config. The replacing of base memory has the same restrictions
2904 * as during registration, of course.
2905 */
2906VMMR3DECL(int) PGMR3PhysMMIO2Unmap(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
2907{
2908 /*
2909 * Validate input
2910 */
2911 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2912 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2913 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2914 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
2915 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
2916 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2917
2918 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2919 AssertReturn(pCur, VERR_NOT_FOUND);
2920 AssertReturn(pCur->fMapped, VERR_WRONG_ORDER);
2921 AssertReturn(pCur->RamRange.GCPhys == GCPhys, VERR_INVALID_PARAMETER);
2922 Assert(pCur->RamRange.GCPhysLast != NIL_RTGCPHYS);
2923
2924 Log(("PGMR3PhysMMIO2Unmap: %RGp-%RGp %s\n",
2925 pCur->RamRange.GCPhys, pCur->RamRange.GCPhysLast, pCur->RamRange.pszDesc));
2926
2927 /*
2928 * Unmap it.
2929 */
2930 pgmLock(pVM);
2931
2932#ifdef VBOX_WITH_REM
2933 RTGCPHYS GCPhysRangeREM;
2934 RTGCPHYS cbRangeREM;
2935 bool fInformREM;
2936#endif
2937 if (pCur->fOverlapping)
2938 {
2939 /* Restore the RAM pages we've replaced. */
2940 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2941 while (pRam->GCPhys > pCur->RamRange.GCPhysLast)
2942 pRam = pRam->pNextR3;
2943
2944 PPGMPAGE pPageDst = &pRam->aPages[(pCur->RamRange.GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2945 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2946 while (cPagesLeft-- > 0)
2947 {
2948 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
2949 pVM->pgm.s.cZeroPages++;
2950 pPageDst++;
2951 }
2952
2953 /* Flush physical page map TLB. */
2954 pgmPhysInvalidatePageMapTLB(pVM);
2955#ifdef VBOX_WITH_REM
2956 GCPhysRangeREM = NIL_RTGCPHYS; /* shuts up gcc */
2957 cbRangeREM = RTGCPHYS_MAX; /* ditto */
2958 fInformREM = false;
2959#endif
2960 }
2961 else
2962 {
2963#ifdef VBOX_WITH_REM
2964 GCPhysRangeREM = pCur->RamRange.GCPhys;
2965 cbRangeREM = pCur->RamRange.cb;
2966 fInformREM = true;
2967#endif
2968 pgmR3PhysUnlinkRamRange(pVM, &pCur->RamRange);
2969 }
2970
2971 pCur->RamRange.GCPhys = NIL_RTGCPHYS;
2972 pCur->RamRange.GCPhysLast = NIL_RTGCPHYS;
2973 pCur->fOverlapping = false;
2974 pCur->fMapped = false;
2975
2976 /* Force a PGM pool flush as guest ram references have been changed. */
2977 /** @todo not entirely SMP safe; assuming for now the guest takes care
2978 * of this internally (not touch mapped mmio while changing the
2979 * mapping). */
2980 PVMCPU pVCpu = VMMGetCpu(pVM);
2981 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2982 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2983
2984 pgmPhysInvalidatePageMapTLB(pVM);
2985 pgmPhysInvalidRamRangeTlbs(pVM);
2986 pgmUnlock(pVM);
2987
2988#ifdef VBOX_WITH_REM
2989 if (fInformREM)
2990 REMR3NotifyPhysRamDeregister(pVM, GCPhysRangeREM, cbRangeREM);
2991#endif
2992
2993 return VINF_SUCCESS;
2994}
2995
2996
2997/**
2998 * Checks if the given address is an MMIO2 base address or not.
2999 *
3000 * @returns true/false accordingly.
3001 * @param pVM Pointer to the VM.
3002 * @param pDevIns The owner of the memory, optional.
3003 * @param GCPhys The address to check.
3004 */
3005VMMR3DECL(bool) PGMR3PhysMMIO2IsBase(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys)
3006{
3007 /*
3008 * Validate input
3009 */
3010 VM_ASSERT_EMT_RETURN(pVM, false);
3011 AssertPtrReturn(pDevIns, false);
3012 AssertReturn(GCPhys != NIL_RTGCPHYS, false);
3013 AssertReturn(GCPhys != 0, false);
3014 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), false);
3015
3016 /*
3017 * Search the list.
3018 */
3019 pgmLock(pVM);
3020 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
3021 if (pCur->RamRange.GCPhys == GCPhys)
3022 {
3023 Assert(pCur->fMapped);
3024 pgmUnlock(pVM);
3025 return true;
3026 }
3027 pgmUnlock(pVM);
3028 return false;
3029}
3030
3031
3032/**
3033 * Gets the HC physical address of a page in the MMIO2 region.
3034 *
3035 * This is API is intended for MMHyper and shouldn't be called
3036 * by anyone else...
3037 *
3038 * @returns VBox status code.
3039 * @param pVM Pointer to the VM.
3040 * @param pDevIns The owner of the memory, optional.
3041 * @param iRegion The region.
3042 * @param off The page expressed an offset into the MMIO2 region.
3043 * @param pHCPhys Where to store the result.
3044 */
3045VMMR3DECL(int) PGMR3PhysMMIO2GetHCPhys(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, PRTHCPHYS pHCPhys)
3046{
3047 /*
3048 * Validate input
3049 */
3050 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3051 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3052 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3053
3054 pgmLock(pVM);
3055 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
3056 AssertReturn(pCur, VERR_NOT_FOUND);
3057 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
3058
3059 PCPGMPAGE pPage = &pCur->RamRange.aPages[off >> PAGE_SHIFT];
3060 *pHCPhys = PGM_PAGE_GET_HCPHYS(pPage);
3061 pgmUnlock(pVM);
3062 return VINF_SUCCESS;
3063}
3064
3065
3066/**
3067 * Maps a portion of an MMIO2 region into kernel space (host).
3068 *
3069 * The kernel mapping will become invalid when the MMIO2 memory is deregistered
3070 * or the VM is terminated.
3071 *
3072 * @return VBox status code.
3073 *
3074 * @param pVM Pointer to the VM.
3075 * @param pDevIns The device owning the MMIO2 memory.
3076 * @param iRegion The region.
3077 * @param off The offset into the region. Must be page aligned.
3078 * @param cb The number of bytes to map. Must be page aligned.
3079 * @param pszDesc Mapping description.
3080 * @param pR0Ptr Where to store the R0 address.
3081 */
3082VMMR3DECL(int) PGMR3PhysMMIO2MapKernel(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, RTGCPHYS cb,
3083 const char *pszDesc, PRTR0PTR pR0Ptr)
3084{
3085 /*
3086 * Validate input.
3087 */
3088 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3089 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3090 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
3091
3092 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
3093 AssertReturn(pCur, VERR_NOT_FOUND);
3094 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
3095 AssertReturn(cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
3096 AssertReturn(off + cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
3097 NOREF(pszDesc);
3098
3099 /*
3100 * Pass the request on to the support library/driver.
3101 */
3102 int rc = SUPR3PageMapKernel(pCur->pvR3, off, cb, 0, pR0Ptr);
3103
3104 return rc;
3105}
3106
3107
3108/**
3109 * Worker for PGMR3PhysRomRegister.
3110 *
3111 * This is here to simplify lock management, i.e. the caller does all the
3112 * locking and we can simply return without needing to remember to unlock
3113 * anything first.
3114 *
3115 * @returns VBox status.
3116 * @param pVM Pointer to the VM.
3117 * @param pDevIns The device instance owning the ROM.
3118 * @param GCPhys First physical address in the range.
3119 * Must be page aligned!
3120 * @param cb The size of the range (in bytes).
3121 * Must be page aligned!
3122 * @param pvBinary Pointer to the binary data backing the ROM image.
3123 * @param cbBinary The size of the binary data pvBinary points to.
3124 * This must be less or equal to @a cb.
3125 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
3126 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
3127 * @param pszDesc Pointer to description string. This must not be freed.
3128 */
3129static int pgmR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
3130 const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
3131{
3132 /*
3133 * Validate input.
3134 */
3135 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3136 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
3137 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
3138 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
3139 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3140 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
3141 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
3142 AssertReturn(!(fFlags & ~(PGMPHYS_ROM_FLAGS_SHADOWED | PGMPHYS_ROM_FLAGS_PERMANENT_BINARY)), VERR_INVALID_PARAMETER);
3143 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
3144
3145 const uint32_t cPages = cb >> PAGE_SHIFT;
3146
3147 /*
3148 * Find the ROM location in the ROM list first.
3149 */
3150 PPGMROMRANGE pRomPrev = NULL;
3151 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
3152 while (pRom && GCPhysLast >= pRom->GCPhys)
3153 {
3154 if ( GCPhys <= pRom->GCPhysLast
3155 && GCPhysLast >= pRom->GCPhys)
3156 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
3157 GCPhys, GCPhysLast, pszDesc,
3158 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
3159 VERR_PGM_RAM_CONFLICT);
3160 /* next */
3161 pRomPrev = pRom;
3162 pRom = pRom->pNextR3;
3163 }
3164
3165 /*
3166 * Find the RAM location and check for conflicts.
3167 *
3168 * Conflict detection is a bit different than for RAM
3169 * registration since a ROM can be located within a RAM
3170 * range. So, what we have to check for is other memory
3171 * types (other than RAM that is) and that we don't span
3172 * more than one RAM range (layz).
3173 */
3174 bool fRamExists = false;
3175 PPGMRAMRANGE pRamPrev = NULL;
3176 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3177 while (pRam && GCPhysLast >= pRam->GCPhys)
3178 {
3179 if ( GCPhys <= pRam->GCPhysLast
3180 && GCPhysLast >= pRam->GCPhys)
3181 {
3182 /* completely within? */
3183 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
3184 && GCPhysLast <= pRam->GCPhysLast,
3185 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
3186 GCPhys, GCPhysLast, pszDesc,
3187 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
3188 VERR_PGM_RAM_CONFLICT);
3189 fRamExists = true;
3190 break;
3191 }
3192
3193 /* next */
3194 pRamPrev = pRam;
3195 pRam = pRam->pNextR3;
3196 }
3197 if (fRamExists)
3198 {
3199 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3200 uint32_t cPagesLeft = cPages;
3201 while (cPagesLeft-- > 0)
3202 {
3203 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
3204 ("%RGp (%R[pgmpage]) isn't a RAM page - registering %RGp-%RGp (%s).\n",
3205 pRam->GCPhys + ((RTGCPHYS)(uintptr_t)(pPage - &pRam->aPages[0]) << PAGE_SHIFT),
3206 pPage, GCPhys, GCPhysLast, pszDesc), VERR_PGM_RAM_CONFLICT);
3207 Assert(PGM_PAGE_IS_ZERO(pPage));
3208 pPage++;
3209 }
3210 }
3211
3212 /*
3213 * Update the base memory reservation if necessary.
3214 */
3215 uint32_t cExtraBaseCost = fRamExists ? 0 : cPages;
3216 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3217 cExtraBaseCost += cPages;
3218 if (cExtraBaseCost)
3219 {
3220 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
3221 if (RT_FAILURE(rc))
3222 return rc;
3223 }
3224
3225 /*
3226 * Allocate memory for the virgin copy of the RAM.
3227 */
3228 PGMMALLOCATEPAGESREQ pReq;
3229 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cPages, GMMACCOUNT_BASE);
3230 AssertRCReturn(rc, rc);
3231
3232 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3233 {
3234 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << PAGE_SHIFT);
3235 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
3236 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
3237 }
3238
3239 rc = GMMR3AllocatePagesPerform(pVM, pReq);
3240 if (RT_FAILURE(rc))
3241 {
3242 GMMR3AllocatePagesCleanup(pReq);
3243 return rc;
3244 }
3245
3246 /*
3247 * Allocate the new ROM range and RAM range (if necessary).
3248 */
3249 PPGMROMRANGE pRomNew;
3250 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMROMRANGE, aPages[cPages]), 0, MM_TAG_PGM_PHYS, (void **)&pRomNew);
3251 if (RT_SUCCESS(rc))
3252 {
3253 PPGMRAMRANGE pRamNew = NULL;
3254 if (!fRamExists)
3255 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), sizeof(PGMPAGE), MM_TAG_PGM_PHYS, (void **)&pRamNew);
3256 if (RT_SUCCESS(rc))
3257 {
3258 /*
3259 * Initialize and insert the RAM range (if required).
3260 */
3261 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
3262 if (!fRamExists)
3263 {
3264 pRamNew->pSelfR0 = MMHyperCCToR0(pVM, pRamNew);
3265 pRamNew->pSelfRC = MMHyperCCToRC(pVM, pRamNew);
3266 pRamNew->GCPhys = GCPhys;
3267 pRamNew->GCPhysLast = GCPhysLast;
3268 pRamNew->cb = cb;
3269 pRamNew->pszDesc = pszDesc;
3270 pRamNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_ROM;
3271 pRamNew->pvR3 = NULL;
3272 pRamNew->paLSPages = NULL;
3273
3274 PPGMPAGE pPage = &pRamNew->aPages[0];
3275 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
3276 {
3277 PGM_PAGE_INIT(pPage,
3278 pReq->aPages[iPage].HCPhysGCPhys,
3279 pReq->aPages[iPage].idPage,
3280 PGMPAGETYPE_ROM,
3281 PGM_PAGE_STATE_ALLOCATED);
3282
3283 pRomPage->Virgin = *pPage;
3284 }
3285
3286 pVM->pgm.s.cAllPages += cPages;
3287 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
3288 }
3289 else
3290 {
3291 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
3292 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
3293 {
3294 PGM_PAGE_SET_TYPE(pVM, pPage, PGMPAGETYPE_ROM);
3295 PGM_PAGE_SET_HCPHYS(pVM, pPage, pReq->aPages[iPage].HCPhysGCPhys);
3296 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ALLOCATED);
3297 PGM_PAGE_SET_PAGEID(pVM, pPage, pReq->aPages[iPage].idPage);
3298 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
3299 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
3300 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
3301
3302 pRomPage->Virgin = *pPage;
3303 }
3304
3305 pRamNew = pRam;
3306
3307 pVM->pgm.s.cZeroPages -= cPages;
3308 }
3309 pVM->pgm.s.cPrivatePages += cPages;
3310
3311 /* Flush physical page map TLB. */
3312 pgmPhysInvalidatePageMapTLB(pVM);
3313
3314
3315 /*
3316 * !HACK ALERT! REM + (Shadowed) ROM ==> mess.
3317 *
3318 * If it's shadowed we'll register the handler after the ROM notification
3319 * so we get the access handler callbacks that we should. If it isn't
3320 * shadowed we'll do it the other way around to make REM use the built-in
3321 * ROM behavior and not the handler behavior (which is to route all access
3322 * to PGM atm).
3323 */
3324 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3325 {
3326#ifdef VBOX_WITH_REM
3327 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, true /* fShadowed */);
3328#endif
3329 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, pVM->pgm.s.hRomPhysHandlerType,
3330 pRomNew, MMHyperCCToR0(pVM, pRomNew), MMHyperCCToRC(pVM, pRomNew),
3331 pszDesc);
3332 }
3333 else
3334 {
3335 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, pVM->pgm.s.hRomPhysHandlerType,
3336 pRomNew, MMHyperCCToR0(pVM, pRomNew), MMHyperCCToRC(pVM, pRomNew),
3337 pszDesc);
3338#ifdef VBOX_WITH_REM
3339 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, false /* fShadowed */);
3340#endif
3341 }
3342 if (RT_SUCCESS(rc))
3343 {
3344 /*
3345 * Copy the image over to the virgin pages.
3346 * This must be done after linking in the RAM range.
3347 */
3348 size_t cbBinaryLeft = cbBinary;
3349 PPGMPAGE pRamPage = &pRamNew->aPages[(GCPhys - pRamNew->GCPhys) >> PAGE_SHIFT];
3350 for (uint32_t iPage = 0; iPage < cPages; iPage++, pRamPage++)
3351 {
3352 void *pvDstPage;
3353 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << PAGE_SHIFT), &pvDstPage);
3354 if (RT_FAILURE(rc))
3355 {
3356 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
3357 break;
3358 }
3359 if (cbBinaryLeft >= PAGE_SIZE)
3360 {
3361 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), PAGE_SIZE);
3362 cbBinaryLeft -= PAGE_SIZE;
3363 }
3364 else
3365 {
3366 ASMMemZeroPage(pvDstPage); /* (shouldn't be necessary, but can't hurt either) */
3367 if (cbBinaryLeft > 0)
3368 {
3369 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << PAGE_SHIFT), cbBinaryLeft);
3370 cbBinaryLeft = 0;
3371 }
3372 }
3373 }
3374 if (RT_SUCCESS(rc))
3375 {
3376 /*
3377 * Initialize the ROM range.
3378 * Note that the Virgin member of the pages has already been initialized above.
3379 */
3380 pRomNew->GCPhys = GCPhys;
3381 pRomNew->GCPhysLast = GCPhysLast;
3382 pRomNew->cb = cb;
3383 pRomNew->fFlags = fFlags;
3384 pRomNew->idSavedState = UINT8_MAX;
3385 pRomNew->cbOriginal = cbBinary;
3386#ifdef VBOX_STRICT
3387 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY
3388 ? pvBinary : RTMemDup(pvBinary, cbBinary);
3389#else
3390 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY ? pvBinary : NULL;
3391#endif
3392 pRomNew->pszDesc = pszDesc;
3393
3394 for (unsigned iPage = 0; iPage < cPages; iPage++)
3395 {
3396 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
3397 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
3398 PGM_PAGE_INIT_ZERO(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
3399 }
3400
3401 /* update the page count stats for the shadow pages. */
3402 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3403 {
3404 pVM->pgm.s.cZeroPages += cPages;
3405 pVM->pgm.s.cAllPages += cPages;
3406 }
3407
3408 /*
3409 * Insert the ROM range, tell REM and return successfully.
3410 */
3411 pRomNew->pNextR3 = pRom;
3412 pRomNew->pNextR0 = pRom ? MMHyperCCToR0(pVM, pRom) : NIL_RTR0PTR;
3413 pRomNew->pNextRC = pRom ? MMHyperCCToRC(pVM, pRom) : NIL_RTRCPTR;
3414
3415 if (pRomPrev)
3416 {
3417 pRomPrev->pNextR3 = pRomNew;
3418 pRomPrev->pNextR0 = MMHyperCCToR0(pVM, pRomNew);
3419 pRomPrev->pNextRC = MMHyperCCToRC(pVM, pRomNew);
3420 }
3421 else
3422 {
3423 pVM->pgm.s.pRomRangesR3 = pRomNew;
3424 pVM->pgm.s.pRomRangesR0 = MMHyperCCToR0(pVM, pRomNew);
3425 pVM->pgm.s.pRomRangesRC = MMHyperCCToRC(pVM, pRomNew);
3426 }
3427
3428 pgmPhysInvalidatePageMapTLB(pVM);
3429 GMMR3AllocatePagesCleanup(pReq);
3430 return VINF_SUCCESS;
3431 }
3432
3433 /* bail out */
3434
3435 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
3436 AssertRC(rc2);
3437 }
3438
3439 if (!fRamExists)
3440 {
3441 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
3442 MMHyperFree(pVM, pRamNew);
3443 }
3444 }
3445 MMHyperFree(pVM, pRomNew);
3446 }
3447
3448 /** @todo Purge the mapping cache or something... */
3449 GMMR3FreeAllocatedPages(pVM, pReq);
3450 GMMR3AllocatePagesCleanup(pReq);
3451 return rc;
3452}
3453
3454
3455/**
3456 * Registers a ROM image.
3457 *
3458 * Shadowed ROM images requires double the amount of backing memory, so,
3459 * don't use that unless you have to. Shadowing of ROM images is process
3460 * where we can select where the reads go and where the writes go. On real
3461 * hardware the chipset provides means to configure this. We provide
3462 * PGMR3PhysProtectROM() for this purpose.
3463 *
3464 * A read-only copy of the ROM image will always be kept around while we
3465 * will allocate RAM pages for the changes on demand (unless all memory
3466 * is configured to be preallocated).
3467 *
3468 * @returns VBox status.
3469 * @param pVM Pointer to the VM.
3470 * @param pDevIns The device instance owning the ROM.
3471 * @param GCPhys First physical address in the range.
3472 * Must be page aligned!
3473 * @param cb The size of the range (in bytes).
3474 * Must be page aligned!
3475 * @param pvBinary Pointer to the binary data backing the ROM image.
3476 * @param cbBinary The size of the binary data pvBinary points to.
3477 * This must be less or equal to @a cb.
3478 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
3479 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
3480 * @param pszDesc Pointer to description string. This must not be freed.
3481 *
3482 * @remark There is no way to remove the rom, automatically on device cleanup or
3483 * manually from the device yet. This isn't difficult in any way, it's
3484 * just not something we expect to be necessary for a while.
3485 */
3486VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
3487 const void *pvBinary, uint32_t cbBinary, uint32_t fFlags, const char *pszDesc)
3488{
3489 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p cbBinary=%#x fFlags=%#x pszDesc=%s\n",
3490 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, cbBinary, fFlags, pszDesc));
3491 pgmLock(pVM);
3492 int rc = pgmR3PhysRomRegister(pVM, pDevIns, GCPhys, cb, pvBinary, cbBinary, fFlags, pszDesc);
3493 pgmUnlock(pVM);
3494 return rc;
3495}
3496
3497
3498/**
3499 * Called by PGMR3MemSetup to reset the shadow, switch to the virgin, and verify
3500 * that the virgin part is untouched.
3501 *
3502 * This is done after the normal memory has been cleared.
3503 *
3504 * ASSUMES that the caller owns the PGM lock.
3505 *
3506 * @param pVM Pointer to the VM.
3507 */
3508int pgmR3PhysRomReset(PVM pVM)
3509{
3510 PGM_LOCK_ASSERT_OWNER(pVM);
3511 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3512 {
3513 const uint32_t cPages = pRom->cb >> PAGE_SHIFT;
3514
3515 if (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
3516 {
3517 /*
3518 * Reset the physical handler.
3519 */
3520 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
3521 AssertRCReturn(rc, rc);
3522
3523 /*
3524 * What we do with the shadow pages depends on the memory
3525 * preallocation option. If not enabled, we'll just throw
3526 * out all the dirty pages and replace them by the zero page.
3527 */
3528 if (!pVM->pgm.s.fRamPreAlloc)
3529 {
3530 /* Free the dirty pages. */
3531 uint32_t cPendingPages = 0;
3532 PGMMFREEPAGESREQ pReq;
3533 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
3534 AssertRCReturn(rc, rc);
3535
3536 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3537 if ( !PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow)
3538 && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow))
3539 {
3540 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
3541 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, &pRom->aPages[iPage].Shadow,
3542 pRom->GCPhys + (iPage << PAGE_SHIFT));
3543 AssertLogRelRCReturn(rc, rc);
3544 }
3545
3546 if (cPendingPages)
3547 {
3548 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
3549 AssertLogRelRCReturn(rc, rc);
3550 }
3551 GMMR3FreePagesCleanup(pReq);
3552 }
3553 else
3554 {
3555 /* clear all the shadow pages. */
3556 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3557 {
3558 if (PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow))
3559 continue;
3560 Assert(!PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow));
3561 void *pvDstPage;
3562 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
3563 rc = pgmPhysPageMakeWritableAndMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pvDstPage);
3564 if (RT_FAILURE(rc))
3565 break;
3566 ASMMemZeroPage(pvDstPage);
3567 }
3568 AssertRCReturn(rc, rc);
3569 }
3570 }
3571
3572#ifdef VBOX_STRICT
3573 /*
3574 * Verify that the virgin page is unchanged if possible.
3575 */
3576 if (pRom->pvOriginal)
3577 {
3578 size_t cbSrcLeft = pRom->cbOriginal;
3579 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
3580 for (uint32_t iPage = 0; iPage < cPages && cbSrcLeft > 0; iPage++, pbSrcPage += PAGE_SIZE)
3581 {
3582 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
3583 void const *pvDstPage;
3584 int rc = pgmPhysPageMapReadOnly(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPage);
3585 if (RT_FAILURE(rc))
3586 break;
3587
3588 if (memcmp(pvDstPage, pbSrcPage, RT_MIN(cbSrcLeft, PAGE_SIZE)))
3589 {
3590# ifdef DEBUG_bird /* This is darn handy for EFI debugging w/ snapshots, should be made default later. */
3591 void *pvDstPageW;
3592 rc = pgmPhysPageMap(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPageW);
3593 AssertRCReturn(rc, rc);
3594 memcpy(pvDstPageW, pbSrcPage, RT_MIN(cbSrcLeft, PAGE_SIZE));
3595# else
3596 LogRel(("pgmR3PhysRomReset: %RGp rom page changed (%s) - loaded saved state?\n",
3597 GCPhys, pRom->pszDesc));
3598# endif
3599 }
3600 cbSrcLeft -= RT_MIN(cbSrcLeft, PAGE_SIZE);
3601 }
3602 }
3603#endif
3604 }
3605
3606 return VINF_SUCCESS;
3607}
3608
3609
3610/**
3611 * Called by PGMR3Term to free resources.
3612 *
3613 * ASSUMES that the caller owns the PGM lock.
3614 *
3615 * @param pVM Pointer to the VM.
3616 */
3617void pgmR3PhysRomTerm(PVM pVM)
3618{
3619#ifdef RT_STRICT
3620 /*
3621 * Free the heap copy of the original bits.
3622 */
3623 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3624 {
3625 if ( pRom->pvOriginal
3626 && !(pRom->fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY))
3627 {
3628 RTMemFree((void *)pRom->pvOriginal);
3629 pRom->pvOriginal = NULL;
3630 }
3631 }
3632#endif
3633}
3634
3635
3636/**
3637 * Change the shadowing of a range of ROM pages.
3638 *
3639 * This is intended for implementing chipset specific memory registers
3640 * and will not be very strict about the input. It will silently ignore
3641 * any pages that are not the part of a shadowed ROM.
3642 *
3643 * @returns VBox status code.
3644 * @retval VINF_PGM_SYNC_CR3
3645 *
3646 * @param pVM Pointer to the VM.
3647 * @param GCPhys Where to start. Page aligned.
3648 * @param cb How much to change. Page aligned.
3649 * @param enmProt The new ROM protection.
3650 */
3651VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
3652{
3653 /*
3654 * Check input
3655 */
3656 if (!cb)
3657 return VINF_SUCCESS;
3658 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3659 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3660 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
3661 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3662 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
3663
3664 /*
3665 * Process the request.
3666 */
3667 pgmLock(pVM);
3668 int rc = VINF_SUCCESS;
3669 bool fFlushTLB = false;
3670 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
3671 {
3672 if ( GCPhys <= pRom->GCPhysLast
3673 && GCPhysLast >= pRom->GCPhys
3674 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
3675 {
3676 /*
3677 * Iterate the relevant pages and make necessary the changes.
3678 */
3679 bool fChanges = false;
3680 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
3681 ? pRom->cb >> PAGE_SHIFT
3682 : (GCPhysLast - pRom->GCPhys + 1) >> PAGE_SHIFT;
3683 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
3684 iPage < cPages;
3685 iPage++)
3686 {
3687 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
3688 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
3689 {
3690 fChanges = true;
3691
3692 /* flush references to the page. */
3693 PPGMPAGE pRamPage = pgmPhysGetPage(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT));
3694 int rc2 = pgmPoolTrackUpdateGCPhys(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT), pRamPage,
3695 true /*fFlushPTEs*/, &fFlushTLB);
3696 if (rc2 != VINF_SUCCESS && (rc == VINF_SUCCESS || RT_FAILURE(rc2)))
3697 rc = rc2;
3698
3699 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
3700 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
3701
3702 *pOld = *pRamPage;
3703 *pRamPage = *pNew;
3704 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
3705 }
3706 pRomPage->enmProt = enmProt;
3707 }
3708
3709 /*
3710 * Reset the access handler if we made changes, no need
3711 * to optimize this.
3712 */
3713 if (fChanges)
3714 {
3715 int rc2 = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
3716 if (RT_FAILURE(rc2))
3717 {
3718 pgmUnlock(pVM);
3719 AssertRC(rc);
3720 return rc2;
3721 }
3722 }
3723
3724 /* Advance - cb isn't updated. */
3725 GCPhys = pRom->GCPhys + (cPages << PAGE_SHIFT);
3726 }
3727 }
3728 pgmUnlock(pVM);
3729 if (fFlushTLB)
3730 PGM_INVL_ALL_VCPU_TLBS(pVM);
3731
3732 return rc;
3733}
3734
3735
3736/**
3737 * Sets the Address Gate 20 state.
3738 *
3739 * @param pVCpu Pointer to the VMCPU.
3740 * @param fEnable True if the gate should be enabled.
3741 * False if the gate should be disabled.
3742 */
3743VMMDECL(void) PGMR3PhysSetA20(PVMCPU pVCpu, bool fEnable)
3744{
3745 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVCpu->pgm.s.fA20Enabled));
3746 if (pVCpu->pgm.s.fA20Enabled != fEnable)
3747 {
3748 pVCpu->pgm.s.fA20Enabled = fEnable;
3749 pVCpu->pgm.s.GCPhysA20Mask = ~((RTGCPHYS)!fEnable << 20);
3750#ifdef VBOX_WITH_REM
3751 REMR3A20Set(pVCpu->pVMR3, pVCpu, fEnable);
3752#endif
3753#ifdef PGM_WITH_A20
3754 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_UPDATE_PAGE_BIT_VIRTUAL;
3755 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3756 pgmR3RefreshShadowModeAfterA20Change(pVCpu);
3757 HMFlushTLB(pVCpu);
3758#endif
3759 STAM_REL_COUNTER_INC(&pVCpu->pgm.s.cA20Changes);
3760 }
3761}
3762
3763
3764/**
3765 * Tree enumeration callback for dealing with age rollover.
3766 * It will perform a simple compression of the current age.
3767 */
3768static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
3769{
3770 /* Age compression - ASSUMES iNow == 4. */
3771 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3772 if (pChunk->iLastUsed >= UINT32_C(0xffffff00))
3773 pChunk->iLastUsed = 3;
3774 else if (pChunk->iLastUsed >= UINT32_C(0xfffff000))
3775 pChunk->iLastUsed = 2;
3776 else if (pChunk->iLastUsed)
3777 pChunk->iLastUsed = 1;
3778 else /* iLastUsed = 0 */
3779 pChunk->iLastUsed = 4;
3780
3781 NOREF(pvUser);
3782 return 0;
3783}
3784
3785
3786/**
3787 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
3788 */
3789typedef struct PGMR3PHYSCHUNKUNMAPCB
3790{
3791 PVM pVM; /**< Pointer to the VM. */
3792 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
3793} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
3794
3795
3796/**
3797 * Callback used to find the mapping that's been unused for
3798 * the longest time.
3799 */
3800static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLU32NODECORE pNode, void *pvUser)
3801{
3802 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3803 PPGMR3PHYSCHUNKUNMAPCB pArg = (PPGMR3PHYSCHUNKUNMAPCB)pvUser;
3804
3805 /*
3806 * Check for locks and compare when last used.
3807 */
3808 if (pChunk->cRefs)
3809 return 0;
3810 if (pChunk->cPermRefs)
3811 return 0;
3812 if ( pArg->pChunk
3813 && pChunk->iLastUsed >= pArg->pChunk->iLastUsed)
3814 return 0;
3815
3816 /*
3817 * Check that it's not in any of the TLBs.
3818 */
3819 PVM pVM = pArg->pVM;
3820 if ( pVM->pgm.s.ChunkR3Map.Tlb.aEntries[PGM_CHUNKR3MAPTLB_IDX(pChunk->Core.Key)].idChunk
3821 == pChunk->Core.Key)
3822 {
3823 pChunk = NULL;
3824 return 0;
3825 }
3826#ifdef VBOX_STRICT
3827 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
3828 {
3829 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk != pChunk);
3830 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk != pChunk->Core.Key);
3831 }
3832#endif
3833
3834 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbHC.aEntries); i++)
3835 if (pVM->pgm.s.PhysTlbHC.aEntries[i].pMap == pChunk)
3836 return 0;
3837
3838 pArg->pChunk = pChunk;
3839 return 0;
3840}
3841
3842
3843/**
3844 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
3845 *
3846 * The candidate will not be part of any TLBs, so no need to flush
3847 * anything afterwards.
3848 *
3849 * @returns Chunk id.
3850 * @param pVM Pointer to the VM.
3851 */
3852static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
3853{
3854 PGM_LOCK_ASSERT_OWNER(pVM);
3855
3856 /*
3857 * Enumerate the age tree starting with the left most node.
3858 */
3859 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3860 PGMR3PHYSCHUNKUNMAPCB Args;
3861 Args.pVM = pVM;
3862 Args.pChunk = NULL;
3863 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, &Args);
3864 Assert(Args.pChunk);
3865 if (Args.pChunk)
3866 {
3867 Assert(Args.pChunk->cRefs == 0);
3868 Assert(Args.pChunk->cPermRefs == 0);
3869 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3870 return Args.pChunk->Core.Key;
3871 }
3872
3873 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkFindCandidate, a);
3874 return INT32_MAX;
3875}
3876
3877
3878/**
3879 * Rendezvous callback used by pgmR3PhysUnmapChunk that unmaps a chunk
3880 *
3881 * This is only called on one of the EMTs while the other ones are waiting for
3882 * it to complete this function.
3883 *
3884 * @returns VINF_SUCCESS (VBox strict status code).
3885 * @param pVM Pointer to the VM.
3886 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
3887 * @param pvUser User pointer. Unused
3888 *
3889 */
3890static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysUnmapChunkRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
3891{
3892 int rc = VINF_SUCCESS;
3893 pgmLock(pVM);
3894 NOREF(pVCpu); NOREF(pvUser);
3895
3896 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
3897 {
3898 /* Flush the pgm pool cache; call the internal rendezvous handler as we're already in a rendezvous handler here. */
3899 /** @todo also not really efficient to unmap a chunk that contains PD
3900 * or PT pages. */
3901 pgmR3PoolClearAllRendezvous(pVM, &pVM->aCpus[0], NULL /* no need to flush the REM TLB as we already did that above */);
3902
3903 /*
3904 * Request the ring-0 part to unmap a chunk to make space in the mapping cache.
3905 */
3906 GMMMAPUNMAPCHUNKREQ Req;
3907 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
3908 Req.Hdr.cbReq = sizeof(Req);
3909 Req.pvR3 = NULL;
3910 Req.idChunkMap = NIL_GMM_CHUNKID;
3911 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
3912 if (Req.idChunkUnmap != INT32_MAX)
3913 {
3914 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
3915 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
3916 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkUnmap, a);
3917 if (RT_SUCCESS(rc))
3918 {
3919 /*
3920 * Remove the unmapped one.
3921 */
3922 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
3923 AssertRelease(pUnmappedChunk);
3924 AssertRelease(!pUnmappedChunk->cRefs);
3925 AssertRelease(!pUnmappedChunk->cPermRefs);
3926 pUnmappedChunk->pv = NULL;
3927 pUnmappedChunk->Core.Key = UINT32_MAX;
3928#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3929 MMR3HeapFree(pUnmappedChunk);
3930#else
3931 MMR3UkHeapFree(pVM, pUnmappedChunk, MM_TAG_PGM_CHUNK_MAPPING);
3932#endif
3933 pVM->pgm.s.ChunkR3Map.c--;
3934 pVM->pgm.s.cUnmappedChunks++;
3935
3936 /*
3937 * Flush dangling PGM pointers (R3 & R0 ptrs to GC physical addresses).
3938 */
3939 /** @todo We should not flush chunks which include cr3 mappings. */
3940 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
3941 {
3942 PPGMCPU pPGM = &pVM->aCpus[idCpu].pgm.s;
3943
3944 pPGM->pGst32BitPdR3 = NULL;
3945 pPGM->pGstPaePdptR3 = NULL;
3946 pPGM->pGstAmd64Pml4R3 = NULL;
3947#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
3948 pPGM->pGst32BitPdR0 = NIL_RTR0PTR;
3949 pPGM->pGstPaePdptR0 = NIL_RTR0PTR;
3950 pPGM->pGstAmd64Pml4R0 = NIL_RTR0PTR;
3951#endif
3952 for (unsigned i = 0; i < RT_ELEMENTS(pPGM->apGstPaePDsR3); i++)
3953 {
3954 pPGM->apGstPaePDsR3[i] = NULL;
3955#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE
3956 pPGM->apGstPaePDsR0[i] = NIL_RTR0PTR;
3957#endif
3958 }
3959
3960 /* Flush REM TLBs. */
3961 CPUMSetChangedFlags(&pVM->aCpus[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
3962 }
3963#ifdef VBOX_WITH_REM
3964 /* Flush REM translation blocks. */
3965 REMFlushTBs(pVM);
3966#endif
3967 }
3968 }
3969 }
3970 pgmUnlock(pVM);
3971 return rc;
3972}
3973
3974/**
3975 * Unmap a chunk to free up virtual address space (request packet handler for pgmR3PhysChunkMap)
3976 *
3977 * @returns VBox status code.
3978 * @param pVM Pointer to the VM.
3979 */
3980void pgmR3PhysUnmapChunk(PVM pVM)
3981{
3982 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysUnmapChunkRendezvous, NULL);
3983 AssertRC(rc);
3984}
3985
3986
3987/**
3988 * Maps the given chunk into the ring-3 mapping cache.
3989 *
3990 * This will call ring-0.
3991 *
3992 * @returns VBox status code.
3993 * @param pVM Pointer to the VM.
3994 * @param idChunk The chunk in question.
3995 * @param ppChunk Where to store the chunk tracking structure.
3996 *
3997 * @remarks Called from within the PGM critical section.
3998 * @remarks Can be called from any thread!
3999 */
4000int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
4001{
4002 int rc;
4003
4004 PGM_LOCK_ASSERT_OWNER(pVM);
4005
4006 /*
4007 * Move the chunk time forward.
4008 */
4009 pVM->pgm.s.ChunkR3Map.iNow++;
4010 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
4011 {
4012 pVM->pgm.s.ChunkR3Map.iNow = 4;
4013 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, NULL);
4014 }
4015
4016 /*
4017 * Allocate a new tracking structure first.
4018 */
4019#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
4020 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
4021#else
4022 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3UkHeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk), NULL);
4023#endif
4024 AssertReturn(pChunk, VERR_NO_MEMORY);
4025 pChunk->Core.Key = idChunk;
4026 pChunk->iLastUsed = pVM->pgm.s.ChunkR3Map.iNow;
4027
4028 /*
4029 * Request the ring-0 part to map the chunk in question.
4030 */
4031 GMMMAPUNMAPCHUNKREQ Req;
4032 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
4033 Req.Hdr.cbReq = sizeof(Req);
4034 Req.pvR3 = NULL;
4035 Req.idChunkMap = idChunk;
4036 Req.idChunkUnmap = NIL_GMM_CHUNKID;
4037
4038 /* Must be callable from any thread, so can't use VMMR3CallR0. */
4039 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
4040 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, NIL_VMCPUID, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
4041 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatChunkMap, a);
4042 if (RT_SUCCESS(rc))
4043 {
4044 pChunk->pv = Req.pvR3;
4045
4046 /*
4047 * If we're running out of virtual address space, then we should
4048 * unmap another chunk.
4049 *
4050 * Currently, an unmap operation requires that all other virtual CPUs
4051 * are idling and not by chance making use of the memory we're
4052 * unmapping. So, we create an async unmap operation here.
4053 *
4054 * Now, when creating or restoring a saved state this wont work very
4055 * well since we may want to restore all guest RAM + a little something.
4056 * So, we have to do the unmap synchronously. Fortunately for us
4057 * though, during these operations the other virtual CPUs are inactive
4058 * and it should be safe to do this.
4059 */
4060 /** @todo Eventually we should lock all memory when used and do
4061 * map+unmap as one kernel call without any rendezvous or
4062 * other precautions. */
4063 if (pVM->pgm.s.ChunkR3Map.c + 1 >= pVM->pgm.s.ChunkR3Map.cMax)
4064 {
4065 switch (VMR3GetState(pVM))
4066 {
4067 case VMSTATE_LOADING:
4068 case VMSTATE_SAVING:
4069 {
4070 PVMCPU pVCpu = VMMGetCpu(pVM);
4071 if ( pVCpu
4072 && pVM->pgm.s.cDeprecatedPageLocks == 0)
4073 {
4074 pgmR3PhysUnmapChunkRendezvous(pVM, pVCpu, NULL);
4075 break;
4076 }
4077 /* fall thru */
4078 }
4079 default:
4080 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysUnmapChunk, 1, pVM);
4081 AssertRC(rc);
4082 break;
4083 }
4084 }
4085
4086 /*
4087 * Update the tree. We must do this after any unmapping to make sure
4088 * the chunk we're going to return isn't unmapped by accident.
4089 */
4090 AssertPtr(Req.pvR3);
4091 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
4092 AssertRelease(fRc);
4093 pVM->pgm.s.ChunkR3Map.c++;
4094 pVM->pgm.s.cMappedChunks++;
4095 }
4096 else
4097 {
4098 /** @todo this may fail because of /proc/sys/vm/max_map_count, so we
4099 * should probably restrict ourselves on linux. */
4100 AssertRC(rc);
4101#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
4102 MMR3HeapFree(pChunk);
4103#else
4104 MMR3UkHeapFree(pVM, pChunk, MM_TAG_PGM_CHUNK_MAPPING);
4105#endif
4106 pChunk = NULL;
4107 }
4108
4109 *ppChunk = pChunk;
4110 return rc;
4111}
4112
4113
4114/**
4115 * For VMMCALLRING3_PGM_MAP_CHUNK, considered internal.
4116 *
4117 * @returns see pgmR3PhysChunkMap.
4118 * @param pVM Pointer to the VM.
4119 * @param idChunk The chunk to map.
4120 */
4121VMMR3DECL(int) PGMR3PhysChunkMap(PVM pVM, uint32_t idChunk)
4122{
4123 PPGMCHUNKR3MAP pChunk;
4124 int rc;
4125
4126 pgmLock(pVM);
4127 rc = pgmR3PhysChunkMap(pVM, idChunk, &pChunk);
4128 pgmUnlock(pVM);
4129 return rc;
4130}
4131
4132
4133/**
4134 * Invalidates the TLB for the ring-3 mapping cache.
4135 *
4136 * @param pVM Pointer to the VM.
4137 */
4138VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
4139{
4140 pgmLock(pVM);
4141 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
4142 {
4143 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
4144 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
4145 }
4146 /* The page map TLB references chunks, so invalidate that one too. */
4147 pgmPhysInvalidatePageMapTLB(pVM);
4148 pgmUnlock(pVM);
4149}
4150
4151
4152/**
4153 * Response to VMMCALLRING3_PGM_ALLOCATE_LARGE_HANDY_PAGE to allocate a large
4154 * (2MB) page for use with a nested paging PDE.
4155 *
4156 * @returns The following VBox status codes.
4157 * @retval VINF_SUCCESS on success.
4158 * @retval VINF_EM_NO_MEMORY if we're out of memory.
4159 *
4160 * @param pVM Pointer to the VM.
4161 * @param GCPhys GC physical start address of the 2 MB range
4162 */
4163VMMR3DECL(int) PGMR3PhysAllocateLargeHandyPage(PVM pVM, RTGCPHYS GCPhys)
4164{
4165#ifdef PGM_WITH_LARGE_PAGES
4166 uint64_t u64TimeStamp1, u64TimeStamp2;
4167
4168 pgmLock(pVM);
4169
4170 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
4171 u64TimeStamp1 = RTTimeMilliTS();
4172 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_LARGE_HANDY_PAGE, 0, NULL);
4173 u64TimeStamp2 = RTTimeMilliTS();
4174 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatAllocLargePage, a);
4175 if (RT_SUCCESS(rc))
4176 {
4177 Assert(pVM->pgm.s.cLargeHandyPages == 1);
4178
4179 uint32_t idPage = pVM->pgm.s.aLargeHandyPage[0].idPage;
4180 RTHCPHYS HCPhys = pVM->pgm.s.aLargeHandyPage[0].HCPhysGCPhys;
4181
4182 void *pv;
4183
4184 /* Map the large page into our address space.
4185 *
4186 * Note: assuming that within the 2 MB range:
4187 * - GCPhys + PAGE_SIZE = HCPhys + PAGE_SIZE (whole point of this exercise)
4188 * - user space mapping is continuous as well
4189 * - page id (GCPhys) + 1 = page id (GCPhys + PAGE_SIZE)
4190 */
4191 rc = pgmPhysPageMapByPageID(pVM, idPage, HCPhys, &pv);
4192 AssertLogRelMsg(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n", idPage, HCPhys, rc));
4193
4194 if (RT_SUCCESS(rc))
4195 {
4196 /*
4197 * Clear the pages.
4198 */
4199 STAM_PROFILE_START(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
4200 for (unsigned i = 0; i < _2M/PAGE_SIZE; i++)
4201 {
4202 ASMMemZeroPage(pv);
4203
4204 PPGMPAGE pPage;
4205 rc = pgmPhysGetPageEx(pVM, GCPhys, &pPage);
4206 AssertRC(rc);
4207
4208 Assert(PGM_PAGE_IS_ZERO(pPage));
4209 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatRZPageReplaceZero);
4210 pVM->pgm.s.cZeroPages--;
4211
4212 /*
4213 * Do the PGMPAGE modifications.
4214 */
4215 pVM->pgm.s.cPrivatePages++;
4216 PGM_PAGE_SET_HCPHYS(pVM, pPage, HCPhys);
4217 PGM_PAGE_SET_PAGEID(pVM, pPage, idPage);
4218 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ALLOCATED);
4219 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_PDE);
4220 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
4221 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
4222
4223 /* Somewhat dirty assumption that page ids are increasing. */
4224 idPage++;
4225
4226 HCPhys += PAGE_SIZE;
4227 GCPhys += PAGE_SIZE;
4228
4229 pv = (void *)((uintptr_t)pv + PAGE_SIZE);
4230
4231 Log3(("PGMR3PhysAllocateLargePage: idPage=%#x HCPhys=%RGp\n", idPage, HCPhys));
4232 }
4233 STAM_PROFILE_STOP(&pVM->pgm.s.CTX_SUFF(pStats)->StatClearLargePage, b);
4234
4235 /* Flush all TLBs. */
4236 PGM_INVL_ALL_VCPU_TLBS(pVM);
4237 pgmPhysInvalidatePageMapTLB(pVM);
4238 }
4239 pVM->pgm.s.cLargeHandyPages = 0;
4240 }
4241
4242 if (RT_SUCCESS(rc))
4243 {
4244 static uint32_t cTimeOut = 0;
4245 uint64_t u64TimeStampDelta = u64TimeStamp2 - u64TimeStamp1;
4246
4247 if (u64TimeStampDelta > 100)
4248 {
4249 STAM_COUNTER_INC(&pVM->pgm.s.CTX_SUFF(pStats)->StatLargePageOverflow);
4250 if ( ++cTimeOut > 10
4251 || u64TimeStampDelta > 1000 /* more than one second forces an early retirement from allocating large pages. */)
4252 {
4253 /* If repeated attempts to allocate a large page takes more than 100 ms, then we fall back to normal 4k pages.
4254 * E.g. Vista 64 tries to move memory around, which takes a huge amount of time.
4255 */
4256 LogRel(("PGMR3PhysAllocateLargePage: allocating large pages takes too long (last attempt %d ms; nr of timeouts %d); DISABLE\n", u64TimeStampDelta, cTimeOut));
4257 PGMSetLargePageUsage(pVM, false);
4258 }
4259 }
4260 else
4261 if (cTimeOut > 0)
4262 cTimeOut--;
4263 }
4264
4265 pgmUnlock(pVM);
4266 return rc;
4267#else
4268 return VERR_NOT_IMPLEMENTED;
4269#endif /* PGM_WITH_LARGE_PAGES */
4270}
4271
4272
4273/**
4274 * Response to VM_FF_PGM_NEED_HANDY_PAGES and VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES.
4275 *
4276 * This function will also work the VM_FF_PGM_NO_MEMORY force action flag, to
4277 * signal and clear the out of memory condition. When contracted, this API is
4278 * used to try clear the condition when the user wants to resume.
4279 *
4280 * @returns The following VBox status codes.
4281 * @retval VINF_SUCCESS on success. FFs cleared.
4282 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in
4283 * this case and it gets accompanied by VM_FF_PGM_NO_MEMORY.
4284 *
4285 * @param pVM Pointer to the VM.
4286 *
4287 * @remarks The VINF_EM_NO_MEMORY status is for the benefit of the FF processing
4288 * in EM.cpp and shouldn't be propagated outside TRPM, HM, EM and
4289 * pgmPhysEnsureHandyPage. There is one exception to this in the \#PF
4290 * handler.
4291 */
4292VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
4293{
4294 pgmLock(pVM);
4295
4296 /*
4297 * Allocate more pages, noting down the index of the first new page.
4298 */
4299 uint32_t iClear = pVM->pgm.s.cHandyPages;
4300 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_PGM_HANDY_PAGE_IPE);
4301 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
4302 int rcAlloc = VINF_SUCCESS;
4303 int rcSeed = VINF_SUCCESS;
4304 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
4305 while (rc == VERR_GMM_SEED_ME)
4306 {
4307 void *pvChunk;
4308 rcAlloc = rc = SUPR3PageAlloc(GMM_CHUNK_SIZE >> PAGE_SHIFT, &pvChunk);
4309 if (RT_SUCCESS(rc))
4310 {
4311 rcSeed = rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_SEED_CHUNK, (uintptr_t)pvChunk, NULL);
4312 if (RT_FAILURE(rc))
4313 SUPR3PageFree(pvChunk, GMM_CHUNK_SIZE >> PAGE_SHIFT);
4314 }
4315 if (RT_SUCCESS(rc))
4316 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
4317 }
4318
4319 /* 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) */
4320 if ( rc == VERR_GMM_HIT_VM_ACCOUNT_LIMIT
4321 && pVM->pgm.s.cHandyPages > 0)
4322 {
4323 /* Still handy pages left, so don't panic. */
4324 rc = VINF_SUCCESS;
4325 }
4326
4327 if (RT_SUCCESS(rc))
4328 {
4329 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
4330 Assert(pVM->pgm.s.cHandyPages > 0);
4331 VM_FF_CLEAR(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
4332 VM_FF_CLEAR(pVM, VM_FF_PGM_NO_MEMORY);
4333
4334#ifdef VBOX_STRICT
4335 uint32_t i;
4336 for (i = iClear; i < pVM->pgm.s.cHandyPages; i++)
4337 if ( pVM->pgm.s.aHandyPages[i].idPage == NIL_GMM_PAGEID
4338 || pVM->pgm.s.aHandyPages[i].idSharedPage != NIL_GMM_PAGEID
4339 || (pVM->pgm.s.aHandyPages[i].HCPhysGCPhys & PAGE_OFFSET_MASK))
4340 break;
4341 if (i != pVM->pgm.s.cHandyPages)
4342 {
4343 RTAssertMsg1Weak(NULL, __LINE__, __FILE__, __FUNCTION__);
4344 RTAssertMsg2Weak("i=%d iClear=%d cHandyPages=%d\n", i, iClear, pVM->pgm.s.cHandyPages);
4345 for (uint32_t j = iClear; j < pVM->pgm.s.cHandyPages; j++)
4346 RTAssertMsg2Add(("%03d: idPage=%d HCPhysGCPhys=%RHp idSharedPage=%d%\n", j,
4347 pVM->pgm.s.aHandyPages[j].idPage,
4348 pVM->pgm.s.aHandyPages[j].HCPhysGCPhys,
4349 pVM->pgm.s.aHandyPages[j].idSharedPage,
4350 j == i ? " <---" : ""));
4351 RTAssertPanic();
4352 }
4353#endif
4354 /*
4355 * Clear the pages.
4356 */
4357 while (iClear < pVM->pgm.s.cHandyPages)
4358 {
4359 PGMMPAGEDESC pPage = &pVM->pgm.s.aHandyPages[iClear];
4360 void *pv;
4361 rc = pgmPhysPageMapByPageID(pVM, pPage->idPage, pPage->HCPhysGCPhys, &pv);
4362 AssertLogRelMsgBreak(RT_SUCCESS(rc),
4363 ("%u/%u: idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc\n",
4364 iClear, pVM->pgm.s.cHandyPages, pPage->idPage, pPage->HCPhysGCPhys, rc));
4365 ASMMemZeroPage(pv);
4366 iClear++;
4367 Log3(("PGMR3PhysAllocateHandyPages: idPage=%#x HCPhys=%RGp\n", pPage->idPage, pPage->HCPhysGCPhys));
4368 }
4369 }
4370 else
4371 {
4372 uint64_t cAllocPages, cMaxPages, cBalloonPages;
4373
4374 /*
4375 * We should never get here unless there is a genuine shortage of
4376 * memory (or some internal error). Flag the error so the VM can be
4377 * suspended ASAP and the user informed. If we're totally out of
4378 * handy pages we will return failure.
4379 */
4380 /* Report the failure. */
4381 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc rcAlloc=%Rrc rcSeed=%Rrc cHandyPages=%#x\n"
4382 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
4383 rc, rcAlloc, rcSeed,
4384 pVM->pgm.s.cHandyPages,
4385 pVM->pgm.s.cAllPages,
4386 pVM->pgm.s.cPrivatePages,
4387 pVM->pgm.s.cSharedPages,
4388 pVM->pgm.s.cZeroPages));
4389
4390 if (GMMR3QueryMemoryStats(pVM, &cAllocPages, &cMaxPages, &cBalloonPages) == VINF_SUCCESS)
4391 {
4392 LogRel(("GMM: Statistics:\n"
4393 " Allocated pages: %RX64\n"
4394 " Maximum pages: %RX64\n"
4395 " Ballooned pages: %RX64\n", cAllocPages, cMaxPages, cBalloonPages));
4396 }
4397
4398 if ( rc != VERR_NO_MEMORY
4399 && rc != VERR_NO_PHYS_MEMORY
4400 && rc != VERR_LOCK_FAILED)
4401 {
4402 for (uint32_t i = 0; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
4403 {
4404 LogRel(("PGM: aHandyPages[#%#04x] = {.HCPhysGCPhys=%RHp, .idPage=%#08x, .idSharedPage=%#08x}\n",
4405 i, pVM->pgm.s.aHandyPages[i].HCPhysGCPhys, pVM->pgm.s.aHandyPages[i].idPage,
4406 pVM->pgm.s.aHandyPages[i].idSharedPage));
4407 uint32_t const idPage = pVM->pgm.s.aHandyPages[i].idPage;
4408 if (idPage != NIL_GMM_PAGEID)
4409 {
4410 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
4411 pRam;
4412 pRam = pRam->pNextR3)
4413 {
4414 uint32_t const cPages = pRam->cb >> PAGE_SHIFT;
4415 for (uint32_t iPage = 0; iPage < cPages; iPage++)
4416 if (PGM_PAGE_GET_PAGEID(&pRam->aPages[iPage]) == idPage)
4417 LogRel(("PGM: Used by %RGp %R[pgmpage] (%s)\n",
4418 pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pRam->aPages[iPage], pRam->pszDesc));
4419 }
4420 }
4421 }
4422 }
4423
4424 /* Set the FFs and adjust rc. */
4425 VM_FF_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
4426 VM_FF_SET(pVM, VM_FF_PGM_NO_MEMORY);
4427 if ( rc == VERR_NO_MEMORY
4428 || rc == VERR_NO_PHYS_MEMORY
4429 || rc == VERR_LOCK_FAILED)
4430 rc = VINF_EM_NO_MEMORY;
4431 }
4432
4433 pgmUnlock(pVM);
4434 return rc;
4435}
4436
4437
4438/**
4439 * Frees the specified RAM page and replaces it with the ZERO page.
4440 *
4441 * This is used by ballooning, remapping MMIO2, RAM reset and state loading.
4442 *
4443 * @param pVM Pointer to the VM.
4444 * @param pReq Pointer to the request.
4445 * @param pcPendingPages Where the number of pages waiting to be freed are
4446 * kept. This will normally be incremented.
4447 * @param pPage Pointer to the page structure.
4448 * @param GCPhys The guest physical address of the page, if applicable.
4449 *
4450 * @remarks The caller must own the PGM lock.
4451 */
4452int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys)
4453{
4454 /*
4455 * Assert sanity.
4456 */
4457 PGM_LOCK_ASSERT_OWNER(pVM);
4458 if (RT_UNLIKELY( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM
4459 && PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_ROM_SHADOW))
4460 {
4461 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
4462 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
4463 }
4464
4465 /** @todo What about ballooning of large pages??! */
4466 Assert( PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE
4467 && PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE_DISABLED);
4468
4469 if ( PGM_PAGE_IS_ZERO(pPage)
4470 || PGM_PAGE_IS_BALLOONED(pPage))
4471 return VINF_SUCCESS;
4472
4473 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
4474 Log3(("pgmPhysFreePage: idPage=%#x GCPhys=%RGp pPage=%R[pgmpage]\n", idPage, GCPhys, pPage));
4475 if (RT_UNLIKELY( idPage == NIL_GMM_PAGEID
4476 || idPage > GMM_PAGEID_LAST
4477 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID))
4478 {
4479 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
4480 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
4481 }
4482
4483 /* update page count stats. */
4484 if (PGM_PAGE_IS_SHARED(pPage))
4485 pVM->pgm.s.cSharedPages--;
4486 else
4487 pVM->pgm.s.cPrivatePages--;
4488 pVM->pgm.s.cZeroPages++;
4489
4490 /* Deal with write monitored pages. */
4491 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
4492 {
4493 PGM_PAGE_SET_WRITTEN_TO(pVM, pPage);
4494 pVM->pgm.s.cWrittenToPages++;
4495 }
4496
4497 /*
4498 * pPage = ZERO page.
4499 */
4500 PGM_PAGE_SET_HCPHYS(pVM, pPage, pVM->pgm.s.HCPhysZeroPg);
4501 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
4502 PGM_PAGE_SET_PAGEID(pVM, pPage, NIL_GMM_PAGEID);
4503 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4504 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
4505 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
4506
4507 /* Flush physical page map TLB entry. */
4508 pgmPhysInvalidatePageMapTLBEntry(pVM, GCPhys);
4509
4510 /*
4511 * Make sure it's not in the handy page array.
4512 */
4513 for (uint32_t i = pVM->pgm.s.cHandyPages; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
4514 {
4515 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
4516 {
4517 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
4518 break;
4519 }
4520 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
4521 {
4522 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
4523 break;
4524 }
4525 }
4526
4527 /*
4528 * Push it onto the page array.
4529 */
4530 uint32_t iPage = *pcPendingPages;
4531 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
4532 *pcPendingPages += 1;
4533
4534 pReq->aPages[iPage].idPage = idPage;
4535
4536 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
4537 return VINF_SUCCESS;
4538
4539 /*
4540 * Flush the pages.
4541 */
4542 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
4543 if (RT_SUCCESS(rc))
4544 {
4545 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
4546 *pcPendingPages = 0;
4547 }
4548 return rc;
4549}
4550
4551
4552/**
4553 * Converts a GC physical address to a HC ring-3 pointer, with some
4554 * additional checks.
4555 *
4556 * @returns VBox status code.
4557 * @retval VINF_SUCCESS on success.
4558 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
4559 * access handler of some kind.
4560 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
4561 * accesses or is odd in any way.
4562 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
4563 *
4564 * @param pVM Pointer to the VM.
4565 * @param GCPhys The GC physical address to convert. Since this is only
4566 * used for filling the REM TLB, the A20 mask must be
4567 * applied before calling this API.
4568 * @param fWritable Whether write access is required.
4569 * @param ppv Where to store the pointer corresponding to GCPhys on
4570 * success.
4571 */
4572VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
4573{
4574 pgmLock(pVM);
4575 PGM_A20_ASSERT_MASKED(VMMGetCpu(pVM), GCPhys);
4576
4577 PPGMRAMRANGE pRam;
4578 PPGMPAGE pPage;
4579 int rc = pgmPhysGetPageAndRangeEx(pVM, GCPhys, &pPage, &pRam);
4580 if (RT_SUCCESS(rc))
4581 {
4582 if (PGM_PAGE_IS_BALLOONED(pPage))
4583 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4584 else if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
4585 rc = VINF_SUCCESS;
4586 else
4587 {
4588 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
4589 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
4590 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
4591 {
4592 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
4593 * in -norawr0 mode. */
4594 if (fWritable)
4595 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4596 }
4597 else
4598 {
4599 /* Temporarily disabled physical handler(s), since the recompiler
4600 doesn't get notified when it's reset we'll have to pretend it's
4601 operating normally. */
4602 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
4603 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
4604 else
4605 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
4606 }
4607 }
4608 if (RT_SUCCESS(rc))
4609 {
4610 int rc2;
4611
4612 /* Make sure what we return is writable. */
4613 if (fWritable)
4614 switch (PGM_PAGE_GET_STATE(pPage))
4615 {
4616 case PGM_PAGE_STATE_ALLOCATED:
4617 break;
4618 case PGM_PAGE_STATE_BALLOONED:
4619 AssertFailed();
4620 break;
4621 case PGM_PAGE_STATE_ZERO:
4622 case PGM_PAGE_STATE_SHARED:
4623 if (rc == VINF_PGM_PHYS_TLB_CATCH_WRITE)
4624 break;
4625 case PGM_PAGE_STATE_WRITE_MONITORED:
4626 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)PAGE_OFFSET_MASK);
4627 AssertLogRelRCReturn(rc2, rc2);
4628 break;
4629 }
4630
4631 /* Get a ring-3 mapping of the address. */
4632 PPGMPAGER3MAPTLBE pTlbe;
4633 rc2 = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
4634 AssertLogRelRCReturn(rc2, rc2);
4635 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
4636 /** @todo mapping/locking hell; this isn't horribly efficient since
4637 * pgmPhysPageLoadIntoTlb will repeat the lookup we've done here. */
4638
4639 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
4640 }
4641 else
4642 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
4643
4644 /* else: handler catching all access, no pointer returned. */
4645 }
4646 else
4647 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
4648
4649 pgmUnlock(pVM);
4650 return rc;
4651}
4652
Note: See TracBrowser for help on using the repository browser.

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