VirtualBox

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

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

Logging

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