VirtualBox

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

Last change on this file since 18046 was 18046, checked in by vboxsync, 16 years ago

PGM,MM: saved state bugfixes for VBOX_WITH_NEW_PHYS_CODE.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 107.8 KB
Line 
1/* $Id: PGMPhys.cpp 18046 2009-03-17 22:30:35Z 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
27#include <VBox/pgm.h>
28#include <VBox/cpum.h>
29#include <VBox/iom.h>
30#include <VBox/sup.h>
31#include <VBox/mm.h>
32#include <VBox/stam.h>
33#include <VBox/rem.h>
34#include <VBox/csam.h>
35#include "PGMInternal.h"
36#include <VBox/vm.h>
37#include <VBox/dbg.h>
38#include <VBox/param.h>
39#include <VBox/err.h>
40#include <iprt/assert.h>
41#include <iprt/alloc.h>
42#include <iprt/asm.h>
43#include <VBox/log.h>
44#include <iprt/thread.h>
45#include <iprt/string.h>
46
47
48/*******************************************************************************
49* Defined Constants And Macros *
50*******************************************************************************/
51/** The number of pages to free in one batch. */
52#define PGMPHYS_FREE_PAGE_BATCH_SIZE 128
53
54
55/*******************************************************************************
56* Internal Functions *
57*******************************************************************************/
58static DECLCALLBACK(int) pgmR3PhysRomWriteHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser);
59static int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys);
60
61
62/*
63 * PGMR3PhysReadU8-64
64 * PGMR3PhysWriteU8-64
65 */
66#define PGMPHYSFN_READNAME PGMR3PhysReadU8
67#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU8
68#define PGMPHYS_DATASIZE 1
69#define PGMPHYS_DATATYPE uint8_t
70#include "PGMPhysRWTmpl.h"
71
72#define PGMPHYSFN_READNAME PGMR3PhysReadU16
73#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU16
74#define PGMPHYS_DATASIZE 2
75#define PGMPHYS_DATATYPE uint16_t
76#include "PGMPhysRWTmpl.h"
77
78#define PGMPHYSFN_READNAME PGMR3PhysReadU32
79#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU32
80#define PGMPHYS_DATASIZE 4
81#define PGMPHYS_DATATYPE uint32_t
82#include "PGMPhysRWTmpl.h"
83
84#define PGMPHYSFN_READNAME PGMR3PhysReadU64
85#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU64
86#define PGMPHYS_DATASIZE 8
87#define PGMPHYS_DATATYPE uint64_t
88#include "PGMPhysRWTmpl.h"
89
90
91/**
92 * EMT worker for PGMR3PhysReadExternal.
93 */
94static DECLCALLBACK(int) pgmR3PhysReadExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, void *pvBuf, size_t cbRead)
95{
96 PGMPhysRead(pVM, *pGCPhys, pvBuf, cbRead);
97 return VINF_SUCCESS;
98}
99
100
101/**
102 * Write to physical memory, external users.
103 *
104 * @returns VBox status code.
105 * @retval VINF_SUCCESS.
106 *
107 * @param pVM VM Handle.
108 * @param GCPhys Physical address to write to.
109 * @param pvBuf What to write.
110 * @param cbWrite How many bytes to write.
111 *
112 * @thread Any but EMTs.
113 */
114VMMR3DECL(int) PGMR3PhysReadExternal(PVM pVM, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead)
115{
116 VM_ASSERT_OTHER_THREAD(pVM);
117
118 AssertMsgReturn(cbRead > 0, ("don't even think about reading zero bytes!\n"), VINF_SUCCESS);
119 LogFlow(("PGMR3PhysReadExternal: %RGp %d\n", GCPhys, cbRead));
120
121 pgmLock(pVM);
122
123 /*
124 * Copy loop on ram ranges.
125 */
126 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
127 for (;;)
128 {
129 /* Find range. */
130 while (pRam && GCPhys > pRam->GCPhysLast)
131 pRam = pRam->CTX_SUFF(pNext);
132 /* Inside range or not? */
133 if (pRam && GCPhys >= pRam->GCPhys)
134 {
135 /*
136 * Must work our way thru this page by page.
137 */
138 RTGCPHYS off = GCPhys - pRam->GCPhys;
139 while (off < pRam->cb)
140 {
141 unsigned iPage = off >> PAGE_SHIFT;
142 PPGMPAGE pPage = &pRam->aPages[iPage];
143
144 /*
145 * If the page has an ALL access handler, we'll have to
146 * delegate the job to EMT.
147 */
148 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
149 {
150 pgmUnlock(pVM);
151
152 PVMREQ pReq = NULL;
153 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT,
154 (PFNRT)pgmR3PhysReadExternalEMT, 4, pVM, &GCPhys, pvBuf, cbRead);
155 if (RT_SUCCESS(rc))
156 {
157 rc = pReq->iStatus;
158 VMR3ReqFree(pReq);
159 }
160 return rc;
161 }
162 Assert(!PGM_PAGE_IS_MMIO(pPage));
163
164 /*
165 * Simple stuff, go ahead.
166 */
167 size_t cb = PAGE_SIZE - (off & PAGE_OFFSET_MASK);
168 if (cb > cbRead)
169 cb = cbRead;
170 const void *pvSrc;
171 int rc = pgmPhysGCPhys2CCPtrInternalReadOnly(pVM, pPage, pRam->GCPhys + off, &pvSrc);
172 if (RT_SUCCESS(rc))
173 memcpy(pvBuf, pvSrc, cb);
174 else
175 {
176 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternalReadOnly failed on %RGp / %R[pgmpage] -> %Rrc\n",
177 pRam->GCPhys + off, pPage, rc));
178 memset(pvBuf, 0xff, cb);
179 }
180
181 /* next page */
182 if (cb >= cbRead)
183 {
184 pgmUnlock(pVM);
185 return VINF_SUCCESS;
186 }
187 cbRead -= cb;
188 off += cb;
189 GCPhys += cb;
190 pvBuf = (char *)pvBuf + cb;
191 } /* walk pages in ram range. */
192 }
193 else
194 {
195 LogFlow(("PGMPhysRead: Unassigned %RGp size=%u\n", GCPhys, cbRead));
196
197 /*
198 * Unassigned address space.
199 */
200 if (!pRam)
201 break;
202 size_t cb = pRam->GCPhys - GCPhys;
203 if (cb >= cbRead)
204 {
205 memset(pvBuf, 0xff, cbRead);
206 break;
207 }
208 memset(pvBuf, 0xff, cb);
209
210 cbRead -= cb;
211 pvBuf = (char *)pvBuf + cb;
212 GCPhys += cb;
213 }
214 } /* Ram range walk */
215
216 pgmUnlock(pVM);
217
218 return VINF_SUCCESS;
219}
220
221
222/**
223 * EMT worker for PGMR3PhysWriteExternal.
224 */
225static DECLCALLBACK(int) pgmR3PhysWriteExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, const void *pvBuf, size_t cbWrite)
226{
227 /** @todo VERR_EM_NO_MEMORY */
228 PGMPhysWrite(pVM, *pGCPhys, pvBuf, cbWrite);
229 return VINF_SUCCESS;
230}
231
232
233/**
234 * Write to physical memory, external users.
235 *
236 * @returns VBox status code.
237 * @retval VINF_SUCCESS.
238 * @retval VERR_EM_NO_MEMORY.
239 *
240 * @param pVM VM Handle.
241 * @param GCPhys Physical address to write to.
242 * @param pvBuf What to write.
243 * @param cbWrite How many bytes to write.
244 *
245 * @thread Any but EMTs.
246 */
247VMMDECL(int) PGMR3PhysWriteExternal(PVM pVM, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite)
248{
249 VM_ASSERT_OTHER_THREAD(pVM);
250
251 AssertMsg(!pVM->pgm.s.fNoMorePhysWrites, ("Calling PGMR3PhysWriteExternal after pgmR3Save()!\n"));
252 AssertMsgReturn(cbWrite > 0, ("don't even think about writing zero bytes!\n"), VINF_SUCCESS);
253 LogFlow(("PGMR3PhysWriteExternal: %RGp %d\n", GCPhys, cbWrite));
254
255 pgmLock(pVM);
256
257 /*
258 * Copy loop on ram ranges, stop when we hit something difficult.
259 */
260 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
261 for (;;)
262 {
263 /* Find range. */
264 while (pRam && GCPhys > pRam->GCPhysLast)
265 pRam = pRam->CTX_SUFF(pNext);
266 /* Inside range or not? */
267 if (pRam && GCPhys >= pRam->GCPhys)
268 {
269 /*
270 * Must work our way thru this page by page.
271 */
272 RTGCPTR off = GCPhys - pRam->GCPhys;
273 while (off < pRam->cb)
274 {
275 RTGCPTR iPage = off >> PAGE_SHIFT;
276 PPGMPAGE pPage = &pRam->aPages[iPage];
277
278 /*
279 * It the page is in any way problematic, we have to
280 * do the work on the EMT. Anything that needs to be made
281 * writable or involves access handlers is problematic.
282 */
283 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
284 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED)
285 {
286 pgmUnlock(pVM);
287
288 PVMREQ pReq = NULL;
289 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT,
290 (PFNRT)pgmR3PhysWriteExternalEMT, 4, pVM, &GCPhys, pvBuf, cbWrite);
291 if (RT_SUCCESS(rc))
292 {
293 rc = pReq->iStatus;
294 VMR3ReqFree(pReq);
295 }
296 return rc;
297 }
298 Assert(!PGM_PAGE_IS_MMIO(pPage));
299
300 /*
301 * Simple stuff, go ahead.
302 */
303 size_t cb = PAGE_SIZE - (off & PAGE_OFFSET_MASK);
304 if (cb > cbWrite)
305 cb = cbWrite;
306 void *pvDst;
307 int rc = pgmPhysGCPhys2CCPtrInternal(pVM, pPage, pRam->GCPhys + off, &pvDst);
308 if (RT_SUCCESS(rc))
309 memcpy(pvDst, pvBuf, cb);
310 else
311 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternal failed on %RGp / %R[pgmpage] -> %Rrc\n",
312 pRam->GCPhys + off, pPage, rc));
313
314 /* next page */
315 if (cb >= cbWrite)
316 {
317 pgmUnlock(pVM);
318 return VINF_SUCCESS;
319 }
320
321 cbWrite -= cb;
322 off += cb;
323 GCPhys += cb;
324 pvBuf = (const char *)pvBuf + cb;
325 } /* walk pages in ram range */
326 }
327 else
328 {
329 /*
330 * Unassigned address space, skip it.
331 */
332 if (!pRam)
333 break;
334 size_t cb = pRam->GCPhys - GCPhys;
335 if (cb >= cbWrite)
336 break;
337 cbWrite -= cb;
338 pvBuf = (const char *)pvBuf + cb;
339 GCPhys += cb;
340 }
341 } /* Ram range walk */
342
343 pgmUnlock(pVM);
344 return VINF_SUCCESS;
345}
346
347
348
349/**
350 * Links a new RAM range into the list.
351 *
352 * @param pVM Pointer to the shared VM structure.
353 * @param pNew Pointer to the new list entry.
354 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
355 */
356static void pgmR3PhysLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, PPGMRAMRANGE pPrev)
357{
358 AssertMsg(pNew->pszDesc, ("%RGp-%RGp\n", pNew->GCPhys, pNew->GCPhysLast));
359
360 pgmLock(pVM);
361
362 PPGMRAMRANGE pRam = pPrev ? pPrev->pNextR3 : pVM->pgm.s.pRamRangesR3;
363 pNew->pNextR3 = pRam;
364 pNew->pNextR0 = pRam ? MMHyperCCToR0(pVM, pRam) : NIL_RTR0PTR;
365 pNew->pNextRC = pRam ? MMHyperCCToRC(pVM, pRam) : NIL_RTRCPTR;
366
367 if (pPrev)
368 {
369 pPrev->pNextR3 = pNew;
370 pPrev->pNextR0 = MMHyperCCToR0(pVM, pNew);
371 pPrev->pNextRC = MMHyperCCToRC(pVM, pNew);
372 }
373 else
374 {
375 pVM->pgm.s.pRamRangesR3 = pNew;
376 pVM->pgm.s.pRamRangesR0 = MMHyperCCToR0(pVM, pNew);
377 pVM->pgm.s.pRamRangesRC = MMHyperCCToRC(pVM, pNew);
378 }
379
380 pgmUnlock(pVM);
381}
382
383
384/**
385 * Unlink an existing RAM range from the list.
386 *
387 * @param pVM Pointer to the shared VM structure.
388 * @param pRam Pointer to the new list entry.
389 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
390 */
391static void pgmR3PhysUnlinkRamRange2(PVM pVM, PPGMRAMRANGE pRam, PPGMRAMRANGE pPrev)
392{
393 Assert(pPrev ? pPrev->pNextR3 == pRam : pVM->pgm.s.pRamRangesR3 == pRam);
394
395 pgmLock(pVM);
396
397 PPGMRAMRANGE pNext = pRam->pNextR3;
398 if (pPrev)
399 {
400 pPrev->pNextR3 = pNext;
401 pPrev->pNextR0 = pNext ? MMHyperCCToR0(pVM, pNext) : NIL_RTR0PTR;
402 pPrev->pNextRC = pNext ? MMHyperCCToRC(pVM, pNext) : NIL_RTRCPTR;
403 }
404 else
405 {
406 Assert(pVM->pgm.s.pRamRangesR3 == pRam);
407 pVM->pgm.s.pRamRangesR3 = pNext;
408 pVM->pgm.s.pRamRangesR0 = pNext ? MMHyperCCToR0(pVM, pNext) : NIL_RTR0PTR;
409 pVM->pgm.s.pRamRangesRC = pNext ? MMHyperCCToRC(pVM, pNext) : NIL_RTRCPTR;
410 }
411
412 pgmUnlock(pVM);
413}
414
415
416/**
417 * Unlink an existing RAM range from the list.
418 *
419 * @param pVM Pointer to the shared VM structure.
420 * @param pRam Pointer to the new list entry.
421 */
422static void pgmR3PhysUnlinkRamRange(PVM pVM, PPGMRAMRANGE pRam)
423{
424 /* find prev. */
425 PPGMRAMRANGE pPrev = NULL;
426 PPGMRAMRANGE pCur = pVM->pgm.s.pRamRangesR3;
427 while (pCur != pRam)
428 {
429 pPrev = pCur;
430 pCur = pCur->pNextR3;
431 }
432 AssertFatal(pCur);
433
434 pgmR3PhysUnlinkRamRange2(pVM, pRam, pPrev);
435}
436
437
438/**
439 * Sets up a range RAM.
440 *
441 * This will check for conflicting registrations, make a resource
442 * reservation for the memory (with GMM), and setup the per-page
443 * tracking structures (PGMPAGE).
444 *
445 * @returns VBox stutus code.
446 * @param pVM Pointer to the shared VM structure.
447 * @param GCPhys The physical address of the RAM.
448 * @param cb The size of the RAM.
449 * @param pszDesc The description - not copied, so, don't free or change it.
450 */
451VMMR3DECL(int) PGMR3PhysRegisterRam(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, const char *pszDesc)
452{
453 /*
454 * Validate input.
455 */
456 Log(("PGMR3PhysRegisterRam: GCPhys=%RGp cb=%RGp pszDesc=%s\n", GCPhys, cb, pszDesc));
457 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
458 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
459 AssertReturn(cb > 0, VERR_INVALID_PARAMETER);
460 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
461 AssertMsgReturn(GCPhysLast > GCPhys, ("The range wraps! GCPhys=%RGp cb=%RGp\n", GCPhys, cb), VERR_INVALID_PARAMETER);
462 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
463 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
464
465 /*
466 * Find range location and check for conflicts.
467 * (We don't lock here because the locking by EMT is only required on update.)
468 */
469 PPGMRAMRANGE pPrev = NULL;
470 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
471 while (pRam && GCPhysLast >= pRam->GCPhys)
472 {
473 if ( GCPhysLast >= pRam->GCPhys
474 && GCPhys <= pRam->GCPhysLast)
475 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
476 GCPhys, GCPhysLast, pszDesc,
477 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
478 VERR_PGM_RAM_CONFLICT);
479
480 /* next */
481 pPrev = pRam;
482 pRam = pRam->pNextR3;
483 }
484
485 /*
486 * Register it with GMM (the API bitches).
487 */
488 const RTGCPHYS cPages = cb >> PAGE_SHIFT;
489 int rc = MMR3IncreaseBaseReservation(pVM, cPages);
490 if (RT_FAILURE(rc))
491 return rc;
492
493 /*
494 * Allocate RAM range.
495 */
496 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
497 PPGMRAMRANGE pNew;
498 rc = MMR3HyperAllocOnceNoRel(pVM, cbRamRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
499 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
500
501 /*
502 * Initialize the range.
503 */
504 pNew->GCPhys = GCPhys;
505 pNew->GCPhysLast = GCPhysLast;
506 pNew->pszDesc = pszDesc;
507 pNew->cb = cb;
508 pNew->fFlags = 0;
509
510 pNew->pvR3 = NULL;
511#ifndef VBOX_WITH_NEW_PHYS_CODE
512 pNew->paChunkR3Ptrs = NULL;
513
514 /* Allocate memory for chunk to HC ptr lookup array. */
515 rc = MMHyperAlloc(pVM, (cb >> PGM_DYNAMIC_CHUNK_SHIFT) * sizeof(void *), 16, MM_TAG_PGM, (void **)&pNew->paChunkR3Ptrs);
516 AssertRCReturn(rc, rc);
517 pNew->fFlags |= MM_RAM_FLAGS_DYNAMIC_ALLOC;
518
519#endif
520 RTGCPHYS iPage = cPages;
521 while (iPage-- > 0)
522 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_RAM);
523
524 /* Update the page count stats. */
525 pVM->pgm.s.cZeroPages += cPages;
526 pVM->pgm.s.cAllPages += cPages;
527
528 /*
529 * Insert the new RAM range.
530 */
531 pgmR3PhysLinkRamRange(pVM, pNew, pPrev);
532
533 /*
534 * Notify REM.
535 */
536#ifdef VBOX_WITH_NEW_PHYS_CODE
537 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, REM_NOTIFY_PHYS_RAM_FLAGS_RAM);
538#else
539 REMR3NotifyPhysRamRegister(pVM, GCPhys, cb, MM_RAM_FLAGS_DYNAMIC_ALLOC);
540#endif
541
542 return VINF_SUCCESS;
543}
544
545
546/**
547 * Resets (zeros) the RAM.
548 *
549 * ASSUMES that the caller owns the PGM lock.
550 *
551 * @returns VBox status code.
552 * @param pVM Pointer to the shared VM structure.
553 */
554int pgmR3PhysRamReset(PVM pVM)
555{
556#ifdef VBOX_WITH_NEW_PHYS_CODE
557 /*
558 * We batch up pages before freeing them.
559 */
560 uint32_t cPendingPages = 0;
561 PGMMFREEPAGESREQ pReq;
562 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
563 AssertLogRelRCReturn(rc, rc);
564#endif
565
566 /*
567 * Walk the ram ranges.
568 */
569 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3; pRam; pRam = pRam->pNextR3)
570 {
571 uint32_t iPage = pRam->cb >> PAGE_SHIFT; Assert((RTGCPHYS)iPage << PAGE_SHIFT == pRam->cb);
572#ifdef VBOX_WITH_NEW_PHYS_CODE
573 if (!pVM->pgm.s.fRamPreAlloc)
574 {
575 /* Replace all RAM pages by ZERO pages. */
576 while (iPage-- > 0)
577 {
578 PPGMPAGE pPage = &pRam->aPages[iPage];
579 switch (PGM_PAGE_GET_TYPE(pPage))
580 {
581 case PGMPAGETYPE_RAM:
582 if (!PGM_PAGE_IS_ZERO(pPage))
583 {
584 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
585 AssertLogRelRCReturn(rc, rc);
586 }
587 break;
588
589 case PGMPAGETYPE_MMIO2:
590 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
591 case PGMPAGETYPE_ROM:
592 case PGMPAGETYPE_MMIO:
593 break;
594 default:
595 AssertFailed();
596 }
597 } /* for each page */
598 }
599 else
600#endif
601 {
602 /* Zero the memory. */
603 while (iPage-- > 0)
604 {
605 PPGMPAGE pPage = &pRam->aPages[iPage];
606 switch (PGM_PAGE_GET_TYPE(pPage))
607 {
608#ifndef VBOX_WITH_NEW_PHYS_CODE
609 case PGMPAGETYPE_INVALID:
610 case PGMPAGETYPE_RAM:
611 if (pRam->aPages[iPage].HCPhys & (MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_ROM | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_MMIO2)) /** @todo PAGE FLAGS */
612 {
613 /* shadow ram is reloaded elsewhere. */
614 Log4(("PGMR3Reset: not clearing phys page %RGp due to flags %RHp\n", pRam->GCPhys + (iPage << PAGE_SHIFT), pRam->aPages[iPage].HCPhys & (MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_ROM | MM_RAM_FLAGS_MMIO))); /** @todo PAGE FLAGS */
615 continue;
616 }
617 if (pRam->fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC)
618 {
619 unsigned iChunk = iPage >> (PGM_DYNAMIC_CHUNK_SHIFT - PAGE_SHIFT);
620 if (pRam->paChunkR3Ptrs[iChunk])
621 ASMMemZero32((char *)pRam->paChunkR3Ptrs[iChunk] + ((iPage << PAGE_SHIFT) & PGM_DYNAMIC_CHUNK_OFFSET_MASK), PAGE_SIZE);
622 }
623 else
624 ASMMemZero32((char *)pRam->pvR3 + (iPage << PAGE_SHIFT), PAGE_SIZE);
625 break;
626#else /* VBOX_WITH_NEW_PHYS_CODE */
627 case PGMPAGETYPE_RAM:
628 switch (PGM_PAGE_GET_STATE(pPage))
629 {
630 case PGM_PAGE_STATE_ZERO:
631 break;
632 case PGM_PAGE_STATE_SHARED:
633 case PGM_PAGE_STATE_WRITE_MONITORED:
634 rc = pgmPhysPageMakeWritable(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT));
635 AssertLogRelRCReturn(rc, rc);
636 case PGM_PAGE_STATE_ALLOCATED:
637 {
638 void *pvPage;
639 PPGMPAGEMAP pMapIgnored;
640 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << PAGE_SHIFT), &pMapIgnored, &pvPage);
641 AssertLogRelRCReturn(rc, rc);
642 ASMMemZeroPage(pvPage);
643 break;
644 }
645 }
646 break;
647#endif /* VBOX_WITH_NEW_PHYS_CODE */
648
649 case PGMPAGETYPE_MMIO2:
650 case PGMPAGETYPE_ROM_SHADOW:
651 case PGMPAGETYPE_ROM:
652 case PGMPAGETYPE_MMIO:
653 break;
654 default:
655 AssertFailed();
656
657 }
658 } /* for each page */
659 }
660
661 }
662
663#ifdef VBOX_WITH_NEW_PHYS_CODE
664 /*
665 * Finish off any pages pending freeing.
666 */
667 if (cPendingPages)
668 {
669 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
670 AssertLogRelRCReturn(rc, rc);
671 }
672 GMMR3FreePagesCleanup(pReq);
673#endif
674
675
676 return VINF_SUCCESS;
677}
678
679
680/**
681 * This is the interface IOM is using to register an MMIO region.
682 *
683 * It will check for conflicts and ensure that a RAM range structure
684 * is present before calling the PGMR3HandlerPhysicalRegister API to
685 * register the callbacks.
686 *
687 * @returns VBox status code.
688 *
689 * @param pVM Pointer to the shared VM structure.
690 * @param GCPhys The start of the MMIO region.
691 * @param cb The size of the MMIO region.
692 * @param pfnHandlerR3 The address of the ring-3 handler. (IOMR3MMIOHandler)
693 * @param pvUserR3 The user argument for R3.
694 * @param pfnHandlerR0 The address of the ring-0 handler. (IOMMMIOHandler)
695 * @param pvUserR0 The user argument for R0.
696 * @param pfnHandlerRC The address of the RC handler. (IOMMMIOHandler)
697 * @param pvUserRC The user argument for RC.
698 * @param pszDesc The description of the MMIO region.
699 */
700VMMR3DECL(int) PGMR3PhysMMIORegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb,
701 R3PTRTYPE(PFNPGMR3PHYSHANDLER) pfnHandlerR3, RTR3PTR pvUserR3,
702 R0PTRTYPE(PFNPGMR0PHYSHANDLER) pfnHandlerR0, RTR0PTR pvUserR0,
703 RCPTRTYPE(PFNPGMRCPHYSHANDLER) pfnHandlerRC, RTRCPTR pvUserRC,
704 R3PTRTYPE(const char *) pszDesc)
705{
706 /*
707 * Assert on some assumption.
708 */
709 VM_ASSERT_EMT(pVM);
710 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
711 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
712 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
713 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
714
715 /*
716 * Make sure there's a RAM range structure for the region.
717 */
718 int rc;
719 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
720 bool fRamExists = false;
721 PPGMRAMRANGE pRamPrev = NULL;
722 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
723 while (pRam && GCPhysLast >= pRam->GCPhys)
724 {
725 if ( GCPhysLast >= pRam->GCPhys
726 && GCPhys <= pRam->GCPhysLast)
727 {
728 /* Simplification: all within the same range. */
729 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
730 && GCPhysLast <= pRam->GCPhysLast,
731 ("%RGp-%RGp (MMIO/%s) falls partly outside %RGp-%RGp (%s)\n",
732 GCPhys, GCPhysLast, pszDesc,
733 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
734 VERR_PGM_RAM_CONFLICT);
735
736 /* Check that it's all RAM or MMIO pages. */
737 PCPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
738 uint32_t cLeft = cb >> PAGE_SHIFT;
739 while (cLeft-- > 0)
740 {
741 AssertLogRelMsgReturn( PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM
742 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO,
743 ("%RGp-%RGp (MMIO/%s): %RGp is not a RAM or MMIO page - type=%d desc=%s\n",
744 GCPhys, GCPhysLast, pszDesc, PGM_PAGE_GET_TYPE(pPage), pRam->pszDesc),
745 VERR_PGM_RAM_CONFLICT);
746 pPage++;
747 }
748
749 /* Looks good. */
750 fRamExists = true;
751 break;
752 }
753
754 /* next */
755 pRamPrev = pRam;
756 pRam = pRam->pNextR3;
757 }
758 PPGMRAMRANGE pNew;
759 if (fRamExists)
760 pNew = NULL;
761 else
762 {
763 /*
764 * No RAM range, insert an ad-hoc one.
765 *
766 * Note that we don't have to tell REM about this range because
767 * PGMHandlerPhysicalRegisterEx will do that for us.
768 */
769 Log(("PGMR3PhysMMIORegister: Adding ad-hoc MMIO range for %RGp-%RGp %s\n", GCPhys, GCPhysLast, pszDesc));
770
771 const uint32_t cPages = cb >> PAGE_SHIFT;
772 const size_t cbRamRange = RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]);
773 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), 16, MM_TAG_PGM_PHYS, (void **)&pNew);
774 AssertLogRelMsgRCReturn(rc, ("cbRamRange=%zu\n", cbRamRange), rc);
775
776 /* Initialize the range. */
777 pNew->GCPhys = GCPhys;
778 pNew->GCPhysLast = GCPhysLast;
779 pNew->pszDesc = pszDesc;
780 pNew->cb = cb;
781 pNew->fFlags = 0; /* Some MMIO flag here? */
782
783 pNew->pvR3 = NULL;
784#ifndef VBOX_WITH_NEW_PHYS_CODE
785 pNew->paChunkR3Ptrs = NULL;
786#endif
787
788 uint32_t iPage = cPages;
789 while (iPage-- > 0)
790 PGM_PAGE_INIT_ZERO_REAL(&pNew->aPages[iPage], pVM, PGMPAGETYPE_MMIO);
791 Assert(PGM_PAGE_GET_TYPE(&pNew->aPages[0]) == PGMPAGETYPE_MMIO);
792
793 /* update the page count stats. */
794 pVM->pgm.s.cZeroPages += cPages;
795 pVM->pgm.s.cAllPages += cPages;
796
797 /* link it */
798 pgmR3PhysLinkRamRange(pVM, pNew, pRamPrev);
799 }
800
801 /*
802 * Register the access handler.
803 */
804 rc = PGMHandlerPhysicalRegisterEx(pVM, PGMPHYSHANDLERTYPE_MMIO, GCPhys, GCPhysLast,
805 pfnHandlerR3, pvUserR3,
806 pfnHandlerR0, pvUserR0,
807 pfnHandlerRC, pvUserRC, pszDesc);
808 if ( RT_FAILURE(rc)
809 && !fRamExists)
810 {
811 pVM->pgm.s.cZeroPages -= cb >> PAGE_SHIFT;
812 pVM->pgm.s.cAllPages -= cb >> PAGE_SHIFT;
813
814 /* remove the ad-hoc range. */
815 pgmR3PhysUnlinkRamRange2(pVM, pNew, pRamPrev);
816 pNew->cb = pNew->GCPhys = pNew->GCPhysLast = NIL_RTGCPHYS;
817 MMHyperFree(pVM, pRam);
818 }
819
820 return rc;
821}
822
823
824/**
825 * This is the interface IOM is using to register an MMIO region.
826 *
827 * It will take care of calling PGMHandlerPhysicalDeregister and clean up
828 * any ad-hoc PGMRAMRANGE left behind.
829 *
830 * @returns VBox status code.
831 * @param pVM Pointer to the shared VM structure.
832 * @param GCPhys The start of the MMIO region.
833 * @param cb The size of the MMIO region.
834 */
835VMMR3DECL(int) PGMR3PhysMMIODeregister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb)
836{
837 VM_ASSERT_EMT(pVM);
838
839 /*
840 * First deregister the handler, then check if we should remove the ram range.
841 */
842 int rc = PGMHandlerPhysicalDeregister(pVM, GCPhys);
843 if (RT_SUCCESS(rc))
844 {
845 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
846 PPGMRAMRANGE pRamPrev = NULL;
847 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
848 while (pRam && GCPhysLast >= pRam->GCPhys)
849 {
850 /*if ( GCPhysLast >= pRam->GCPhys
851 && GCPhys <= pRam->GCPhysLast) - later */
852 if ( GCPhysLast == pRam->GCPhysLast
853 && GCPhys == pRam->GCPhys)
854 {
855 Assert(pRam->cb == cb);
856
857 /*
858 * See if all the pages are dead MMIO pages.
859 */
860 bool fAllMMIO = true;
861 PPGMPAGE pPage = &pRam->aPages[0];
862 uint32_t const cPages = cb >> PAGE_SHIFT;
863 uint32_t cLeft = cPages;
864 while (cLeft-- > 0)
865 {
866 if ( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_MMIO
867 /*|| not-out-of-action later */)
868 {
869 fAllMMIO = false;
870 Assert(PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_MMIO2_ALIAS_MMIO);
871 break;
872 }
873 Assert(PGM_PAGE_IS_ZERO(pPage));
874 pPage++;
875 }
876
877 /*
878 * Unlink it and free if it's all MMIO.
879 */
880 if (fAllMMIO)
881 {
882 Log(("PGMR3PhysMMIODeregister: Freeing ad-hoc MMIO range for %RGp-%RGp %s\n",
883 GCPhys, GCPhysLast, pRam->pszDesc));
884
885 pVM->pgm.s.cAllPages -= cPages;
886 pVM->pgm.s.cZeroPages -= cPages;
887
888 pgmR3PhysUnlinkRamRange2(pVM, pRam, pRamPrev);
889 pRam->cb = pRam->GCPhys = pRam->GCPhysLast = NIL_RTGCPHYS;
890 MMHyperFree(pVM, pRam);
891 }
892 break;
893 }
894
895 /* next */
896 pRamPrev = pRam;
897 pRam = pRam->pNextR3;
898 }
899 }
900
901 return rc;
902}
903
904
905/**
906 * Locate a MMIO2 range.
907 *
908 * @returns Pointer to the MMIO2 range.
909 * @param pVM Pointer to the shared VM structure.
910 * @param pDevIns The device instance owning the region.
911 * @param iRegion The region.
912 */
913DECLINLINE(PPGMMMIO2RANGE) pgmR3PhysMMIO2Find(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
914{
915 /*
916 * Search the list.
917 */
918 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
919 if ( pCur->pDevInsR3 == pDevIns
920 && pCur->iRegion == iRegion)
921 return pCur;
922 return NULL;
923}
924
925
926/**
927 * Allocate and register an MMIO2 region.
928 *
929 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's
930 * RAM associated with a device. It is also non-shared memory with a
931 * permanent ring-3 mapping and page backing (presently).
932 *
933 * A MMIO2 range may overlap with base memory if a lot of RAM
934 * is configured for the VM, in which case we'll drop the base
935 * memory pages. Presently we will make no attempt to preserve
936 * anything that happens to be present in the base memory that
937 * is replaced, this is of course incorrectly but it's too much
938 * effort.
939 *
940 * @returns VBox status code.
941 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the memory.
942 * @retval VERR_ALREADY_EXISTS if the region already exists.
943 *
944 * @param pVM Pointer to the shared VM structure.
945 * @param pDevIns The device instance owning the region.
946 * @param iRegion The region number. If the MMIO2 memory is a PCI I/O region
947 * this number has to be the number of that region. Otherwise
948 * it can be any number safe UINT8_MAX.
949 * @param cb The size of the region. Must be page aligned.
950 * @param fFlags Reserved for future use, must be zero.
951 * @param ppv Where to store the pointer to the ring-3 mapping of the memory.
952 * @param pszDesc The description.
953 */
954VMMR3DECL(int) PGMR3PhysMMIO2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags, void **ppv, const char *pszDesc)
955{
956 /*
957 * Validate input.
958 */
959 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
960 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
961 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
962 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
963 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
964 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
965 AssertReturn(pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion) == NULL, VERR_ALREADY_EXISTS);
966 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
967 AssertReturn(cb, VERR_INVALID_PARAMETER);
968 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
969
970 const uint32_t cPages = cb >> PAGE_SHIFT;
971 AssertLogRelReturn((RTGCPHYS)cPages << PAGE_SHIFT == cb, VERR_INVALID_PARAMETER);
972 AssertLogRelReturn(cPages <= INT32_MAX / 2, VERR_NO_MEMORY);
973
974 /*
975 * Try reserve and allocate the backing memory first as this is what is
976 * most likely to fail.
977 */
978 int rc = MMR3AdjustFixedReservation(pVM, cPages, pszDesc);
979 if (RT_FAILURE(rc))
980 return rc;
981
982 void *pvPages;
983 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cPages * sizeof(SUPPAGE));
984 if (RT_SUCCESS(rc))
985 rc = SUPR3PageAllocEx(cPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
986 if (RT_SUCCESS(rc))
987 {
988 memset(pvPages, 0, cPages * PAGE_SIZE);
989
990 /*
991 * Create the MMIO2 range record for it.
992 */
993 const size_t cbRange = RT_OFFSETOF(PGMMMIO2RANGE, RamRange.aPages[cPages]);
994 PPGMMMIO2RANGE pNew;
995 rc = MMR3HyperAllocOnceNoRel(pVM, cbRange, 0, MM_TAG_PGM_PHYS, (void **)&pNew);
996 AssertLogRelMsgRC(rc, ("cbRamRange=%zu\n", cbRange));
997 if (RT_SUCCESS(rc))
998 {
999 pNew->pDevInsR3 = pDevIns;
1000 pNew->pvR3 = pvPages;
1001 //pNew->pNext = NULL;
1002 //pNew->fMapped = false;
1003 //pNew->fOverlapping = false;
1004 pNew->iRegion = iRegion;
1005 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
1006 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
1007 pNew->RamRange.pszDesc = pszDesc;
1008 pNew->RamRange.cb = cb;
1009 //pNew->RamRange.fFlags = 0;
1010
1011 pNew->RamRange.pvR3 = pvPages; ///@todo remove this [new phys code]
1012#ifndef VBOX_WITH_NEW_PHYS_CODE
1013 pNew->RamRange.paChunkR3Ptrs = NULL; ///@todo remove this [new phys code]
1014#endif
1015
1016 uint32_t iPage = cPages;
1017 while (iPage-- > 0)
1018 {
1019 PGM_PAGE_INIT(&pNew->RamRange.aPages[iPage],
1020 paPages[iPage].Phys & X86_PTE_PAE_PG_MASK, NIL_GMM_PAGEID,
1021 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
1022 }
1023
1024 /* update page count stats */
1025 pVM->pgm.s.cAllPages += cPages;
1026 pVM->pgm.s.cPrivatePages += cPages;
1027
1028 /*
1029 * Link it into the list.
1030 * Since there is no particular order, just push it.
1031 */
1032 pNew->pNextR3 = pVM->pgm.s.pMmio2RangesR3;
1033 pVM->pgm.s.pMmio2RangesR3 = pNew;
1034
1035 *ppv = pvPages;
1036 RTMemTmpFree(paPages);
1037 return VINF_SUCCESS;
1038 }
1039
1040 SUPR3PageFreeEx(pvPages, cPages);
1041 }
1042 RTMemTmpFree(paPages);
1043 MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pszDesc);
1044 return rc;
1045}
1046
1047
1048/**
1049 * Deregisters and frees an MMIO2 region.
1050 *
1051 * Any physical (and virtual) access handlers registered for the region must
1052 * be deregistered before calling this function.
1053 *
1054 * @returns VBox status code.
1055 * @param pVM Pointer to the shared VM structure.
1056 * @param pDevIns The device instance owning the region.
1057 * @param iRegion The region. If it's UINT32_MAX it'll be a wildcard match.
1058 */
1059VMMR3DECL(int) PGMR3PhysMMIO2Deregister(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion)
1060{
1061 /*
1062 * Validate input.
1063 */
1064 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1065 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
1066 AssertReturn(iRegion <= UINT8_MAX || iRegion == UINT32_MAX, VERR_INVALID_PARAMETER);
1067
1068 int rc = VINF_SUCCESS;
1069 unsigned cFound = 0;
1070 PPGMMMIO2RANGE pPrev = NULL;
1071 PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3;
1072 while (pCur)
1073 {
1074 if ( pCur->pDevInsR3 == pDevIns
1075 && ( iRegion == UINT32_MAX
1076 || pCur->iRegion == iRegion))
1077 {
1078 cFound++;
1079
1080 /*
1081 * Unmap it if it's mapped.
1082 */
1083 if (pCur->fMapped)
1084 {
1085 int rc2 = PGMR3PhysMMIO2Unmap(pVM, pCur->pDevInsR3, pCur->iRegion, pCur->RamRange.GCPhys);
1086 AssertRC(rc2);
1087 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1088 rc = rc2;
1089 }
1090
1091 /*
1092 * Unlink it
1093 */
1094 PPGMMMIO2RANGE pNext = pCur->pNextR3;
1095 if (pPrev)
1096 pPrev->pNextR3 = pNext;
1097 else
1098 pVM->pgm.s.pMmio2RangesR3 = pNext;
1099 pCur->pNextR3 = NULL;
1100
1101 /*
1102 * Free the memory.
1103 */
1104 int rc2 = SUPR3PageFreeEx(pCur->pvR3, pCur->RamRange.cb >> PAGE_SHIFT);
1105 AssertRC(rc2);
1106 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1107 rc = rc2;
1108
1109 uint32_t const cPages = pCur->RamRange.cb >> PAGE_SHIFT;
1110 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cPages, pCur->RamRange.pszDesc);
1111 AssertRC(rc2);
1112 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1113 rc = rc2;
1114
1115 /* we're leaking hyper memory here if done at runtime. */
1116 Assert( VMR3GetState(pVM) == VMSTATE_OFF
1117 || VMR3GetState(pVM) == VMSTATE_DESTROYING
1118 || VMR3GetState(pVM) == VMSTATE_TERMINATED
1119 || VMR3GetState(pVM) == VMSTATE_CREATING);
1120 /*rc = MMHyperFree(pVM, pCur);
1121 AssertRCReturn(rc, rc); - not safe, see the alloc call. */
1122
1123
1124 /* update page count stats */
1125 pVM->pgm.s.cAllPages -= cPages;
1126 pVM->pgm.s.cPrivatePages -= cPages;
1127
1128 /* next */
1129 pCur = pNext;
1130 }
1131 else
1132 {
1133 pPrev = pCur;
1134 pCur = pCur->pNextR3;
1135 }
1136 }
1137
1138 return !cFound && iRegion != UINT32_MAX ? VERR_NOT_FOUND : rc;
1139}
1140
1141
1142/**
1143 * Maps a MMIO2 region.
1144 *
1145 * This is done when a guest / the bios / state loading changes the
1146 * PCI config. The replacing of base memory has the same restrictions
1147 * as during registration, of course.
1148 *
1149 * @returns VBox status code.
1150 *
1151 * @param pVM Pointer to the shared VM structure.
1152 * @param pDevIns The
1153 */
1154VMMR3DECL(int) PGMR3PhysMMIO2Map(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
1155{
1156 /*
1157 * Validate input
1158 */
1159 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1160 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
1161 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
1162 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
1163 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
1164 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
1165
1166 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
1167 AssertReturn(pCur, VERR_NOT_FOUND);
1168 AssertReturn(!pCur->fMapped, VERR_WRONG_ORDER);
1169 Assert(pCur->RamRange.GCPhys == NIL_RTGCPHYS);
1170 Assert(pCur->RamRange.GCPhysLast == NIL_RTGCPHYS);
1171
1172 const RTGCPHYS GCPhysLast = GCPhys + pCur->RamRange.cb - 1;
1173 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
1174
1175 /*
1176 * Find our location in the ram range list, checking for
1177 * restriction we don't bother implementing yet (partially overlapping).
1178 */
1179 bool fRamExists = false;
1180 PPGMRAMRANGE pRamPrev = NULL;
1181 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
1182 while (pRam && GCPhysLast >= pRam->GCPhys)
1183 {
1184 if ( GCPhys <= pRam->GCPhysLast
1185 && GCPhysLast >= pRam->GCPhys)
1186 {
1187 /* completely within? */
1188 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
1189 && GCPhysLast <= pRam->GCPhysLast,
1190 ("%RGp-%RGp (MMIO2/%s) falls partly outside %RGp-%RGp (%s)\n",
1191 GCPhys, GCPhysLast, pCur->RamRange.pszDesc,
1192 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1193 VERR_PGM_RAM_CONFLICT);
1194 fRamExists = true;
1195 break;
1196 }
1197
1198 /* next */
1199 pRamPrev = pRam;
1200 pRam = pRam->pNextR3;
1201 }
1202 if (fRamExists)
1203 {
1204 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
1205 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
1206 while (cPagesLeft-- > 0)
1207 {
1208 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
1209 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
1210 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pCur->RamRange.pszDesc),
1211 VERR_PGM_RAM_CONFLICT);
1212 pPage++;
1213 }
1214 }
1215 Log(("PGMR3PhysMMIO2Map: %RGp-%RGp fRamExists=%RTbool %s\n",
1216 GCPhys, GCPhysLast, fRamExists, pCur->RamRange.pszDesc));
1217
1218 /*
1219 * Make the changes.
1220 */
1221 pgmLock(pVM);
1222
1223 pCur->RamRange.GCPhys = GCPhys;
1224 pCur->RamRange.GCPhysLast = GCPhysLast;
1225 pCur->fMapped = true;
1226 pCur->fOverlapping = fRamExists;
1227
1228 if (fRamExists)
1229 {
1230 uint32_t cPendingPages = 0;
1231 PGMMFREEPAGESREQ pReq;
1232 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1233 AssertLogRelRCReturn(rc, rc);
1234
1235 /* replace the pages, freeing all present RAM pages. */
1236 PPGMPAGE pPageSrc = &pCur->RamRange.aPages[0];
1237 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
1238 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
1239 while (cPagesLeft-- > 0)
1240 {
1241 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys);
1242 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
1243
1244 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
1245 PGM_PAGE_SET_HCPHYS(pPageDst, HCPhys);
1246 PGM_PAGE_SET_TYPE(pPageDst, PGMPAGETYPE_MMIO2);
1247 PGM_PAGE_SET_STATE(pPageDst, PGM_PAGE_STATE_ALLOCATED);
1248
1249 pVM->pgm.s.cZeroPages--;
1250 GCPhys += PAGE_SIZE;
1251 pPageSrc++;
1252 pPageDst++;
1253 }
1254
1255 if (cPendingPages)
1256 {
1257 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
1258 AssertLogRelRCReturn(rc, rc);
1259 }
1260 GMMR3FreePagesCleanup(pReq);
1261 }
1262 else
1263 {
1264 /* link in the ram range */
1265 pgmR3PhysLinkRamRange(pVM, &pCur->RamRange, pRamPrev);
1266 REMR3NotifyPhysRamRegister(pVM, GCPhys, pCur->RamRange.cb, REM_NOTIFY_PHYS_RAM_FLAGS_MMIO2);
1267 }
1268
1269 pgmUnlock(pVM);
1270
1271 return VINF_SUCCESS;
1272}
1273
1274
1275/**
1276 * Unmaps a MMIO2 region.
1277 *
1278 * This is done when a guest / the bios / state loading changes the
1279 * PCI config. The replacing of base memory has the same restrictions
1280 * as during registration, of course.
1281 */
1282VMMR3DECL(int) PGMR3PhysMMIO2Unmap(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS GCPhys)
1283{
1284 /*
1285 * Validate input
1286 */
1287 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1288 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
1289 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
1290 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
1291 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
1292 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
1293
1294 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
1295 AssertReturn(pCur, VERR_NOT_FOUND);
1296 AssertReturn(pCur->fMapped, VERR_WRONG_ORDER);
1297 AssertReturn(pCur->RamRange.GCPhys == GCPhys, VERR_INVALID_PARAMETER);
1298 Assert(pCur->RamRange.GCPhysLast != NIL_RTGCPHYS);
1299
1300 Log(("PGMR3PhysMMIO2Unmap: %RGp-%RGp %s\n",
1301 pCur->RamRange.GCPhys, pCur->RamRange.GCPhysLast, pCur->RamRange.pszDesc));
1302
1303 /*
1304 * Unmap it.
1305 */
1306 pgmLock(pVM);
1307
1308 if (pCur->fOverlapping)
1309 {
1310 /* Restore the RAM pages we've replaced. */
1311 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
1312 while (pRam->GCPhys > pCur->RamRange.GCPhysLast)
1313 pRam = pRam->pNextR3;
1314
1315 RTHCPHYS const HCPhysZeroPg = pVM->pgm.s.HCPhysZeroPg;
1316 Assert(HCPhysZeroPg != 0 && HCPhysZeroPg != NIL_RTHCPHYS);
1317 PPGMPAGE pPageDst = &pRam->aPages[(pCur->RamRange.GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
1318 uint32_t cPagesLeft = pCur->RamRange.cb >> PAGE_SHIFT;
1319 while (cPagesLeft-- > 0)
1320 {
1321 PGM_PAGE_SET_HCPHYS(pPageDst, HCPhysZeroPg);
1322 PGM_PAGE_SET_TYPE(pPageDst, PGMPAGETYPE_RAM);
1323 PGM_PAGE_SET_STATE(pPageDst, PGM_PAGE_STATE_ZERO);
1324 PGM_PAGE_SET_PAGEID(pPageDst, NIL_GMM_PAGEID);
1325
1326 pVM->pgm.s.cZeroPages++;
1327 pPageDst++;
1328 }
1329 }
1330 else
1331 {
1332 REMR3NotifyPhysRamDeregister(pVM, pCur->RamRange.GCPhys, pCur->RamRange.cb);
1333 pgmR3PhysUnlinkRamRange(pVM, &pCur->RamRange);
1334 }
1335
1336 pCur->RamRange.GCPhys = NIL_RTGCPHYS;
1337 pCur->RamRange.GCPhysLast = NIL_RTGCPHYS;
1338 pCur->fOverlapping = false;
1339 pCur->fMapped = false;
1340
1341 pgmUnlock(pVM);
1342
1343 return VINF_SUCCESS;
1344}
1345
1346
1347/**
1348 * Checks if the given address is an MMIO2 base address or not.
1349 *
1350 * @returns true/false accordingly.
1351 * @param pVM Pointer to the shared VM structure.
1352 * @param pDevIns The owner of the memory, optional.
1353 * @param GCPhys The address to check.
1354 */
1355VMMR3DECL(bool) PGMR3PhysMMIO2IsBase(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys)
1356{
1357 /*
1358 * Validate input
1359 */
1360 VM_ASSERT_EMT_RETURN(pVM, false);
1361 AssertPtrReturn(pDevIns, false);
1362 AssertReturn(GCPhys != NIL_RTGCPHYS, false);
1363 AssertReturn(GCPhys != 0, false);
1364 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), false);
1365
1366 /*
1367 * Search the list.
1368 */
1369 for (PPGMMMIO2RANGE pCur = pVM->pgm.s.pMmio2RangesR3; pCur; pCur = pCur->pNextR3)
1370 if (pCur->RamRange.GCPhys == GCPhys)
1371 {
1372 Assert(pCur->fMapped);
1373 return true;
1374 }
1375 return false;
1376}
1377
1378
1379/**
1380 * Gets the HC physical address of a page in the MMIO2 region.
1381 *
1382 * This is API is intended for MMHyper and shouldn't be called
1383 * by anyone else...
1384 *
1385 * @returns VBox status code.
1386 * @param pVM Pointer to the shared VM structure.
1387 * @param pDevIns The owner of the memory, optional.
1388 * @param iRegion The region.
1389 * @param off The page expressed an offset into the MMIO2 region.
1390 * @param pHCPhys Where to store the result.
1391 */
1392VMMR3DECL(int) PGMR3PhysMMIO2GetHCPhys(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, PRTHCPHYS pHCPhys)
1393{
1394 /*
1395 * Validate input
1396 */
1397 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1398 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
1399 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
1400
1401 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
1402 AssertReturn(pCur, VERR_NOT_FOUND);
1403 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
1404
1405 PCPGMPAGE pPage = &pCur->RamRange.aPages[off >> PAGE_SHIFT];
1406 *pHCPhys = PGM_PAGE_GET_HCPHYS(pPage);
1407 return VINF_SUCCESS;
1408}
1409
1410
1411/**
1412 * Maps a portion of an MMIO2 region into kernel space (host).
1413 *
1414 * The kernel mapping will become invalid when the MMIO2 memory is deregistered
1415 * or the VM is terminated.
1416 *
1417 * @return VBox status code.
1418 *
1419 * @param pVM Pointer to the shared VM structure.
1420 * @param pDevIns The device owning the MMIO2 memory.
1421 * @param iRegion The region.
1422 * @param off The offset into the region. Must be page aligned.
1423 * @param cb The number of bytes to map. Must be page aligned.
1424 * @param pszDesc Mapping description.
1425 * @param pR0Ptr Where to store the R0 address.
1426 */
1427VMMR3DECL(int) PGMR3PhysMMIO2MapKernel(PVM pVM, PPDMDEVINS pDevIns, uint32_t iRegion, RTGCPHYS off, RTGCPHYS cb,
1428 const char *pszDesc, PRTR0PTR pR0Ptr)
1429{
1430 /*
1431 * Validate input.
1432 */
1433 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1434 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
1435 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
1436
1437 PPGMMMIO2RANGE pCur = pgmR3PhysMMIO2Find(pVM, pDevIns, iRegion);
1438 AssertReturn(pCur, VERR_NOT_FOUND);
1439 AssertReturn(off < pCur->RamRange.cb, VERR_INVALID_PARAMETER);
1440 AssertReturn(cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
1441 AssertReturn(off + cb <= pCur->RamRange.cb, VERR_INVALID_PARAMETER);
1442
1443 /*
1444 * Pass the request on to the support library/driver.
1445 */
1446 int rc = SUPR3PageMapKernel(pCur->pvR3, off, cb, 0, pR0Ptr);
1447
1448 return rc;
1449}
1450
1451
1452/**
1453 * Registers a ROM image.
1454 *
1455 * Shadowed ROM images requires double the amount of backing memory, so,
1456 * don't use that unless you have to. Shadowing of ROM images is process
1457 * where we can select where the reads go and where the writes go. On real
1458 * hardware the chipset provides means to configure this. We provide
1459 * PGMR3PhysProtectROM() for this purpose.
1460 *
1461 * A read-only copy of the ROM image will always be kept around while we
1462 * will allocate RAM pages for the changes on demand (unless all memory
1463 * is configured to be preallocated).
1464 *
1465 * @returns VBox status.
1466 * @param pVM VM Handle.
1467 * @param pDevIns The device instance owning the ROM.
1468 * @param GCPhys First physical address in the range.
1469 * Must be page aligned!
1470 * @param cbRange The size of the range (in bytes).
1471 * Must be page aligned!
1472 * @param pvBinary Pointer to the binary data backing the ROM image.
1473 * This must be exactly \a cbRange in size.
1474 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAG_SHADOWED
1475 * and/or PGMPHYS_ROM_FLAG_PERMANENT_BINARY.
1476 * @param pszDesc Pointer to description string. This must not be freed.
1477 *
1478 * @remark There is no way to remove the rom, automatically on device cleanup or
1479 * manually from the device yet. This isn't difficult in any way, it's
1480 * just not something we expect to be necessary for a while.
1481 */
1482VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
1483 const void *pvBinary, uint32_t fFlags, const char *pszDesc)
1484{
1485 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p fFlags=%#x pszDesc=%s\n",
1486 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, fFlags, pszDesc));
1487
1488 /*
1489 * Validate input.
1490 */
1491 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
1492 AssertReturn(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
1493 AssertReturn(RT_ALIGN_T(cb, PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
1494 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1495 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
1496 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
1497 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1498 AssertReturn(!(fFlags & ~(PGMPHYS_ROM_FLAG_SHADOWED | PGMPHYS_ROM_FLAG_PERMANENT_BINARY)), VERR_INVALID_PARAMETER);
1499 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
1500
1501 const uint32_t cPages = cb >> PAGE_SHIFT;
1502
1503 /*
1504 * Find the ROM location in the ROM list first.
1505 */
1506 PPGMROMRANGE pRomPrev = NULL;
1507 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
1508 while (pRom && GCPhysLast >= pRom->GCPhys)
1509 {
1510 if ( GCPhys <= pRom->GCPhysLast
1511 && GCPhysLast >= pRom->GCPhys)
1512 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
1513 GCPhys, GCPhysLast, pszDesc,
1514 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
1515 VERR_PGM_RAM_CONFLICT);
1516 /* next */
1517 pRomPrev = pRom;
1518 pRom = pRom->pNextR3;
1519 }
1520
1521 /*
1522 * Find the RAM location and check for conflicts.
1523 *
1524 * Conflict detection is a bit different than for RAM
1525 * registration since a ROM can be located within a RAM
1526 * range. So, what we have to check for is other memory
1527 * types (other than RAM that is) and that we don't span
1528 * more than one RAM range (layz).
1529 */
1530 bool fRamExists = false;
1531 PPGMRAMRANGE pRamPrev = NULL;
1532 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesR3;
1533 while (pRam && GCPhysLast >= pRam->GCPhys)
1534 {
1535 if ( GCPhys <= pRam->GCPhysLast
1536 && GCPhysLast >= pRam->GCPhys)
1537 {
1538 /* completely within? */
1539 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
1540 && GCPhysLast <= pRam->GCPhysLast,
1541 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
1542 GCPhys, GCPhysLast, pszDesc,
1543 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1544 VERR_PGM_RAM_CONFLICT);
1545 fRamExists = true;
1546 break;
1547 }
1548
1549 /* next */
1550 pRamPrev = pRam;
1551 pRam = pRam->pNextR3;
1552 }
1553 if (fRamExists)
1554 {
1555 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
1556 uint32_t cPagesLeft = cPages;
1557 while (cPagesLeft-- > 0)
1558 {
1559 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
1560 ("%RGp isn't a RAM page (%d) - registering %RGp-%RGp (%s).\n",
1561 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pszDesc),
1562 VERR_PGM_RAM_CONFLICT);
1563 Assert(PGM_PAGE_IS_ZERO(pPage));
1564 pPage++;
1565 }
1566 }
1567
1568 /*
1569 * Update the base memory reservation if necessary.
1570 */
1571 uint32_t cExtraBaseCost = fRamExists ? cPages : 0;
1572 if (fFlags & PGMPHYS_ROM_FLAG_SHADOWED)
1573 cExtraBaseCost += cPages;
1574 if (cExtraBaseCost)
1575 {
1576 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
1577 if (RT_FAILURE(rc))
1578 return rc;
1579 }
1580
1581 /*
1582 * Allocate memory for the virgin copy of the RAM.
1583 */
1584 PGMMALLOCATEPAGESREQ pReq;
1585 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cPages, GMMACCOUNT_BASE);
1586 AssertRCReturn(rc, rc);
1587
1588 for (uint32_t iPage = 0; iPage < cPages; iPage++)
1589 {
1590 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << PAGE_SHIFT);
1591 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
1592 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
1593 }
1594
1595 pgmLock(pVM);
1596 rc = GMMR3AllocatePagesPerform(pVM, pReq);
1597 pgmUnlock(pVM);
1598 if (RT_FAILURE(rc))
1599 {
1600 GMMR3AllocatePagesCleanup(pReq);
1601 return rc;
1602 }
1603
1604 /*
1605 * Allocate the new ROM range and RAM range (if necessary).
1606 */
1607 PPGMROMRANGE pRomNew;
1608 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMROMRANGE, aPages[cPages]), 0, MM_TAG_PGM_PHYS, (void **)&pRomNew);
1609 if (RT_SUCCESS(rc))
1610 {
1611 PPGMRAMRANGE pRamNew = NULL;
1612 if (!fRamExists)
1613 rc = MMHyperAlloc(pVM, RT_OFFSETOF(PGMRAMRANGE, aPages[cPages]), sizeof(PGMPAGE), MM_TAG_PGM_PHYS, (void **)&pRamNew);
1614 if (RT_SUCCESS(rc))
1615 {
1616 pgmLock(pVM);
1617
1618 /*
1619 * Initialize and insert the RAM range (if required).
1620 */
1621 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
1622 if (!fRamExists)
1623 {
1624 pRamNew->GCPhys = GCPhys;
1625 pRamNew->GCPhysLast = GCPhysLast;
1626 pRamNew->pszDesc = pszDesc;
1627 pRamNew->cb = cb;
1628 pRamNew->fFlags = 0;
1629 pRamNew->pvR3 = NULL;
1630
1631 PPGMPAGE pPage = &pRamNew->aPages[0];
1632 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
1633 {
1634 PGM_PAGE_INIT(pPage,
1635 pReq->aPages[iPage].HCPhysGCPhys,
1636 pReq->aPages[iPage].idPage,
1637 PGMPAGETYPE_ROM,
1638 PGM_PAGE_STATE_ALLOCATED);
1639
1640 pRomPage->Virgin = *pPage;
1641 }
1642
1643 pVM->pgm.s.cAllPages += cPages;
1644 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
1645 }
1646 else
1647 {
1648 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> PAGE_SHIFT];
1649 for (uint32_t iPage = 0; iPage < cPages; iPage++, pPage++, pRomPage++)
1650 {
1651 PGM_PAGE_SET_TYPE(pPage, PGMPAGETYPE_ROM);
1652 PGM_PAGE_SET_HCPHYS(pPage, pReq->aPages[iPage].HCPhysGCPhys);
1653 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ALLOCATED);
1654 PGM_PAGE_SET_PAGEID(pPage, pReq->aPages[iPage].idPage);
1655
1656 pRomPage->Virgin = *pPage;
1657 }
1658
1659 pRamNew = pRam;
1660
1661 pVM->pgm.s.cZeroPages -= cPages;
1662 }
1663 pVM->pgm.s.cPrivatePages += cPages;
1664
1665 pgmUnlock(pVM);
1666
1667
1668 /*
1669 * !HACK ALERT! REM + (Shadowed) ROM ==> mess.
1670 *
1671 * If it's shadowed we'll register the handler after the ROM notification
1672 * so we get the access handler callbacks that we should. If it isn't
1673 * shadowed we'll do it the other way around to make REM use the built-in
1674 * ROM behavior and not the handler behavior (which is to route all access
1675 * to PGM atm).
1676 */
1677 if (fFlags & PGMPHYS_ROM_FLAG_SHADOWED)
1678 {
1679 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, true /* fShadowed */);
1680 rc = PGMR3HandlerPhysicalRegister(pVM,
1681 fFlags & PGMPHYS_ROM_FLAG_SHADOWED
1682 ? PGMPHYSHANDLERTYPE_PHYSICAL_ALL
1683 : PGMPHYSHANDLERTYPE_PHYSICAL_WRITE,
1684 GCPhys, GCPhysLast,
1685 pgmR3PhysRomWriteHandler, pRomNew,
1686 NULL, "pgmPhysRomWriteHandler", MMHyperCCToR0(pVM, pRomNew),
1687 NULL, "pgmPhysRomWriteHandler", MMHyperCCToRC(pVM, pRomNew), pszDesc);
1688 }
1689 else
1690 {
1691 rc = PGMR3HandlerPhysicalRegister(pVM,
1692 fFlags & PGMPHYS_ROM_FLAG_SHADOWED
1693 ? PGMPHYSHANDLERTYPE_PHYSICAL_ALL
1694 : PGMPHYSHANDLERTYPE_PHYSICAL_WRITE,
1695 GCPhys, GCPhysLast,
1696 pgmR3PhysRomWriteHandler, pRomNew,
1697 NULL, "pgmPhysRomWriteHandler", MMHyperCCToR0(pVM, pRomNew),
1698 NULL, "pgmPhysRomWriteHandler", MMHyperCCToRC(pVM, pRomNew), pszDesc);
1699 REMR3NotifyPhysRomRegister(pVM, GCPhys, cb, NULL, false /* fShadowed */);
1700 }
1701 if (RT_SUCCESS(rc))
1702 {
1703 pgmLock(pVM);
1704
1705 /*
1706 * Copy the image over to the virgin pages.
1707 * This must be done after linking in the RAM range.
1708 */
1709 PPGMPAGE pRamPage = &pRamNew->aPages[(GCPhys - pRamNew->GCPhys) >> PAGE_SHIFT];
1710 for (uint32_t iPage = 0; iPage < cPages; iPage++, pRamPage++)
1711 {
1712 void *pvDstPage;
1713 PPGMPAGEMAP pMapIgnored;
1714 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << PAGE_SHIFT), &pMapIgnored, &pvDstPage);
1715 if (RT_FAILURE(rc))
1716 {
1717 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
1718 break;
1719 }
1720 memcpy(pvDstPage, (const uint8_t *)pvBinary + (iPage << PAGE_SHIFT), PAGE_SIZE);
1721 }
1722 if (RT_SUCCESS(rc))
1723 {
1724 /*
1725 * Initialize the ROM range.
1726 * Note that the Virgin member of the pages has already been initialized above.
1727 */
1728 pRomNew->GCPhys = GCPhys;
1729 pRomNew->GCPhysLast = GCPhysLast;
1730 pRomNew->cb = cb;
1731 pRomNew->fFlags = fFlags;
1732 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAG_PERMANENT_BINARY ? pvBinary : NULL;
1733 pRomNew->pszDesc = pszDesc;
1734
1735 for (unsigned iPage = 0; iPage < cPages; iPage++)
1736 {
1737 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
1738 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
1739 PGM_PAGE_INIT_ZERO_REAL(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
1740 }
1741
1742 /* update the page count stats */
1743 pVM->pgm.s.cZeroPages += cPages;
1744 pVM->pgm.s.cAllPages += cPages;
1745
1746 /*
1747 * Insert the ROM range, tell REM and return successfully.
1748 */
1749 pRomNew->pNextR3 = pRom;
1750 pRomNew->pNextR0 = pRom ? MMHyperCCToR0(pVM, pRom) : NIL_RTR0PTR;
1751 pRomNew->pNextRC = pRom ? MMHyperCCToRC(pVM, pRom) : NIL_RTRCPTR;
1752
1753 if (pRomPrev)
1754 {
1755 pRomPrev->pNextR3 = pRomNew;
1756 pRomPrev->pNextR0 = MMHyperCCToR0(pVM, pRomNew);
1757 pRomPrev->pNextRC = MMHyperCCToRC(pVM, pRomNew);
1758 }
1759 else
1760 {
1761 pVM->pgm.s.pRomRangesR3 = pRomNew;
1762 pVM->pgm.s.pRomRangesR0 = MMHyperCCToR0(pVM, pRomNew);
1763 pVM->pgm.s.pRomRangesRC = MMHyperCCToRC(pVM, pRomNew);
1764 }
1765
1766 GMMR3AllocatePagesCleanup(pReq);
1767 pgmUnlock(pVM);
1768 return VINF_SUCCESS;
1769 }
1770
1771 /* bail out */
1772
1773 pgmUnlock(pVM);
1774 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
1775 AssertRC(rc2);
1776 pgmLock(pVM);
1777 }
1778
1779 if (!fRamExists)
1780 {
1781 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
1782 MMHyperFree(pVM, pRamNew);
1783 }
1784 }
1785 MMHyperFree(pVM, pRomNew);
1786 }
1787
1788 /** @todo Purge the mapping cache or something... */
1789 GMMR3FreeAllocatedPages(pVM, pReq);
1790 GMMR3AllocatePagesCleanup(pReq);
1791 pgmUnlock(pVM);
1792 return rc;
1793}
1794
1795
1796/**
1797 * \#PF Handler callback for ROM write accesses.
1798 *
1799 * @returns VINF_SUCCESS if the handler have carried out the operation.
1800 * @returns VINF_PGM_HANDLER_DO_DEFAULT if the caller should carry out the access operation.
1801 * @param pVM VM Handle.
1802 * @param GCPhys The physical address the guest is writing to.
1803 * @param pvPhys The HC mapping of that address.
1804 * @param pvBuf What the guest is reading/writing.
1805 * @param cbBuf How much it's reading/writing.
1806 * @param enmAccessType The access type.
1807 * @param pvUser User argument.
1808 */
1809static DECLCALLBACK(int) pgmR3PhysRomWriteHandler(PVM pVM, RTGCPHYS GCPhys, void *pvPhys, void *pvBuf, size_t cbBuf, PGMACCESSTYPE enmAccessType, void *pvUser)
1810{
1811 PPGMROMRANGE pRom = (PPGMROMRANGE)pvUser;
1812 const uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
1813 Assert(iPage < (pRom->cb >> PAGE_SHIFT));
1814 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
1815 switch (pRomPage->enmProt)
1816 {
1817 /*
1818 * Ignore.
1819 */
1820 case PGMROMPROT_READ_ROM_WRITE_IGNORE:
1821 case PGMROMPROT_READ_RAM_WRITE_IGNORE:
1822 return VINF_SUCCESS;
1823
1824 /*
1825 * Write to the ram page.
1826 */
1827 case PGMROMPROT_READ_ROM_WRITE_RAM:
1828 case PGMROMPROT_READ_RAM_WRITE_RAM: /* yes this will get here too, it's *way* simpler that way. */
1829 {
1830 /* This should be impossible now, pvPhys doesn't work cross page anylonger. */
1831 Assert(((GCPhys - pRom->GCPhys + cbBuf - 1) >> PAGE_SHIFT) == iPage);
1832
1833 /*
1834 * Take the lock, do lazy allocation, map the page and copy the data.
1835 *
1836 * Note that we have to bypass the mapping TLB since it works on
1837 * guest physical addresses and entering the shadow page would
1838 * kind of screw things up...
1839 */
1840 int rc = pgmLock(pVM);
1841 AssertRC(rc);
1842
1843 if (RT_UNLIKELY(PGM_PAGE_GET_STATE(&pRomPage->Shadow) != PGM_PAGE_STATE_ALLOCATED))
1844 {
1845 rc = pgmPhysPageMakeWritable(pVM, &pRomPage->Shadow, GCPhys);
1846 if (RT_FAILURE(rc))
1847 {
1848 pgmUnlock(pVM);
1849 return rc;
1850 }
1851 AssertMsg(rc == VINF_SUCCESS || rc == VINF_PGM_SYNC_CR3 /* returned */, ("%Rrc\n", rc));
1852 }
1853
1854 void *pvDstPage;
1855 PPGMPAGEMAP pMapIgnored;
1856 int rc2 = pgmPhysPageMap(pVM, &pRomPage->Shadow, GCPhys & X86_PTE_PG_MASK, &pMapIgnored, &pvDstPage);
1857 if (RT_SUCCESS(rc2))
1858 memcpy((uint8_t *)pvDstPage + (GCPhys & PAGE_OFFSET_MASK), pvBuf, cbBuf);
1859 else
1860 rc = rc2;
1861
1862 pgmUnlock(pVM);
1863 return rc;
1864 }
1865
1866 default:
1867 AssertMsgFailedReturn(("enmProt=%d iPage=%d GCPhys=%RGp\n",
1868 pRom->aPages[iPage].enmProt, iPage, GCPhys),
1869 VERR_INTERNAL_ERROR);
1870 }
1871}
1872
1873
1874/**
1875 * Called by PGMR3Reset to reset the shadow, switch to the virgin,
1876 * and verify that the virgin part is untouched.
1877 *
1878 * This is done after the normal memory has been cleared.
1879 *
1880 * ASSUMES that the caller owns the PGM lock.
1881 *
1882 * @param pVM The VM handle.
1883 */
1884int pgmR3PhysRomReset(PVM pVM)
1885{
1886 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
1887 {
1888 const uint32_t cPages = pRom->cb >> PAGE_SHIFT;
1889
1890 if (pRom->fFlags & PGMPHYS_ROM_FLAG_SHADOWED)
1891 {
1892 /*
1893 * Reset the physical handler.
1894 */
1895 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
1896 AssertRCReturn(rc, rc);
1897
1898 /*
1899 * What we do with the shadow pages depends on the memory
1900 * preallocation option. If not enabled, we'll just throw
1901 * out all the dirty pages and replace them by the zero page.
1902 */
1903 if (!pVM->pgm.s.fRamPreAlloc)
1904 {
1905 /* Count dirty shadow pages. */
1906 uint32_t cDirty = 0;
1907 uint32_t iPage = cPages;
1908 while (iPage-- > 0)
1909 if (PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) != PGM_PAGE_STATE_ZERO)
1910 cDirty++;
1911 if (cDirty)
1912 {
1913 /* Free the dirty pages. */
1914 PGMMFREEPAGESREQ pReq;
1915 rc = GMMR3FreePagesPrepare(pVM, &pReq, cDirty, GMMACCOUNT_BASE);
1916 AssertRCReturn(rc, rc);
1917
1918 uint32_t iReqPage = 0;
1919 for (iPage = 0; iPage < cPages; iPage++)
1920 if (PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) != PGM_PAGE_STATE_ZERO)
1921 {
1922 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
1923 pReq->aPages[iReqPage].idPage = PGM_PAGE_GET_PAGEID(&pRom->aPages[iPage].Shadow);
1924 iReqPage++;
1925 }
1926
1927 rc = GMMR3FreePagesPerform(pVM, pReq, cDirty);
1928 GMMR3FreePagesCleanup(pReq);
1929 AssertRCReturn(rc, rc);
1930
1931 /* setup the zero page. */
1932 for (iPage = 0; iPage < cPages; iPage++)
1933 if (PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) != PGM_PAGE_STATE_ZERO)
1934 PGM_PAGE_INIT_ZERO_REAL(&pRom->aPages[iPage].Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
1935
1936 /* update the page count stats. */
1937 pVM->pgm.s.cPrivatePages -= cDirty;
1938 pVM->pgm.s.cZeroPages += cDirty;
1939 }
1940 }
1941 else
1942 {
1943 /* clear all the pages. */
1944 for (uint32_t iPage = 0; iPage < cPages; iPage++)
1945 {
1946 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) != PGM_PAGE_STATE_ZERO);
1947
1948 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
1949 rc = pgmPhysPageMakeWritable(pVM, &pRom->aPages[iPage].Shadow, GCPhys);
1950 if (RT_FAILURE(rc))
1951 break;
1952
1953 void *pvDstPage;
1954 PPGMPAGEMAP pMapIgnored;
1955 rc = pgmPhysPageMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pMapIgnored, &pvDstPage);
1956 if (RT_FAILURE(rc))
1957 break;
1958 ASMMemZeroPage(pvDstPage);
1959 }
1960 AssertRCReturn(rc, rc);
1961 }
1962 }
1963
1964#ifdef VBOX_STRICT
1965 /*
1966 * Verify that the virgin page is unchanged if possible.
1967 */
1968 if (pRom->pvOriginal)
1969 {
1970 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
1971 for (uint32_t iPage = 0; iPage < cPages; iPage++, pbSrcPage += PAGE_SIZE)
1972 {
1973 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << PAGE_SHIFT);
1974 PPGMPAGEMAP pMapIgnored;
1975 void *pvDstPage;
1976 int rc = pgmPhysPageMap(pVM, &pRom->aPages[iPage].Virgin, GCPhys, &pMapIgnored, &pvDstPage);
1977 if (RT_FAILURE(rc))
1978 break;
1979 if (memcmp(pvDstPage, pbSrcPage, PAGE_SIZE))
1980 LogRel(("pgmR3PhysRomReset: %RGp rom page changed (%s) - loaded saved state?\n",
1981 GCPhys, pRom->pszDesc));
1982 }
1983 }
1984#endif
1985 }
1986
1987 return VINF_SUCCESS;
1988}
1989
1990
1991/**
1992 * Change the shadowing of a range of ROM pages.
1993 *
1994 * This is intended for implementing chipset specific memory registers
1995 * and will not be very strict about the input. It will silently ignore
1996 * any pages that are not the part of a shadowed ROM.
1997 *
1998 * @returns VBox status code.
1999 * @param pVM Pointer to the shared VM structure.
2000 * @param GCPhys Where to start. Page aligned.
2001 * @param cb How much to change. Page aligned.
2002 * @param enmProt The new ROM protection.
2003 */
2004VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
2005{
2006 /*
2007 * Check input
2008 */
2009 if (!cb)
2010 return VINF_SUCCESS;
2011 AssertReturn(!(GCPhys & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2012 AssertReturn(!(cb & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2013 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2014 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2015 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
2016
2017 /*
2018 * Process the request.
2019 */
2020 bool fFlushedPool = false;
2021 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
2022 if ( GCPhys <= pRom->GCPhysLast
2023 && GCPhysLast >= pRom->GCPhys
2024 && (pRom->fFlags & PGMPHYS_ROM_FLAG_SHADOWED))
2025 {
2026 /*
2027 * Iterate the relevant pages and the ncessary make changes.
2028 */
2029 bool fChanges = false;
2030 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
2031 ? pRom->cb >> PAGE_SHIFT
2032 : (GCPhysLast - pRom->GCPhys) >> PAGE_SHIFT;
2033 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> PAGE_SHIFT;
2034 iPage < cPages;
2035 iPage++)
2036 {
2037 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
2038 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
2039 {
2040 fChanges = true;
2041
2042 /* flush the page pool first so we don't leave any usage references dangling. */
2043 if (!fFlushedPool)
2044 {
2045 pgmPoolFlushAll(pVM);
2046 fFlushedPool = true;
2047 }
2048
2049 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
2050 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
2051 PPGMPAGE pRamPage = pgmPhysGetPage(&pVM->pgm.s, pRom->GCPhys + (iPage << PAGE_SHIFT));
2052
2053 *pOld = *pRamPage;
2054 *pRamPage = *pNew;
2055 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
2056 }
2057 }
2058
2059 /*
2060 * Reset the access handler if we made changes, no need
2061 * to optimize this.
2062 */
2063 if (fChanges)
2064 {
2065 int rc = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
2066 AssertRCReturn(rc, rc);
2067 }
2068
2069 /* Advance - cb isn't updated. */
2070 GCPhys = pRom->GCPhys + (cPages << PAGE_SHIFT);
2071 }
2072
2073 return VINF_SUCCESS;
2074}
2075
2076#ifndef VBOX_WITH_NEW_PHYS_CODE
2077
2078/**
2079 * Interface that the MMR3RamRegister(), MMR3RomRegister() and MMIO handler
2080 * registration APIs calls to inform PGM about memory registrations.
2081 *
2082 * It registers the physical memory range with PGM. MM is responsible
2083 * for the toplevel things - allocation and locking - while PGM is taking
2084 * care of all the details and implements the physical address space virtualization.
2085 *
2086 * @returns VBox status.
2087 * @param pVM The VM handle.
2088 * @param pvRam HC virtual address of the RAM range. (page aligned)
2089 * @param GCPhys GC physical address of the RAM range. (page aligned)
2090 * @param cb Size of the RAM range. (page aligned)
2091 * @param fFlags Flags, MM_RAM_*.
2092 * @param paPages Pointer an array of physical page descriptors.
2093 * @param pszDesc Description string.
2094 */
2095VMMR3DECL(int) PGMR3PhysRegister(PVM pVM, void *pvRam, RTGCPHYS GCPhys, size_t cb, unsigned fFlags, const SUPPAGE *paPages, const char *pszDesc)
2096{
2097 /*
2098 * Validate input.
2099 * (Not so important because callers are only MMR3PhysRegister()
2100 * and PGMR3HandlerPhysicalRegisterEx(), but anyway...)
2101 */
2102 Log(("PGMR3PhysRegister %08X %x bytes flags %x %s\n", GCPhys, cb, fFlags, pszDesc));
2103
2104 Assert((fFlags & (MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_DYNAMIC_ALLOC)) || paPages);
2105 /*Assert(!(fFlags & MM_RAM_FLAGS_RESERVED) || !paPages);*/
2106 Assert((fFlags == (MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_MMIO)) || (fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC) || pvRam);
2107 /*Assert(!(fFlags & MM_RAM_FLAGS_RESERVED) || !pvRam);*/
2108 Assert(!(fFlags & ~0xfff));
2109 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb && cb);
2110 Assert(RT_ALIGN_P(pvRam, PAGE_SIZE) == pvRam);
2111 Assert(!(fFlags & ~(MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_ROM | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_MMIO2 | MM_RAM_FLAGS_DYNAMIC_ALLOC)));
2112 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2113 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2114 if (GCPhysLast < GCPhys)
2115 {
2116 AssertMsgFailed(("The range wraps! GCPhys=%RGp cb=%#x\n", GCPhys, cb));
2117 return VERR_INVALID_PARAMETER;
2118 }
2119
2120 /*
2121 * Find range location and check for conflicts.
2122 */
2123 PPGMRAMRANGE pPrev = NULL;
2124 PPGMRAMRANGE pCur = pVM->pgm.s.pRamRangesR3;
2125 while (pCur)
2126 {
2127 if (GCPhys <= pCur->GCPhysLast && GCPhysLast >= pCur->GCPhys)
2128 {
2129 AssertMsgFailed(("Conflict! This cannot happen!\n"));
2130 return VERR_PGM_RAM_CONFLICT;
2131 }
2132 if (GCPhysLast < pCur->GCPhys)
2133 break;
2134
2135 /* next */
2136 pPrev = pCur;
2137 pCur = pCur->pNextR3;
2138 }
2139
2140 /*
2141 * Allocate RAM range.
2142 * Small ranges are allocated from the heap, big ones have separate mappings.
2143 */
2144 size_t cbRam = RT_OFFSETOF(PGMRAMRANGE, aPages[cb >> PAGE_SHIFT]);
2145 PPGMRAMRANGE pNew;
2146 int rc = VERR_NO_MEMORY;
2147 if (cbRam > PAGE_SIZE / 2)
2148 { /* large */
2149 cbRam = RT_ALIGN_Z(cbRam, PAGE_SIZE);
2150 rc = MMR3HyperAllocOnceNoRel(pVM, cbRam, PAGE_SIZE, MM_TAG_PGM_PHYS, (void **)&pNew);
2151 AssertMsgRC(rc, ("MMR3HyperAllocOnceNoRel(,%#x,,) -> %Rrc\n", cbRam, rc));
2152 }
2153 else
2154 { /* small */
2155 rc = MMHyperAlloc(pVM, cbRam, 16, MM_TAG_PGM, (void **)&pNew);
2156 AssertMsgRC(rc, ("MMHyperAlloc(,%#x,,,) -> %Rrc\n", cbRam, rc));
2157 }
2158 if (RT_SUCCESS(rc))
2159 {
2160 /*
2161 * Initialize the range.
2162 */
2163 pNew->pvR3 = pvRam;
2164 pNew->GCPhys = GCPhys;
2165 pNew->GCPhysLast = GCPhysLast;
2166 pNew->cb = cb;
2167 pNew->fFlags = fFlags;
2168 pNew->paChunkR3Ptrs = NULL;
2169
2170 unsigned iPage = (unsigned)(cb >> PAGE_SHIFT);
2171 if (paPages)
2172 {
2173 while (iPage-- > 0)
2174 {
2175 PGM_PAGE_INIT(&pNew->aPages[iPage], paPages[iPage].Phys & X86_PTE_PAE_PG_MASK, NIL_GMM_PAGEID,
2176 fFlags & MM_RAM_FLAGS_MMIO2 ? PGMPAGETYPE_MMIO2 : PGMPAGETYPE_RAM,
2177 PGM_PAGE_STATE_ALLOCATED);
2178 pNew->aPages[iPage].HCPhys |= fFlags; /** @todo PAGE FLAGS*/
2179 }
2180 }
2181 else if (fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC)
2182 {
2183 /* Allocate memory for chunk to HC ptr lookup array. */
2184 rc = MMHyperAlloc(pVM, (cb >> PGM_DYNAMIC_CHUNK_SHIFT) * sizeof(void *), 16, MM_TAG_PGM, (void **)&pNew->paChunkR3Ptrs);
2185 AssertMsgReturn(rc == VINF_SUCCESS, ("MMHyperAlloc(,%#x,,,) -> %Rrc\n", cbRam, cb), rc);
2186
2187 /* Physical memory will be allocated on demand. */
2188 while (iPage-- > 0)
2189 {
2190 PGM_PAGE_INIT(&pNew->aPages[iPage], 0, NIL_GMM_PAGEID, PGMPAGETYPE_RAM, PGM_PAGE_STATE_ZERO);
2191 pNew->aPages[iPage].HCPhys = fFlags; /** @todo PAGE FLAGS */
2192 }
2193 }
2194 else
2195 {
2196 Assert(fFlags == (MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_MMIO));
2197 RTHCPHYS HCPhysDummyPage = MMR3PageDummyHCPhys(pVM);
2198 while (iPage-- > 0)
2199 {
2200 PGM_PAGE_INIT(&pNew->aPages[iPage], HCPhysDummyPage, NIL_GMM_PAGEID, PGMPAGETYPE_MMIO, PGM_PAGE_STATE_ZERO);
2201 pNew->aPages[iPage].HCPhys |= fFlags; /** @todo PAGE FLAGS*/
2202 }
2203 }
2204
2205 /*
2206 * Insert the new RAM range.
2207 */
2208 pgmLock(pVM);
2209 pNew->pNextR3 = pCur;
2210 pNew->pNextR0 = pCur ? MMHyperCCToR0(pVM, pCur) : NIL_RTR0PTR;
2211 pNew->pNextRC = pCur ? MMHyperCCToRC(pVM, pCur) : NIL_RTRCPTR;
2212 if (pPrev)
2213 {
2214 pPrev->pNextR3 = pNew;
2215 pPrev->pNextR0 = MMHyperCCToR0(pVM, pNew);
2216 pPrev->pNextRC = MMHyperCCToRC(pVM, pNew);
2217 }
2218 else
2219 {
2220 pVM->pgm.s.pRamRangesR3 = pNew;
2221 pVM->pgm.s.pRamRangesR0 = MMHyperCCToR0(pVM, pNew);
2222 pVM->pgm.s.pRamRangesRC = MMHyperCCToRC(pVM, pNew);
2223 }
2224 pgmUnlock(pVM);
2225 }
2226 return rc;
2227}
2228
2229
2230/**
2231 * Register a chunk of a the physical memory range with PGM. MM is responsible
2232 * for the toplevel things - allocation and locking - while PGM is taking
2233 * care of all the details and implements the physical address space virtualization.
2234 *
2235 *
2236 * @returns VBox status.
2237 * @param pVM The VM handle.
2238 * @param pvRam HC virtual address of the RAM range. (page aligned)
2239 * @param GCPhys GC physical address of the RAM range. (page aligned)
2240 * @param cb Size of the RAM range. (page aligned)
2241 * @param fFlags Flags, MM_RAM_*.
2242 * @param paPages Pointer an array of physical page descriptors.
2243 * @param pszDesc Description string.
2244 */
2245VMMR3DECL(int) PGMR3PhysRegisterChunk(PVM pVM, void *pvRam, RTGCPHYS GCPhys, size_t cb, unsigned fFlags, const SUPPAGE *paPages, const char *pszDesc)
2246{
2247 NOREF(pszDesc);
2248
2249 /*
2250 * Validate input.
2251 * (Not so important because callers are only MMR3PhysRegister()
2252 * and PGMR3HandlerPhysicalRegisterEx(), but anyway...)
2253 */
2254 Log(("PGMR3PhysRegisterChunk %08X %x bytes flags %x %s\n", GCPhys, cb, fFlags, pszDesc));
2255
2256 Assert(paPages);
2257 Assert(pvRam);
2258 Assert(!(fFlags & ~0xfff));
2259 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb && cb);
2260 Assert(RT_ALIGN_P(pvRam, PAGE_SIZE) == pvRam);
2261 Assert(!(fFlags & ~(MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_ROM | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_MMIO2 | MM_RAM_FLAGS_DYNAMIC_ALLOC)));
2262 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2263 Assert(VM_IS_EMT(pVM));
2264 Assert(!(GCPhys & PGM_DYNAMIC_CHUNK_OFFSET_MASK));
2265 Assert(cb == PGM_DYNAMIC_CHUNK_SIZE);
2266
2267 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2268 if (GCPhysLast < GCPhys)
2269 {
2270 AssertMsgFailed(("The range wraps! GCPhys=%RGp cb=%#x\n", GCPhys, cb));
2271 return VERR_INVALID_PARAMETER;
2272 }
2273
2274 /*
2275 * Find existing range location.
2276 */
2277 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
2278 while (pRam)
2279 {
2280 RTGCPHYS off = GCPhys - pRam->GCPhys;
2281 if ( off < pRam->cb
2282 && (pRam->fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC))
2283 break;
2284
2285 pRam = pRam->CTX_SUFF(pNext);
2286 }
2287 AssertReturn(pRam, VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS);
2288
2289 unsigned off = (GCPhys - pRam->GCPhys) >> PAGE_SHIFT;
2290 unsigned iPage = (unsigned)(cb >> PAGE_SHIFT);
2291 if (paPages)
2292 {
2293 while (iPage-- > 0)
2294 pRam->aPages[off + iPage].HCPhys = (paPages[iPage].Phys & X86_PTE_PAE_PG_MASK) | fFlags; /** @todo PAGE FLAGS */
2295 }
2296 off >>= (PGM_DYNAMIC_CHUNK_SHIFT - PAGE_SHIFT);
2297 pRam->paChunkR3Ptrs[off] = (uintptr_t)pvRam;
2298
2299 /* Notify the recompiler. */
2300 REMR3NotifyPhysRamChunkRegister(pVM, GCPhys, PGM_DYNAMIC_CHUNK_SIZE, (RTHCUINTPTR)pvRam, fFlags);
2301
2302 return VINF_SUCCESS;
2303}
2304
2305
2306/**
2307 * Allocate missing physical pages for an existing guest RAM range.
2308 *
2309 * @returns VBox status.
2310 * @param pVM The VM handle.
2311 * @param GCPhys GC physical address of the RAM range. (page aligned)
2312 */
2313VMMR3DECL(int) PGM3PhysGrowRange(PVM pVM, PCRTGCPHYS pGCPhys)
2314{
2315 RTGCPHYS GCPhys = *pGCPhys;
2316
2317 /*
2318 * Walk range list.
2319 */
2320 pgmLock(pVM);
2321
2322 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
2323 while (pRam)
2324 {
2325 RTGCPHYS off = GCPhys - pRam->GCPhys;
2326 if ( off < pRam->cb
2327 && (pRam->fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC))
2328 {
2329 bool fRangeExists = false;
2330 unsigned off = (GCPhys - pRam->GCPhys) >> PGM_DYNAMIC_CHUNK_SHIFT;
2331
2332 /* Note: A request made from another thread may end up in EMT after somebody else has already allocated the range. */
2333 if (pRam->paChunkR3Ptrs[off])
2334 fRangeExists = true;
2335
2336 pgmUnlock(pVM);
2337 if (fRangeExists)
2338 return VINF_SUCCESS;
2339 return pgmr3PhysGrowRange(pVM, GCPhys);
2340 }
2341
2342 pRam = pRam->CTX_SUFF(pNext);
2343 }
2344 pgmUnlock(pVM);
2345 return VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS;
2346}
2347
2348
2349/**
2350 * Allocate missing physical pages for an existing guest RAM range.
2351 *
2352 * @returns VBox status.
2353 * @param pVM The VM handle.
2354 * @param pRamRange RAM range
2355 * @param GCPhys GC physical address of the RAM range. (page aligned)
2356 */
2357int pgmr3PhysGrowRange(PVM pVM, RTGCPHYS GCPhys)
2358{
2359 void *pvRam;
2360 int rc;
2361
2362 /* We must execute this function in the EMT thread, otherwise we'll run into problems. */
2363 if (!VM_IS_EMT(pVM))
2364 {
2365 PVMREQ pReq;
2366 const RTGCPHYS GCPhysParam = GCPhys;
2367
2368 AssertMsg(!PDMCritSectIsOwner(&pVM->pgm.s.CritSect), ("We own the PGM lock -> deadlock danger!!\n"));
2369
2370 rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)PGM3PhysGrowRange, 2, pVM, &GCPhysParam);
2371 if (RT_SUCCESS(rc))
2372 {
2373 rc = pReq->iStatus;
2374 VMR3ReqFree(pReq);
2375 }
2376 return rc;
2377 }
2378
2379 /* Round down to chunk boundary */
2380 GCPhys = GCPhys & PGM_DYNAMIC_CHUNK_BASE_MASK;
2381
2382 STAM_COUNTER_INC(&pVM->pgm.s.StatR3DynRamGrow);
2383 STAM_COUNTER_ADD(&pVM->pgm.s.StatR3DynRamTotal, PGM_DYNAMIC_CHUNK_SIZE/(1024*1024));
2384
2385 Log(("pgmr3PhysGrowRange: allocate chunk of size 0x%X at %RGp\n", PGM_DYNAMIC_CHUNK_SIZE, GCPhys));
2386
2387 unsigned cPages = PGM_DYNAMIC_CHUNK_SIZE >> PAGE_SHIFT;
2388
2389 for (;;)
2390 {
2391 rc = SUPPageAlloc(cPages, &pvRam);
2392 if (RT_SUCCESS(rc))
2393 {
2394 rc = MMR3PhysRegisterEx(pVM, pvRam, GCPhys, PGM_DYNAMIC_CHUNK_SIZE, 0, MM_PHYS_TYPE_DYNALLOC_CHUNK, "Main Memory");
2395 if (RT_SUCCESS(rc))
2396 return rc;
2397
2398 SUPPageFree(pvRam, cPages);
2399 }
2400
2401 VMSTATE enmVMState = VMR3GetState(pVM);
2402 if (enmVMState != VMSTATE_RUNNING)
2403 {
2404 AssertMsgFailed(("Out of memory while trying to allocate a guest RAM chunk at %RGp!\n", GCPhys));
2405 LogRel(("PGM: Out of memory while trying to allocate a guest RAM chunk at %RGp (VMstate=%s)!\n", GCPhys, VMR3GetStateName(enmVMState)));
2406 return rc;
2407 }
2408
2409 LogRel(("pgmr3PhysGrowRange: out of memory. pause until the user resumes execution.\n"));
2410
2411 /* Pause first, then inform Main. */
2412 rc = VMR3SuspendNoSave(pVM);
2413 AssertRC(rc);
2414
2415 VMSetRuntimeError(pVM, false, "HostMemoryLow", "Unable to allocate and lock memory. The virtual machine will be paused. Please close applications to free up memory or close the VM");
2416
2417 /* Wait for resume event; will only return in that case. If the VM is stopped, the EMT thread will be destroyed. */
2418 rc = VMR3WaitForResume(pVM);
2419
2420 /* Retry */
2421 LogRel(("pgmr3PhysGrowRange: VM execution resumed -> retry.\n"));
2422 }
2423}
2424
2425
2426/**
2427 * Interface MMR3RomRegister() and MMR3PhysReserve calls to update the
2428 * flags of existing RAM ranges.
2429 *
2430 * @returns VBox status.
2431 * @param pVM The VM handle.
2432 * @param GCPhys GC physical address of the RAM range. (page aligned)
2433 * @param cb Size of the RAM range. (page aligned)
2434 * @param fFlags The Or flags, MM_RAM_* \#defines.
2435 * @param fMask The and mask for the flags.
2436 */
2437VMMR3DECL(int) PGMR3PhysSetFlags(PVM pVM, RTGCPHYS GCPhys, size_t cb, unsigned fFlags, unsigned fMask)
2438{
2439 Log(("PGMR3PhysSetFlags %08X %x %x %x\n", GCPhys, cb, fFlags, fMask));
2440
2441 /*
2442 * Validate input.
2443 * (Not so important because caller is always MMR3RomRegister() and MMR3PhysReserve(), but anyway...)
2444 */
2445 Assert(!(fFlags & ~(MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_ROM | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_MMIO2)));
2446 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb && cb);
2447 Assert(RT_ALIGN_T(GCPhys, PAGE_SIZE, RTGCPHYS) == GCPhys);
2448 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2449 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
2450
2451 /*
2452 * Lookup the range.
2453 */
2454 PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRanges);
2455 while (pRam && GCPhys > pRam->GCPhysLast)
2456 pRam = pRam->CTX_SUFF(pNext);
2457 if ( !pRam
2458 || GCPhys > pRam->GCPhysLast
2459 || GCPhysLast < pRam->GCPhys)
2460 {
2461 AssertMsgFailed(("No RAM range for %RGp-%RGp\n", GCPhys, GCPhysLast));
2462 return VERR_INVALID_PARAMETER;
2463 }
2464
2465 /*
2466 * Update the requested flags.
2467 */
2468 RTHCPHYS fFullMask = ~(RTHCPHYS)(MM_RAM_FLAGS_RESERVED | MM_RAM_FLAGS_ROM | MM_RAM_FLAGS_MMIO | MM_RAM_FLAGS_MMIO2)
2469 | fMask;
2470 unsigned iPageEnd = (GCPhysLast - pRam->GCPhys + 1) >> PAGE_SHIFT;
2471 unsigned iPage = (GCPhys - pRam->GCPhys) >> PAGE_SHIFT;
2472 for ( ; iPage < iPageEnd; iPage++)
2473 pRam->aPages[iPage].HCPhys = (pRam->aPages[iPage].HCPhys & fFullMask) | fFlags; /** @todo PAGE FLAGS */
2474
2475 return VINF_SUCCESS;
2476}
2477
2478#endif /* !VBOX_WITH_NEW_PHYS_CODE */
2479
2480/**
2481 * Sets the Address Gate 20 state.
2482 *
2483 * @param pVM VM handle.
2484 * @param fEnable True if the gate should be enabled.
2485 * False if the gate should be disabled.
2486 */
2487VMMDECL(void) PGMR3PhysSetA20(PVM pVM, bool fEnable)
2488{
2489 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVM->pgm.s.fA20Enabled));
2490 if (pVM->pgm.s.fA20Enabled != fEnable)
2491 {
2492 pVM->pgm.s.fA20Enabled = fEnable;
2493 pVM->pgm.s.GCPhysA20Mask = ~(RTGCPHYS)(!fEnable << 20);
2494 REMR3A20Set(pVM, fEnable);
2495 /** @todo we're not handling this correctly for VT-x / AMD-V. See #2911 */
2496 }
2497}
2498
2499
2500/**
2501 * Tree enumeration callback for dealing with age rollover.
2502 * It will perform a simple compression of the current age.
2503 */
2504static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
2505{
2506 /* Age compression - ASSUMES iNow == 4. */
2507 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
2508 if (pChunk->iAge >= UINT32_C(0xffffff00))
2509 pChunk->iAge = 3;
2510 else if (pChunk->iAge >= UINT32_C(0xfffff000))
2511 pChunk->iAge = 2;
2512 else if (pChunk->iAge)
2513 pChunk->iAge = 1;
2514 else /* iAge = 0 */
2515 pChunk->iAge = 4;
2516
2517 /* reinsert */
2518 PVM pVM = (PVM)pvUser;
2519 RTAvllU32Remove(&pVM->pgm.s.ChunkR3Map.pAgeTree, pChunk->AgeCore.Key);
2520 pChunk->AgeCore.Key = pChunk->iAge;
2521 RTAvllU32Insert(&pVM->pgm.s.ChunkR3Map.pAgeTree, &pChunk->AgeCore);
2522 return 0;
2523}
2524
2525
2526/**
2527 * Tree enumeration callback that updates the chunks that have
2528 * been used since the last
2529 */
2530static DECLCALLBACK(int) pgmR3PhysChunkAgeingCallback(PAVLU32NODECORE pNode, void *pvUser)
2531{
2532 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
2533 if (!pChunk->iAge)
2534 {
2535 PVM pVM = (PVM)pvUser;
2536 RTAvllU32Remove(&pVM->pgm.s.ChunkR3Map.pAgeTree, pChunk->AgeCore.Key);
2537 pChunk->AgeCore.Key = pChunk->iAge = pVM->pgm.s.ChunkR3Map.iNow;
2538 RTAvllU32Insert(&pVM->pgm.s.ChunkR3Map.pAgeTree, &pChunk->AgeCore);
2539 }
2540
2541 return 0;
2542}
2543
2544
2545/**
2546 * Performs ageing of the ring-3 chunk mappings.
2547 *
2548 * @param pVM The VM handle.
2549 */
2550VMMR3DECL(void) PGMR3PhysChunkAgeing(PVM pVM)
2551{
2552 pVM->pgm.s.ChunkR3Map.AgeingCountdown = RT_MIN(pVM->pgm.s.ChunkR3Map.cMax / 4, 1024);
2553 pVM->pgm.s.ChunkR3Map.iNow++;
2554 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
2555 {
2556 pVM->pgm.s.ChunkR3Map.iNow = 4;
2557 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, pVM);
2558 }
2559 else
2560 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingCallback, pVM);
2561}
2562
2563
2564/**
2565 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
2566 */
2567typedef struct PGMR3PHYSCHUNKUNMAPCB
2568{
2569 PVM pVM; /**< The VM handle. */
2570 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
2571} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
2572
2573
2574/**
2575 * Callback used to find the mapping that's been unused for
2576 * the longest time.
2577 */
2578static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLLU32NODECORE pNode, void *pvUser)
2579{
2580 do
2581 {
2582 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)((uint8_t *)pNode - RT_OFFSETOF(PGMCHUNKR3MAP, AgeCore));
2583 if ( pChunk->iAge
2584 && !pChunk->cRefs)
2585 {
2586 /*
2587 * Check that it's not in any of the TLBs.
2588 */
2589 PVM pVM = ((PPGMR3PHYSCHUNKUNMAPCB)pvUser)->pVM;
2590 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
2591 if (pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk == pChunk)
2592 {
2593 pChunk = NULL;
2594 break;
2595 }
2596 if (pChunk)
2597 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbHC.aEntries); i++)
2598 if (pVM->pgm.s.PhysTlbHC.aEntries[i].pMap == pChunk)
2599 {
2600 pChunk = NULL;
2601 break;
2602 }
2603 if (pChunk)
2604 {
2605 ((PPGMR3PHYSCHUNKUNMAPCB)pvUser)->pChunk = pChunk;
2606 return 1; /* done */
2607 }
2608 }
2609
2610 /* next with the same age - this version of the AVL API doesn't enumerate the list, so we have to do it. */
2611 pNode = pNode->pList;
2612 } while (pNode);
2613 return 0;
2614}
2615
2616
2617/**
2618 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
2619 *
2620 * The candidate will not be part of any TLBs, so no need to flush
2621 * anything afterwards.
2622 *
2623 * @returns Chunk id.
2624 * @param pVM The VM handle.
2625 */
2626static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
2627{
2628 /*
2629 * Do tree ageing first?
2630 */
2631 if (pVM->pgm.s.ChunkR3Map.AgeingCountdown-- == 0)
2632 PGMR3PhysChunkAgeing(pVM);
2633
2634 /*
2635 * Enumerate the age tree starting with the left most node.
2636 */
2637 PGMR3PHYSCHUNKUNMAPCB Args;
2638 Args.pVM = pVM;
2639 Args.pChunk = NULL;
2640 if (RTAvllU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pAgeTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, pVM))
2641 return Args.pChunk->Core.Key;
2642 return INT32_MAX;
2643}
2644
2645
2646/**
2647 * Maps the given chunk into the ring-3 mapping cache.
2648 *
2649 * This will call ring-0.
2650 *
2651 * @returns VBox status code.
2652 * @param pVM The VM handle.
2653 * @param idChunk The chunk in question.
2654 * @param ppChunk Where to store the chunk tracking structure.
2655 *
2656 * @remarks Called from within the PGM critical section.
2657 */
2658int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
2659{
2660 int rc;
2661 /*
2662 * Allocate a new tracking structure first.
2663 */
2664#if 0 /* for later when we've got a separate mapping method for ring-0. */
2665 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAlloc(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
2666 AssertReturn(pChunk, VERR_NO_MEMORY);
2667#else
2668 PPGMCHUNKR3MAP pChunk;
2669 rc = MMHyperAlloc(pVM, sizeof(*pChunk), 0, MM_TAG_PGM_CHUNK_MAPPING, (void **)&pChunk);
2670 AssertRCReturn(rc, rc);
2671#endif
2672 pChunk->Core.Key = idChunk;
2673 pChunk->AgeCore.Key = pVM->pgm.s.ChunkR3Map.iNow;
2674 pChunk->iAge = 0;
2675 pChunk->cRefs = 0;
2676 pChunk->cPermRefs = 0;
2677 pChunk->pv = NULL;
2678
2679 /*
2680 * Request the ring-0 part to map the chunk in question and if
2681 * necessary unmap another one to make space in the mapping cache.
2682 */
2683 GMMMAPUNMAPCHUNKREQ Req;
2684 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
2685 Req.Hdr.cbReq = sizeof(Req);
2686 Req.pvR3 = NULL;
2687 Req.idChunkMap = idChunk;
2688 Req.idChunkUnmap = NIL_GMM_CHUNKID;
2689 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
2690 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
2691 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
2692 if (RT_SUCCESS(rc))
2693 {
2694 /*
2695 * Update the tree.
2696 */
2697 /* insert the new one. */
2698 AssertPtr(Req.pvR3);
2699 pChunk->pv = Req.pvR3;
2700 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
2701 AssertRelease(fRc);
2702 pVM->pgm.s.ChunkR3Map.c++;
2703
2704 fRc = RTAvllU32Insert(&pVM->pgm.s.ChunkR3Map.pAgeTree, &pChunk->AgeCore);
2705 AssertRelease(fRc);
2706
2707 /* remove the unmapped one. */
2708 if (Req.idChunkUnmap != NIL_GMM_CHUNKID)
2709 {
2710 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
2711 AssertRelease(pUnmappedChunk);
2712 pUnmappedChunk->pv = NULL;
2713 pUnmappedChunk->Core.Key = UINT32_MAX;
2714#if 0 /* for later when we've got a separate mapping method for ring-0. */
2715 MMR3HeapFree(pUnmappedChunk);
2716#else
2717 MMHyperFree(pVM, pUnmappedChunk);
2718#endif
2719 pVM->pgm.s.ChunkR3Map.c--;
2720 }
2721 }
2722 else
2723 {
2724 AssertRC(rc);
2725#if 0 /* for later when we've got a separate mapping method for ring-0. */
2726 MMR3HeapFree(pChunk);
2727#else
2728 MMHyperFree(pVM, pChunk);
2729#endif
2730 pChunk = NULL;
2731 }
2732
2733 *ppChunk = pChunk;
2734 return rc;
2735}
2736
2737
2738/**
2739 * For VMMCALLHOST_PGM_MAP_CHUNK, considered internal.
2740 *
2741 * @returns see pgmR3PhysChunkMap.
2742 * @param pVM The VM handle.
2743 * @param idChunk The chunk to map.
2744 */
2745VMMR3DECL(int) PGMR3PhysChunkMap(PVM pVM, uint32_t idChunk)
2746{
2747 PPGMCHUNKR3MAP pChunk;
2748 return pgmR3PhysChunkMap(pVM, idChunk, &pChunk);
2749}
2750
2751
2752/**
2753 * Invalidates the TLB for the ring-3 mapping cache.
2754 *
2755 * @param pVM The VM handle.
2756 */
2757VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
2758{
2759 pgmLock(pVM);
2760 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
2761 {
2762 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
2763 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
2764 }
2765 pgmUnlock(pVM);
2766}
2767
2768
2769/**
2770 * Response to VM_FF_PGM_NEED_HANDY_PAGES and VMMCALLHOST_PGM_ALLOCATE_HANDY_PAGES.
2771 *
2772 * @returns The following VBox status codes.
2773 * @retval VINF_SUCCESS on success. FF cleared.
2774 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in this case.
2775 *
2776 * @param pVM The VM handle.
2777 */
2778VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
2779{
2780 pgmLock(pVM);
2781
2782 /*
2783 * Allocate more pages, noting down the index of the first new page.
2784 */
2785 uint32_t iClear = pVM->pgm.s.cHandyPages;
2786 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_INTERNAL_ERROR);
2787 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
2788 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
2789 while (rc == VERR_GMM_SEED_ME)
2790 {
2791 void *pvChunk;
2792 rc = SUPPageAlloc(GMM_CHUNK_SIZE >> PAGE_SHIFT, &pvChunk);
2793 if (RT_SUCCESS(rc))
2794 {
2795 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_SEED_CHUNK, (uintptr_t)pvChunk, NULL);
2796 if (RT_FAILURE(rc))
2797 SUPPageFree(pvChunk, GMM_CHUNK_SIZE >> PAGE_SHIFT);
2798 }
2799 if (RT_SUCCESS(rc))
2800 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
2801 }
2802
2803 /*
2804 * Clear the pages.
2805 */
2806 if (RT_SUCCESS(rc))
2807 {
2808 while (iClear < pVM->pgm.s.cHandyPages)
2809 {
2810 PGMMPAGEDESC pPage = &pVM->pgm.s.aHandyPages[iClear];
2811 void *pv;
2812 rc = pgmPhysPageMapByPageID(pVM, pPage->idPage, pPage->HCPhysGCPhys, &pv);
2813 AssertLogRelMsgBreak(RT_SUCCESS(rc), ("idPage=%#x HCPhysGCPhys=%RHp rc=%Rrc", pPage->idPage, pPage->HCPhysGCPhys, rc));
2814 ASMMemZeroPage(pv);
2815 iClear++;
2816 }
2817
2818 VM_FF_CLEAR(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
2819 }
2820 else
2821 {
2822 LogRel(("PGM: Failed to procure handy pages, rc=%Rrc cHandyPages=%u\n",
2823 rc, pVM->pgm.s.cHandyPages));
2824 rc = VERR_EM_NO_MEMORY;
2825 //rc = VINF_EM_NO_MEMORY;
2826 //VM_FF_SET(pVM, VM_FF_PGM_WE_ARE_SCREWED?);
2827 }
2828
2829/** @todo Do proper VERR_EM_NO_MEMORY reporting. */
2830 AssertMsg( pVM->pgm.s.cHandyPages == RT_ELEMENTS(pVM->pgm.s.aHandyPages)
2831 || rc != VINF_SUCCESS, ("%d rc=%Rrc\n", pVM->pgm.s.cHandyPages, rc));
2832 pgmUnlock(pVM);
2833 Assert(rc == VINF_SUCCESS || rc == VINF_EM_NO_MEMORY || rc == VERR_EM_NO_MEMORY);
2834 return rc;
2835}
2836
2837
2838/**
2839 * Frees the specified RAM page and replaces it with the ZERO page.
2840 *
2841 * This is used by ballooning, remapping MMIO2 and RAM reset.
2842 *
2843 * @param pVM Pointer to the shared VM structure.
2844 * @param pReq Pointer to the request.
2845 * @param pPage Pointer to the page structure.
2846 * @param GCPhys The guest physical address of the page, if applicable.
2847 *
2848 * @remarks The caller must own the PGM lock.
2849 */
2850static int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys)
2851{
2852 /*
2853 * Assert sanity.
2854 */
2855 Assert(PDMCritSectIsOwner(&pVM->pgm.s.CritSect));
2856 if (RT_UNLIKELY(PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM))
2857 {
2858 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
2859 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
2860 }
2861
2862 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_ZERO)
2863 return VINF_SUCCESS;
2864
2865 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
2866 if (RT_UNLIKELY( idPage == NIL_GMM_PAGEID
2867 || idPage > GMM_PAGEID_LAST
2868 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID))
2869 {
2870 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
2871 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
2872 }
2873
2874 /* update page count stats. */
2875 if (PGM_PAGE_IS_SHARED(pPage))
2876 pVM->pgm.s.cSharedPages--;
2877 else
2878 pVM->pgm.s.cPrivatePages--;
2879 pVM->pgm.s.cZeroPages++;
2880
2881 /*
2882 * pPage = ZERO page.
2883 */
2884 PGM_PAGE_SET_HCPHYS(pPage, pVM->pgm.s.HCPhysZeroPg);
2885 PGM_PAGE_SET_STATE(pPage, PGM_PAGE_STATE_ZERO);
2886 PGM_PAGE_SET_PAGEID(pPage, NIL_GMM_PAGEID);
2887
2888 /*
2889 * Make sure it's not in the handy page array.
2890 */
2891 uint32_t i = pVM->pgm.s.cHandyPages;
2892 while (i < RT_ELEMENTS(pVM->pgm.s.aHandyPages))
2893 {
2894 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
2895 {
2896 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
2897 break;
2898 }
2899 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
2900 {
2901 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
2902 break;
2903 }
2904 i++;
2905 }
2906
2907 /*
2908 * Push it onto the page array.
2909 */
2910 uint32_t iPage = *pcPendingPages;
2911 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
2912 *pcPendingPages += 1;
2913
2914 pReq->aPages[iPage].idPage = idPage;
2915
2916 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
2917 return VINF_SUCCESS;
2918
2919 /*
2920 * Flush the pages.
2921 */
2922 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
2923 if (RT_SUCCESS(rc))
2924 {
2925 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2926 *pcPendingPages = 0;
2927 }
2928 return rc;
2929}
2930
2931
2932/**
2933 * Converts a GC physical address to a HC ring-3 pointer, with some
2934 * additional checks.
2935 *
2936 * @returns VBox status code.
2937 * @retval VINF_SUCCESS on success.
2938 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
2939 * access handler of some kind.
2940 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
2941 * accesses or is odd in any way.
2942 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
2943 *
2944 * @param pVM The VM handle.
2945 * @param GCPhys The GC physical address to convert.
2946 * @param fWritable Whether write access is required.
2947 * @param ppv Where to store the pointer corresponding to GCPhys on
2948 * success.
2949 */
2950VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
2951{
2952 pgmLock(pVM);
2953
2954 PPGMRAMRANGE pRam;
2955 PPGMPAGE pPage;
2956 int rc = pgmPhysGetPageAndRangeEx(&pVM->pgm.s, GCPhys, &pPage, &pRam);
2957 if (RT_SUCCESS(rc))
2958 {
2959#ifdef VBOX_WITH_NEW_PHYS_CODE
2960 if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
2961 rc = VINF_SUCCESS;
2962 else
2963 {
2964 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
2965 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
2966 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
2967 {
2968 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
2969 * in -norawr0 mode. */
2970 if (fWritable)
2971 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
2972 }
2973 else
2974 {
2975 /* Temporariliy disabled phycial handler(s), since the recompiler
2976 doesn't get notified when it's reset we'll have to pretend its
2977 operating normally. */
2978 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
2979 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
2980 else
2981 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
2982 }
2983 }
2984 if (RT_SUCCESS(rc))
2985 {
2986 int rc2;
2987
2988 /* Make sure what we return is writable. */
2989 if (fWritable && rc != VINF_PGM_PHYS_TLB_CATCH_WRITE)
2990 switch (PGM_PAGE_GET_STATE(pPage))
2991 {
2992 case PGM_PAGE_STATE_ALLOCATED:
2993 break;
2994 case PGM_PAGE_STATE_ZERO:
2995 case PGM_PAGE_STATE_SHARED:
2996 case PGM_PAGE_STATE_WRITE_MONITORED:
2997 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)PAGE_OFFSET_MASK);
2998 AssertLogRelRCReturn(rc2, rc2);
2999 break;
3000 }
3001
3002 /* Get a ring-3 mapping of the address. */
3003 PPGMPAGER3MAPTLBE pTlbe;
3004 rc2 = pgmPhysPageQueryTlbe(&pVM->pgm.s, GCPhys, &pTlbe);
3005 AssertLogRelRCReturn(rc2, rc2);
3006 *ppv = (void *)((uintptr_t)pTlbe->pv | (GCPhys & PAGE_OFFSET_MASK));
3007 /** @todo mapping/locking hell; this isn't horribly efficient since
3008 * pgmPhysPageLoadIntoTlb will repeate the lookup we've done here. */
3009
3010 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
3011 }
3012 else
3013 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
3014
3015 /* else: handler catching all access, no pointer returned. */
3016
3017#else
3018 if (0)
3019 /* nothing */;
3020 else if (PGM_PAGE_HAS_ANY_HANDLERS(pPage))
3021 {
3022 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
3023 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
3024 else if (fWritable && PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
3025 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
3026 else
3027 {
3028 /* Temporariliy disabled phycial handler(s), since the recompiler
3029 doesn't get notified when it's reset we'll have to pretend its
3030 operating normally. */
3031 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
3032 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
3033 else
3034 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
3035 }
3036 }
3037 else
3038 rc = VINF_SUCCESS;
3039 if (RT_SUCCESS(rc))
3040 {
3041 if (pRam->fFlags & MM_RAM_FLAGS_DYNAMIC_ALLOC)
3042 {
3043 AssertMsg(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM, ("GCPhys=%RGp type=%d\n", GCPhys, PGM_PAGE_GET_TYPE(pPage)));
3044 RTGCPHYS off = GCPhys - pRam->GCPhys;
3045 unsigned iChunk = (off >> PGM_DYNAMIC_CHUNK_SHIFT);
3046 *ppv = (void *)(pRam->paChunkR3Ptrs[iChunk] + (off & PGM_DYNAMIC_CHUNK_OFFSET_MASK));
3047 }
3048 else if (RT_LIKELY(pRam->pvR3))
3049 {
3050 AssertMsg(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2, ("GCPhys=%RGp type=%d\n", GCPhys, PGM_PAGE_GET_TYPE(pPage)));
3051 RTGCPHYS off = GCPhys - pRam->GCPhys;
3052 *ppv = (uint8_t *)pRam->pvR3 + off;
3053 }
3054 else
3055 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
3056 }
3057#endif /* !VBOX_WITH_NEW_PHYS_CODE */
3058 }
3059 else
3060 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
3061
3062 pgmUnlock(pVM);
3063 return rc;
3064}
3065
3066
3067
Note: See TracBrowser for help on using the repository browser.

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