VirtualBox

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

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

Compile fix

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