VirtualBox

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

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

Make PGMR3PhysChangeMemBalloon return VERR_NOT_IMPLEMENTED on hosts that do not support ballooning.

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