VirtualBox

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

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

Use PGMR3QueryFreeMemory instead

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

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