VirtualBox

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

Last change on this file since 29297 was 29297, checked in by vboxsync, 15 years ago

Same goes for map/unmap

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 134.4 KB
Line 
1/* $Id: PGMPhys.cpp 29297 2010-05-10 12:03:50Z vboxsync $ */
2/** @file
3 * PGM - Page Manager and Monitor, Physical Memory Addressing.
4 */
5
6/*
7 * Copyright (C) 2006-2007 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/pgm.h>
24#include <VBox/iom.h>
25#include <VBox/mm.h>
26#include <VBox/stam.h>
27#include <VBox/rem.h>
28#include <VBox/pdmdev.h>
29#include "PGMInternal.h"
30#include <VBox/vm.h>
31#include "PGMInline.h"
32#include <VBox/sup.h>
33#include <VBox/param.h>
34#include <VBox/err.h>
35#include <VBox/log.h>
36#include <iprt/assert.h>
37#include <iprt/alloc.h>
38#include <iprt/asm.h>
39#include <iprt/thread.h>
40#include <iprt/string.h>
41
42
43/*******************************************************************************
44* Defined Constants And Macros *
45*******************************************************************************/
46/** The number of pages to free in one batch. */
47#define PGMPHYS_FREE_PAGE_BATCH_SIZE 128
48
49
50/*******************************************************************************
51* Internal Functions *
52*******************************************************************************/
53static DECLCALLBACK(int) pgmR3PhysRomWriteHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser);
54static int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys);
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{
91 PGMPhysRead(pVM, *pGCPhys, pvBuf, cbRead);
92 return VINF_SUCCESS;
93}
94
95
96/**
97 * Write to physical memory, external users.
98 *
99 * @returns VBox status code.
100 * @retval VINF_SUCCESS.
101 *
102 * @param pVM VM Handle.
103 * @param GCPhys Physical address to write to.
104 * @param pvBuf What to write.
105 * @param cbWrite How many bytes to write.
106 *
107 * @thread Any but EMTs.
108 */
109VMMR3DECL(int) PGMR3PhysReadExternal(PVM pVM, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead)
110{
111 VM_ASSERT_OTHER_THREAD(pVM);
112
113 AssertMsgReturn(cbRead > 0, ("don't even think about reading zero bytes!\n"), VINF_SUCCESS);
114 LogFlow(("PGMR3PhysReadExternal: %RGp %d\n", GCPhys, cbRead));
115
116 pgmLock(pVM);
117
118 /*
119 * Copy loop on ram ranges.
120 */
121 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
122 for (;;)
123 {
124 /* Find range. */
125 while (pRam && GCPhys > pRam->GCPhysLast)
126 pRam = pRam->CTX_SUFF(pNext);
127 /* Inside range or not? */
128 if (pRam && GCPhys >= pRam->GCPhys)
129 {
130 /*
131 * Must work our way thru this page by page.
132 */
133 RTGCPHYS off = GCPhys - pRam->GCPhys;
134 while (off < pRam->cb)
135 {
136 unsigned iPage = off >> PAGE_SHIFT;
137 PPGMPAGE pPage = &pRam->aPages[iPage];
138
139 /*
140 * If the page has an ALL access handler, we'll have to
141 * delegate the job to EMT.
142 */
143 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
144 {
145 pgmUnlock(pVM);
146
147 return VMR3ReqCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysReadExternalEMT, 4,
148 pVM, &GCPhys, pvBuf, cbRead);
149 }
150 Assert(!PGM_PAGE_IS_MMIO(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 const void *pvSrc;
159 int rc = pgmPhysGCPhys2CCPtrInternalReadOnly(pVM, pPage, pRam->GCPhys + off, &pvSrc);
160 if (RT_SUCCESS(rc))
161 memcpy(pvBuf, pvSrc, cb);
162 else
163 {
164 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternalReadOnly failed on %RGp / %R[pgmpage] -> %Rrc\n",
165 pRam->GCPhys + off, pPage, rc));
166 memset(pvBuf, 0xff, cb);
167 }
168
169 /* next page */
170 if (cb >= cbRead)
171 {
172 pgmUnlock(pVM);
173 return VINF_SUCCESS;
174 }
175 cbRead -= cb;
176 off += cb;
177 GCPhys += cb;
178 pvBuf = (char *)pvBuf + cb;
179 } /* walk pages in ram range. */
180 }
181 else
182 {
183 LogFlow(("PGMPhysRead: Unassigned %RGp size=%u\n", GCPhys, cbRead));
184
185 /*
186 * Unassigned address space.
187 */
188 if (!pRam)
189 break;
190 size_t cb = pRam->GCPhys - GCPhys;
191 if (cb >= cbRead)
192 {
193 memset(pvBuf, 0xff, cbRead);
194 break;
195 }
196 memset(pvBuf, 0xff, cb);
197
198 cbRead -= cb;
199 pvBuf = (char *)pvBuf + cb;
200 GCPhys += cb;
201 }
202 } /* Ram range walk */
203
204 pgmUnlock(pVM);
205
206 return VINF_SUCCESS;
207}
208
209
210/**
211 * EMT worker for PGMR3PhysWriteExternal.
212 */
213static DECLCALLBACK(int) pgmR3PhysWriteExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, const void *pvBuf, size_t cbWrite)
214{
215 /** @todo VERR_EM_NO_MEMORY */
216 PGMPhysWrite(pVM, *pGCPhys, pvBuf, cbWrite);
217 return VINF_SUCCESS;
218}
219
220
221/**
222 * Write to physical memory, external users.
223 *
224 * @returns VBox status code.
225 * @retval VINF_SUCCESS.
226 * @retval VERR_EM_NO_MEMORY.
227 *
228 * @param pVM VM Handle.
229 * @param GCPhys Physical address to write to.
230 * @param pvBuf What to write.
231 * @param cbWrite How many bytes to write.
232 * @param pszWho Who is writing. For tracking down who is writing
233 * after we've saved the state.
234 *
235 * @thread Any but EMTs.
236 */
237VMMDECL(int) PGMR3PhysWriteExternal(PVM pVM, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite, const char *pszWho)
238{
239 VM_ASSERT_OTHER_THREAD(pVM);
240
241 AssertMsg(!pVM->pgm.s.fNoMorePhysWrites,
242 ("Calling PGMR3PhysWriteExternal after pgmR3Save()! GCPhys=%RGp cbWrite=%#x pszWho=%s\n",
243 GCPhys, cbWrite, pszWho));
244 AssertMsgReturn(cbWrite > 0, ("don't even think about writing zero bytes!\n"), VINF_SUCCESS);
245 LogFlow(("PGMR3PhysWriteExternal: %RGp %d\n", GCPhys, cbWrite));
246
247 pgmLock(pVM);
248
249 /*
250 * Copy loop on ram ranges, stop when we hit something difficult.
251 */
252 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
253 for (;;)
254 {
255 /* Find range. */
256 while (pRam && GCPhys > pRam->GCPhysLast)
257 pRam = pRam->CTX_SUFF(pNext);
258 /* Inside range or not? */
259 if (pRam && GCPhys >= pRam->GCPhys)
260 {
261 /*
262 * Must work our way thru this page by page.
263 */
264 RTGCPTR off = GCPhys - pRam->GCPhys;
265 while (off < pRam->cb)
266 {
267 RTGCPTR iPage = off >> PAGE_SHIFT;
268 PPGMPAGE pPage = &pRam->aPages[iPage];
269
270 /*
271 * Is the page problematic, we have to do the work on the EMT.
272 *
273 * Allocating writable pages and access handlers are
274 * problematic, write monitored pages are simple and can be
275 * dealth with here.
276 */
277 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
278 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED)
279 {
280 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
281 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
282 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage);
283 else
284 {
285 pgmUnlock(pVM);
286
287 return VMR3ReqCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysWriteExternalEMT, 4,
288 pVM, &GCPhys, pvBuf, cbWrite);
289 }
290 }
291 Assert(!PGM_PAGE_IS_MMIO(pPage));
292
293 /*
294 * Simple stuff, go ahead.
295 */
296 size_t cb = PAGE_SIZE - (off & PAGE_OFFSET_MASK);
297 if (cb > cbWrite)
298 cb = cbWrite;
299 void *pvDst;
300 int rc = pgmPhysGCPhys2CCPtrInternal(pVM, pPage, pRam->GCPhys + off, &pvDst);
301 if (RT_SUCCESS(rc))
302 memcpy(pvDst, pvBuf, cb);
303 else
304 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternal failed on %RGp / %R[pgmpage] -> %Rrc\n",
305 pRam->GCPhys + off, pPage, rc));
306
307 /* next page */
308 if (cb >= cbWrite)
309 {
310 pgmUnlock(pVM);
311 return VINF_SUCCESS;
312 }
313
314 cbWrite -= cb;
315 off += cb;
316 GCPhys += cb;
317 pvBuf = (const char *)pvBuf + cb;
318 } /* walk pages in ram range */
319 }
320 else
321 {
322 /*
323 * Unassigned address space, skip it.
324 */
325 if (!pRam)
326 break;
327 size_t cb = pRam->GCPhys - GCPhys;
328 if (cb >= cbWrite)
329 break;
330 cbWrite -= cb;
331 pvBuf = (const char *)pvBuf + cb;
332 GCPhys += cb;
333 }
334 } /* Ram range walk */
335
336 pgmUnlock(pVM);
337 return VINF_SUCCESS;
338}
339
340
341/**
342 * VMR3ReqCall worker for PGMR3PhysGCPhys2CCPtrExternal to make pages writable.
343 *
344 * @returns see PGMR3PhysGCPhys2CCPtrExternal
345 * @param pVM The VM handle.
346 * @param pGCPhys Pointer to the guest physical address.
347 * @param ppv Where to store the mapping address.
348 * @param pLock Where to store the lock.
349 */
350static DECLCALLBACK(int) pgmR3PhysGCPhys2CCPtrDelegated(PVM pVM, PRTGCPHYS pGCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
351{
352 /*
353 * Just hand it to PGMPhysGCPhys2CCPtr and check that it's not a page with
354 * an access handler after it succeeds.
355 */
356 int rc = pgmLock(pVM);
357 AssertRCReturn(rc, rc);
358
359 rc = PGMPhysGCPhys2CCPtr(pVM, *pGCPhys, ppv, pLock);
360 if (RT_SUCCESS(rc))
361 {
362 PPGMPAGEMAPTLBE pTlbe;
363 int rc2 = pgmPhysPageQueryTlbe(&pVM->pgm.s, *pGCPhys, &pTlbe);
364 AssertFatalRC(rc2);
365 PPGMPAGE pPage = pTlbe->pPage;
366 if (PGM_PAGE_IS_MMIO(pPage))
367 {
368 PGMPhysReleasePageMappingLock(pVM, pLock);
369 rc = VERR_PGM_PHYS_PAGE_RESERVED;
370 }
371 else if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
372#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
373 || pgmPoolIsDirtyPage(pVM, *pGCPhys)
374#endif
375 )
376 {
377 /* We *must* flush any corresponding pgm pool page here, otherwise we'll
378 * not be informed about writes and keep bogus gst->shw mappings around.
379 */
380 pgmPoolFlushPageByGCPhys(pVM, *pGCPhys);
381 Assert(!PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage));
382 /** @todo r=bird: return VERR_PGM_PHYS_PAGE_RESERVED here if it still has
383 * active handlers, see the PGMR3PhysGCPhys2CCPtrExternal docs. */
384 }
385 }
386
387 pgmUnlock(pVM);
388 return rc;
389}
390
391
392/**
393 * Requests the mapping of a guest page into ring-3, external threads.
394 *
395 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
396 * release it.
397 *
398 * This API will assume your intention is to write to the page, and will
399 * therefore replace shared and zero pages. If you do not intend to modify the
400 * page, use the PGMR3PhysGCPhys2CCPtrReadOnlyExternal() API.
401 *
402 * @returns VBox status code.
403 * @retval VINF_SUCCESS on success.
404 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
405 * backing or if the page has any active access handlers. The caller
406 * must fall back on using PGMR3PhysWriteExternal.
407 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
408 *
409 * @param pVM The VM handle.
410 * @param GCPhys The guest physical address of the page that should be mapped.
411 * @param ppv Where to store the address corresponding to GCPhys.
412 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
413 *
414 * @remark Avoid calling this API from within critical sections (other than the
415 * PGM one) because of the deadlock risk when we have to delegating the
416 * task to an EMT.
417 * @thread Any.
418 */
419VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrExternal(PVM pVM, RTGCPHYS GCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
420{
421 AssertPtr(ppv);
422 AssertPtr(pLock);
423
424 Assert(VM_IS_EMT(pVM) || !PGMIsLockOwner(pVM));
425
426 int rc = pgmLock(pVM);
427 AssertRCReturn(rc, rc);
428
429 /*
430 * Query the Physical TLB entry for the page (may fail).
431 */
432 PPGMPAGEMAPTLBE pTlbe;
433 rc = pgmPhysPageQueryTlbe(&pVM->pgm.s, GCPhys, &pTlbe);
434 if (RT_SUCCESS(rc))
435 {
436 PPGMPAGE pPage = pTlbe->pPage;
437 if (PGM_PAGE_IS_MMIO(pPage))
438 rc = VERR_PGM_PHYS_PAGE_RESERVED;
439 else
440 {
441 /*
442 * If the page is shared, the zero page, or being write monitored
443 * it must be converted to an page that's writable if possible.
444 * We can only deal with write monitored pages here, the rest have
445 * to be on an EMT.
446 */
447 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
448 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED
449#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
450 || pgmPoolIsDirtyPage(pVM, GCPhys)
451#endif
452 )
453 {
454 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
455 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
456#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
457 && !pgmPoolIsDirtyPage(pVM, GCPhys)
458#endif
459 )
460 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage);
461 else
462 {
463 pgmUnlock(pVM);
464
465 return VMR3ReqCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysGCPhys2CCPtrDelegated, 4,
466 pVM, &GCPhys, ppv, pLock);
467 }
468 }
469
470 /*
471 * Now, just perform the locking and calculate the return address.
472 */
473 PPGMPAGEMAP pMap = pTlbe->pMap;
474 if (pMap)
475 pMap->cRefs++;
476
477 unsigned cLocks = PGM_PAGE_GET_WRITE_LOCKS(pPage);
478 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
479 {
480 if (cLocks == 0)
481 pVM->pgm.s.cWriteLockedPages++;
482 PGM_PAGE_INC_WRITE_LOCKS(pPage);
483 }
484 else if (cLocks != PGM_PAGE_GET_WRITE_LOCKS(pPage))
485 {
486 PGM_PAGE_INC_WRITE_LOCKS(pPage);
487 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent write locked state!\n", GCPhys, pPage));
488 if (pMap)
489 pMap->cRefs++; /* Extra ref to prevent it from going away. */
490 }
491
492 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
493 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_WRITE;
494 pLock->pvMap = pMap;
495 }
496 }
497
498 pgmUnlock(pVM);
499 return rc;
500}
501
502
503/**
504 * Requests the mapping of a guest page into ring-3, external threads.
505 *
506 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
507 * release it.
508 *
509 * @returns VBox status code.
510 * @retval VINF_SUCCESS on success.
511 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
512 * backing or if the page as an active ALL access handler. The caller
513 * must fall back on using PGMPhysRead.
514 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
515 *
516 * @param pVM The VM handle.
517 * @param GCPhys The guest physical address of the page that should be mapped.
518 * @param ppv Where to store the address corresponding to GCPhys.
519 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
520 *
521 * @remark Avoid calling this API from within critical sections (other than
522 * the PGM one) because of the deadlock risk.
523 * @thread Any.
524 */
525VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrReadOnlyExternal(PVM pVM, RTGCPHYS GCPhys, void const **ppv, PPGMPAGEMAPLOCK pLock)
526{
527 int rc = pgmLock(pVM);
528 AssertRCReturn(rc, rc);
529
530 /*
531 * Query the Physical TLB entry for the page (may fail).
532 */
533 PPGMPAGEMAPTLBE pTlbe;
534 rc = pgmPhysPageQueryTlbe(&pVM->pgm.s, GCPhys, &pTlbe);
535 if (RT_SUCCESS(rc))
536 {
537 PPGMPAGE pPage = pTlbe->pPage;
538#if 1
539 /* MMIO pages doesn't have any readable backing. */
540 if (PGM_PAGE_IS_MMIO(pPage))
541 rc = VERR_PGM_PHYS_PAGE_RESERVED;
542#else
543 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
544 rc = VERR_PGM_PHYS_PAGE_RESERVED;
545#endif
546 else
547 {
548 /*
549 * Now, just perform the locking and calculate the return address.
550 */
551 PPGMPAGEMAP pMap = pTlbe->pMap;
552 if (pMap)
553 pMap->cRefs++;
554
555 unsigned cLocks = PGM_PAGE_GET_READ_LOCKS(pPage);
556 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
557 {
558 if (cLocks == 0)
559 pVM->pgm.s.cReadLockedPages++;
560 PGM_PAGE_INC_READ_LOCKS(pPage);
561 }
562 else if (cLocks != PGM_PAGE_GET_READ_LOCKS(pPage))
563 {
564 PGM_PAGE_INC_READ_LOCKS(pPage);
565 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent readonly locked state!\n", GCPhys, pPage));
566 if (pMap)
567 pMap->cRefs++; /* Extra ref to prevent it from going away. */
568 }
569
570 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
571 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_READ;
572 pLock->pvMap = pMap;
573 }
574 }
575
576 pgmUnlock(pVM);
577 return rc;
578}
579
580
581/**
582 * Relinks the RAM ranges using the pSelfRC and pSelfR0 pointers.
583 *
584 * Called when anything was relocated.
585 *
586 * @param pVM Pointer to the shared VM structure.
587 */
588void pgmR3PhysRelinkRamRanges(PVM pVM)
589{
590 PPGMRAMRANGE pCur;
591
592#ifdef VBOX_STRICT
593 for (pCur = pVM->pgm.s.pRamRangesR3; pCur; pCur = pCur->pNextR3)
594 {
595 Assert((pCur->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pCur->pSelfR0 == MMHyperCCToR0(pVM, pCur));
596 Assert((pCur->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pCur->pSelfRC == MMHyperCCToRC(pVM, pCur));
597 Assert((pCur->GCPhys & PAGE_OFFSET_MASK) == 0);
598 Assert((pCur->GCPhysLast & PAGE_OFFSET_MASK) == PAGE_OFFSET_MASK);
599 Assert((pCur->cb & PAGE_OFFSET_MASK) == 0);
600 Assert(pCur->cb == pCur->GCPhysLast - pCur->GCPhys + 1);
601 for (PPGMRAMRANGE pCur2 = pVM->pgm.s.pRamRangesR3; pCur2; pCur2 = pCur2->pNextR3)
602 Assert( pCur2 == pCur
603 || strcmp(pCur2->pszDesc, pCur->pszDesc)); /** @todo fix MMIO ranges!! */
604 }
605#endif
606
607 pCur = pVM->pgm.s.pRamRangesR3;
608 if (pCur)
609 {
610 pVM->pgm.s.pRamRangesR0 = pCur->pSelfR0;
611 pVM->pgm.s.pRamRangesRC = pCur->pSelfRC;
612
613 for (; pCur->pNextR3; pCur = pCur->pNextR3)
614 {
615 pCur->pNextR0 = pCur->pNextR3->pSelfR0;
616 pCur->pNextRC = pCur->pNextR3->pSelfRC;
617 }
618
619 Assert(pCur->pNextR0 == NIL_RTR0PTR);
620 Assert(pCur->pNextRC == NIL_RTRCPTR);
621 }
622 else
623 {
624 Assert(pVM->pgm.s.pRamRangesR0 == NIL_RTR0PTR);
625 Assert(pVM->pgm.s.pRamRangesRC == NIL_RTRCPTR);
626 }
627 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
628}
629
630
631/**
632 * Links a new RAM range into the list.
633 *
634 * @param pVM Pointer to the shared VM structure.
635 * @param pNew Pointer to the new list entry.
636 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
637 */
638static void pgmR3PhysLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, PPGMRAMRANGE pPrev)
639{
640 AssertMsg(pNew->pszDesc, ("%RGp-%RGp\n", pNew->GCPhys, pNew->GCPhysLast));
641 Assert((pNew->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pNew->pSelfR0 == MMHyperCCToR0(pVM, pNew));
642 Assert((pNew->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pNew->pSelfRC == MMHyperCCToRC(pVM, pNew));
643
644 pgmLock(pVM);
645
646 PPGMRAMRANGE pRam = pPrev ? pPrev->pNextR3 : pVM->pgm.s.pRamRangesR3;
647 pNew->pNextR3 = pRam;
648 pNew->pNextR0 = pRam ? pRam->pSelfR0 : NIL_RTR0PTR;
649 pNew->pNextRC = pRam ? pRam->pSelfRC : NIL_RTRCPTR;
650
651 if (pPrev)
652 {
653 pPrev->pNextR3 = pNew;
654 pPrev->pNextR0 = pNew->pSelfR0;
655 pPrev->pNextRC = pNew->pSelfRC;
656 }
657 else
658 {
659 pVM->pgm.s.pRamRangesR3 = pNew;
660 pVM->pgm.s.pRamRangesR0 = pNew->pSelfR0;
661 pVM->pgm.s.pRamRangesRC = pNew->pSelfRC;
662 }
663 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
664 pgmUnlock(pVM);
665}
666
667
668/**
669 * Unlink an existing RAM range from the list.
670 *
671 * @param pVM Pointer to the shared VM structure.
672 * @param pRam Pointer to the new list entry.
673 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
674 */
675static void pgmR3PhysUnlinkRamRange2(PVM pVM, PPGMRAMRANGE pRam, PPGMRAMRANGE pPrev)
676{
677 Assert(pPrev ? pPrev->pNextR3 == pRam : pVM->pgm.s.pRamRangesR3 == pRam);
678 Assert((pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pRam->pSelfR0 == MMHyperCCToR0(pVM, pRam));
679 Assert((pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING) || pRam->pSelfRC == MMHyperCCToRC(pVM, pRam));
680
681 pgmLock(pVM);
682
683 PPGMRAMRANGE pNext = pRam->pNextR3;
684 if (pPrev)
685 {
686 pPrev->pNextR3 = pNext;
687 pPrev->pNextR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
688 pPrev->pNextRC = pNext ? pNext->pSelfRC : NIL_RTRCPTR;
689 }
690 else
691 {
692 Assert(pVM->pgm.s.pRamRangesR3 == pRam);
693 pVM->pgm.s.pRamRangesR3 = pNext;
694 pVM->pgm.s.pRamRangesR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
695 pVM->pgm.s.pRamRangesRC = pNext ? pNext->pSelfRC : NIL_RTRCPTR;
696 }
697 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
698 pgmUnlock(pVM);
699}
700
701
702/**
703 * Unlink an existing RAM range from the list.
704 *
705 * @param pVM Pointer to the shared VM structure.
706 * @param pRam Pointer to the new list entry.
707 */
708static void pgmR3PhysUnlinkRamRange(PVM pVM, PPGMRAMRANGE pRam)
709{
710 pgmLock(pVM);
711
712 /* find prev. */
713 PPGMRAMRANGE pPrev = NULL;
714 PPGMRAMRANGE pCur = pVM->pgm.s.pRamRangesR3;
715 while (pCur != pRam)
716 {
717 pPrev = pCur;
718 pCur = pCur->pNextR3;
719 }
720 AssertFatal(pCur);
721
722 pgmR3PhysUnlinkRamRange2(pVM, pRam, pPrev);
723 pgmUnlock(pVM);
724}
725
726
727/**
728 * Frees a range of pages, replacing them with ZERO pages of the specified type.
729 *
730 * @returns VBox status code.
731 * @param pVM The VM handle.
732 * @param pRam The RAM range in which the pages resides.
733 * @param GCPhys The address of the first page.
734 * @param GCPhysLast The address of the last page.
735 * @param uType The page type to replace then with.
736 */
737static int pgmR3PhysFreePageRange(PVM pVM, PPGMRAMRANGE pRam, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast, uint8_t uType)
738{
739 Assert(PGMIsLockOwner(pVM));
740 uint32_t cPendingPages = 0;
741 PGMMFREEPAGESREQ pReq;
742 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
743 AssertLogRelRCReturn(rc, rc);
744
745 /* Iterate the pages. */
746 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
747 uint32_t cPagesLeft = ((GCPhysLast - GCPhys) >> PAGE_SHIFT) + 1;
748 while (cPagesLeft-- > 0)
749 {
750 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys);
751 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
752
753 PGM_PAGE_SET_TYPE(pPageDst, uType);
754
755 GCPhys += PAGE_SIZE;
756 pPageDst++;
757 }
758
759 if (cPendingPages)
760 {
761 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
762 AssertLogRelRCReturn(rc, rc);
763 }
764 GMMR3FreePagesCleanup(pReq);
765
766 return rc;
767}
768
769/**
770 * Rendezvous callback used by PGMR3ChangeMemBalloon that changes the memory balloon size
771 *
772 * This is only called on one of the EMTs while the other ones are waiting for
773 * it to complete this function.
774 *
775 * @returns VINF_SUCCESS (VBox strict status code).
776 * @param pVM The VM handle.
777 * @param pVCpu The VMCPU for the EMT we're being called on. Unused.
778 * @param pvUser User parameter
779 */
780static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysChangeMemBalloonRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
781{
782 uintptr_t *paUser = (uintptr_t *)pvUser;
783 bool fInflate = !!paUser[0];
784 unsigned cPages = paUser[1];
785 RTGCPHYS *paPhysPage = (RTGCPHYS *)paUser[2];
786 uint32_t cPendingPages = 0;
787 PGMMFREEPAGESREQ pReq;
788 int rc;
789
790 Log(("pgmR3PhysChangeMemBalloonRendezvous: %s %x pages\n", (fInflate) ? "inflate" : "deflate", cPages));
791 pgmLock(pVM);
792
793 if (fInflate)
794 {
795 /* Flush the PGM pool cache as we might have stale references to pages that we just freed. */
796 pgmR3PoolClearAllRendezvous(pVM, pVCpu, NULL);
797
798 /* Replace pages with ZERO pages. */
799 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
800 if (RT_FAILURE(rc))
801 {
802 pgmUnlock(pVM);
803 AssertLogRelRC(rc);
804 return rc;
805 }
806
807 /* Iterate the pages. */
808 for (unsigned i = 0; i < cPages; i++)
809 {
810 PPGMPAGE pPage = pgmPhysGetPage(&pVM->pgm.s, paPhysPage[i]);
811 if ( pPage == NULL
812 || pPage->uTypeY != PGMPAGETYPE_RAM)
813 {
814 Log(("pgmR3PhysChangeMemBalloonRendezvous: invalid physical page %RGp pPage->u3Type=%d\n", paPhysPage[i], (pPage) ? pPage->uTypeY : 0));
815 break;
816 }
817
818 LogFlow(("balloon page: %RGp\n", paPhysPage[i]));
819
820 /* Flush the shadow PT if this page was previously used as a guest page table. */
821 pgmPoolFlushPageByGCPhys(pVM, paPhysPage[i]);
822
823 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, paPhysPage[i]);
824 if (RT_FAILURE(rc))
825 {
826 pgmUnlock(pVM);
827 AssertLogRelRC(rc);
828 return rc;
829 }
830 Assert(PGM_PAGE_IS_ZERO(pPage));
831 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_BALLOONED);
832 }
833
834 if (cPendingPages)
835 {
836 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
837 if (RT_FAILURE(rc))
838 {
839 pgmUnlock(pVM);
840 AssertLogRelRC(rc);
841 return rc;
842 }
843 }
844 GMMR3FreePagesCleanup(pReq);
845 }
846 else
847 {
848 /* Iterate the pages. */
849 for (unsigned i = 0; i < cPages; i++)
850 {
851 PPGMPAGE pPage = pgmPhysGetPage(&pVM->pgm.s, paPhysPage[i]);
852 AssertBreak(pPage && pPage->uTypeY == PGMPAGETYPE_RAM);
853
854 LogFlow(("Free ballooned page: %RGp\n", paPhysPage[i]));
855
856 Assert(PGM_PAGE_IS_BALLOONED(pPage));
857
858 /* Change back to zero page. */
859 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
860 }
861
862 /* Note that we currently do not map any ballooned pages in our shadow page tables, so no need to flush the pgm pool. */
863 }
864
865 /* Notify GMM about the balloon change. */
866 rc = GMMR3BalloonedPages(pVM, (fInflate) ? GMMBALLOONACTION_INFLATE : GMMBALLOONACTION_DEFLATE, cPages);
867 if (RT_SUCCESS(rc))
868 {
869 if (!fInflate)
870 {
871 Assert(pVM->pgm.s.cBalloonedPages >= cPages);
872 pVM->pgm.s.cBalloonedPages -= cPages;
873 }
874 else
875 pVM->pgm.s.cBalloonedPages += cPages;
876 }
877
878 pgmUnlock(pVM);
879
880 /* Flush the recompiler's TLB as well. */
881 for (unsigned i = 0; i < pVM->cCpus; i++)
882 CPUMSetChangedFlags(&pVM->aCpus[i], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
883
884 AssertLogRelRC(rc);
885 return rc;
886}
887
888/**
889 * Frees a range of ram pages, replacing them with ZERO pages; helper for PGMR3PhysFreeRamPages
890 *
891 * @returns VBox status code.
892 * @param pVM The VM handle.
893 * @param fInflate Inflate or deflate memory balloon
894 * @param cPages Number of pages to free
895 * @param paPhysPage Array of guest physical addresses
896 */
897static DECLCALLBACK(void) pgmR3PhysChangeMemBalloonHelper(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
898{
899 uintptr_t paUser[3];
900
901 paUser[0] = fInflate;
902 paUser[1] = cPages;
903 paUser[2] = (uintptr_t)paPhysPage;
904 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
905 AssertRC(rc);
906
907 /* Made a copy in PGMR3PhysFreeRamPages; free it here. */
908 RTMemFree(paPhysPage);
909}
910
911/**
912 * Inflate or deflate a memory balloon
913 *
914 * @returns VBox status code.
915 * @param pVM The VM handle.
916 * @param fInflate Inflate or deflate memory balloon
917 * @param cPages Number of pages to free
918 * @param paPhysPage Array of guest physical addresses
919 */
920VMMR3DECL(int) PGMR3PhysChangeMemBalloon(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
921{
922 int rc;
923
924 /* Older additions (ancient non-functioning balloon code) pass wrong physical addresses. */
925 AssertReturn(!(paPhysPage[0] & 0xfff), VERR_INVALID_PARAMETER);
926
927 /* We own the IOM lock here and could cause a deadlock by waiting for another VCPU that is blocking on the IOM lock.
928 * In the SMP case we post a request packet to postpone the job.
929 */
930 if (pVM->cCpus > 1)
931 {
932 unsigned cbPhysPage = cPages * sizeof(paPhysPage[0]);
933 RTGCPHYS *paPhysPageCopy = (RTGCPHYS *)RTMemAlloc(cbPhysPage);
934 AssertReturn(paPhysPageCopy, VERR_NO_MEMORY);
935
936 memcpy(paPhysPageCopy, paPhysPage, cbPhysPage);
937
938 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysChangeMemBalloonHelper, 4, pVM, fInflate, cPages, paPhysPageCopy);
939 AssertRC(rc);
940 }
941 else
942 {
943 uintptr_t paUser[3];
944
945 paUser[0] = fInflate;
946 paUser[1] = cPages;
947 paUser[2] = (uintptr_t)paPhysPage;
948 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
949 AssertRC(rc);
950 }
951 return rc;
952}
953
954/**
955 * Query the amount of free memory inside VMMR0
956 *
957 * @returns VBox status code.
958 * @param pVM The VM handle.
959 * @param puTotalAllocSize Pointer to total allocated memory inside VMMR0 (in bytes)
960 * @param puTotalFreeSize Pointer to total free (allocated but not used yet) memory inside VMMR0 (in bytes)
961 * @param puTotalBalloonSize Pointer to total ballooned memory inside VMMR0 (in bytes)
962 */
963VMMR3DECL(int) PGMR3QueryVMMMemoryStats(PVM pVM, uint64_t *puTotalAllocSize, uint64_t *puTotalFreeSize, uint64_t *puTotalBalloonSize)
964{
965 int rc;
966
967 uint64_t cAllocPages = 0, cFreePages = 0, cBalloonPages = 0;
968 rc = GMMR3QueryHypervisorMemoryStats(pVM, &cAllocPages, &cFreePages, &cBalloonPages);
969 AssertRCReturn(rc, rc);
970
971 if (puTotalAllocSize)
972 *puTotalAllocSize = cAllocPages * _4K;
973
974 if (puTotalFreeSize)
975 *puTotalFreeSize = cFreePages * _4K;
976
977 if (puTotalBalloonSize)
978 *puTotalBalloonSize = cBalloonPages * _4K;
979
980 return VINF_SUCCESS;
981}
982
983/**
984 * PGMR3PhysRegisterRam worker that initializes and links a RAM range.
985 *
986 * @param pVM The VM handle.
987 * @param pNew The new RAM range.
988 * @param GCPhys The address of the RAM range.
989 * @param GCPhysLast The last address of the RAM range.
990 * @param RCPtrNew The RC address if the range is floating. NIL_RTRCPTR
991 * if in HMA.
992 * @param R0PtrNew Ditto for R0.
993 * @param pszDesc The description.
994 * @param pPrev The previous RAM range (for linking).
995 */
996static void pgmR3PhysInitAndLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast,
997 RTRCPTR RCPtrNew, RTR0PTR R0PtrNew, const char *pszDesc, PPGMRAMRANGE pPrev)
998{
999 /*
1000 * Initialize the range.
1001 */
1002 pNew->pSelfR0 = R0PtrNew != NIL_RTR0PTR ? R0PtrNew : MMHyperCCToR0(pVM, pNew);
1003 pNew->pSelfRC = RCPtrNew != NIL_RTRCPTR ? RCPtrNew : MMHyperCCToRC(pVM, pNew);
1004 pNew->GCPhys = GCPhys;
1005 pNew->GCPhysLast = GCPhysLast;
1006 pNew->cb = GCPhysLast - GCPhys + 1;
1007 pNew->pszDesc = pszDesc;
1008 pNew->fFlags = RCPtrNew != NIL_RTRCPTR ? PGM_RAM_RANGE_FLAGS_FLOATING : 0;
1009 pNew->pvR3 = NULL;
1010 pNew->paLSPages = NULL;
1011
1012 uint32_t const cPages = pNew->cb >> PAGE_SHIFT;
1013 RTGCPHYS iPage = cPages;
1014 while (iPage-- > 0)
1015 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_RAM);
1016
1017 /* Update the page count stats. */
1018 pVM->pgm.s.cZeroPages += cPages;
1019 pVM->pgm.s.cAllPages += cPages;
1020
1021 /*
1022 * Link it.
1023 */
1024 pgmR3PhysLinkRamRange(pVM, pNew, pPrev);
1025}
1026
1027
1028/**
1029 * Relocate a floating RAM range.
1030 *
1031 * @copydoc FNPGMRELOCATE.
1032 */
1033static DECLCALLBACK(bool) pgmR3PhysRamRangeRelocate(PVM pVM, RTGCPTR GCPtrOld, RTGCPTR GCPtrNew, PGMRELOCATECALL enmMode, void *pvUser)
1034{
1035 PPGMRAMRANGE pRam = (PPGMRAMRANGE)pvUser;
1036 Assert(pRam->fFlags & PGM_RAM_RANGE_FLAGS_FLOATING);
1037 Assert(pRam->pSelfRC == GCPtrOld + PAGE_SIZE);
1038
1039 switch (enmMode)
1040 {
1041 case PGMRELOCATECALL_SUGGEST:
1042 return true;
1043 case PGMRELOCATECALL_RELOCATE:
1044 {
1045 /* Update myself and then relink all the ranges. */
1046 pgmLock(pVM);
1047 pRam->pSelfRC = (RTRCPTR)(GCPtrNew + PAGE_SIZE);
1048 pgmR3PhysRelinkRamRanges(pVM);
1049 pgmUnlock(pVM);
1050 return true;
1051 }
1052
1053 default:
1054 AssertFailedReturn(false);
1055 }
1056}
1057
1058
1059/**
1060 * PGMR3PhysRegisterRam worker that registers a high chunk.
1061 *
1062 * @returns VBox status code.
1063 * @param pVM The VM handle.
1064 * @param GCPhys The address of the RAM.
1065 * @param cRamPages The number of RAM pages to register.
1066 * @param cbChunk The size of the PGMRAMRANGE guest mapping.
1067 * @param iChunk The chunk number.
1068 * @param pszDesc The RAM range description.
1069 * @param ppPrev Previous RAM range pointer. In/Out.
1070 */
1071static int pgmR3PhysRegisterHighRamChunk(PVM pVM, RTGCPHYS GCPhys, uint32_t cRamPages,
1072 uint32_t cbChunk, uint32_t iChunk, const char *pszDesc,
1073 PPGMRAMRANGE *ppPrev)
1074{
1075 const char *pszDescChunk = iChunk == 0
1076 ? pszDesc
1077 : MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s (#%u)", pszDesc, iChunk + 1);
1078 AssertReturn(pszDescChunk, VERR_NO_MEMORY);
1079
1080 /*
1081 * Allocate memory for the new chunk.
1082 */
1083 size_t const cChunkPages = RT_ALIGN_Z(RT_UOFFSETOF(PGMRAMRANGE, aPages[cRamPages]), PAGE_SIZE) >> PAGE_SHIFT;
1084 PSUPPAGE paChunkPages = (PSUPPAGE)RTMemTmpAllocZ(sizeof(SUPPAGE) * cChunkPages);
1085 AssertReturn(paChunkPages, VERR_NO_TMP_MEMORY);
1086 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
1087 void *pvChunk = NULL;
1088 int rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk,
1089#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1090 VMMIsHwVirtExtForced(pVM) ? &R0PtrChunk : NULL,
1091#else
1092 NULL,
1093#endif
1094 paChunkPages);
1095 if (RT_SUCCESS(rc))
1096 {
1097#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1098 if (!VMMIsHwVirtExtForced(pVM))
1099 R0PtrChunk = NIL_RTR0PTR;
1100#else
1101 R0PtrChunk = (uintptr_t)pvChunk;
1102#endif
1103 memset(pvChunk, 0, cChunkPages << PAGE_SHIFT);
1104
1105 PPGMRAMRANGE pNew = (PPGMRAMRANGE)pvChunk;
1106
1107 /*
1108 * Create a mapping and map the pages into it.
1109 * We push these in below the HMA.
1110 */
1111 RTGCPTR GCPtrChunkMap = pVM->pgm.s.GCPtrPrevRamRangeMapping - cbChunk;
1112 rc = PGMR3MapPT(pVM, GCPtrChunkMap, cbChunk, 0 /*fFlags*/, pgmR3PhysRamRangeRelocate, pNew, pszDescChunk);
1113 if (RT_SUCCESS(rc))
1114 {
1115 pVM->pgm.s.GCPtrPrevRamRangeMapping = GCPtrChunkMap;
1116
1117 RTGCPTR const GCPtrChunk = GCPtrChunkMap + PAGE_SIZE;
1118 RTGCPTR GCPtrPage = GCPtrChunk;
1119 for (uint32_t iPage = 0; iPage < cChunkPages && RT_SUCCESS(rc); iPage++, GCPtrPage += PAGE_SIZE)
1120 rc = PGMMap(pVM, GCPtrPage, paChunkPages[iPage].Phys, PAGE_SIZE, 0);
1121 if (RT_SUCCESS(rc))
1122 {
1123 /*
1124 * Ok, init and link the range.
1125 */
1126 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhys + ((RTGCPHYS)cRamPages << PAGE_SHIFT) - 1,
1127 (RTRCPTR)GCPtrChunk, R0PtrChunk, pszDescChunk, *ppPrev);
1128 *ppPrev = pNew;
1129 }
1130 }
1131
1132 if (RT_FAILURE(rc))
1133 SUPR3PageFreeEx(pvChunk, cChunkPages);
1134 }
1135
1136 RTMemTmpFree(paChunkPages);
1137 return rc;
1138}
1139
1140
1141/**
1142 * Sets up a range RAM.
1143 *
1144 * This will check for conflicting registrations, make a resource
1145 * reservation for the memory (with GMM), and setup the per-page
1146 * tracking structures (PGMPAGE).
1147 *
1148 * @returns VBox stutus code.
1149 * @param pVM Pointer to the shared VM structure.
1150 * @param GCPhys The physical address of the RAM.
1151 * @param cb The size of the RAM.
1152 * @param pszDesc The description - not copied, so, don't free or change it.
1153 */
1154VMMR3DECL(int) PGMR3PhysRegisterRam(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, const char *pszDesc)
1155{
1156 /*
1157 * Validate input.
1158 */
1159 Log(("PGMR3PhysRegisterRam: GCPhys=%RGp cb=%RGp pszDesc=%s\n", GCPhys, cb, pszDesc));
1160 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
1161 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
1162 AssertReturn(cb > 0, VERR_INVALID_PARAMETER);
1163 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1164 AssertMsgReturn(GCPhysLast > GCPhys, ("The range wraps! GCPhys=%RGp cb=%RGp\n", GCPhys, cb), VERR_INVALID_PARAMETER);
1165 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1166 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1167
1168 pgmLock(pVM);
1169
1170 /*
1171 * Find range location and check for conflicts.
1172 * (We don't lock here because the locking by EMT is only required on update.)
1173 */
1174 PPGMRAMRANGE pPrev = NULL;
1175 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
1176 while (pRam && GCPhysLast >= pRam->GCPhys)
1177 {
1178 if ( GCPhysLast >= pRam->GCPhys
1179 && GCPhys <= pRam->GCPhysLast)
1180 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
1181 GCPhys, GCPhysLast, pszDesc,
1182 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1183 VERR_PGM_RAM_CONFLICT);
1184
1185 /* next */
1186 pPrev = pRam;
1187 pRam = pRam->pNextR3;
1188 }
1189
1190 /*
1191 * Register it with GMM (the API bitches).
1192 */
1193 const RTGCPHYS cPages = cb >> PAGE_SHIFT;
1194 int rc = MMR3IncreaseBaseReservation(pVM, cPages);
1195 if (RT_FAILURE(rc))
1196 {
1197 pgmUnlock(pVM);
1198 return rc;
1199 }
1200
1201 if ( GCPhys >= _4G
1202 && cPages > 256)
1203 {
1204 /*
1205 * The PGMRAMRANGE structures for the high memory can get very big.
1206 * In order to avoid SUPR3PageAllocEx allocation failures due to the
1207 * allocation size limit there and also to avoid being unable to find
1208 * guest mapping space for them, we split this memory up into 4MB in
1209 * (potential) raw-mode configs and 16MB chunks in forced AMD-V/VT-x
1210 * mode.
1211 *
1212 * The first and last page of each mapping are guard pages and marked
1213 * not-present. So, we've got 4186112 and 16769024 bytes available for
1214 * the PGMRAMRANGE structure.
1215 *
1216 * Note! The sizes used here will influence the saved state.
1217 */
1218 uint32_t cbChunk;
1219 uint32_t cPagesPerChunk;
1220 if (VMMIsHwVirtExtForced(pVM))
1221 {
1222 cbChunk = 16U*_1M;
1223 cPagesPerChunk = 1048048; /* max ~1048059 */
1224 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 1048048 < 16U*_1M - PAGE_SIZE * 2);
1225 }
1226 else
1227 {
1228 cbChunk = 4U*_1M;
1229 cPagesPerChunk = 261616; /* max ~261627 */
1230 AssertCompile(sizeof(PGMRAMRANGE) + sizeof(PGMPAGE) * 261616 < 4U*_1M - PAGE_SIZE * 2);
1231 }
1232 AssertRelease(RT_UOFFSETOF(PGMRAMRANGE, aPages[cPagesPerChunk]) + PAGE_SIZE * 2 <= cbChunk);
1233
1234 RTGCPHYS cPagesLeft = cPages;
1235 RTGCPHYS GCPhysChunk = GCPhys;
1236 uint32_t iChunk = 0;
1237 while (cPagesLeft > 0)
1238 {
1239 uint32_t cPagesInChunk = cPagesLeft;
1240 if (cPagesInChunk > cPagesPerChunk)
1241 cPagesInChunk = cPagesPerChunk;
1242
1243 rc = pgmR3PhysRegisterHighRamChunk(pVM, GCPhysChunk, cPagesInChunk, cbChunk, iChunk, pszDesc, &pPrev);
1244 AssertRCReturn(rc, rc);
1245
1246 /* advance */
1247 GCPhysChunk += (RTGCPHYS)cPagesInChunk << PAGE_SHIFT;
1248 cPagesLeft -= cPagesInChunk;
1249 iChunk++;
1250 }
1251 }
1252 else
1253 {
1254 /*
1255 * Allocate, initialize and link the new RAM range.
1256 */
1257 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
1258 PPGMRAMRANGE pNew;
1259 rc = MMR3HyperAllocOnceNoRel(pVM, cbRamRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
1260 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
1261
1262 pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhysLast, NIL_RTRCPTR, NIL_RTR0PTR, pszDesc, pPrev);
1263 }
1264 PGMPhysInvalidatePageMapTLB(pVM);
1265 pgmUnlock(pVM);
1266
1267 /*
1268 * Notify REM.
1269 */
1270 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_RAM);
1271
1272 return VINF_SUCCESS;
1273}
1274
1275
1276/**
1277 * Worker called by PGMR3InitFinalize if we're configured to pre-allocate RAM.
1278 *
1279 * We do this late in the init process so that all the ROM and MMIO ranges have
1280 * been registered already and we don't go wasting memory on them.
1281 *
1282 * @returns VBox status code.
1283 *
1284 * @param pVM Pointer to the shared VM structure.
1285 */
1286int pgmR3PhysRamPreAllocate(PVM pVM)
1287{
1288 Assert(pVM->pgm.s.fRamPreAlloc);
1289 Log(("pgmR3PhysRamPreAllocate: enter\n"));
1290
1291 /*
1292 * Walk the RAM ranges and allocate all RAM pages, halt at
1293 * the first allocation error.
1294 */
1295 uint64_t cPages = 0;
1296 uint64_t NanoTS = RTTimeNanoTS();
1297 pgmLock(pVM);
1298 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3; pRam; pRam = pRam->pNextR3)
1299 {
1300 PPGMPAGE pPage = &pRam->aPages[0];
1301 RTGCPHYS GCPhys = pRam->GCPhys;
1302 uint32_t cLeft = pRam->cb >> PAGE_SHIFT;
1303 while (cLeft-- > 0)
1304 {
1305 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM)
1306 {
1307 switch (PGM_PAGE_GET_STATE(pPage))
1308 {
1309 case PGM_PAGE_STATE_ZERO:
1310 {
1311 int rc = pgmPhysAllocPage(pVM, pPage, GCPhys);
1312 if (RT_FAILURE(rc))
1313 {
1314 LogRel(("PGM: RAM Pre-allocation failed at %RGp (in %s) with rc=%Rrc\n", GCPhys, pRam->pszDesc, rc));
1315 pgmUnlock(pVM);
1316 return rc;
1317 }
1318 cPages++;
1319 break;
1320 }
1321
1322 case PGM_PAGE_STATE_BALLOONED:
1323 case PGM_PAGE_STATE_ALLOCATED:
1324 case PGM_PAGE_STATE_WRITE_MONITORED:
1325 case PGM_PAGE_STATE_SHARED:
1326 /* nothing to do here. */
1327 break;
1328 }
1329 }
1330
1331 /* next */
1332 pPage++;
1333 GCPhys += PAGE_SIZE;
1334 }
1335 }
1336 pgmUnlock(pVM);
1337 NanoTS = RTTimeNanoTS() - NanoTS;
1338
1339 LogRel(("PGM: Pre-allocated %llu pages in %llu ms\n", cPages, NanoTS / 1000000));
1340 Log(("pgmR3PhysRamPreAllocate: returns VINF_SUCCESS\n"));
1341 return VINF_SUCCESS;
1342}
1343
1344
1345/**
1346 * Resets (zeros) the RAM.
1347 *
1348 * ASSUMES that the caller owns the PGM lock.
1349 *
1350 * @returns VBox status code.
1351 * @param pVM Pointer to the shared VM structure.
1352 */
1353int pgmR3PhysRamReset(PVM pVM)
1354{
1355 Assert(PGMIsLockOwner(pVM));
1356
1357 /* Reset the memory balloon. */
1358 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
1359 AssertRC(rc);
1360
1361#ifdef VBOX_WITH_PAGE_SHARING
1362 /* Clear all registered shared modules. */
1363 rc = GMMR3ResetSharedModules(pVM);
1364 AssertRC(rc);
1365#endif
1366
1367 /*
1368 * We batch up pages that should be freed instead of calling GMM for
1369 * each and every one of them.
1370 */
1371 uint32_t cPendingPages = 0;
1372 PGMMFREEPAGESREQ pReq;
1373 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1374 AssertLogRelRCReturn(rc, rc);
1375
1376 /*
1377 * Walk the ram ranges.
1378 */
1379 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3; pRam; pRam = pRam->pNextR3)
1380 {
1381 uint32_t iPage = pRam->cb >> PAGE_SHIFT;
1382 AssertMsg(((RTGCPHYS)iPage << PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << PAGE_SHIFT, pRam->cb));
1383
1384 if (!pVM->pgm.s.fRamPreAlloc)
1385 {
1386 /* Replace all RAM pages by ZERO pages. */
1387 while (iPage-- > 0)
1388 {
1389 PPGMPAGE pPage = &pRam->aPages[iPage];
1390 switch (PGM_PAGE_GET_TYPE(pPage))
1391 {
1392 case PGMPAGETYPE_RAM:
1393 /* Do not replace pages part of a 2 MB continuous range with zero pages, but zero them instead. */
1394 if (PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE)
1395 {
1396 void *pvPage;
1397 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
1398 AssertLogRelRCReturn(rc, rc);
1399 ASMMemZeroPage(pvPage);
1400 }
1401 else
1402 if (PGM_PAGE_IS_BALLOONED(pPage))
1403 {
1404 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
1405 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
1406 }
1407 else
1408 if (!PGM_PAGE_IS_ZERO(pPage))
1409 {
1410 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1411 AssertLogRelRCReturn(rc, rc);
1412 }
1413 break;
1414
1415 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
1416 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1417 break;
1418
1419 case PGMPAGETYPE_MMIO2:
1420 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
1421 case PGMPAGETYPE_ROM:
1422 case PGMPAGETYPE_MMIO:
1423 break;
1424 default:
1425 AssertFailed();
1426 }
1427 } /* for each page */
1428 }
1429 else
1430 {
1431 /* Zero the memory. */
1432 while (iPage-- > 0)
1433 {
1434 PPGMPAGE pPage = &pRam->aPages[iPage];
1435 switch (PGM_PAGE_GET_TYPE(pPage))
1436 {
1437 case PGMPAGETYPE_RAM:
1438 switch (PGM_PAGE_GET_STATE(pPage))
1439 {
1440 case PGM_PAGE_STATE_ZERO:
1441 break;
1442
1443 case PGM_PAGE_STATE_BALLOONED:
1444 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
1445 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
1446 break;
1447
1448 case PGM_PAGE_STATE_SHARED:
1449 case PGM_PAGE_STATE_WRITE_MONITORED:
1450 rc = pgmPhysPageMakeWritable(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1451 AssertLogRelRCReturn(rc, rc);
1452 /* no break */
1453
1454 case PGM_PAGE_STATE_ALLOCATED:
1455 {
1456 void *pvPage;
1457 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pvPage);
1458 AssertLogRelRCReturn(rc, rc);
1459 ASMMemZeroPage(pvPage);
1460 break;
1461 }
1462 }
1463 break;
1464
1465 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
1466 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
1467 break;
1468
1469 case PGMPAGETYPE_MMIO2:
1470 case PGMPAGETYPE_ROM_SHADOW:
1471 case PGMPAGETYPE_ROM:
1472 case PGMPAGETYPE_MMIO:
1473 break;
1474 default:
1475 AssertFailed();
1476
1477 }
1478 } /* for each page */
1479 }
1480
1481 }
1482
1483 /*
1484 * Finish off any pages pending freeing.
1485 */
1486 if (cPendingPages)
1487 {
1488 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
1489 AssertLogRelRCReturn(rc, rc);
1490 }
1491 GMMR3FreePagesCleanup(pReq);
1492
1493 return VINF_SUCCESS;
1494}
1495
1496
1497/**
1498 * This is the interface IOM is using to register an MMIO region.
1499 *
1500 * It will check for conflicts and ensure that a RAM range structure
1501 * is present before calling the PGMR3HandlerPhysicalRegister API to
1502 * register the callbacks.
1503 *
1504 * @returns VBox status code.
1505 *
1506 * @param pVM Pointer to the shared VM structure.
1507 * @param GCPhys The start of the MMIO region.
1508 * @param cb The size of the MMIO region.
1509 * @param pfnHandlerR3 The address of the ring-3 handler. (IOMR3MMIOHandler)
1510 * @param pvUserR3 The user argument for R3.
1511 * @param pfnHandlerR0 The address of the ring-0 handler. (IOMMMIOHandler)
1512 * @param pvUserR0 The user argument for R0.
1513 * @param pfnHandlerRC The address of the RC handler. (IOMMMIOHandler)
1514 * @param pvUserRC The user argument for RC.
1515 * @param pszDesc The description of the MMIO region.
1516 */
1517VMMR3DECL(int) PGMR3PhysMMIORegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb,
1518 R3PTRTYPE(PFNPGMR3PHYSHANDLER) pfnHandlerR3, RTR3PTR pvUserR3,
1519 R0PTRTYPE(PFNPGMR0PHYSHANDLER) pfnHandlerR0, RTR0PTR pvUserR0,
1520 RCPTRTYPE(PFNPGMRCPHYSHANDLER) pfnHandlerRC, RTRCPTR pvUserRC,
1521 R3PTRTYPE(const char *) pszDesc)
1522{
1523 /*
1524 * Assert on some assumption.
1525 */
1526 VM_ASSERT_EMT(pVM);
1527 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
1528 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
1529 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1530 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
1531
1532 /*
1533 * Make sure there's a RAM range structure for the region.
1534 */
1535 int rc;
1536 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1537 bool fRamExists = false;
1538 PPGMRAMRANGE pRamPrev = NULL;
1539 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
1540 while (pRam && GCPhysLast >= pRam->GCPhys)
1541 {
1542 if ( GCPhysLast >= pRam->GCPhys
1543 && GCPhys <= pRam->GCPhysLast)
1544 {
1545 /* Simplification: all within the same range. */
1546 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
1547 && GCPhysLast <= pRam->GCPhysLast,
1548 ("%RGp-%RGp (MMIO/%s) falls partly outside %RGp-%RGp (%s)\n",
1549 GCPhys, GCPhysLast, pszDesc,
1550 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1551 VERR_PGM_RAM_CONFLICT);
1552
1553 /* Check that it's all RAM or MMIO pages. */
1554 PCPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
1555 uint32_t cLeft = cb >> PAGE_SHIFT;
1556 while (cLeft-- > 0)
1557 {
1558 AssertLogRelMsgReturn( PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM
1559 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO,
1560 ("%RGp-%RGp (MMIO/%s): %RGp is not a RAM or MMIO page - type=%d desc=%s\n",
1561 GCPhys, GCPhysLast, pszDesc, PGM_PAGE_GET_TYPE(pPage), pRam->pszDesc),
1562 VERR_PGM_RAM_CONFLICT);
1563 pPage++;
1564 }
1565
1566 /* Looks good. */
1567 fRamExists = true;
1568 break;
1569 }
1570
1571 /* next */
1572 pRamPrev = pRam;
1573 pRam = pRam->pNextR3;
1574 }
1575 PPGMRAMRANGE pNew;
1576 if (fRamExists)
1577 {
1578 pNew = NULL;
1579
1580 /*
1581 * Make all the pages in the range MMIO/ZERO pages, freeing any
1582 * RAM pages currently mapped here. This might not be 100% correct
1583 * for PCI memory, but we're doing the same thing for MMIO2 pages.
1584 */
1585 rc = pgmLock(pVM);
1586 if (RT_SUCCESS(rc))
1587 {
1588 rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, PGMPAGETYPE_MMIO);
1589 pgmUnlock(pVM);
1590 }
1591 AssertRCReturn(rc, rc);
1592
1593 /* Force a PGM pool flush as guest ram references have been changed. */
1594 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
1595 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1596 {
1597 PVMCPU pVCpu = &pVM->aCpus[idCpu];
1598
1599 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
1600 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
1601 }
1602 }
1603 else
1604 {
1605 pgmLock(pVM);
1606
1607 /*
1608 * No RAM range, insert an ad hoc one.
1609 *
1610 * Note that we don't have to tell REM about this range because
1611 * PGMHandlerPhysicalRegisterEx will do that for us.
1612 */
1613 Log(("PGMR3PhysMMIORegister: Adding ad hoc MMIO range for %RGp-%RGp %s\n", GCPhys, GCPhysLast, pszDesc));
1614
1615 const uint32_t cPages = cb >> PAGE_SHIFT;
1616 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
1617 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), 16, MM_TAG_PGM_PHYS, (void **)&pNew);
1618 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
1619
1620 /* Initialize the range. */
1621 pNew->pSelfR0 = MMHyperCCToR0(pVM, pNew);
1622 pNew->pSelfRC = MMHyperCCToRC(pVM, pNew);
1623 pNew->GCPhys = GCPhys;
1624 pNew->GCPhysLast = GCPhysLast;
1625 pNew->cb = cb;
1626 pNew->pszDesc = pszDesc;
1627 pNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO;
1628 pNew->pvR3 = NULL;
1629 pNew->paLSPages = NULL;
1630
1631 uint32_t iPage = cPages;
1632 while (iPage-- > 0)
1633 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_MMIO);
1634 Assert(PGM_PAGE_GET_TYPE(&pNew->aPages[0]) == PGMPAGETYPE_MMIO);
1635
1636 /* update the page count stats. */
1637 pVM->pgm.s.cPureMmioPages += cPages;
1638 pVM->pgm.s.cAllPages += cPages;
1639
1640 /* link it */
1641 pgmR3PhysLinkRamRange(pVM, pNew, pRamPrev);
1642
1643 pgmUnlock(pVM);
1644 }
1645
1646 /*
1647 * Register the access handler.
1648 */
1649 rc = PGMHandlerPhysicalRegisterEx(pVM, PGMPHYSHANDLERTYPE_MMIO, GCPhys, GCPhysLast,
1650 pfnHandlerR3, pvUserR3,
1651 pfnHandlerR0, pvUserR0,
1652 pfnHandlerRC, pvUserRC, pszDesc);
1653 if ( RT_FAILURE(rc)
1654 && !fRamExists)
1655 {
1656 pVM->pgm.s.cPureMmioPages -= cb >> PAGE_SHIFT;
1657 pVM->pgm.s.cAllPages -= cb >> PAGE_SHIFT;
1658
1659 /* remove the ad hoc range. */
1660 pgmR3PhysUnlinkRamRange2(pVM, pNew, pRamPrev);
1661 pNew->cb = pNew->GCPhys = pNew->GCPhysLast = NIL_RTGCPHYS;
1662 MMHyperFree(pVM, pRam);
1663 }
1664 PGMPhysInvalidatePageMapTLB(pVM);
1665
1666 return rc;
1667}
1668
1669
1670/**
1671 * This is the interface IOM is using to register an MMIO region.
1672 *
1673 * It will take care of calling PGMHandlerPhysicalDeregister and clean up
1674 * any ad hoc PGMRAMRANGE left behind.
1675 *
1676 * @returns VBox status code.
1677 * @param pVM Pointer to the shared VM structure.
1678 * @param GCPhys The start of the MMIO region.
1679 * @param cb The size of the MMIO region.
1680 */
1681VMMR3DECL(int) PGMR3PhysMMIODeregister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb)
1682{
1683 VM_ASSERT_EMT(pVM);
1684
1685 /*
1686 * First deregister the handler, then check if we should remove the ram range.
1687 */
1688 int rc = PGMHandlerPhysicalDeregister(pVM, GCPhys);
1689 if (RT_SUCCESS(rc))
1690 {
1691 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1692 PPGMRAMRANGE pRamPrev = NULL;
1693 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
1694 while (pRam && GCPhysLast >= pRam->GCPhys)
1695 {
1696 /** @todo We're being a bit too careful here. rewrite. */
1697 if ( GCPhysLast == pRam->GCPhysLast
1698 && GCPhys == pRam->GCPhys)
1699 {
1700 Assert(pRam->cb == cb);
1701
1702 /*
1703 * See if all the pages are dead MMIO pages.
1704 */
1705 uint32_t const cPages = cb >> PAGE_SHIFT;
1706 bool fAllMMIO = true;
1707 uint32_t iPage = 0;
1708 uint32_t cLeft = cPages;
1709 while (cLeft-- > 0)
1710 {
1711 PPGMPAGE pPage = &pRam->aPages[iPage];
1712 if ( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_MMIO
1713 /*|| not-out-of-action later */)
1714 {
1715 fAllMMIO = false;
1716 Assert(PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_MMIO2_ALIAS_MMIO);
1717 AssertMsgFailed(("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
1718 break;
1719 }
1720 Assert(PGM_PAGE_IS_ZERO(pPage));
1721 pPage++;
1722 }
1723 if (fAllMMIO)
1724 {
1725 /*
1726 * Ad-hoc range, unlink and free it.
1727 */
1728 Log(("PGMR3PhysMMIODeregister: Freeing ad hoc MMIO range for %RGp-%RGp %s\n",
1729 GCPhys, GCPhysLast, pRam->pszDesc));
1730
1731 pVM->pgm.s.cAllPages -= cPages;
1732 pVM->pgm.s.cPureMmioPages -= cPages;
1733
1734 pgmR3PhysUnlinkRamRange2(pVM, pRam, pRamPrev);
1735 pRam->cb = pRam->GCPhys = pRam->GCPhysLast = NIL_RTGCPHYS;
1736 MMHyperFree(pVM, pRam);
1737 break;
1738 }
1739 }
1740
1741 /*
1742 * Range match? It will all be within one range (see PGMAllHandler.cpp).
1743 */
1744 if ( GCPhysLast >= pRam->GCPhys
1745 && GCPhys <= pRam->GCPhysLast)
1746 {
1747 Assert(GCPhys >= pRam->GCPhys);
1748 Assert(GCPhysLast <= pRam->GCPhysLast);
1749
1750 /*
1751 * Turn the pages back into RAM pages.
1752 */
1753 uint32_t iPage = (GCPhys - pRam->GCPhys) >> PAGE_SHIFT;
1754 uint32_t cLeft = cb >> PAGE_SHIFT;
1755 while (cLeft--)
1756 {
1757 PPGMPAGE pPage = &pRam->aPages[iPage];
1758 AssertMsg(PGM_PAGE_IS_MMIO(pPage), ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
1759 AssertMsg(PGM_PAGE_IS_ZERO(pPage), ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), pPage));
1760 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO)
1761 PGM_PAGE_SET_TYPE(pPage, PGMPAGETYPE_RAM);
1762 }
1763 break;
1764 }
1765
1766 /* next */
1767 pRamPrev = pRam;
1768 pRam = pRam->pNextR3;
1769 }
1770 }
1771
1772 /* Force a PGM pool flush as guest ram references have been changed. */
1773 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
1774 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1775 {
1776 PVMCPU pVCpu = &pVM->aCpus[idCpu];
1777
1778 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
1779 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
1780 }
1781
1782 PGMPhysInvalidatePageMapTLB(pVM);
1783 return rc;
1784}
1785
1786
1787/**
1788 * Locate a MMIO2 range.
1789 *
1790 * @returns Pointer to the MMIO2 range.
1791 * @param pVM Pointer to the shared VM structure.
1792 * @param pDevIns The device instance owning the region.
1793 * @param iRegion The region.
1794 */
1795DECLINLINE(PPGMMMIO2RANGE) pgmR3PhysMMIO2Find(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
1796{
1797 /*
1798 * Search the list.
1799 */
1800 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
1801 if ( pCur->pDevInsR3 == pDevIns
1802 && pCur->iRegion == iRegion)
1803 return pCur;
1804 return NULL;
1805}
1806
1807
1808/**
1809 * Allocate and register an MMIO2 region.
1810 *
1811 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's
1812 * RAM associated with a device. It is also non-shared memory with a
1813 * permanent ring-3 mapping and page backing (presently).
1814 *
1815 * A MMIO2 range may overlap with base memory if a lot of RAM
1816 * is configured for the VM, in which case we'll drop the base
1817 * memory pages. Presently we will make no attempt to preserve
1818 * anything that happens to be present in the base memory that
1819 * is replaced, this is of course incorrectly but it's too much
1820 * effort.
1821 *
1822 * @returns VBox status code.
1823 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the memory.
1824 * @retval VERR_ALREADY_EXISTS if the region already exists.
1825 *
1826 * @param pVM Pointer to the shared VM structure.
1827 * @param pDevIns The device instance owning the region.
1828 * @param iRegion The region number. If the MMIO2 memory is a PCI I/O region
1829 * this number has to be the number of that region. Otherwise
1830 * it can be any number safe UINT8_MAX.
1831 * @param cb The size of the region. Must be page aligned.
1832 * @param fFlags Reserved for future use, must be zero.
1833 * @param ppv Where to store the pointer to the ring-3 mapping of the memory.
1834 * @param pszDesc The description.
1835 */
1836VMMR3DECL(int) PGMR3PhysMMIO2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags, void **ppv, const char *pszDesc)
1837{
1838 /*
1839 * Validate input.
1840 */
1841 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1842 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
1843 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
1844 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
1845 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1846 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
1847 AssertReturn(pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion) == NULL, VERR_ALREADY_EXISTS);
1848 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
1849 AssertReturn(cb, VERR_INVALID_PARAMETER);
1850 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
1851
1852 const uint32_t cPages = cb >> PAGE_SHIFT;
1853 AssertLogRelReturn(((RTGCPHYS)cPages << PAGE_SHIFT) == cb, VERR_INVALID_PARAMETER);
1854 AssertLogRelReturn(cPages <= INT32_MAX / 2, VERR_NO_MEMORY);
1855
1856 /*
1857 * For the 2nd+ instance, mangle the description string so it's unique.
1858 */
1859 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
1860 {
1861 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
1862 if (!pszDesc)
1863 return VERR_NO_MEMORY;
1864 }
1865
1866 /*
1867 * Try reserve and allocate the backing memory first as this is what is
1868 * most likely to fail.
1869 */
1870 int rc = MMR3AdjustFixedReservation(pVM, cPages, pszDesc);
1871 if (RT_SUCCESS(rc))
1872 {
1873 void *pvPages;
1874 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cPages * sizeof(SUPPAGE));
1875 if (RT_SUCCESS(rc))
1876 rc = SUPR3PageAllocEx(cPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
1877 if (RT_SUCCESS(rc))
1878 {
1879 memset(pvPages, 0, cPages * PAGE_SIZE);
1880
1881 /*
1882 * Create the MMIO2 range record for it.
1883 */
1884 const size_t cbRange = RT_OFFSETOF(PGMMMIO2RANGE, RamRange.aPages[cPages]);
1885 PPGMMMIO2RANGE pNew;
1886 rc = MMR3HyperAllocOnceNoRel(pVM, cbRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
1887 AssertLogRelMsgRC(rc, ("cbRamRange=%zu\n", cbRange));
1888 if (RT_SUCCESS(rc))
1889 {
1890 pNew->pDevInsR3 = pDevIns;
1891 pNew->pvR3 = pvPages;
1892 //pNew->pNext = NULL;
1893 //pNew->fMapped = false;
1894 //pNew->fOverlapping = false;
1895 pNew->iRegion = iRegion;
1896 pNew->idSavedState = UINT8_MAX;
1897 pNew->RamRange.pSelfR0 = MMHyperCCToR0(pVM, &pNew->RamRange);
1898 pNew->RamRange.pSelfRC = MMHyperCCToRC(pVM, &pNew->RamRange);
1899 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
1900 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
1901 pNew->RamRange.pszDesc = pszDesc;
1902 pNew->RamRange.cb = cb;
1903 pNew->RamRange.fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO2;
1904 pNew->RamRange.pvR3 = pvPages;
1905 //pNew->RamRange.paLSPages = NULL;
1906
1907 uint32_t iPage = cPages;
1908 while (iPage-- > 0)
1909 {
1910 PGM_PAGE_INIT(&pNew->RamRange.aPages[iPage],
1911 paPages[iPage].Phys, NIL_GMM_PAGEID,
1912 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
1913 }
1914
1915 /* update page count stats */
1916 pVM->pgm.s.cAllPages += cPages;
1917 pVM->pgm.s.cPrivatePages += cPages;
1918
1919 /*
1920 * Link it into the list.
1921 * Since there is no particular order, just push it.
1922 */
1923 pgmLock(pVM);
1924 pNew->pNextR3 = pVM->pgm.s.pMmio2RangesR3;
1925 pVM->pgm.s.pMmio2RangesR3 = pNew;
1926 pgmUnlock(pVM);
1927
1928 *ppv = pvPages;
1929 RTMemTmpFree(paPages);
1930 PGMPhysInvalidatePageMapTLB(pVM);
1931 return VINF_SUCCESS;
1932 }
1933
1934 SUPR3PageFreeEx(pvPages, cPages);
1935 }
1936 RTMemTmpFree(paPages);
1937 MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pszDesc);
1938 }
1939 if (pDevIns->iInstance > 0)
1940 MMR3HeapFree((void *)pszDesc);
1941 return rc;
1942}
1943
1944
1945/**
1946 * Deregisters and frees an MMIO2 region.
1947 *
1948 * Any physical (and virtual) access handlers registered for the region must
1949 * be deregistered before calling this function.
1950 *
1951 * @returns VBox status code.
1952 * @param pVM Pointer to the shared VM structure.
1953 * @param pDevIns The device instance owning the region.
1954 * @param iRegion The region. If it's UINT32_MAX it'll be a wildcard match.
1955 */
1956VMMR3DECL(int) PGMR3PhysMMIO2Deregister(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
1957{
1958 /*
1959 * Validate input.
1960 */
1961 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1962 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
1963 AssertReturn(iRegion <= UINT8_MAX || iRegion == UINT32_MAX, VERR_INVALID_PARAMETER);
1964
1965 pgmLock(pVM);
1966 int rc = VINF_SUCCESS;
1967 unsigned cFound = 0;
1968 PPGMMMIO2RANGE pPrev = NULL;
1969 PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3;
1970 while (pCur)
1971 {
1972 if ( pCur->pDevInsR3 == pDevIns
1973 && ( iRegion == UINT32_MAX
1974 || pCur->iRegion == iRegion))
1975 {
1976 cFound++;
1977
1978 /*
1979 * Unmap it if it's mapped.
1980 */
1981 if (pCur->fMapped)
1982 {
1983 int rc2 = PGMR3PhysMMIO2Unmap(pVM, pCur->pDevInsR3, pCur->iRegion, pCur->RamRange.GCPhys);
1984 AssertRC(rc2);
1985 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1986 rc = rc2;
1987 }
1988
1989 /*
1990 * Unlink it
1991 */
1992 PPGMMMIO2RANGE pNext = pCur->pNextR3;
1993 if (pPrev)
1994 pPrev->pNextR3 = pNext;
1995 else
1996 pVM->pgm.s.pMmio2RangesR3 = pNext;
1997 pCur->pNextR3 = NULL;
1998
1999 /*
2000 * Free the memory.
2001 */
2002 int rc2 = SUPR3PageFreeEx(pCur->pvR3, pCur->RamRange.cb >> PAGE_SHIFT);
2003 AssertRC(rc2);
2004 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2005 rc = rc2;
2006
2007 uint32_t const cPages = pCur->RamRange.cb >> PAGE_SHIFT;
2008 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pCur->RamRange.pszDesc);
2009 AssertRC(rc2);
2010 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
2011 rc = rc2;
2012
2013 /* we're leaking hyper memory here if done at runtime. */
2014#ifdef VBOX_STRICT
2015 VMSTATE const enmState = VMR3GetState(pVM);
2016 AssertMsg( enmState == VMSTATE_POWERING_OFF
2017 || enmState == VMSTATE_POWERING_OFF_LS
2018 || enmState == VMSTATE_OFF
2019 || enmState == VMSTATE_OFF_LS
2020 || enmState == VMSTATE_DESTROYING
2021 || enmState == VMSTATE_TERMINATED
2022 || enmState == VMSTATE_CREATING
2023 , ("%s\n", VMR3GetStateName(enmState)));
2024#endif
2025 /*rc = MMHyperFree(pVM, pCur);
2026 AssertRCReturn(rc, rc); - not safe, see the alloc call. */
2027
2028
2029 /* update page count stats */
2030 pVM->pgm.s.cAllPages -= cPages;
2031 pVM->pgm.s.cPrivatePages -= cPages;
2032
2033 /* next */
2034 pCur = pNext;
2035 }
2036 else
2037 {
2038 pPrev = pCur;
2039 pCur = pCur->pNextR3;
2040 }
2041 }
2042 PGMPhysInvalidatePageMapTLB(pVM);
2043 pgmUnlock(pVM);
2044 return !cFound && iRegion != UINT32_MAX ? VERR_NOT_FOUND : rc;
2045}
2046
2047
2048/**
2049 * Maps a MMIO2 region.
2050 *
2051 * This is done when a guest / the bios / state loading changes the
2052 * PCI config. The replacing of base memory has the same restrictions
2053 * as during registration, of course.
2054 *
2055 * @returns VBox status code.
2056 *
2057 * @param pVM Pointer to the shared VM structure.
2058 * @param pDevIns The
2059 */
2060VMMR3DECL(int) PGMR3PhysMMIO2Map(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
2061{
2062 /*
2063 * Validate input
2064 */
2065 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2066 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2067 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2068 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
2069 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
2070 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2071
2072 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2073 AssertReturn(pCur, VERR_NOT_FOUND);
2074 AssertReturn(!pCur->fMapped, VERR_WRONG_ORDER);
2075 Assert(pCur->RamRange.GCPhys == NIL_RTGCPHYS);
2076 Assert(pCur->RamRange.GCPhysLast == NIL_RTGCPHYS);
2077
2078 const RTGCPHYS GCPhysLast = GCPhys + pCur->RamRange.cb - 1;
2079 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2080
2081 /*
2082 * Find our location in the ram range list, checking for
2083 * restriction we don't bother implementing yet (partially overlapping).
2084 */
2085 bool fRamExists = false;
2086 PPGMRAMRANGE pRamPrev = NULL;
2087 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2088 while (pRam && GCPhysLast >= pRam->GCPhys)
2089 {
2090 if ( GCPhys <= pRam->GCPhysLast
2091 && GCPhysLast >= pRam->GCPhys)
2092 {
2093 /* completely within? */
2094 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
2095 && GCPhysLast <= pRam->GCPhysLast,
2096 ("%RGp-%RGp (MMIO2/%s) falls partly outside %RGp-%RGp (%s)\n",
2097 GCPhys, GCPhysLast, pCur->RamRange.pszDesc,
2098 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2099 VERR_PGM_RAM_CONFLICT);
2100 fRamExists = true;
2101 break;
2102 }
2103
2104 /* next */
2105 pRamPrev = pRam;
2106 pRam = pRam->pNextR3;
2107 }
2108 if (fRamExists)
2109 {
2110 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2111 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2112 while (cPagesLeft-- > 0)
2113 {
2114 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
2115 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
2116 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pCur->RamRange.pszDesc),
2117 VERR_PGM_RAM_CONFLICT);
2118 pPage++;
2119 }
2120 }
2121 Log(("PGMR3PhysMMIO2Map: %RGp-%RGp fRamExists=%RTbool %s\n",
2122 GCPhys, GCPhysLast, fRamExists, pCur->RamRange.pszDesc));
2123
2124 /*
2125 * Make the changes.
2126 */
2127 pgmLock(pVM);
2128
2129 pCur->RamRange.GCPhys = GCPhys;
2130 pCur->RamRange.GCPhysLast = GCPhysLast;
2131 pCur->fMapped = true;
2132 pCur->fOverlapping = fRamExists;
2133
2134 if (fRamExists)
2135 {
2136/** @todo use pgmR3PhysFreePageRange here. */
2137 uint32_t cPendingPages = 0;
2138 PGMMFREEPAGESREQ pReq;
2139 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2140 AssertLogRelRCReturn(rc, rc);
2141
2142 /* replace the pages, freeing all present RAM pages. */
2143 PPGMPAGE pPageSrc = &pCur->RamRange.aPages[0];
2144 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2145 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2146 while (cPagesLeft-- > 0)
2147 {
2148 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys);
2149 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
2150
2151 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
2152 PGM_PAGE_SET_HCPHYS(pPageDst, HCPhys);
2153 PGM_PAGE_SET_TYPE(pPageDst, PGMPAGETYPE_MMIO2);
2154 PGM_PAGE_SET_STATE(pPageDst, PGM_PAGE_STATE_ALLOCATED);
2155
2156 pVM->pgm.s.cZeroPages--;
2157 GCPhys += PAGE_SIZE;
2158 pPageSrc++;
2159 pPageDst++;
2160 }
2161
2162 /* Flush physical page map TLB. */
2163 PGMPhysInvalidatePageMapTLB(pVM);
2164
2165 if (cPendingPages)
2166 {
2167 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2168 AssertLogRelRCReturn(rc, rc);
2169 }
2170 GMMR3FreePagesCleanup(pReq);
2171
2172 /* Force a PGM pool flush as guest ram references have been changed. */
2173 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
2174 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
2175 {
2176 PVMCPU pVCpu = &pVM->aCpus[idCpu];
2177
2178 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2179 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2180 }
2181
2182 pgmUnlock(pVM);
2183 }
2184 else
2185 {
2186 RTGCPHYS cb = pCur->RamRange.cb;
2187
2188 /* link in the ram range */
2189 pgmR3PhysLinkRamRange(pVM, &pCur->RamRange, pRamPrev);
2190 pgmUnlock(pVM);
2191
2192 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_MMIO2);
2193 }
2194
2195 PGMPhysInvalidatePageMapTLB(pVM);
2196 return VINF_SUCCESS;
2197}
2198
2199
2200/**
2201 * Unmaps a MMIO2 region.
2202 *
2203 * This is done when a guest / the bios / state loading changes the
2204 * PCI config. The replacing of base memory has the same restrictions
2205 * as during registration, of course.
2206 */
2207VMMR3DECL(int) PGMR3PhysMMIO2Unmap(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
2208{
2209 /*
2210 * Validate input
2211 */
2212 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2213 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2214 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2215 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
2216 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
2217 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2218
2219 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2220 AssertReturn(pCur, VERR_NOT_FOUND);
2221 AssertReturn(pCur->fMapped, VERR_WRONG_ORDER);
2222 AssertReturn(pCur->RamRange.GCPhys == GCPhys, VERR_INVALID_PARAMETER);
2223 Assert(pCur->RamRange.GCPhysLast != NIL_RTGCPHYS);
2224
2225 Log(("PGMR3PhysMMIO2Unmap: %RGp-%RGp %s\n",
2226 pCur->RamRange.GCPhys, pCur->RamRange.GCPhysLast, pCur->RamRange.pszDesc));
2227
2228 /*
2229 * Unmap it.
2230 */
2231 pgmLock(pVM);
2232
2233 RTGCPHYS GCPhysRangeREM;
2234 RTGCPHYS cbRangeREM;
2235 bool fInformREM;
2236 if (pCur->fOverlapping)
2237 {
2238 /* Restore the RAM pages we've replaced. */
2239 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2240 while (pRam->GCPhys > pCur->RamRange.GCPhysLast)
2241 pRam = pRam->pNextR3;
2242
2243 RTHCPHYS const HCPhysZeroPg = pVM->pgm.s.HCPhysZeroPg;
2244 Assert(HCPhysZeroPg != 0 && HCPhysZeroPg != NIL_RTHCPHYS);
2245 PPGMPAGE pPageDst = &pRam->aPages[(pCur->RamRange.GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2246 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
2247 while (cPagesLeft-- > 0)
2248 {
2249 PGM_PAGE_SET_HCPHYS(pPageDst, HCPhysZeroPg);
2250 PGM_PAGE_SET_TYPE(pPageDst, PGMPAGETYPE_RAM);
2251 PGM_PAGE_SET_STATE(pPageDst, PGM_PAGE_STATE_ZERO);
2252 PGM_PAGE_SET_PAGEID(pPageDst, NIL_GMM_PAGEID);
2253 PGM_PAGE_SET_PDE_TYPE(pPageDst, PGM_PAGE_PDE_TYPE_DONTCARE);
2254
2255 pVM->pgm.s.cZeroPages++;
2256 pPageDst++;
2257 }
2258
2259 /* Flush physical page map TLB. */
2260 PGMPhysInvalidatePageMapTLB(pVM);
2261
2262 GCPhysRangeREM = NIL_RTGCPHYS; /* shuts up gcc */
2263 cbRangeREM = RTGCPHYS_MAX; /* ditto */
2264 fInformREM = false;
2265 }
2266 else
2267 {
2268 GCPhysRangeREM = pCur->RamRange.GCPhys;
2269 cbRangeREM = pCur->RamRange.cb;
2270 fInformREM = true;
2271
2272 pgmR3PhysUnlinkRamRange(pVM, &pCur->RamRange);
2273 }
2274
2275 pCur->RamRange.GCPhys = NIL_RTGCPHYS;
2276 pCur->RamRange.GCPhysLast = NIL_RTGCPHYS;
2277 pCur->fOverlapping = false;
2278 pCur->fMapped = false;
2279
2280 /* Force a PGM pool flush as guest ram references have been changed. */
2281 /** todo; not entirely SMP safe; assuming for now the guest takes care of this internally (not touch mapped mmio while changing the mapping). */
2282 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
2283 {
2284 PVMCPU pVCpu = &pVM->aCpus[idCpu];
2285
2286 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2287 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2288 }
2289
2290 PGMPhysInvalidatePageMapTLB(pVM);
2291 pgmUnlock(pVM);
2292
2293 if (fInformREM)
2294 REMR3NotifyPhysRamDeregister(pVM, GCPhysRangeREM, cbRangeREM);
2295
2296 return VINF_SUCCESS;
2297}
2298
2299
2300/**
2301 * Checks if the given address is an MMIO2 base address or not.
2302 *
2303 * @returns true/false accordingly.
2304 * @param pVM Pointer to the shared VM structure.
2305 * @param pDevIns The owner of the memory, optional.
2306 * @param GCPhys The address to check.
2307 */
2308VMMR3DECL(bool) PGMR3PhysMMIO2IsBase(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys)
2309{
2310 /*
2311 * Validate input
2312 */
2313 VM_ASSERT_EMT_RETURN(pVM, false);
2314 AssertPtrReturn(pDevIns, false);
2315 AssertReturn(GCPhys != NIL_RTGCPHYS, false);
2316 AssertReturn(GCPhys != 0, false);
2317 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), false);
2318
2319 /*
2320 * Search the list.
2321 */
2322 pgmLock(pVM);
2323 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
2324 if (pCur->RamRange.GCPhys == GCPhys)
2325 {
2326 Assert(pCur->fMapped);
2327 pgmUnlock(pVM);
2328 return true;
2329 }
2330 pgmUnlock(pVM);
2331 return false;
2332}
2333
2334
2335/**
2336 * Gets the HC physical address of a page in the MMIO2 region.
2337 *
2338 * This is API is intended for MMHyper and shouldn't be called
2339 * by anyone else...
2340 *
2341 * @returns VBox status code.
2342 * @param pVM Pointer to the shared VM structure.
2343 * @param pDevIns The owner of the memory, optional.
2344 * @param iRegion The region.
2345 * @param off The page expressed an offset into the MMIO2 region.
2346 * @param pHCPhys Where to store the result.
2347 */
2348VMMR3DECL(int) PGMR3PhysMMIO2GetHCPhys(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, PRTHCPHYS pHCPhys)
2349{
2350 /*
2351 * Validate input
2352 */
2353 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2354 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2355 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2356
2357 pgmLock(pVM);
2358 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2359 AssertReturn(pCur, VERR_NOT_FOUND);
2360 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2361
2362 PCPGMPAGE pPage = &pCur->RamRange.aPages[off >> PAGE_SHIFT];
2363 *pHCPhys = PGM_PAGE_GET_HCPHYS(pPage);
2364 pgmUnlock(pVM);
2365 return VINF_SUCCESS;
2366}
2367
2368
2369/**
2370 * Maps a portion of an MMIO2 region into kernel space (host).
2371 *
2372 * The kernel mapping will become invalid when the MMIO2 memory is deregistered
2373 * or the VM is terminated.
2374 *
2375 * @return VBox status code.
2376 *
2377 * @param pVM Pointer to the shared VM structure.
2378 * @param pDevIns The device owning the MMIO2 memory.
2379 * @param iRegion The region.
2380 * @param off The offset into the region. Must be page aligned.
2381 * @param cb The number of bytes to map. Must be page aligned.
2382 * @param pszDesc Mapping description.
2383 * @param pR0Ptr Where to store the R0 address.
2384 */
2385VMMR3DECL(int) PGMR3PhysMMIO2MapKernel(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, RTGCPHYS cb,
2386 const char *pszDesc, PRTR0PTR pR0Ptr)
2387{
2388 /*
2389 * Validate input.
2390 */
2391 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2392 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2393 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2394
2395 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
2396 AssertReturn(pCur, VERR_NOT_FOUND);
2397 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2398 AssertReturn(cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2399 AssertReturn(off + cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
2400
2401 /*
2402 * Pass the request on to the support library/driver.
2403 */
2404 int rc = SUPR3PageMapKernel(pCur->pvR3, off, cb, 0, pR0Ptr);
2405
2406 return rc;
2407}
2408
2409
2410/**
2411 * Registers a ROM image.
2412 *
2413 * Shadowed ROM images requires double the amount of backing memory, so,
2414 * don't use that unless you have to. Shadowing of ROM images is process
2415 * where we can select where the reads go and where the writes go. On real
2416 * hardware the chipset provides means to configure this. We provide
2417 * PGMR3PhysProtectROM() for this purpose.
2418 *
2419 * A read-only copy of the ROM image will always be kept around while we
2420 * will allocate RAM pages for the changes on demand (unless all memory
2421 * is configured to be preallocated).
2422 *
2423 * @returns VBox status.
2424 * @param pVM VM Handle.
2425 * @param pDevIns The device instance owning the ROM.
2426 * @param GCPhys First physical address in the range.
2427 * Must be page aligned!
2428 * @param cbRange The size of the range (in bytes).
2429 * Must be page aligned!
2430 * @param pvBinary Pointer to the binary data backing the ROM image.
2431 * This must be exactly \a cbRange in size.
2432 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
2433 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
2434 * @param pszDesc Pointer to description string. This must not be freed.
2435 *
2436 * @remark There is no way to remove the rom, automatically on device cleanup or
2437 * manually from the device yet. This isn't difficult in any way, it's
2438 * just not something we expect to be necessary for a while.
2439 */
2440VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
2441 const void *pvBinary, uint32_t fFlags, const char *pszDesc)
2442{
2443 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p fFlags=%#x pszDesc=%s\n",
2444 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, fFlags, pszDesc));
2445
2446 /*
2447 * Validate input.
2448 */
2449 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2450 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
2451 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
2452 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2453 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2454 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
2455 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2456 AssertReturn(!(fFlags & ~(PGMPHYS_ROM_FLAGS_SHADOWED | PGMPHYS_ROM_FLAGS_PERMANENT_BINARY)), VERR_INVALID_PARAMETER);
2457 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
2458
2459 const uint32_t cPages = cb >> PAGE_SHIFT;
2460
2461 /*
2462 * Find the ROM location in the ROM list first.
2463 */
2464 PPGMROMRANGE pRomPrev = NULL;
2465 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
2466 while (pRom && GCPhysLast >= pRom->GCPhys)
2467 {
2468 if ( GCPhys <= pRom->GCPhysLast
2469 && GCPhysLast >= pRom->GCPhys)
2470 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
2471 GCPhys, GCPhysLast, pszDesc,
2472 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
2473 VERR_PGM_RAM_CONFLICT);
2474 /* next */
2475 pRomPrev = pRom;
2476 pRom = pRom->pNextR3;
2477 }
2478
2479 /*
2480 * Find the RAM location and check for conflicts.
2481 *
2482 * Conflict detection is a bit different than for RAM
2483 * registration since a ROM can be located within a RAM
2484 * range. So, what we have to check for is other memory
2485 * types (other than RAM that is) and that we don't span
2486 * more than one RAM range (layz).
2487 */
2488 bool fRamExists = false;
2489 PPGMRAMRANGE pRamPrev = NULL;
2490 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
2491 while (pRam && GCPhysLast >= pRam->GCPhys)
2492 {
2493 if ( GCPhys <= pRam->GCPhysLast
2494 && GCPhysLast >= pRam->GCPhys)
2495 {
2496 /* completely within? */
2497 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
2498 && GCPhysLast <= pRam->GCPhysLast,
2499 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
2500 GCPhys, GCPhysLast, pszDesc,
2501 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2502 VERR_PGM_RAM_CONFLICT);
2503 fRamExists = true;
2504 break;
2505 }
2506
2507 /* next */
2508 pRamPrev = pRam;
2509 pRam = pRam->pNextR3;
2510 }
2511 if (fRamExists)
2512 {
2513 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2514 uint32_t cPagesLeft = cPages;
2515 while (cPagesLeft-- > 0)
2516 {
2517 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
2518 ("%RGp (%R[pgmpage]) isn't a RAM page - registering %RGp-%RGp (%s).\n",
2519 pRam->GCPhys + ((RTGCPHYS)(uintptr_t)(pPage - &pRam->aPages[0]) << PAGE_SHIFT),
2520 pPage, GCPhys, GCPhysLast, pszDesc), VERR_PGM_RAM_CONFLICT);
2521 Assert(PGM_PAGE_IS_ZERO(pPage));
2522 pPage++;
2523 }
2524 }
2525
2526 /*
2527 * Update the base memory reservation if necessary.
2528 */
2529 uint32_t cExtraBaseCost = fRamExists ? 0 : cPages;
2530 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
2531 cExtraBaseCost += cPages;
2532 if (cExtraBaseCost)
2533 {
2534 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
2535 if (RT_FAILURE(rc))
2536 return rc;
2537 }
2538
2539 /*
2540 * Allocate memory for the virgin copy of the RAM.
2541 */
2542 PGMMALLOCATEPAGESREQ pReq;
2543 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cPages, GMMACCOUNT_BASE);
2544 AssertRCReturn(rc, rc);
2545
2546 for (uint32_t iPage = 0; iPage < cPages; iPage++)
2547 {
2548 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << PAGE_SHIFT);
2549 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
2550 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
2551 }
2552
2553 pgmLock(pVM);
2554 rc = GMMR3AllocatePagesPerform(pVM, pReq);
2555 pgmUnlock(pVM);
2556 if (RT_FAILURE(rc))
2557 {
2558 GMMR3AllocatePagesCleanup(pReq);
2559 return rc;
2560 }
2561
2562 /*
2563 * Allocate the new ROM range and RAM range (if necessary).
2564 */
2565 PPGMROMRANGE pRomNew;
2566 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMROMRANGE, aPages[cPages]), 0, MM_TAG_PGM_PHYS, (void **)&pRomNew);
2567 if (RT_SUCCESS(rc))
2568 {
2569 PPGMRAMRANGE pRamNew = NULL;
2570 if (!fRamExists)
2571 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), sizeof(PGMPAGE), MM_TAG_PGM_PHYS, (void **)&pRamNew);
2572 if (RT_SUCCESS(rc))
2573 {
2574 pgmLock(pVM);
2575
2576 /*
2577 * Initialize and insert the RAM range (if required).
2578 */
2579 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
2580 if (!fRamExists)
2581 {
2582 pRamNew->pSelfR0 = MMHyperCCToR0(pVM, pRamNew);
2583 pRamNew->pSelfRC = MMHyperCCToRC(pVM, pRamNew);
2584 pRamNew->GCPhys = GCPhys;
2585 pRamNew->GCPhysLast = GCPhysLast;
2586 pRamNew->cb = cb;
2587 pRamNew->pszDesc = pszDesc;
2588 pRamNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_ROM;
2589 pRamNew->pvR3 = NULL;
2590 pRamNew->paLSPages = NULL;
2591
2592 PPGMPAGE pPage = &pRamNew->aPages[0];
2593 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
2594 {
2595 PGM_PAGE_INIT(pPage,
2596 pReq->aPages[iPage].HCPhysGCPhys,
2597 pReq->aPages[iPage].idPage,
2598 PGMPAGETYPE_ROM,
2599 PGM_PAGE_STATE_ALLOCATED);
2600
2601 pRomPage->Virgin = *pPage;
2602 }
2603
2604 pVM->pgm.s.cAllPages += cPages;
2605 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
2606 }
2607 else
2608 {
2609 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
2610 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
2611 {
2612 PGM_PAGE_SET_TYPE(pPage, PGMPAGETYPE_ROM);
2613 PGM_PAGE_SET_HCPHYS(pPage, pReq->aPages[iPage].HCPhysGCPhys);
2614 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ALLOCATED);
2615 PGM_PAGE_SET_PAGEID(pPage, pReq->aPages[iPage].idPage);
2616
2617 pRomPage->Virgin = *pPage;
2618 }
2619
2620 pRamNew = pRam;
2621
2622 pVM->pgm.s.cZeroPages -= cPages;
2623 }
2624 pVM->pgm.s.cPrivatePages += cPages;
2625
2626 /* Flush physical page map TLB. */
2627 PGMPhysInvalidatePageMapTLB(pVM);
2628
2629 pgmUnlock(pVM);
2630
2631
2632 /*
2633 * !HACK ALERT! REM + (Shadowed) ROM ==> mess.
2634 *
2635 * If it's shadowed we'll register the handler after the ROM notification
2636 * so we get the access handler callbacks that we should. If it isn't
2637 * shadowed we'll do it the other way around to make REM use the built-in
2638 * ROM behavior and not the handler behavior (which is to route all access
2639 * to PGM atm).
2640 */
2641 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
2642 {
2643 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, true /* fShadowed */);
2644 rc = PGMR3HandlerPhysicalRegister(pVM,
2645 fFlags & PGMPHYS_ROM_FLAGS_SHADOWED
2646 ? PGMPHYSHANDLERTYPE_PHYSICAL_ALL
2647 : PGMPHYSHANDLERTYPE_PHYSICAL_WRITE,
2648 GCPhys, GCPhysLast,
2649 pgmR3PhysRomWriteHandler, pRomNew,
2650 NULL, "pgmPhysRomWriteHandler", MMHyperCCToR0(pVM, pRomNew),
2651 NULL, "pgmPhysRomWriteHandler", MMHyperCCToRC(pVM, pRomNew), pszDesc);
2652 }
2653 else
2654 {
2655 rc = PGMR3HandlerPhysicalRegister(pVM,
2656 fFlags & PGMPHYS_ROM_FLAGS_SHADOWED
2657 ? PGMPHYSHANDLERTYPE_PHYSICAL_ALL
2658 : PGMPHYSHANDLERTYPE_PHYSICAL_WRITE,
2659 GCPhys, GCPhysLast,
2660 pgmR3PhysRomWriteHandler, pRomNew,
2661 NULL, "pgmPhysRomWriteHandler", MMHyperCCToR0(pVM, pRomNew),
2662 NULL, "pgmPhysRomWriteHandler", MMHyperCCToRC(pVM, pRomNew), pszDesc);
2663 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, false /* fShadowed */);
2664 }
2665 if (RT_SUCCESS(rc))
2666 {
2667 pgmLock(pVM);
2668
2669 /*
2670 * Copy the image over to the virgin pages.
2671 * This must be done after linking in the RAM range.
2672 */
2673 PPGMPAGE pRamPage = &pRamNew->aPages[(GCPhys - pRamNew->GCPhys) >> PAGE_SHIFT];
2674 for (uint32_t iPage = 0; iPage < cPages; iPage++, pRamPage++)
2675 {
2676 void *pvDstPage;
2677 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << PAGE_SHIFT), &pvDstPage);
2678 if (RT_FAILURE(rc))
2679 {
2680 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
2681 break;
2682 }
2683 memcpy(pvDstPage, (const uint8_t *)pvBinary + (iPage << PAGE_SHIFT), PAGE_SIZE);
2684 }
2685 if (RT_SUCCESS(rc))
2686 {
2687 /*
2688 * Initialize the ROM range.
2689 * Note that the Virgin member of the pages has already been initialized above.
2690 */
2691 pRomNew->GCPhys = GCPhys;
2692 pRomNew->GCPhysLast = GCPhysLast;
2693 pRomNew->cb = cb;
2694 pRomNew->fFlags = fFlags;
2695 pRomNew->idSavedState = UINT8_MAX;
2696 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY ? pvBinary : NULL;
2697 pRomNew->pszDesc = pszDesc;
2698
2699 for (unsigned iPage = 0; iPage < cPages; iPage++)
2700 {
2701 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
2702 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
2703 PGM_PAGE_INIT_ZERO(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
2704 }
2705
2706 /* update the page count stats for the shadow pages. */
2707 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
2708 {
2709 pVM->pgm.s.cZeroPages += cPages;
2710 pVM->pgm.s.cAllPages += cPages;
2711 }
2712
2713 /*
2714 * Insert the ROM range, tell REM and return successfully.
2715 */
2716 pRomNew->pNextR3 = pRom;
2717 pRomNew->pNextR0 = pRom ? MMHyperCCToR0(pVM, pRom) : NIL_RTR0PTR;
2718 pRomNew->pNextRC = pRom ? MMHyperCCToRC(pVM, pRom) : NIL_RTRCPTR;
2719
2720 if (pRomPrev)
2721 {
2722 pRomPrev->pNextR3 = pRomNew;
2723 pRomPrev->pNextR0 = MMHyperCCToR0(pVM, pRomNew);
2724 pRomPrev->pNextRC = MMHyperCCToRC(pVM, pRomNew);
2725 }
2726 else
2727 {
2728 pVM->pgm.s.pRomRangesR3 = pRomNew;
2729 pVM->pgm.s.pRomRangesR0 = MMHyperCCToR0(pVM, pRomNew);
2730 pVM->pgm.s.pRomRangesRC = MMHyperCCToRC(pVM, pRomNew);
2731 }
2732
2733 PGMPhysInvalidatePageMapTLB(pVM);
2734 GMMR3AllocatePagesCleanup(pReq);
2735 pgmUnlock(pVM);
2736 return VINF_SUCCESS;
2737 }
2738
2739 /* bail out */
2740
2741 pgmUnlock(pVM);
2742 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
2743 AssertRC(rc2);
2744 pgmLock(pVM);
2745 }
2746
2747 if (!fRamExists)
2748 {
2749 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
2750 MMHyperFree(pVM, pRamNew);
2751 }
2752 }
2753 MMHyperFree(pVM, pRomNew);
2754 }
2755
2756 /** @todo Purge the mapping cache or something... */
2757 GMMR3FreeAllocatedPages(pVM, pReq);
2758 GMMR3AllocatePagesCleanup(pReq);
2759 pgmUnlock(pVM);
2760 return rc;
2761}
2762
2763
2764/**
2765 * \#PF Handler callback for ROM write accesses.
2766 *
2767 * @returns VINF_SUCCESS if the handler have carried out the operation.
2768 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
2769 * @param pVM VM Handle.
2770 * @param GCPhys The physical address the guest is writing to.
2771 * @param pvPhys The HC mapping of that address.
2772 * @param pvBuf What the guest is reading/writing.
2773 * @param cbBuf How much it's reading/writing.
2774 * @param enmAccessType The access type.
2775 * @param pvUser User argument.
2776 */
2777static DECLCALLBACK(int) pgmR3PhysRomWriteHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser)
2778{
2779 PPGMROMRANGE pRom = (PPGMROMRANGE)pvUser;
2780 const uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
2781 Assert(iPage < (pRom->cb >> PAGE_SHIFT));
2782 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
2783 Log5(("pgmR3PhysRomWriteHandler: %d %c %#08RGp %#04zx\n", pRomPage->enmProt, enmAccessType == PGMACCESSTYPE_READ ? 'R' : 'W', GCPhys, cbBuf));
2784
2785 if (enmAccessType == PGMACCESSTYPE_READ)
2786 {
2787 switch (pRomPage->enmProt)
2788 {
2789 /*
2790 * Take the default action.
2791 */
2792 case PGMROMPROT_READ_ROM_WRITE_IGNORE:
2793 case PGMROMPROT_READ_RAM_WRITE_IGNORE:
2794 case PGMROMPROT_READ_ROM_WRITE_RAM:
2795 case PGMROMPROT_READ_RAM_WRITE_RAM:
2796 return VINF_PGM_HANDLER_DO_DEFAULT;
2797
2798 default:
2799 AssertMsgFailedReturn(("enmProt=%d iPage=%d GCPhys=%RGp\n",
2800 pRom->aPages[iPage].enmProt, iPage, GCPhys),
2801 VERR_INTERNAL_ERROR);
2802 }
2803 }
2804 else
2805 {
2806 Assert(enmAccessType == PGMACCESSTYPE_WRITE);
2807 switch (pRomPage->enmProt)
2808 {
2809 /*
2810 * Ignore writes.
2811 */
2812 case PGMROMPROT_READ_ROM_WRITE_IGNORE:
2813 case PGMROMPROT_READ_RAM_WRITE_IGNORE:
2814 return VINF_SUCCESS;
2815
2816 /*
2817 * Write to the ram page.
2818 */
2819 case PGMROMPROT_READ_ROM_WRITE_RAM:
2820 case PGMROMPROT_READ_RAM_WRITE_RAM: /* yes this will get here too, it's *way* simpler that way. */
2821 {
2822 /* This should be impossible now, pvPhys doesn't work cross page anylonger. */
2823 Assert(((GCPhys - pRom->GCPhys + cbBuf - 1) >> PAGE_SHIFT) == iPage);
2824
2825 /*
2826 * Take the lock, do lazy allocation, map the page and copy the data.
2827 *
2828 * Note that we have to bypass the mapping TLB since it works on
2829 * guest physical addresses and entering the shadow page would
2830 * kind of screw things up...
2831 */
2832 int rc = pgmLock(pVM);
2833 AssertRC(rc);
2834
2835 PPGMPAGE pShadowPage = &pRomPage->Shadow;
2836 if (!PGMROMPROT_IS_ROM(pRomPage->enmProt))
2837 {
2838 pShadowPage = pgmPhysGetPage(&pVM->pgm.s, GCPhys);
2839 AssertLogRelReturn(pShadowPage, VERR_INTERNAL_ERROR);
2840 }
2841
2842 void *pvDstPage;
2843 rc = pgmPhysPageMakeWritableAndMap(pVM, pShadowPage, GCPhys & X86_PTE_PG_MASK, &pvDstPage);
2844 if (RT_SUCCESS(rc))
2845 {
2846 memcpy((uint8_t *)pvDstPage + (GCPhys & PAGE_OFFSET_MASK), pvBuf, cbBuf);
2847 pRomPage->LiveSave.fWrittenTo = true;
2848 }
2849
2850 pgmUnlock(pVM);
2851 return rc;
2852 }
2853
2854 default:
2855 AssertMsgFailedReturn(("enmProt=%d iPage=%d GCPhys=%RGp\n",
2856 pRom->aPages[iPage].enmProt, iPage, GCPhys),
2857 VERR_INTERNAL_ERROR);
2858 }
2859 }
2860}
2861
2862
2863/**
2864 * Called by PGMR3Reset to reset the shadow, switch to the virgin,
2865 * and verify that the virgin part is untouched.
2866 *
2867 * This is done after the normal memory has been cleared.
2868 *
2869 * ASSUMES that the caller owns the PGM lock.
2870 *
2871 * @param pVM The VM handle.
2872 */
2873int pgmR3PhysRomReset(PVM pVM)
2874{
2875 Assert(PGMIsLockOwner(pVM));
2876 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
2877 {
2878 const uint32_t cPages = pRom->cb >> PAGE_SHIFT;
2879
2880 if (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
2881 {
2882 /*
2883 * Reset the physical handler.
2884 */
2885 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
2886 AssertRCReturn(rc, rc);
2887
2888 /*
2889 * What we do with the shadow pages depends on the memory
2890 * preallocation option. If not enabled, we'll just throw
2891 * out all the dirty pages and replace them by the zero page.
2892 */
2893 if (!pVM->pgm.s.fRamPreAlloc)
2894 {
2895 /* Free the dirty pages. */
2896 uint32_t cPendingPages = 0;
2897 PGMMFREEPAGESREQ pReq;
2898 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2899 AssertRCReturn(rc, rc);
2900
2901 for (uint32_t iPage = 0; iPage < cPages; iPage++)
2902 if ( !PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow)
2903 && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow))
2904 {
2905 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
2906 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, &pRom->aPages[iPage].Shadow, pRom->GCPhys + (iPage << PAGE_SHIFT));
2907 AssertLogRelRCReturn(rc, rc);
2908 }
2909
2910 if (cPendingPages)
2911 {
2912 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2913 AssertLogRelRCReturn(rc, rc);
2914 }
2915 GMMR3FreePagesCleanup(pReq);
2916 }
2917 else
2918 {
2919 /* clear all the shadow pages. */
2920 for (uint32_t iPage = 0; iPage < cPages; iPage++)
2921 {
2922 Assert(!PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow) && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow));
2923 void *pvDstPage;
2924 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
2925 rc = pgmPhysPageMakeWritableAndMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pvDstPage);
2926 if (RT_FAILURE(rc))
2927 break;
2928 ASMMemZeroPage(pvDstPage);
2929 }
2930 AssertRCReturn(rc, rc);
2931 }
2932 }
2933
2934#ifdef VBOX_STRICT
2935 /*
2936 * Verify that the virgin page is unchanged if possible.
2937 */
2938 if (pRom->pvOriginal)
2939 {
2940 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
2941 for (uint32_t iPage = 0; iPage < cPages; iPage++, pbSrcPage += PAGE_SIZE)
2942 {
2943 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
2944 void const *pvDstPage;
2945 int rc = pgmPhysPageMapReadOnly(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pvDstPage);
2946 if (RT_FAILURE(rc))
2947 break;
2948 if (memcmp(pvDstPage, pbSrcPage, PAGE_SIZE))
2949 LogRel(("pgmR3PhysRomReset: %RGp rom page changed (%s) - loaded saved state?\n",
2950 GCPhys, pRom->pszDesc));
2951 }
2952 }
2953#endif
2954 }
2955
2956 return VINF_SUCCESS;
2957}
2958
2959
2960/**
2961 * Change the shadowing of a range of ROM pages.
2962 *
2963 * This is intended for implementing chipset specific memory registers
2964 * and will not be very strict about the input. It will silently ignore
2965 * any pages that are not the part of a shadowed ROM.
2966 *
2967 * @returns VBox status code.
2968 * @retval VINF_PGM_SYNC_CR3
2969 *
2970 * @param pVM Pointer to the shared VM structure.
2971 * @param GCPhys Where to start. Page aligned.
2972 * @param cb How much to change. Page aligned.
2973 * @param enmProt The new ROM protection.
2974 */
2975VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
2976{
2977 /*
2978 * Check input
2979 */
2980 if (!cb)
2981 return VINF_SUCCESS;
2982 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2983 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2984 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2985 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2986 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
2987
2988 /*
2989 * Process the request.
2990 */
2991 pgmLock(pVM);
2992 int rc = VINF_SUCCESS;
2993 bool fFlushTLB = false;
2994 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
2995 {
2996 if ( GCPhys <= pRom->GCPhysLast
2997 && GCPhysLast >= pRom->GCPhys
2998 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
2999 {
3000 /*
3001 * Iterate the relevant pages and make necessary the changes.
3002 */
3003 bool fChanges = false;
3004 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
3005 ? pRom->cb >> PAGE_SHIFT
3006 : (GCPhysLast - pRom->GCPhys + 1) >> PAGE_SHIFT;
3007 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
3008 iPage < cPages;
3009 iPage++)
3010 {
3011 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
3012 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
3013 {
3014 fChanges = true;
3015
3016 /* flush references to the page. */
3017 PPGMPAGE pRamPage = pgmPhysGetPage(&pVM->pgm.s, pRom->GCPhys + (iPage << PAGE_SHIFT));
3018 int rc2 = pgmPoolTrackFlushGCPhys(pVM, pRom->GCPhys + (iPage << PAGE_SHIFT), pRamPage, &fFlushTLB);
3019 if (rc2 != VINF_SUCCESS && (rc == VINF_SUCCESS || RT_FAILURE(rc2)))
3020 rc = rc2;
3021
3022 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
3023 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
3024
3025 *pOld = *pRamPage;
3026 *pRamPage = *pNew;
3027 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
3028 }
3029 pRomPage->enmProt = enmProt;
3030 }
3031
3032 /*
3033 * Reset the access handler if we made changes, no need
3034 * to optimize this.
3035 */
3036 if (fChanges)
3037 {
3038 int rc2 = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
3039 if (RT_FAILURE(rc2))
3040 {
3041 pgmUnlock(pVM);
3042 AssertRC(rc);
3043 return rc2;
3044 }
3045 }
3046
3047 /* Advance - cb isn't updated. */
3048 GCPhys = pRom->GCPhys + (cPages << PAGE_SHIFT);
3049 }
3050 }
3051 pgmUnlock(pVM);
3052 if (fFlushTLB)
3053 PGM_INVL_ALL_VCPU_TLBS(pVM);
3054
3055 return rc;
3056}
3057
3058
3059/**
3060 * Sets the Address Gate 20 state.
3061 *
3062 * @param pVCpu The VCPU to operate on.
3063 * @param fEnable True if the gate should be enabled.
3064 * False if the gate should be disabled.
3065 */
3066VMMDECL(void) PGMR3PhysSetA20(PVMCPU pVCpu, bool fEnable)
3067{
3068 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVCpu->pgm.s.fA20Enabled));
3069 if (pVCpu->pgm.s.fA20Enabled != fEnable)
3070 {
3071 pVCpu->pgm.s.fA20Enabled = fEnable;
3072 pVCpu->pgm.s.GCPhysA20Mask = ~(RTGCPHYS)(!fEnable << 20);
3073 REMR3A20Set(pVCpu->pVMR3, pVCpu, fEnable);
3074 /** @todo we're not handling this correctly for VT-x / AMD-V. See #2911 */
3075 }
3076}
3077
3078
3079/**
3080 * Tree enumeration callback for dealing with age rollover.
3081 * It will perform a simple compression of the current age.
3082 */
3083static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
3084{
3085 Assert(PGMIsLockOwner((PVM)pvUser));
3086 /* Age compression - ASSUMES iNow == 4. */
3087 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3088 if (pChunk->iAge >= UINT32_C(0xffffff00))
3089 pChunk->iAge = 3;
3090 else if (pChunk->iAge >= UINT32_C(0xfffff000))
3091 pChunk->iAge = 2;
3092 else if (pChunk->iAge)
3093 pChunk->iAge = 1;
3094 else /* iAge = 0 */
3095 pChunk->iAge = 4;
3096
3097 /* reinsert */
3098 PVM pVM = (PVM)pvUser;
3099 RTAvllU32Remove(&pVM->pgm.s.ChunkR3Map.pAgeTree, pChunk->AgeCore.Key);
3100 pChunk->AgeCore.Key = pChunk->iAge;
3101 RTAvllU32Insert(&pVM->pgm.s.ChunkR3Map.pAgeTree, &pChunk->AgeCore);
3102 return 0;
3103}
3104
3105
3106/**
3107 * Tree enumeration callback that updates the chunks that have
3108 * been used since the last
3109 */
3110static DECLCALLBACK(int) pgmR3PhysChunkAgeingCallback(PAVLU32NODECORE pNode, void *pvUser)
3111{
3112 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
3113 if (!pChunk->iAge)
3114 {
3115 PVM pVM = (PVM)pvUser;
3116 RTAvllU32Remove(&pVM->pgm.s.ChunkR3Map.pAgeTree, pChunk->AgeCore.Key);
3117 pChunk->AgeCore.Key = pChunk->iAge = pVM->pgm.s.ChunkR3Map.iNow;
3118 RTAvllU32Insert(&pVM->pgm.s.ChunkR3Map.pAgeTree, &pChunk->AgeCore);
3119 }
3120
3121 return 0;
3122}
3123
3124
3125/**
3126 * Performs ageing of the ring-3 chunk mappings.
3127 *
3128 * @param pVM The VM handle.
3129 */
3130VMMR3DECL(void) PGMR3PhysChunkAgeing(PVM pVM)
3131{
3132 pgmLock(pVM);
3133 pVM->pgm.s.ChunkR3Map.AgeingCountdown = RT_MIN(pVM->pgm.s.ChunkR3Map.cMax / 4, 1024);
3134 pVM->pgm.s.ChunkR3Map.iNow++;
3135 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
3136 {
3137 pVM->pgm.s.ChunkR3Map.iNow = 4;
3138 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, pVM);
3139 }
3140 else
3141 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingCallback, pVM);
3142 pgmUnlock(pVM);
3143}
3144
3145
3146/**
3147 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
3148 */
3149typedef struct PGMR3PHYSCHUNKUNMAPCB
3150{
3151 PVM pVM; /**< The VM handle. */
3152 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
3153} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
3154
3155
3156/**
3157 * Callback used to find the mapping that's been unused for
3158 * the longest time.
3159 */
3160static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLLU32NODECORE pNode, void *pvUser)
3161{
3162 do
3163 {
3164 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)((uint8_t *)pNode - RT_OFFSETOF(PGMCHUNKR3MAP, AgeCore));
3165 if ( pChunk->iAge
3166 && !pChunk->cRefs)
3167 {
3168 /*
3169 * Check that it's not in any of the TLBs.
3170 */
3171 PVM pVM = ((PPGMR3PHYSCHUNKUNMAPCB)pvUser)->pVM;
3172 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
3173 if (pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk == pChunk)
3174 {
3175 pChunk = NULL;
3176 break;
3177 }
3178 if (pChunk)
3179 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbHC.aEntries); i++)
3180 if (pVM->pgm.s.PhysTlbHC.aEntries[i].pMap == pChunk)
3181 {
3182 pChunk = NULL;
3183 break;
3184 }
3185 if (pChunk)
3186 {
3187 ((PPGMR3PHYSCHUNKUNMAPCB)pvUser)->pChunk = pChunk;
3188 return 1; /* done */
3189 }
3190 }
3191
3192 /* next with the same age - this version of the AVL API doesn't enumerate the list, so we have to do it. */
3193 pNode = pNode->pList;
3194 } while (pNode);
3195 return 0;
3196}
3197
3198
3199/**
3200 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
3201 *
3202 * The candidate will not be part of any TLBs, so no need to flush
3203 * anything afterwards.
3204 *
3205 * @returns Chunk id.
3206 * @param pVM The VM handle.
3207 */
3208static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
3209{
3210 Assert(PGMIsLockOwner(pVM));
3211
3212 /*
3213 * Do tree ageing first?
3214 */
3215 if (pVM->pgm.s.ChunkR3Map.AgeingCountdown-- == 0)
3216 PGMR3PhysChunkAgeing(pVM);
3217
3218 /*
3219 * Enumerate the age tree starting with the left most node.
3220 */
3221 PGMR3PHYSCHUNKUNMAPCB Args;
3222 Args.pVM = pVM;
3223 Args.pChunk = NULL;
3224 if (RTAvllU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pAgeTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, pVM))
3225 return Args.pChunk->Core.Key;
3226 return INT32_MAX;
3227}
3228
3229
3230/**
3231 * Maps the given chunk into the ring-3 mapping cache.
3232 *
3233 * This will call ring-0.
3234 *
3235 * @returns VBox status code.
3236 * @param pVM The VM handle.
3237 * @param idChunk The chunk in question.
3238 * @param ppChunk Where to store the chunk tracking structure.
3239 *
3240 * @remarks Called from within the PGM critical section.
3241 */
3242int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
3243{
3244 int rc;
3245
3246 Assert(PGMIsLockOwner(pVM));
3247 /*
3248 * Allocate a new tracking structure first.
3249 */
3250#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3251 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAlloc(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
3252#else
3253 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3UkHeapAlloc(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk), NULL);
3254#endif
3255 AssertReturn(pChunk, VERR_NO_MEMORY);
3256 pChunk->Core.Key = idChunk;
3257 pChunk->AgeCore.Key = pVM->pgm.s.ChunkR3Map.iNow;
3258 pChunk->iAge = 0;
3259 pChunk->cRefs = 0;
3260 pChunk->cPermRefs = 0;
3261 pChunk->pv = NULL;
3262
3263 /*
3264 * Request the ring-0 part to map the chunk in question and if
3265 * necessary unmap another one to make space in the mapping cache.
3266 */
3267 GMMMAPUNMAPCHUNKREQ Req;
3268 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
3269 Req.Hdr.cbReq = sizeof(Req);
3270 Req.pvR3 = NULL;
3271 Req.idChunkMap = idChunk;
3272 Req.idChunkUnmap = NIL_GMM_CHUNKID;
3273 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
3274 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
3275/** @todo This is wrong. Any thread in the VM process should be able to do this,
3276 * there are depenenecies on this. What currently saves the day is that
3277 * we don't unmap anything and that all non-zero memory will therefore
3278 * be present when non-EMTs tries to access it. */
3279 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
3280 if (RT_SUCCESS(rc))
3281 {
3282 /*
3283 * Update the tree.
3284 */
3285 /* insert the new one. */
3286 AssertPtr(Req.pvR3);
3287 pChunk->pv = Req.pvR3;
3288 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
3289 AssertRelease(fRc);
3290 pVM->pgm.s.ChunkR3Map.c++;
3291
3292 fRc = RTAvllU32Insert(&pVM->pgm.s.ChunkR3Map.pAgeTree, &pChunk->AgeCore);
3293 AssertRelease(fRc);
3294
3295 /* remove the unmapped one. */
3296 if (Req.idChunkUnmap != NIL_GMM_CHUNKID)
3297 {
3298 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
3299 AssertRelease(pUnmappedChunk);
3300 pUnmappedChunk->pv = NULL;
3301 pUnmappedChunk->Core.Key = UINT32_MAX;
3302#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3303 MMR3HeapFree(pUnmappedChunk);
3304#else
3305 MMR3UkHeapFree(pVM, pUnmappedChunk, MM_TAG_PGM_CHUNK_MAPPING);
3306#endif
3307 pVM->pgm.s.ChunkR3Map.c--;
3308
3309 /* Chunk removed, so clear the page map TBL as well (might still be referenced). */
3310 PGMPhysInvalidatePageMapTLB(pVM);
3311 }
3312 }
3313 else
3314 {
3315 AssertRC(rc);
3316#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3317 MMR3HeapFree(pChunk);
3318#else
3319 MMR3UkHeapFree(pVM, pChunk, MM_TAG_PGM_CHUNK_MAPPING);
3320#endif
3321 pChunk = NULL;
3322 }
3323
3324 *ppChunk = pChunk;
3325 return rc;
3326}
3327
3328
3329/**
3330 * For VMMCALLRING3_PGM_MAP_CHUNK, considered internal.
3331 *
3332 * @returns see pgmR3PhysChunkMap.
3333 * @param pVM The VM handle.
3334 * @param idChunk The chunk to map.
3335 */
3336VMMR3DECL(int) PGMR3PhysChunkMap(PVM pVM, uint32_t idChunk)
3337{
3338 PPGMCHUNKR3MAP pChunk;
3339 int rc;
3340
3341 pgmLock(pVM);
3342 rc = pgmR3PhysChunkMap(pVM, idChunk, &pChunk);
3343 pgmUnlock(pVM);
3344 return rc;
3345}
3346
3347
3348/**
3349 * Invalidates the TLB for the ring-3 mapping cache.
3350 *
3351 * @param pVM The VM handle.
3352 */
3353VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
3354{
3355 pgmLock(pVM);
3356 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
3357 {
3358 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
3359 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
3360 }
3361 /* The page map TLB references chunks, so invalidate that one too. */
3362 PGMPhysInvalidatePageMapTLB(pVM);
3363 pgmUnlock(pVM);
3364}
3365
3366
3367/**
3368 * Response to VMMCALLRING3_PGM_ALLOCATE_LARGE_PAGE to allocate a large (2MB) page
3369 * for use with a nested paging PDE.
3370 *
3371 * @returns The following VBox status codes.
3372 * @retval VINF_SUCCESS on success.
3373 * @retval VINF_EM_NO_MEMORY if we're out of memory.
3374 *
3375 * @param pVM The VM handle.
3376 * @param GCPhys GC physical start address of the 2 MB range
3377 */
3378VMMR3DECL(int) PGMR3PhysAllocateLargeHandyPage(PVM pVM, RTGCPHYS GCPhys)
3379{
3380 pgmLock(pVM);
3381
3382 STAM_PROFILE_START(&pVM->pgm.s.StatAllocLargePage, a);
3383 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_LARGE_HANDY_PAGE, 0, NULL);
3384 STAM_PROFILE_STOP(&pVM->pgm.s.StatAllocLargePage, a);
3385 if (RT_SUCCESS(rc))
3386 {
3387 Assert(pVM->pgm.s.cLargeHandyPages == 1);
3388
3389 uint32_t idPage = pVM->pgm.s.aLargeHandyPage[0].idPage;
3390 RTHCPHYS HCPhys = pVM->pgm.s.aLargeHandyPage[0].HCPhysGCPhys;
3391
3392 void *pv;
3393
3394 /* Map the large page into our address space.
3395 *
3396 * Note: assuming that within the 2 MB range:
3397 * - GCPhys + PAGE_SIZE = HCPhys + PAGE_SIZE (whole point of this exercise)
3398 * - user space mapping is continuous as well
3399 * - page id (GCPhys) + 1 = page id (GCPhys + PAGE_SIZE)
3400 */
3401 rc = pgmPhysPageMapByPageID(pVM, idPage, HCPhys, &pv);
3402 AssertLogRelMsg(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc", idPage, HCPhys, rc));
3403
3404 if (RT_SUCCESS(rc))
3405 {
3406 /*
3407 * Clear the pages.
3408 */
3409 STAM_PROFILE_START(&pVM->pgm.s.StatClearLargePage, b);
3410 for (unsigned i = 0; i < _2M/PAGE_SIZE; i++)
3411 {
3412 ASMMemZeroPage(pv);
3413
3414 PPGMPAGE pPage;
3415 rc = pgmPhysGetPageEx(&pVM->pgm.s, GCPhys, &pPage);
3416 AssertRC(rc);
3417
3418 Assert(PGM_PAGE_IS_ZERO(pPage));
3419 STAM_COUNTER_INC(&pVM->pgm.s.StatRZPageReplaceZero);
3420 pVM->pgm.s.cZeroPages--;
3421
3422 /*
3423 * Do the PGMPAGE modifications.
3424 */
3425 pVM->pgm.s.cPrivatePages++;
3426 PGM_PAGE_SET_HCPHYS(pPage, HCPhys);
3427 PGM_PAGE_SET_PAGEID(pPage, idPage);
3428 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ALLOCATED);
3429 PGM_PAGE_SET_PDE_TYPE(pPage, PGM_PAGE_PDE_TYPE_PDE);
3430
3431 /* Somewhat dirty assumption that page ids are increasing. */
3432 idPage++;
3433
3434 HCPhys += PAGE_SIZE;
3435 GCPhys += PAGE_SIZE;
3436
3437 pv = (void *)((uintptr_t)pv + PAGE_SIZE);
3438
3439 Log3(("PGMR3PhysAllocateLargePage: idPage=%#x HCPhys=%RGp\n", idPage, HCPhys));
3440 }
3441 STAM_PROFILE_STOP(&pVM->pgm.s.StatClearLargePage, b);
3442
3443 /* Flush all TLBs. */
3444 PGM_INVL_ALL_VCPU_TLBS(pVM);
3445 PGMPhysInvalidatePageMapTLB(pVM);
3446 }
3447 pVM->pgm.s.cLargeHandyPages = 0;
3448 }
3449
3450 pgmUnlock(pVM);
3451 return rc;
3452}
3453
3454
3455/**
3456 * Response to VM_FF_PGM_NEED_HANDY_PAGES and VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES.
3457 *
3458 * This function will also work the VM_FF_PGM_NO_MEMORY force action flag, to
3459 * signal and clear the out of memory condition. When contracted, this API is
3460 * used to try clear the condition when the user wants to resume.
3461 *
3462 * @returns The following VBox status codes.
3463 * @retval VINF_SUCCESS on success. FFs cleared.
3464 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in
3465 * this case and it gets accompanied by VM_FF_PGM_NO_MEMORY.
3466 *
3467 * @param pVM The VM handle.
3468 *
3469 * @remarks The VINF_EM_NO_MEMORY status is for the benefit of the FF processing
3470 * in EM.cpp and shouldn't be propagated outside TRPM, HWACCM, EM and
3471 * pgmPhysEnsureHandyPage. There is one exception to this in the \#PF
3472 * handler.
3473 */
3474VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
3475{
3476 pgmLock(pVM);
3477
3478 /*
3479 * Allocate more pages, noting down the index of the first new page.
3480 */
3481 uint32_t iClear = pVM->pgm.s.cHandyPages;
3482 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_INTERNAL_ERROR);
3483 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
3484 int rcAlloc = VINF_SUCCESS;
3485 int rcSeed = VINF_SUCCESS;
3486 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
3487 while (rc == VERR_GMM_SEED_ME)
3488 {
3489 void *pvChunk;
3490 rcAlloc = rc = SUPR3PageAlloc(GMM_CHUNK_SIZE >> PAGE_SHIFT, &pvChunk);
3491 if (RT_SUCCESS(rc))
3492 {
3493 rcSeed = rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_SEED_CHUNK, (uintptr_t)pvChunk, NULL);
3494 if (RT_FAILURE(rc))
3495 SUPR3PageFree(pvChunk, GMM_CHUNK_SIZE >> PAGE_SHIFT);
3496 }
3497 if (RT_SUCCESS(rc))
3498 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
3499 }
3500
3501 if (RT_SUCCESS(rc))
3502 {
3503 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
3504 Assert(pVM->pgm.s.cHandyPages > 0);
3505 VM_FF_CLEAR(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
3506 VM_FF_CLEAR(pVM, VM_FF_PGM_NO_MEMORY);
3507
3508 /*
3509 * Clear the pages.
3510 */
3511 while (iClear < pVM->pgm.s.cHandyPages)
3512 {
3513 PGMMPAGEDESC pPage = &pVM->pgm.s.aHandyPages[iClear];
3514 void *pv;
3515 rc = pgmPhysPageMapByPageID(pVM, pPage->idPage, pPage->HCPhysGCPhys, &pv);
3516 AssertLogRelMsgBreak(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc", pPage->idPage, pPage->HCPhysGCPhys, rc));
3517 ASMMemZeroPage(pv);
3518 iClear++;
3519 Log3(("PGMR3PhysAllocateHandyPages: idPage=%#x HCPhys=%RGp\n", pPage->idPage, pPage->HCPhysGCPhys));
3520 }
3521 }
3522 else
3523 {
3524 uint64_t cAllocPages, cMaxPages, cBalloonPages;
3525
3526 /*
3527 * We should never get here unless there is a genuine shortage of
3528 * memory (or some internal error). Flag the error so the VM can be
3529 * suspended ASAP and the user informed. If we're totally out of
3530 * handy pages we will return failure.
3531 */
3532 /* Report the failure. */
3533 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc rcAlloc=%Rrc rcSeed=%Rrc cHandyPages=%#x\n"
3534 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
3535 rc, rcAlloc, rcSeed,
3536 pVM->pgm.s.cHandyPages,
3537 pVM->pgm.s.cAllPages,
3538 pVM->pgm.s.cPrivatePages,
3539 pVM->pgm.s.cSharedPages,
3540 pVM->pgm.s.cZeroPages));
3541
3542 if (GMMR3QueryMemoryStats(pVM, &cAllocPages, &cMaxPages, &cBalloonPages) == VINF_SUCCESS)
3543 {
3544 LogRel(("GMM: Statistics:\n"
3545 " Allocated pages: %RX64\n"
3546 " Maximum pages: %RX64\n"
3547 " Ballooned pages: %RX64\n", cAllocPages, cMaxPages, cBalloonPages));
3548 }
3549
3550 if ( rc != VERR_NO_MEMORY
3551 && rc != VERR_LOCK_FAILED)
3552 {
3553 for (uint32_t i = 0; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
3554 {
3555 LogRel(("PGM: aHandyPages[#%#04x] = {.HCPhysGCPhys=%RHp, .idPage=%#08x, .idSharedPage=%#08x}\n",
3556 i, pVM->pgm.s.aHandyPages[i].HCPhysGCPhys, pVM->pgm.s.aHandyPages[i].idPage,
3557 pVM->pgm.s.aHandyPages[i].idSharedPage));
3558 uint32_t const idPage = pVM->pgm.s.aHandyPages[i].idPage;
3559 if (idPage != NIL_GMM_PAGEID)
3560 {
3561 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
3562 pRam;
3563 pRam = pRam->pNextR3)
3564 {
3565 uint32_t const cPages = pRam->cb >> PAGE_SHIFT;
3566 for (uint32_t iPage = 0; iPage < cPages; iPage++)
3567 if (PGM_PAGE_GET_PAGEID(&pRam->aPages[iPage]) == idPage)
3568 LogRel(("PGM: Used by %RGp %R[pgmpage] (%s)\n",
3569 pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pRam->aPages[iPage], pRam->pszDesc));
3570 }
3571 }
3572 }
3573 }
3574
3575 /* Set the FFs and adjust rc. */
3576 VM_FF_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
3577 VM_FF_SET(pVM, VM_FF_PGM_NO_MEMORY);
3578 if ( rc == VERR_NO_MEMORY
3579 || rc == VERR_LOCK_FAILED)
3580 rc = VINF_EM_NO_MEMORY;
3581 }
3582
3583 pgmUnlock(pVM);
3584 return rc;
3585}
3586
3587
3588/**
3589 * Frees the specified RAM page and replaces it with the ZERO page.
3590 *
3591 * This is used by ballooning, remapping MMIO2 and RAM reset.
3592 *
3593 * @param pVM Pointer to the shared VM structure.
3594 * @param pReq Pointer to the request.
3595 * @param pPage Pointer to the page structure.
3596 * @param GCPhys The guest physical address of the page, if applicable.
3597 *
3598 * @remarks The caller must own the PGM lock.
3599 */
3600static int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys)
3601{
3602 /*
3603 * Assert sanity.
3604 */
3605 Assert(PGMIsLockOwner(pVM));
3606 if (RT_UNLIKELY( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM
3607 && PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_ROM_SHADOW))
3608 {
3609 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
3610 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
3611 }
3612
3613 if ( PGM_PAGE_IS_ZERO(pPage)
3614 || PGM_PAGE_IS_BALLOONED(pPage))
3615 return VINF_SUCCESS;
3616
3617 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
3618 Log3(("pgmPhysFreePage: idPage=%#x HCPhys=%RGp pPage=%R[pgmpage]\n", idPage, pPage));
3619 if (RT_UNLIKELY( idPage == NIL_GMM_PAGEID
3620 || idPage > GMM_PAGEID_LAST
3621 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID))
3622 {
3623 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
3624 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
3625 }
3626
3627 /* update page count stats. */
3628 if (PGM_PAGE_IS_SHARED(pPage))
3629 pVM->pgm.s.cSharedPages--;
3630 else
3631 pVM->pgm.s.cPrivatePages--;
3632 pVM->pgm.s.cZeroPages++;
3633
3634 /* Deal with write monitored pages. */
3635 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
3636 {
3637 PGM_PAGE_SET_WRITTEN_TO(pPage);
3638 pVM->pgm.s.cWrittenToPages++;
3639 }
3640
3641 /*
3642 * pPage = ZERO page.
3643 */
3644 PGM_PAGE_SET_HCPHYS(pPage, pVM->pgm.s.HCPhysZeroPg);
3645 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
3646 PGM_PAGE_SET_PAGEID(pPage, NIL_GMM_PAGEID);
3647 PGM_PAGE_SET_PDE_TYPE(pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
3648
3649 /* Flush physical page map TLB entry. */
3650 PGMPhysInvalidatePageMapTLBEntry(pVM, GCPhys);
3651
3652 /*
3653 * Make sure it's not in the handy page array.
3654 */
3655 for (uint32_t i = pVM->pgm.s.cHandyPages; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
3656 {
3657 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
3658 {
3659 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
3660 break;
3661 }
3662 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
3663 {
3664 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
3665 break;
3666 }
3667 }
3668
3669 /*
3670 * Push it onto the page array.
3671 */
3672 uint32_t iPage = *pcPendingPages;
3673 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
3674 *pcPendingPages += 1;
3675
3676 pReq->aPages[iPage].idPage = idPage;
3677
3678 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
3679 return VINF_SUCCESS;
3680
3681 /*
3682 * Flush the pages.
3683 */
3684 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
3685 if (RT_SUCCESS(rc))
3686 {
3687 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
3688 *pcPendingPages = 0;
3689 }
3690 return rc;
3691}
3692
3693
3694/**
3695 * Converts a GC physical address to a HC ring-3 pointer, with some
3696 * additional checks.
3697 *
3698 * @returns VBox status code.
3699 * @retval VINF_SUCCESS on success.
3700 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
3701 * access handler of some kind.
3702 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
3703 * accesses or is odd in any way.
3704 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
3705 *
3706 * @param pVM The VM handle.
3707 * @param GCPhys The GC physical address to convert.
3708 * @param fWritable Whether write access is required.
3709 * @param ppv Where to store the pointer corresponding to GCPhys on
3710 * success.
3711 */
3712VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
3713{
3714 pgmLock(pVM);
3715
3716 PPGMRAMRANGE pRam;
3717 PPGMPAGE pPage;
3718 int rc = pgmPhysGetPageAndRangeEx(&pVM->pgm.s, GCPhys, &pPage, &pRam);
3719 if (RT_SUCCESS(rc))
3720 {
3721 if (PGM_PAGE_IS_BALLOONED(pPage))
3722 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
3723 else if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
3724 rc = VINF_SUCCESS;
3725 else
3726 {
3727 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
3728 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
3729 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
3730 {
3731 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
3732 * in -norawr0 mode. */
3733 if (fWritable)
3734 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
3735 }
3736 else
3737 {
3738 /* Temporarily disabled physical handler(s), since the recompiler
3739 doesn't get notified when it's reset we'll have to pretend it's
3740 operating normally. */
3741 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
3742 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
3743 else
3744 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
3745 }
3746 }
3747 if (RT_SUCCESS(rc))
3748 {
3749 int rc2;
3750
3751 /* Make sure what we return is writable. */
3752 if (fWritable && rc != VINF_PGM_PHYS_TLB_CATCH_WRITE)
3753 switch (PGM_PAGE_GET_STATE(pPage))
3754 {
3755 case PGM_PAGE_STATE_ALLOCATED:
3756 break;
3757 case PGM_PAGE_STATE_BALLOONED:
3758 AssertFailed();
3759 break;
3760 case PGM_PAGE_STATE_ZERO:
3761 case PGM_PAGE_STATE_SHARED:
3762 case PGM_PAGE_STATE_WRITE_MONITORED:
3763 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)PAGE_OFFSET_MASK);
3764 AssertLogRelRCReturn(rc2, rc2);
3765 break;
3766 }
3767
3768 /* Get a ring-3 mapping of the address. */
3769 PPGMPAGER3MAPTLBE pTlbe;
3770 rc2 = pgmPhysPageQueryTlbe(&pVM->pgm.s, GCPhys, &pTlbe);
3771 AssertLogRelRCReturn(rc2, rc2);
3772 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & PAGE_OFFSET_MASK));
3773 /** @todo mapping/locking hell; this isn't horribly efficient since
3774 * pgmPhysPageLoadIntoTlb will repeat the lookup we've done here. */
3775
3776 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
3777 }
3778 else
3779 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
3780
3781 /* else: handler catching all access, no pointer returned. */
3782 }
3783 else
3784 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
3785
3786 pgmUnlock(pVM);
3787 return rc;
3788}
3789
Note: See TracBrowser for help on using the repository browser.

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