VirtualBox

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

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

Comment update

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