VirtualBox

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

Last change on this file since 28800 was 28800, checked in by vboxsync, 14 years ago

Automated rebranding to Oracle copyright/license strings via filemuncher

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

© 2023 Oracle
ContactPrivacy policyTerms of Use