VirtualBox

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

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

Logging

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