VirtualBox

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

Last change on this file since 93661 was 93650, checked in by vboxsync, 3 years ago

VMM/PGM,*: Split the physical access handler type registration into separate ring-0 and ring-3 steps, expanding the type to 64-bit. bugref:10094

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 223.6 KB
Line 
1/* $Id: PGMPhys.cpp 93650 2022-02-08 10:43:53Z vboxsync $ */
2/** @file
3 * PGM - Page Manager and Monitor, Physical Memory Addressing.
4 */
5
6/*
7 * Copyright (C) 2006-2022 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_PGM_PHYS
23#define VBOX_WITHOUT_PAGING_BIT_FIELDS /* 64-bit bitfields are just asking for trouble. See @bugref{9841} and others. */
24#include <VBox/vmm/pgm.h>
25#include <VBox/vmm/iem.h>
26#include <VBox/vmm/iom.h>
27#include <VBox/vmm/mm.h>
28#include <VBox/vmm/nem.h>
29#include <VBox/vmm/stam.h>
30#include <VBox/vmm/pdmdev.h>
31#include "PGMInternal.h"
32#include <VBox/vmm/vmcc.h>
33
34#include "PGMInline.h"
35
36#include <VBox/sup.h>
37#include <VBox/param.h>
38#include <VBox/err.h>
39#include <VBox/log.h>
40#include <iprt/assert.h>
41#include <iprt/alloc.h>
42#include <iprt/asm.h>
43#ifdef VBOX_STRICT
44# include <iprt/crc.h>
45#endif
46#include <iprt/thread.h>
47#include <iprt/string.h>
48#include <iprt/system.h>
49
50
51/*********************************************************************************************************************************
52* Defined Constants And Macros *
53*********************************************************************************************************************************/
54/** The number of pages to free in one batch. */
55#define PGMPHYS_FREE_PAGE_BATCH_SIZE 128
56
57
58
59/*********************************************************************************************************************************
60* Reading and Writing Guest Pysical Memory *
61*********************************************************************************************************************************/
62
63/*
64 * PGMR3PhysReadU8-64
65 * PGMR3PhysWriteU8-64
66 */
67#define PGMPHYSFN_READNAME PGMR3PhysReadU8
68#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU8
69#define PGMPHYS_DATASIZE 1
70#define PGMPHYS_DATATYPE uint8_t
71#include "PGMPhysRWTmpl.h"
72
73#define PGMPHYSFN_READNAME PGMR3PhysReadU16
74#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU16
75#define PGMPHYS_DATASIZE 2
76#define PGMPHYS_DATATYPE uint16_t
77#include "PGMPhysRWTmpl.h"
78
79#define PGMPHYSFN_READNAME PGMR3PhysReadU32
80#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU32
81#define PGMPHYS_DATASIZE 4
82#define PGMPHYS_DATATYPE uint32_t
83#include "PGMPhysRWTmpl.h"
84
85#define PGMPHYSFN_READNAME PGMR3PhysReadU64
86#define PGMPHYSFN_WRITENAME PGMR3PhysWriteU64
87#define PGMPHYS_DATASIZE 8
88#define PGMPHYS_DATATYPE uint64_t
89#include "PGMPhysRWTmpl.h"
90
91
92/**
93 * EMT worker for PGMR3PhysReadExternal.
94 */
95static DECLCALLBACK(int) pgmR3PhysReadExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, void *pvBuf, size_t cbRead,
96 PGMACCESSORIGIN enmOrigin)
97{
98 VBOXSTRICTRC rcStrict = PGMPhysRead(pVM, *pGCPhys, pvBuf, cbRead, enmOrigin);
99 AssertMsg(rcStrict == VINF_SUCCESS, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict))); NOREF(rcStrict);
100 return VINF_SUCCESS;
101}
102
103
104/**
105 * Read from physical memory, external users.
106 *
107 * @returns VBox status code.
108 * @retval VINF_SUCCESS.
109 *
110 * @param pVM The cross context VM structure.
111 * @param GCPhys Physical address to read from.
112 * @param pvBuf Where to read into.
113 * @param cbRead How many bytes to read.
114 * @param enmOrigin Who is calling.
115 *
116 * @thread Any but EMTs.
117 */
118VMMR3DECL(int) PGMR3PhysReadExternal(PVM pVM, RTGCPHYS GCPhys, void *pvBuf, size_t cbRead, PGMACCESSORIGIN enmOrigin)
119{
120 VM_ASSERT_OTHER_THREAD(pVM);
121
122 AssertMsgReturn(cbRead > 0, ("don't even think about reading zero bytes!\n"), VINF_SUCCESS);
123 LogFlow(("PGMR3PhysReadExternal: %RGp %d\n", GCPhys, cbRead));
124
125 PGM_LOCK_VOID(pVM);
126
127 /*
128 * Copy loop on ram ranges.
129 */
130 PPGMRAMRANGE pRam = pgmPhysGetRangeAtOrAbove(pVM, GCPhys);
131 for (;;)
132 {
133 /* Inside range or not? */
134 if (pRam && GCPhys >= pRam->GCPhys)
135 {
136 /*
137 * Must work our way thru this page by page.
138 */
139 RTGCPHYS off = GCPhys - pRam->GCPhys;
140 while (off < pRam->cb)
141 {
142 unsigned iPage = off >> GUEST_PAGE_SHIFT;
143 PPGMPAGE pPage = &pRam->aPages[iPage];
144
145 /*
146 * If the page has an ALL access handler, we'll have to
147 * delegate the job to EMT.
148 */
149 if ( PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)
150 || PGM_PAGE_IS_SPECIAL_ALIAS_MMIO(pPage))
151 {
152 PGM_UNLOCK(pVM);
153
154 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysReadExternalEMT, 5,
155 pVM, &GCPhys, pvBuf, cbRead, enmOrigin);
156 }
157 Assert(!PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage));
158
159 /*
160 * Simple stuff, go ahead.
161 */
162 size_t cb = GUEST_PAGE_SIZE - (off & GUEST_PAGE_OFFSET_MASK);
163 if (cb > cbRead)
164 cb = cbRead;
165 PGMPAGEMAPLOCK PgMpLck;
166 const void *pvSrc;
167 int rc = pgmPhysGCPhys2CCPtrInternalReadOnly(pVM, pPage, pRam->GCPhys + off, &pvSrc, &PgMpLck);
168 if (RT_SUCCESS(rc))
169 {
170 memcpy(pvBuf, pvSrc, cb);
171 pgmPhysReleaseInternalPageMappingLock(pVM, &PgMpLck);
172 }
173 else
174 {
175 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternalReadOnly failed on %RGp / %R[pgmpage] -> %Rrc\n",
176 pRam->GCPhys + off, pPage, rc));
177 memset(pvBuf, 0xff, cb);
178 }
179
180 /* next page */
181 if (cb >= cbRead)
182 {
183 PGM_UNLOCK(pVM);
184 return VINF_SUCCESS;
185 }
186 cbRead -= cb;
187 off += cb;
188 GCPhys += cb;
189 pvBuf = (char *)pvBuf + cb;
190 } /* walk pages in ram range. */
191 }
192 else
193 {
194 LogFlow(("PGMPhysRead: Unassigned %RGp size=%u\n", GCPhys, cbRead));
195
196 /*
197 * Unassigned address space.
198 */
199 size_t cb = pRam ? pRam->GCPhys - GCPhys : ~(size_t)0;
200 if (cb >= cbRead)
201 {
202 memset(pvBuf, 0xff, cbRead);
203 break;
204 }
205 memset(pvBuf, 0xff, cb);
206
207 cbRead -= cb;
208 pvBuf = (char *)pvBuf + cb;
209 GCPhys += cb;
210 }
211
212 /* Advance range if necessary. */
213 while (pRam && GCPhys > pRam->GCPhysLast)
214 pRam = pRam->CTX_SUFF(pNext);
215 } /* Ram range walk */
216
217 PGM_UNLOCK(pVM);
218
219 return VINF_SUCCESS;
220}
221
222
223/**
224 * EMT worker for PGMR3PhysWriteExternal.
225 */
226static DECLCALLBACK(int) pgmR3PhysWriteExternalEMT(PVM pVM, PRTGCPHYS pGCPhys, const void *pvBuf, size_t cbWrite,
227 PGMACCESSORIGIN enmOrigin)
228{
229 /** @todo VERR_EM_NO_MEMORY */
230 VBOXSTRICTRC rcStrict = PGMPhysWrite(pVM, *pGCPhys, pvBuf, cbWrite, enmOrigin);
231 AssertMsg(rcStrict == VINF_SUCCESS, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict))); NOREF(rcStrict);
232 return VINF_SUCCESS;
233}
234
235
236/**
237 * Write to physical memory, external users.
238 *
239 * @returns VBox status code.
240 * @retval VINF_SUCCESS.
241 * @retval VERR_EM_NO_MEMORY.
242 *
243 * @param pVM The cross context VM structure.
244 * @param GCPhys Physical address to write to.
245 * @param pvBuf What to write.
246 * @param cbWrite How many bytes to write.
247 * @param enmOrigin Who is calling.
248 *
249 * @thread Any but EMTs.
250 */
251VMMDECL(int) PGMR3PhysWriteExternal(PVM pVM, RTGCPHYS GCPhys, const void *pvBuf, size_t cbWrite, PGMACCESSORIGIN enmOrigin)
252{
253 VM_ASSERT_OTHER_THREAD(pVM);
254
255 AssertMsg(!pVM->pgm.s.fNoMorePhysWrites,
256 ("Calling PGMR3PhysWriteExternal after pgmR3Save()! GCPhys=%RGp cbWrite=%#x enmOrigin=%d\n",
257 GCPhys, cbWrite, enmOrigin));
258 AssertMsgReturn(cbWrite > 0, ("don't even think about writing zero bytes!\n"), VINF_SUCCESS);
259 LogFlow(("PGMR3PhysWriteExternal: %RGp %d\n", GCPhys, cbWrite));
260
261 PGM_LOCK_VOID(pVM);
262
263 /*
264 * Copy loop on ram ranges, stop when we hit something difficult.
265 */
266 PPGMRAMRANGE pRam = pgmPhysGetRangeAtOrAbove(pVM, GCPhys);
267 for (;;)
268 {
269 /* Inside range or not? */
270 if (pRam && GCPhys >= pRam->GCPhys)
271 {
272 /*
273 * Must work our way thru this page by page.
274 */
275 RTGCPTR off = GCPhys - pRam->GCPhys;
276 while (off < pRam->cb)
277 {
278 RTGCPTR iPage = off >> GUEST_PAGE_SHIFT;
279 PPGMPAGE pPage = &pRam->aPages[iPage];
280
281 /*
282 * Is the page problematic, we have to do the work on the EMT.
283 *
284 * Allocating writable pages and access handlers are
285 * problematic, write monitored pages are simple and can be
286 * dealt with here.
287 */
288 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
289 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED
290 || PGM_PAGE_IS_SPECIAL_ALIAS_MMIO(pPage))
291 {
292 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
293 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
294 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage, GCPhys);
295 else
296 {
297 PGM_UNLOCK(pVM);
298
299 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysWriteExternalEMT, 5,
300 pVM, &GCPhys, pvBuf, cbWrite, enmOrigin);
301 }
302 }
303 Assert(!PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage));
304
305 /*
306 * Simple stuff, go ahead.
307 */
308 size_t cb = GUEST_PAGE_SIZE - (off & GUEST_PAGE_OFFSET_MASK);
309 if (cb > cbWrite)
310 cb = cbWrite;
311 PGMPAGEMAPLOCK PgMpLck;
312 void *pvDst;
313 int rc = pgmPhysGCPhys2CCPtrInternal(pVM, pPage, pRam->GCPhys + off, &pvDst, &PgMpLck);
314 if (RT_SUCCESS(rc))
315 {
316 memcpy(pvDst, pvBuf, cb);
317 pgmPhysReleaseInternalPageMappingLock(pVM, &PgMpLck);
318 }
319 else
320 AssertLogRelMsgFailed(("pgmPhysGCPhys2CCPtrInternal failed on %RGp / %R[pgmpage] -> %Rrc\n",
321 pRam->GCPhys + off, pPage, rc));
322
323 /* next page */
324 if (cb >= cbWrite)
325 {
326 PGM_UNLOCK(pVM);
327 return VINF_SUCCESS;
328 }
329
330 cbWrite -= cb;
331 off += cb;
332 GCPhys += cb;
333 pvBuf = (const char *)pvBuf + cb;
334 } /* walk pages in ram range */
335 }
336 else
337 {
338 /*
339 * Unassigned address space, skip it.
340 */
341 if (!pRam)
342 break;
343 size_t cb = pRam->GCPhys - GCPhys;
344 if (cb >= cbWrite)
345 break;
346 cbWrite -= cb;
347 pvBuf = (const char *)pvBuf + cb;
348 GCPhys += cb;
349 }
350
351 /* Advance range if necessary. */
352 while (pRam && GCPhys > pRam->GCPhysLast)
353 pRam = pRam->CTX_SUFF(pNext);
354 } /* Ram range walk */
355
356 PGM_UNLOCK(pVM);
357 return VINF_SUCCESS;
358}
359
360
361/*********************************************************************************************************************************
362* Mapping Guest Physical Memory *
363*********************************************************************************************************************************/
364
365/**
366 * VMR3ReqCall worker for PGMR3PhysGCPhys2CCPtrExternal to make pages writable.
367 *
368 * @returns see PGMR3PhysGCPhys2CCPtrExternal
369 * @param pVM The cross context VM structure.
370 * @param pGCPhys Pointer to the guest physical address.
371 * @param ppv Where to store the mapping address.
372 * @param pLock Where to store the lock.
373 */
374static DECLCALLBACK(int) pgmR3PhysGCPhys2CCPtrDelegated(PVM pVM, PRTGCPHYS pGCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
375{
376 /*
377 * Just hand it to PGMPhysGCPhys2CCPtr and check that it's not a page with
378 * an access handler after it succeeds.
379 */
380 int rc = PGM_LOCK(pVM);
381 AssertRCReturn(rc, rc);
382
383 rc = PGMPhysGCPhys2CCPtr(pVM, *pGCPhys, ppv, pLock);
384 if (RT_SUCCESS(rc))
385 {
386 PPGMPAGEMAPTLBE pTlbe;
387 int rc2 = pgmPhysPageQueryTlbe(pVM, *pGCPhys, &pTlbe);
388 AssertFatalRC(rc2);
389 PPGMPAGE pPage = pTlbe->pPage;
390 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
391 {
392 PGMPhysReleasePageMappingLock(pVM, pLock);
393 rc = VERR_PGM_PHYS_PAGE_RESERVED;
394 }
395 else if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
396#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
397 || pgmPoolIsDirtyPage(pVM, *pGCPhys)
398#endif
399 )
400 {
401 /* We *must* flush any corresponding pgm pool page here, otherwise we'll
402 * not be informed about writes and keep bogus gst->shw mappings around.
403 */
404 pgmPoolFlushPageByGCPhys(pVM, *pGCPhys);
405 Assert(!PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage));
406 /** @todo r=bird: return VERR_PGM_PHYS_PAGE_RESERVED here if it still has
407 * active handlers, see the PGMR3PhysGCPhys2CCPtrExternal docs. */
408 }
409 }
410
411 PGM_UNLOCK(pVM);
412 return rc;
413}
414
415
416/**
417 * Requests the mapping of a guest page into ring-3, external threads.
418 *
419 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
420 * release it.
421 *
422 * This API will assume your intention is to write to the page, and will
423 * therefore replace shared and zero pages. If you do not intend to modify the
424 * page, use the PGMR3PhysGCPhys2CCPtrReadOnlyExternal() API.
425 *
426 * @returns VBox status code.
427 * @retval VINF_SUCCESS on success.
428 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
429 * backing or if the page has any active access handlers. The caller
430 * must fall back on using PGMR3PhysWriteExternal.
431 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
432 *
433 * @param pVM The cross context VM structure.
434 * @param GCPhys The guest physical address of the page that should be mapped.
435 * @param ppv Where to store the address corresponding to GCPhys.
436 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
437 *
438 * @remark Avoid calling this API from within critical sections (other than the
439 * PGM one) because of the deadlock risk when we have to delegating the
440 * task to an EMT.
441 * @thread Any.
442 */
443VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrExternal(PVM pVM, RTGCPHYS GCPhys, void **ppv, PPGMPAGEMAPLOCK pLock)
444{
445 AssertPtr(ppv);
446 AssertPtr(pLock);
447
448 Assert(VM_IS_EMT(pVM) || !PGMIsLockOwner(pVM));
449
450 int rc = PGM_LOCK(pVM);
451 AssertRCReturn(rc, rc);
452
453 /*
454 * Query the Physical TLB entry for the page (may fail).
455 */
456 PPGMPAGEMAPTLBE pTlbe;
457 rc = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
458 if (RT_SUCCESS(rc))
459 {
460 PPGMPAGE pPage = pTlbe->pPage;
461 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
462 rc = VERR_PGM_PHYS_PAGE_RESERVED;
463 else
464 {
465 /*
466 * If the page is shared, the zero page, or being write monitored
467 * it must be converted to an page that's writable if possible.
468 * We can only deal with write monitored pages here, the rest have
469 * to be on an EMT.
470 */
471 if ( PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
472 || PGM_PAGE_GET_STATE(pPage) != PGM_PAGE_STATE_ALLOCATED
473#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
474 || pgmPoolIsDirtyPage(pVM, GCPhys)
475#endif
476 )
477 {
478 if ( PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED
479 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage)
480#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
481 && !pgmPoolIsDirtyPage(pVM, GCPhys) /** @todo we're very likely doing this twice. */
482#endif
483 )
484 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage, GCPhys);
485 else
486 {
487 PGM_UNLOCK(pVM);
488
489 return VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysGCPhys2CCPtrDelegated, 4,
490 pVM, &GCPhys, ppv, pLock);
491 }
492 }
493
494 /*
495 * Now, just perform the locking and calculate the return address.
496 */
497 PPGMPAGEMAP pMap = pTlbe->pMap;
498 if (pMap)
499 pMap->cRefs++;
500
501 unsigned cLocks = PGM_PAGE_GET_WRITE_LOCKS(pPage);
502 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
503 {
504 if (cLocks == 0)
505 pVM->pgm.s.cWriteLockedPages++;
506 PGM_PAGE_INC_WRITE_LOCKS(pPage);
507 }
508 else if (cLocks != PGM_PAGE_GET_WRITE_LOCKS(pPage))
509 {
510 PGM_PAGE_INC_WRITE_LOCKS(pPage);
511 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent write locked state!\n", GCPhys, pPage));
512 if (pMap)
513 pMap->cRefs++; /* Extra ref to prevent it from going away. */
514 }
515
516 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & GUEST_PAGE_OFFSET_MASK));
517 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_WRITE;
518 pLock->pvMap = pMap;
519 }
520 }
521
522 PGM_UNLOCK(pVM);
523 return rc;
524}
525
526
527/**
528 * Requests the mapping of a guest page into ring-3, external threads.
529 *
530 * When you're done with the page, call PGMPhysReleasePageMappingLock() ASAP to
531 * release it.
532 *
533 * @returns VBox status code.
534 * @retval VINF_SUCCESS on success.
535 * @retval VERR_PGM_PHYS_PAGE_RESERVED it it's a valid page but has no physical
536 * backing or if the page as an active ALL access handler. The caller
537 * must fall back on using PGMPhysRead.
538 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if it's not a valid physical address.
539 *
540 * @param pVM The cross context VM structure.
541 * @param GCPhys The guest physical address of the page that should be mapped.
542 * @param ppv Where to store the address corresponding to GCPhys.
543 * @param pLock Where to store the lock information that PGMPhysReleasePageMappingLock needs.
544 *
545 * @remark Avoid calling this API from within critical sections (other than
546 * the PGM one) because of the deadlock risk.
547 * @thread Any.
548 */
549VMMR3DECL(int) PGMR3PhysGCPhys2CCPtrReadOnlyExternal(PVM pVM, RTGCPHYS GCPhys, void const **ppv, PPGMPAGEMAPLOCK pLock)
550{
551 int rc = PGM_LOCK(pVM);
552 AssertRCReturn(rc, rc);
553
554 /*
555 * Query the Physical TLB entry for the page (may fail).
556 */
557 PPGMPAGEMAPTLBE pTlbe;
558 rc = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
559 if (RT_SUCCESS(rc))
560 {
561 PPGMPAGE pPage = pTlbe->pPage;
562#if 1
563 /* MMIO pages doesn't have any readable backing. */
564 if (PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage))
565 rc = VERR_PGM_PHYS_PAGE_RESERVED;
566#else
567 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
568 rc = VERR_PGM_PHYS_PAGE_RESERVED;
569#endif
570 else
571 {
572 /*
573 * Now, just perform the locking and calculate the return address.
574 */
575 PPGMPAGEMAP pMap = pTlbe->pMap;
576 if (pMap)
577 pMap->cRefs++;
578
579 unsigned cLocks = PGM_PAGE_GET_READ_LOCKS(pPage);
580 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
581 {
582 if (cLocks == 0)
583 pVM->pgm.s.cReadLockedPages++;
584 PGM_PAGE_INC_READ_LOCKS(pPage);
585 }
586 else if (cLocks != PGM_PAGE_GET_READ_LOCKS(pPage))
587 {
588 PGM_PAGE_INC_READ_LOCKS(pPage);
589 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent readonly locked state!\n", GCPhys, pPage));
590 if (pMap)
591 pMap->cRefs++; /* Extra ref to prevent it from going away. */
592 }
593
594 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & GUEST_PAGE_OFFSET_MASK));
595 pLock->uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_READ;
596 pLock->pvMap = pMap;
597 }
598 }
599
600 PGM_UNLOCK(pVM);
601 return rc;
602}
603
604
605/**
606 * Requests the mapping of multiple guest page into ring-3, external threads.
607 *
608 * When you're done with the pages, call PGMPhysBulkReleasePageMappingLock()
609 * ASAP to release them.
610 *
611 * This API will assume your intention is to write to the pages, and will
612 * therefore replace shared and zero pages. If you do not intend to modify the
613 * pages, use the PGMR3PhysBulkGCPhys2CCPtrReadOnlyExternal() API.
614 *
615 * @returns VBox status code.
616 * @retval VINF_SUCCESS on success.
617 * @retval VERR_PGM_PHYS_PAGE_RESERVED if any of the pages has no physical
618 * backing or if any of the pages the page has any active access
619 * handlers. The caller must fall back on using PGMR3PhysWriteExternal.
620 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if @a paGCPhysPages contains
621 * an invalid physical address.
622 *
623 * @param pVM The cross context VM structure.
624 * @param cPages Number of pages to lock.
625 * @param paGCPhysPages The guest physical address of the pages that
626 * should be mapped (@a cPages entries).
627 * @param papvPages Where to store the ring-3 mapping addresses
628 * corresponding to @a paGCPhysPages.
629 * @param paLocks Where to store the locking information that
630 * pfnPhysBulkReleasePageMappingLock needs (@a cPages
631 * in length).
632 *
633 * @remark Avoid calling this API from within critical sections (other than the
634 * PGM one) because of the deadlock risk when we have to delegating the
635 * task to an EMT.
636 * @thread Any.
637 */
638VMMR3DECL(int) PGMR3PhysBulkGCPhys2CCPtrExternal(PVM pVM, uint32_t cPages, PCRTGCPHYS paGCPhysPages,
639 void **papvPages, PPGMPAGEMAPLOCK paLocks)
640{
641 Assert(cPages > 0);
642 AssertPtr(papvPages);
643 AssertPtr(paLocks);
644
645 Assert(VM_IS_EMT(pVM) || !PGMIsLockOwner(pVM));
646
647 int rc = PGM_LOCK(pVM);
648 AssertRCReturn(rc, rc);
649
650 /*
651 * Lock the pages one by one.
652 * The loop body is similar to PGMR3PhysGCPhys2CCPtrExternal.
653 */
654 int32_t cNextYield = 128;
655 uint32_t iPage;
656 for (iPage = 0; iPage < cPages; iPage++)
657 {
658 if (--cNextYield > 0)
659 { /* likely */ }
660 else
661 {
662 PGM_UNLOCK(pVM);
663 ASMNopPause();
664 PGM_LOCK_VOID(pVM);
665 cNextYield = 128;
666 }
667
668 /*
669 * Query the Physical TLB entry for the page (may fail).
670 */
671 PPGMPAGEMAPTLBE pTlbe;
672 rc = pgmPhysPageQueryTlbe(pVM, paGCPhysPages[iPage], &pTlbe);
673 if (RT_SUCCESS(rc))
674 { }
675 else
676 break;
677 PPGMPAGE pPage = pTlbe->pPage;
678
679 /*
680 * No MMIO or active access handlers.
681 */
682 if ( !PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage)
683 && !PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
684 { }
685 else
686 {
687 rc = VERR_PGM_PHYS_PAGE_RESERVED;
688 break;
689 }
690
691 /*
692 * The page must be in the allocated state and not be a dirty pool page.
693 * We can handle converting a write monitored page to an allocated one, but
694 * anything more complicated must be delegated to an EMT.
695 */
696 bool fDelegateToEmt = false;
697 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_ALLOCATED)
698#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
699 fDelegateToEmt = pgmPoolIsDirtyPage(pVM, paGCPhysPages[iPage]);
700#else
701 fDelegateToEmt = false;
702#endif
703 else if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
704 {
705#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
706 if (!pgmPoolIsDirtyPage(pVM, paGCPhysPages[iPage]))
707 pgmPhysPageMakeWriteMonitoredWritable(pVM, pPage, paGCPhysPages[iPage]);
708 else
709 fDelegateToEmt = true;
710#endif
711 }
712 else
713 fDelegateToEmt = true;
714 if (!fDelegateToEmt)
715 { }
716 else
717 {
718 /* We could do this delegation in bulk, but considered too much work vs gain. */
719 PGM_UNLOCK(pVM);
720 rc = VMR3ReqPriorityCallWait(pVM, VMCPUID_ANY, (PFNRT)pgmR3PhysGCPhys2CCPtrDelegated, 4,
721 pVM, &paGCPhysPages[iPage], &papvPages[iPage], &paLocks[iPage]);
722 PGM_LOCK_VOID(pVM);
723 if (RT_FAILURE(rc))
724 break;
725 cNextYield = 128;
726 }
727
728 /*
729 * Now, just perform the locking and address calculation.
730 */
731 PPGMPAGEMAP pMap = pTlbe->pMap;
732 if (pMap)
733 pMap->cRefs++;
734
735 unsigned cLocks = PGM_PAGE_GET_WRITE_LOCKS(pPage);
736 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
737 {
738 if (cLocks == 0)
739 pVM->pgm.s.cWriteLockedPages++;
740 PGM_PAGE_INC_WRITE_LOCKS(pPage);
741 }
742 else if (cLocks != PGM_PAGE_GET_WRITE_LOCKS(pPage))
743 {
744 PGM_PAGE_INC_WRITE_LOCKS(pPage);
745 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent write locked state!\n", paGCPhysPages[iPage], pPage));
746 if (pMap)
747 pMap->cRefs++; /* Extra ref to prevent it from going away. */
748 }
749
750 papvPages[iPage] = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(paGCPhysPages[iPage] & GUEST_PAGE_OFFSET_MASK));
751 paLocks[iPage].uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_WRITE;
752 paLocks[iPage].pvMap = pMap;
753 }
754
755 PGM_UNLOCK(pVM);
756
757 /*
758 * On failure we must unlock any pages we managed to get already.
759 */
760 if (RT_FAILURE(rc) && iPage > 0)
761 PGMPhysBulkReleasePageMappingLocks(pVM, iPage, paLocks);
762
763 return rc;
764}
765
766
767/**
768 * Requests the mapping of multiple guest page into ring-3, for reading only,
769 * external threads.
770 *
771 * When you're done with the pages, call PGMPhysReleasePageMappingLock() ASAP
772 * to release them.
773 *
774 * @returns VBox status code.
775 * @retval VINF_SUCCESS on success.
776 * @retval VERR_PGM_PHYS_PAGE_RESERVED if any of the pages has no physical
777 * backing or if any of the pages the page has an active ALL access
778 * handler. The caller must fall back on using PGMR3PhysWriteExternal.
779 * @retval VERR_PGM_INVALID_GC_PHYSICAL_ADDRESS if @a paGCPhysPages contains
780 * an invalid physical address.
781 *
782 * @param pVM The cross context VM structure.
783 * @param cPages Number of pages to lock.
784 * @param paGCPhysPages The guest physical address of the pages that
785 * should be mapped (@a cPages entries).
786 * @param papvPages Where to store the ring-3 mapping addresses
787 * corresponding to @a paGCPhysPages.
788 * @param paLocks Where to store the lock information that
789 * pfnPhysReleasePageMappingLock needs (@a cPages
790 * in length).
791 *
792 * @remark Avoid calling this API from within critical sections (other than
793 * the PGM one) because of the deadlock risk.
794 * @thread Any.
795 */
796VMMR3DECL(int) PGMR3PhysBulkGCPhys2CCPtrReadOnlyExternal(PVM pVM, uint32_t cPages, PCRTGCPHYS paGCPhysPages,
797 void const **papvPages, PPGMPAGEMAPLOCK paLocks)
798{
799 Assert(cPages > 0);
800 AssertPtr(papvPages);
801 AssertPtr(paLocks);
802
803 Assert(VM_IS_EMT(pVM) || !PGMIsLockOwner(pVM));
804
805 int rc = PGM_LOCK(pVM);
806 AssertRCReturn(rc, rc);
807
808 /*
809 * Lock the pages one by one.
810 * The loop body is similar to PGMR3PhysGCPhys2CCPtrReadOnlyExternal.
811 */
812 int32_t cNextYield = 256;
813 uint32_t iPage;
814 for (iPage = 0; iPage < cPages; iPage++)
815 {
816 if (--cNextYield > 0)
817 { /* likely */ }
818 else
819 {
820 PGM_UNLOCK(pVM);
821 ASMNopPause();
822 PGM_LOCK_VOID(pVM);
823 cNextYield = 256;
824 }
825
826 /*
827 * Query the Physical TLB entry for the page (may fail).
828 */
829 PPGMPAGEMAPTLBE pTlbe;
830 rc = pgmPhysPageQueryTlbe(pVM, paGCPhysPages[iPage], &pTlbe);
831 if (RT_SUCCESS(rc))
832 { }
833 else
834 break;
835 PPGMPAGE pPage = pTlbe->pPage;
836
837 /*
838 * No MMIO or active all access handlers, everything else can be accessed.
839 */
840 if ( !PGM_PAGE_IS_MMIO_OR_SPECIAL_ALIAS(pPage)
841 && !PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage))
842 { }
843 else
844 {
845 rc = VERR_PGM_PHYS_PAGE_RESERVED;
846 break;
847 }
848
849 /*
850 * Now, just perform the locking and address calculation.
851 */
852 PPGMPAGEMAP pMap = pTlbe->pMap;
853 if (pMap)
854 pMap->cRefs++;
855
856 unsigned cLocks = PGM_PAGE_GET_READ_LOCKS(pPage);
857 if (RT_LIKELY(cLocks < PGM_PAGE_MAX_LOCKS - 1))
858 {
859 if (cLocks == 0)
860 pVM->pgm.s.cReadLockedPages++;
861 PGM_PAGE_INC_READ_LOCKS(pPage);
862 }
863 else if (cLocks != PGM_PAGE_GET_READ_LOCKS(pPage))
864 {
865 PGM_PAGE_INC_READ_LOCKS(pPage);
866 AssertMsgFailed(("%RGp / %R[pgmpage] is entering permanent readonly locked state!\n", paGCPhysPages[iPage], pPage));
867 if (pMap)
868 pMap->cRefs++; /* Extra ref to prevent it from going away. */
869 }
870
871 papvPages[iPage] = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(paGCPhysPages[iPage] & GUEST_PAGE_OFFSET_MASK));
872 paLocks[iPage].uPageAndType = (uintptr_t)pPage | PGMPAGEMAPLOCK_TYPE_READ;
873 paLocks[iPage].pvMap = pMap;
874 }
875
876 PGM_UNLOCK(pVM);
877
878 /*
879 * On failure we must unlock any pages we managed to get already.
880 */
881 if (RT_FAILURE(rc) && iPage > 0)
882 PGMPhysBulkReleasePageMappingLocks(pVM, iPage, paLocks);
883
884 return rc;
885}
886
887
888/**
889 * Converts a GC physical address to a HC ring-3 pointer, with some
890 * additional checks.
891 *
892 * @returns VBox status code.
893 * @retval VINF_SUCCESS on success.
894 * @retval VINF_PGM_PHYS_TLB_CATCH_WRITE and *ppv set if the page has a write
895 * access handler of some kind.
896 * @retval VERR_PGM_PHYS_TLB_CATCH_ALL if the page has a handler catching all
897 * accesses or is odd in any way.
898 * @retval VERR_PGM_PHYS_TLB_UNASSIGNED if the page doesn't exist.
899 *
900 * @param pVM The cross context VM structure.
901 * @param GCPhys The GC physical address to convert. Since this is only
902 * used for filling the REM TLB, the A20 mask must be
903 * applied before calling this API.
904 * @param fWritable Whether write access is required.
905 * @param ppv Where to store the pointer corresponding to GCPhys on
906 * success.
907 */
908VMMR3DECL(int) PGMR3PhysTlbGCPhys2Ptr(PVM pVM, RTGCPHYS GCPhys, bool fWritable, void **ppv)
909{
910 PGM_LOCK_VOID(pVM);
911 PGM_A20_ASSERT_MASKED(VMMGetCpu(pVM), GCPhys);
912
913 PPGMRAMRANGE pRam;
914 PPGMPAGE pPage;
915 int rc = pgmPhysGetPageAndRangeEx(pVM, GCPhys, &pPage, &pRam);
916 if (RT_SUCCESS(rc))
917 {
918 if (PGM_PAGE_IS_BALLOONED(pPage))
919 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
920 else if (!PGM_PAGE_HAS_ANY_HANDLERS(pPage))
921 rc = VINF_SUCCESS;
922 else
923 {
924 if (PGM_PAGE_HAS_ACTIVE_ALL_HANDLERS(pPage)) /* catches MMIO */
925 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
926 else if (PGM_PAGE_HAS_ACTIVE_HANDLERS(pPage))
927 {
928 /** @todo Handle TLB loads of virtual handlers so ./test.sh can be made to work
929 * in -norawr0 mode. */
930 if (fWritable)
931 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
932 }
933 else
934 {
935 /* Temporarily disabled physical handler(s), since the recompiler
936 doesn't get notified when it's reset we'll have to pretend it's
937 operating normally. */
938 if (pgmHandlerPhysicalIsAll(pVM, GCPhys))
939 rc = VERR_PGM_PHYS_TLB_CATCH_ALL;
940 else
941 rc = VINF_PGM_PHYS_TLB_CATCH_WRITE;
942 }
943 }
944 if (RT_SUCCESS(rc))
945 {
946 int rc2;
947
948 /* Make sure what we return is writable. */
949 if (fWritable)
950 switch (PGM_PAGE_GET_STATE(pPage))
951 {
952 case PGM_PAGE_STATE_ALLOCATED:
953 break;
954 case PGM_PAGE_STATE_BALLOONED:
955 AssertFailed();
956 break;
957 case PGM_PAGE_STATE_ZERO:
958 case PGM_PAGE_STATE_SHARED:
959 if (rc == VINF_PGM_PHYS_TLB_CATCH_WRITE)
960 break;
961 RT_FALL_THRU();
962 case PGM_PAGE_STATE_WRITE_MONITORED:
963 rc2 = pgmPhysPageMakeWritable(pVM, pPage, GCPhys & ~(RTGCPHYS)GUEST_PAGE_OFFSET_MASK);
964 AssertLogRelRCReturn(rc2, rc2);
965 break;
966 }
967
968 /* Get a ring-3 mapping of the address. */
969 PPGMPAGER3MAPTLBE pTlbe;
970 rc2 = pgmPhysPageQueryTlbe(pVM, GCPhys, &pTlbe);
971 AssertLogRelRCReturn(rc2, rc2);
972 *ppv = (void *)((uintptr_t)pTlbe->pv | (uintptr_t)(GCPhys & GUEST_PAGE_OFFSET_MASK));
973 /** @todo mapping/locking hell; this isn't horribly efficient since
974 * pgmPhysPageLoadIntoTlb will repeat the lookup we've done here. */
975
976 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage] *ppv=%p\n", GCPhys, rc, pPage, *ppv));
977 }
978 else
979 Log6(("PGMR3PhysTlbGCPhys2Ptr: GCPhys=%RGp rc=%Rrc pPage=%R[pgmpage]\n", GCPhys, rc, pPage));
980
981 /* else: handler catching all access, no pointer returned. */
982 }
983 else
984 rc = VERR_PGM_PHYS_TLB_UNASSIGNED;
985
986 PGM_UNLOCK(pVM);
987 return rc;
988}
989
990
991
992/*********************************************************************************************************************************
993* RAM Range Management *
994*********************************************************************************************************************************/
995
996#define MAKE_LEAF(a_pNode) \
997 do { \
998 (a_pNode)->pLeftR3 = NIL_RTR3PTR; \
999 (a_pNode)->pRightR3 = NIL_RTR3PTR; \
1000 (a_pNode)->pLeftR0 = NIL_RTR0PTR; \
1001 (a_pNode)->pRightR0 = NIL_RTR0PTR; \
1002 } while (0)
1003
1004#define INSERT_LEFT(a_pParent, a_pNode) \
1005 do { \
1006 (a_pParent)->pLeftR3 = (a_pNode); \
1007 (a_pParent)->pLeftR0 = (a_pNode)->pSelfR0; \
1008 } while (0)
1009#define INSERT_RIGHT(a_pParent, a_pNode) \
1010 do { \
1011 (a_pParent)->pRightR3 = (a_pNode); \
1012 (a_pParent)->pRightR0 = (a_pNode)->pSelfR0; \
1013 } while (0)
1014
1015
1016/**
1017 * Recursive tree builder.
1018 *
1019 * @param ppRam Pointer to the iterator variable.
1020 * @param iDepth The current depth. Inserts a leaf node if 0.
1021 */
1022static PPGMRAMRANGE pgmR3PhysRebuildRamRangeSearchTreesRecursively(PPGMRAMRANGE *ppRam, int iDepth)
1023{
1024 PPGMRAMRANGE pRam;
1025 if (iDepth <= 0)
1026 {
1027 /*
1028 * Leaf node.
1029 */
1030 pRam = *ppRam;
1031 if (pRam)
1032 {
1033 *ppRam = pRam->pNextR3;
1034 MAKE_LEAF(pRam);
1035 }
1036 }
1037 else
1038 {
1039
1040 /*
1041 * Intermediate node.
1042 */
1043 PPGMRAMRANGE pLeft = pgmR3PhysRebuildRamRangeSearchTreesRecursively(ppRam, iDepth - 1);
1044
1045 pRam = *ppRam;
1046 if (!pRam)
1047 return pLeft;
1048 *ppRam = pRam->pNextR3;
1049 MAKE_LEAF(pRam);
1050 INSERT_LEFT(pRam, pLeft);
1051
1052 PPGMRAMRANGE pRight = pgmR3PhysRebuildRamRangeSearchTreesRecursively(ppRam, iDepth - 1);
1053 if (pRight)
1054 INSERT_RIGHT(pRam, pRight);
1055 }
1056 return pRam;
1057}
1058
1059
1060/**
1061 * Rebuilds the RAM range search trees.
1062 *
1063 * @param pVM The cross context VM structure.
1064 */
1065static void pgmR3PhysRebuildRamRangeSearchTrees(PVM pVM)
1066{
1067
1068 /*
1069 * Create the reasonably balanced tree in a sequential fashion.
1070 * For simplicity (laziness) we use standard recursion here.
1071 */
1072 int iDepth = 0;
1073 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
1074 PPGMRAMRANGE pRoot = pgmR3PhysRebuildRamRangeSearchTreesRecursively(&pRam, 0);
1075 while (pRam)
1076 {
1077 PPGMRAMRANGE pLeft = pRoot;
1078
1079 pRoot = pRam;
1080 pRam = pRam->pNextR3;
1081 MAKE_LEAF(pRoot);
1082 INSERT_LEFT(pRoot, pLeft);
1083
1084 PPGMRAMRANGE pRight = pgmR3PhysRebuildRamRangeSearchTreesRecursively(&pRam, iDepth);
1085 if (pRight)
1086 INSERT_RIGHT(pRoot, pRight);
1087 /** @todo else: rotate the tree. */
1088
1089 iDepth++;
1090 }
1091
1092 pVM->pgm.s.pRamRangeTreeR3 = pRoot;
1093 pVM->pgm.s.pRamRangeTreeR0 = pRoot ? pRoot->pSelfR0 : NIL_RTR0PTR;
1094
1095#ifdef VBOX_STRICT
1096 /*
1097 * Verify that the above code works.
1098 */
1099 unsigned cRanges = 0;
1100 for (pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1101 cRanges++;
1102 Assert(cRanges > 0);
1103
1104 unsigned cMaxDepth = ASMBitLastSetU32(cRanges);
1105 if ((1U << cMaxDepth) < cRanges)
1106 cMaxDepth++;
1107
1108 for (pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1109 {
1110 unsigned cDepth = 0;
1111 PPGMRAMRANGE pRam2 = pVM->pgm.s.pRamRangeTreeR3;
1112 for (;;)
1113 {
1114 if (pRam == pRam2)
1115 break;
1116 Assert(pRam2);
1117 if (pRam->GCPhys < pRam2->GCPhys)
1118 pRam2 = pRam2->pLeftR3;
1119 else
1120 pRam2 = pRam2->pRightR3;
1121 }
1122 AssertMsg(cDepth <= cMaxDepth, ("cDepth=%d cMaxDepth=%d\n", cDepth, cMaxDepth));
1123 }
1124#endif /* VBOX_STRICT */
1125}
1126
1127#undef MAKE_LEAF
1128#undef INSERT_LEFT
1129#undef INSERT_RIGHT
1130
1131/**
1132 * Relinks the RAM ranges using the pSelfRC and pSelfR0 pointers.
1133 *
1134 * Called when anything was relocated.
1135 *
1136 * @param pVM The cross context VM structure.
1137 */
1138void pgmR3PhysRelinkRamRanges(PVM pVM)
1139{
1140 PPGMRAMRANGE pCur;
1141
1142#ifdef VBOX_STRICT
1143 for (pCur = pVM->pgm.s.pRamRangesXR3; pCur; pCur = pCur->pNextR3)
1144 {
1145 Assert((pCur->GCPhys & GUEST_PAGE_OFFSET_MASK) == 0);
1146 Assert((pCur->GCPhysLast & GUEST_PAGE_OFFSET_MASK) == GUEST_PAGE_OFFSET_MASK);
1147 Assert((pCur->cb & GUEST_PAGE_OFFSET_MASK) == 0);
1148 Assert(pCur->cb == pCur->GCPhysLast - pCur->GCPhys + 1);
1149 for (PPGMRAMRANGE pCur2 = pVM->pgm.s.pRamRangesXR3; pCur2; pCur2 = pCur2->pNextR3)
1150 Assert( pCur2 == pCur
1151 || strcmp(pCur2->pszDesc, pCur->pszDesc)); /** @todo fix MMIO ranges!! */
1152 }
1153#endif
1154
1155 pCur = pVM->pgm.s.pRamRangesXR3;
1156 if (pCur)
1157 {
1158 pVM->pgm.s.pRamRangesXR0 = pCur->pSelfR0;
1159
1160 for (; pCur->pNextR3; pCur = pCur->pNextR3)
1161 pCur->pNextR0 = pCur->pNextR3->pSelfR0;
1162
1163 Assert(pCur->pNextR0 == NIL_RTR0PTR);
1164 }
1165 else
1166 {
1167 Assert(pVM->pgm.s.pRamRangesXR0 == NIL_RTR0PTR);
1168 }
1169 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
1170
1171 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
1172}
1173
1174
1175/**
1176 * Links a new RAM range into the list.
1177 *
1178 * @param pVM The cross context VM structure.
1179 * @param pNew Pointer to the new list entry.
1180 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
1181 */
1182static void pgmR3PhysLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, PPGMRAMRANGE pPrev)
1183{
1184 AssertMsg(pNew->pszDesc, ("%RGp-%RGp\n", pNew->GCPhys, pNew->GCPhysLast));
1185
1186 PGM_LOCK_VOID(pVM);
1187
1188 PPGMRAMRANGE pRam = pPrev ? pPrev->pNextR3 : pVM->pgm.s.pRamRangesXR3;
1189 pNew->pNextR3 = pRam;
1190 pNew->pNextR0 = pRam ? pRam->pSelfR0 : NIL_RTR0PTR;
1191
1192 if (pPrev)
1193 {
1194 pPrev->pNextR3 = pNew;
1195 pPrev->pNextR0 = pNew->pSelfR0;
1196 }
1197 else
1198 {
1199 pVM->pgm.s.pRamRangesXR3 = pNew;
1200 pVM->pgm.s.pRamRangesXR0 = pNew->pSelfR0;
1201 }
1202 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
1203
1204 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
1205 PGM_UNLOCK(pVM);
1206}
1207
1208
1209/**
1210 * Unlink an existing RAM range from the list.
1211 *
1212 * @param pVM The cross context VM structure.
1213 * @param pRam Pointer to the new list entry.
1214 * @param pPrev Pointer to the previous list entry. If NULL, insert as head.
1215 */
1216static void pgmR3PhysUnlinkRamRange2(PVM pVM, PPGMRAMRANGE pRam, PPGMRAMRANGE pPrev)
1217{
1218 Assert(pPrev ? pPrev->pNextR3 == pRam : pVM->pgm.s.pRamRangesXR3 == pRam);
1219
1220 PGM_LOCK_VOID(pVM);
1221
1222 PPGMRAMRANGE pNext = pRam->pNextR3;
1223 if (pPrev)
1224 {
1225 pPrev->pNextR3 = pNext;
1226 pPrev->pNextR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
1227 }
1228 else
1229 {
1230 Assert(pVM->pgm.s.pRamRangesXR3 == pRam);
1231 pVM->pgm.s.pRamRangesXR3 = pNext;
1232 pVM->pgm.s.pRamRangesXR0 = pNext ? pNext->pSelfR0 : NIL_RTR0PTR;
1233 }
1234 ASMAtomicIncU32(&pVM->pgm.s.idRamRangesGen);
1235
1236 pgmR3PhysRebuildRamRangeSearchTrees(pVM);
1237 PGM_UNLOCK(pVM);
1238}
1239
1240
1241/**
1242 * Unlink an existing RAM range from the list.
1243 *
1244 * @param pVM The cross context VM structure.
1245 * @param pRam Pointer to the new list entry.
1246 */
1247static void pgmR3PhysUnlinkRamRange(PVM pVM, PPGMRAMRANGE pRam)
1248{
1249 PGM_LOCK_VOID(pVM);
1250
1251 /* find prev. */
1252 PPGMRAMRANGE pPrev = NULL;
1253 PPGMRAMRANGE pCur = pVM->pgm.s.pRamRangesXR3;
1254 while (pCur != pRam)
1255 {
1256 pPrev = pCur;
1257 pCur = pCur->pNextR3;
1258 }
1259 AssertFatal(pCur);
1260
1261 pgmR3PhysUnlinkRamRange2(pVM, pRam, pPrev);
1262 PGM_UNLOCK(pVM);
1263}
1264
1265
1266/**
1267 * Gets the number of ram ranges.
1268 *
1269 * @returns Number of ram ranges. Returns UINT32_MAX if @a pVM is invalid.
1270 * @param pVM The cross context VM structure.
1271 */
1272VMMR3DECL(uint32_t) PGMR3PhysGetRamRangeCount(PVM pVM)
1273{
1274 VM_ASSERT_VALID_EXT_RETURN(pVM, UINT32_MAX);
1275
1276 PGM_LOCK_VOID(pVM);
1277 uint32_t cRamRanges = 0;
1278 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRangesX); pCur; pCur = pCur->CTX_SUFF(pNext))
1279 cRamRanges++;
1280 PGM_UNLOCK(pVM);
1281 return cRamRanges;
1282}
1283
1284
1285/**
1286 * Get information about a range.
1287 *
1288 * @returns VINF_SUCCESS or VERR_OUT_OF_RANGE.
1289 * @param pVM The cross context VM structure.
1290 * @param iRange The ordinal of the range.
1291 * @param pGCPhysStart Where to return the start of the range. Optional.
1292 * @param pGCPhysLast Where to return the address of the last byte in the
1293 * range. Optional.
1294 * @param ppszDesc Where to return the range description. Optional.
1295 * @param pfIsMmio Where to indicate that this is a pure MMIO range.
1296 * Optional.
1297 */
1298VMMR3DECL(int) PGMR3PhysGetRange(PVM pVM, uint32_t iRange, PRTGCPHYS pGCPhysStart, PRTGCPHYS pGCPhysLast,
1299 const char **ppszDesc, bool *pfIsMmio)
1300{
1301 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1302
1303 PGM_LOCK_VOID(pVM);
1304 uint32_t iCurRange = 0;
1305 for (PPGMRAMRANGE pCur = pVM->pgm.s.CTX_SUFF(pRamRangesX); pCur; pCur = pCur->CTX_SUFF(pNext), iCurRange++)
1306 if (iCurRange == iRange)
1307 {
1308 if (pGCPhysStart)
1309 *pGCPhysStart = pCur->GCPhys;
1310 if (pGCPhysLast)
1311 *pGCPhysLast = pCur->GCPhysLast;
1312 if (ppszDesc)
1313 *ppszDesc = pCur->pszDesc;
1314 if (pfIsMmio)
1315 *pfIsMmio = !!(pCur->fFlags & PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO);
1316
1317 PGM_UNLOCK(pVM);
1318 return VINF_SUCCESS;
1319 }
1320 PGM_UNLOCK(pVM);
1321 return VERR_OUT_OF_RANGE;
1322}
1323
1324
1325/*********************************************************************************************************************************
1326* RAM *
1327*********************************************************************************************************************************/
1328
1329/**
1330 * Frees the specified RAM page and replaces it with the ZERO page.
1331 *
1332 * This is used by ballooning, remapping MMIO2, RAM reset and state loading.
1333 *
1334 * @param pVM The cross context VM structure.
1335 * @param pReq Pointer to the request. This is NULL when doing a
1336 * bulk free in NEM memory mode.
1337 * @param pcPendingPages Where the number of pages waiting to be freed are
1338 * kept. This will normally be incremented. This is
1339 * NULL when doing a bulk free in NEM memory mode.
1340 * @param pPage Pointer to the page structure.
1341 * @param GCPhys The guest physical address of the page, if applicable.
1342 * @param enmNewType New page type for NEM notification, since several
1343 * callers will change the type upon successful return.
1344 *
1345 * @remarks The caller must own the PGM lock.
1346 */
1347int pgmPhysFreePage(PVM pVM, PGMMFREEPAGESREQ pReq, uint32_t *pcPendingPages, PPGMPAGE pPage, RTGCPHYS GCPhys,
1348 PGMPAGETYPE enmNewType)
1349{
1350 /*
1351 * Assert sanity.
1352 */
1353 PGM_LOCK_ASSERT_OWNER(pVM);
1354 if (RT_UNLIKELY( PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM
1355 && PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_ROM_SHADOW))
1356 {
1357 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
1358 return VMSetError(pVM, VERR_PGM_PHYS_NOT_RAM, RT_SRC_POS, "GCPhys=%RGp type=%d", GCPhys, PGM_PAGE_GET_TYPE(pPage));
1359 }
1360
1361 /** @todo What about ballooning of large pages??! */
1362 Assert( PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE
1363 && PGM_PAGE_GET_PDE_TYPE(pPage) != PGM_PAGE_PDE_TYPE_PDE_DISABLED);
1364
1365 if ( PGM_PAGE_IS_ZERO(pPage)
1366 || PGM_PAGE_IS_BALLOONED(pPage))
1367 return VINF_SUCCESS;
1368
1369 const uint32_t idPage = PGM_PAGE_GET_PAGEID(pPage);
1370 Log3(("pgmPhysFreePage: idPage=%#x GCPhys=%RGp pPage=%R[pgmpage]\n", idPage, GCPhys, pPage));
1371 if (RT_UNLIKELY(!PGM_IS_IN_NEM_MODE(pVM)
1372 ? idPage == NIL_GMM_PAGEID
1373 || idPage > GMM_PAGEID_LAST
1374 || PGM_PAGE_GET_CHUNKID(pPage) == NIL_GMM_CHUNKID
1375 : idPage != NIL_GMM_PAGEID))
1376 {
1377 AssertMsgFailed(("GCPhys=%RGp pPage=%R[pgmpage]\n", GCPhys, pPage));
1378 return VMSetError(pVM, VERR_PGM_PHYS_INVALID_PAGE_ID, RT_SRC_POS, "GCPhys=%RGp idPage=%#x", GCPhys, pPage);
1379 }
1380#ifdef VBOX_WITH_NATIVE_NEM
1381 const RTHCPHYS HCPhysPrev = PGM_PAGE_GET_HCPHYS(pPage);
1382#endif
1383
1384 /* update page count stats. */
1385 if (PGM_PAGE_IS_SHARED(pPage))
1386 pVM->pgm.s.cSharedPages--;
1387 else
1388 pVM->pgm.s.cPrivatePages--;
1389 pVM->pgm.s.cZeroPages++;
1390
1391 /* Deal with write monitored pages. */
1392 if (PGM_PAGE_GET_STATE(pPage) == PGM_PAGE_STATE_WRITE_MONITORED)
1393 {
1394 PGM_PAGE_SET_WRITTEN_TO(pVM, pPage);
1395 pVM->pgm.s.cWrittenToPages++;
1396 }
1397
1398 /*
1399 * pPage = ZERO page.
1400 */
1401 PGM_PAGE_SET_HCPHYS(pVM, pPage, pVM->pgm.s.HCPhysZeroPg);
1402 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
1403 PGM_PAGE_SET_PAGEID(pVM, pPage, NIL_GMM_PAGEID);
1404 PGM_PAGE_SET_PDE_TYPE(pVM, pPage, PGM_PAGE_PDE_TYPE_DONTCARE);
1405 PGM_PAGE_SET_PTE_INDEX(pVM, pPage, 0);
1406 PGM_PAGE_SET_TRACKING(pVM, pPage, 0);
1407
1408 /* Flush physical page map TLB entry. */
1409 pgmPhysInvalidatePageMapTLBEntry(pVM, GCPhys);
1410
1411#ifdef VBOX_WITH_PGM_NEM_MODE
1412 /*
1413 * Skip the rest if we're doing a bulk free in NEM memory mode.
1414 */
1415 if (!pReq)
1416 return VINF_SUCCESS;
1417 AssertLogRelReturn(!pVM->pgm.s.fNemMode, VERR_PGM_NOT_SUPPORTED_FOR_NEM_MODE);
1418#endif
1419
1420#ifdef VBOX_WITH_NATIVE_NEM
1421 /* Notify NEM. */
1422 /** @todo Remove this one? */
1423 if (VM_IS_NEM_ENABLED(pVM))
1424 {
1425 uint8_t u2State = PGM_PAGE_GET_NEM_STATE(pPage);
1426 NEMHCNotifyPhysPageChanged(pVM, GCPhys, HCPhysPrev, pVM->pgm.s.HCPhysZeroPg, pVM->pgm.s.abZeroPg,
1427 pgmPhysPageCalcNemProtection(pPage, enmNewType), enmNewType, &u2State);
1428 PGM_PAGE_SET_NEM_STATE(pPage, u2State);
1429 }
1430#else
1431 RT_NOREF(enmNewType);
1432#endif
1433
1434 /*
1435 * Make sure it's not in the handy page array.
1436 */
1437 for (uint32_t i = pVM->pgm.s.cHandyPages; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
1438 {
1439 if (pVM->pgm.s.aHandyPages[i].idPage == idPage)
1440 {
1441 pVM->pgm.s.aHandyPages[i].HCPhysGCPhys = NIL_GMMPAGEDESC_PHYS;
1442 pVM->pgm.s.aHandyPages[i].fZeroed = false;
1443 pVM->pgm.s.aHandyPages[i].idPage = NIL_GMM_PAGEID;
1444 break;
1445 }
1446 if (pVM->pgm.s.aHandyPages[i].idSharedPage == idPage)
1447 {
1448 pVM->pgm.s.aHandyPages[i].idSharedPage = NIL_GMM_PAGEID;
1449 break;
1450 }
1451 }
1452
1453 /*
1454 * Push it onto the page array.
1455 */
1456 uint32_t iPage = *pcPendingPages;
1457 Assert(iPage < PGMPHYS_FREE_PAGE_BATCH_SIZE);
1458 *pcPendingPages += 1;
1459
1460 pReq->aPages[iPage].idPage = idPage;
1461
1462 if (iPage + 1 < PGMPHYS_FREE_PAGE_BATCH_SIZE)
1463 return VINF_SUCCESS;
1464
1465 /*
1466 * Flush the pages.
1467 */
1468 int rc = GMMR3FreePagesPerform(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE);
1469 if (RT_SUCCESS(rc))
1470 {
1471 GMMR3FreePagesRePrep(pVM, pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1472 *pcPendingPages = 0;
1473 }
1474 return rc;
1475}
1476
1477
1478/**
1479 * Frees a range of pages, replacing them with ZERO pages of the specified type.
1480 *
1481 * @returns VBox status code.
1482 * @param pVM The cross context VM structure.
1483 * @param pRam The RAM range in which the pages resides.
1484 * @param GCPhys The address of the first page.
1485 * @param GCPhysLast The address of the last page.
1486 * @param pvMmio2 Pointer to the ring-3 mapping of any MMIO2 memory that
1487 * will replace the pages we're freeing up.
1488 */
1489static int pgmR3PhysFreePageRange(PVM pVM, PPGMRAMRANGE pRam, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast, void *pvMmio2)
1490{
1491 PGM_LOCK_ASSERT_OWNER(pVM);
1492
1493#ifdef VBOX_WITH_PGM_NEM_MODE
1494 /*
1495 * In simplified memory mode we don't actually free the memory,
1496 * we just unmap it and let NEM do any unlocking of it.
1497 */
1498 if (pVM->pgm.s.fNemMode)
1499 {
1500 Assert(VM_IS_NEM_ENABLED(pVM));
1501 uint32_t const fNemNotify = (pvMmio2 ? NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2 : 0) | NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE;
1502 uint8_t u2State = 0; /* (We don't support UINT8_MAX here.) */
1503 int rc = NEMR3NotifyPhysMmioExMapEarly(pVM, GCPhys, GCPhysLast - GCPhys + 1, fNemNotify,
1504 pRam->pvR3 ? (uint8_t *)pRam->pvR3 + GCPhys - pRam->GCPhys : NULL,
1505 pvMmio2, &u2State, NULL /*puNemRange*/);
1506 AssertLogRelRCReturn(rc, rc);
1507
1508 /* Iterate the pages. */
1509 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
1510 uint32_t cPagesLeft = ((GCPhysLast - GCPhys) >> GUEST_PAGE_SHIFT) + 1;
1511 while (cPagesLeft-- > 0)
1512 {
1513 rc = pgmPhysFreePage(pVM, NULL, NULL, pPageDst, GCPhys, PGMPAGETYPE_MMIO);
1514 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
1515
1516 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO);
1517 PGM_PAGE_SET_NEM_STATE(pPageDst, u2State);
1518
1519 GCPhys += GUEST_PAGE_SIZE;
1520 pPageDst++;
1521 }
1522 return rc;
1523 }
1524#else /* !VBOX_WITH_PGM_NEM_MODE */
1525 RT_NOREF(pvMmio2);
1526#endif /* !VBOX_WITH_PGM_NEM_MODE */
1527
1528 /*
1529 * Regular mode.
1530 */
1531 /* Prepare. */
1532 uint32_t cPendingPages = 0;
1533 PGMMFREEPAGESREQ pReq;
1534 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
1535 AssertLogRelRCReturn(rc, rc);
1536
1537#ifdef VBOX_WITH_NATIVE_NEM
1538 /* Tell NEM up-front. */
1539 uint8_t u2State = UINT8_MAX;
1540 if (VM_IS_NEM_ENABLED(pVM))
1541 {
1542 uint32_t const fNemNotify = (pvMmio2 ? NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2 : 0) | NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE;
1543 rc = NEMR3NotifyPhysMmioExMapEarly(pVM, GCPhys, GCPhysLast - GCPhys + 1, fNemNotify, NULL, pvMmio2,
1544 &u2State, NULL /*puNemRange*/);
1545 AssertLogRelRCReturnStmt(rc, GMMR3FreePagesCleanup(pReq), rc);
1546 }
1547#endif
1548
1549 /* Iterate the pages. */
1550 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
1551 uint32_t cPagesLeft = ((GCPhysLast - GCPhys) >> GUEST_PAGE_SHIFT) + 1;
1552 while (cPagesLeft-- > 0)
1553 {
1554 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPageDst, GCPhys, PGMPAGETYPE_MMIO);
1555 AssertLogRelRCReturn(rc, rc); /* We're done for if this goes wrong. */
1556
1557 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO);
1558#ifdef VBOX_WITH_NATIVE_NEM
1559 if (u2State != UINT8_MAX)
1560 PGM_PAGE_SET_NEM_STATE(pPageDst, u2State);
1561#endif
1562
1563 GCPhys += GUEST_PAGE_SIZE;
1564 pPageDst++;
1565 }
1566
1567 /* Finish pending and cleanup. */
1568 if (cPendingPages)
1569 {
1570 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
1571 AssertLogRelRCReturn(rc, rc);
1572 }
1573 GMMR3FreePagesCleanup(pReq);
1574
1575 return rc;
1576}
1577
1578
1579/**
1580 * PGMR3PhysRegisterRam worker that initializes and links a RAM range.
1581 *
1582 * In NEM mode, this will allocate the pages backing the RAM range and this may
1583 * fail. NEM registration may also fail. (In regular HM mode it won't fail.)
1584 *
1585 * @returns VBox status code.
1586 * @param pVM The cross context VM structure.
1587 * @param pNew The new RAM range.
1588 * @param GCPhys The address of the RAM range.
1589 * @param GCPhysLast The last address of the RAM range.
1590 * @param R0PtrNew Ditto for R0.
1591 * @param fFlags PGM_RAM_RANGE_FLAGS_FLOATING or zero.
1592 * @param pszDesc The description.
1593 * @param pPrev The previous RAM range (for linking).
1594 */
1595static int pgmR3PhysInitAndLinkRamRange(PVM pVM, PPGMRAMRANGE pNew, RTGCPHYS GCPhys, RTGCPHYS GCPhysLast,
1596 RTR0PTR R0PtrNew, uint32_t fFlags, const char *pszDesc, PPGMRAMRANGE pPrev)
1597{
1598 /*
1599 * Initialize the range.
1600 */
1601 pNew->pSelfR0 = R0PtrNew;
1602 pNew->GCPhys = GCPhys;
1603 pNew->GCPhysLast = GCPhysLast;
1604 pNew->cb = GCPhysLast - GCPhys + 1;
1605 pNew->pszDesc = pszDesc;
1606 pNew->fFlags = fFlags;
1607 pNew->uNemRange = UINT32_MAX;
1608 pNew->pvR3 = NULL;
1609 pNew->paLSPages = NULL;
1610
1611 uint32_t const cPages = pNew->cb >> GUEST_PAGE_SHIFT;
1612#ifdef VBOX_WITH_PGM_NEM_MODE
1613 if (!pVM->pgm.s.fNemMode)
1614#endif
1615 {
1616 RTGCPHYS iPage = cPages;
1617 while (iPage-- > 0)
1618 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_RAM);
1619
1620 /* Update the page count stats. */
1621 pVM->pgm.s.cZeroPages += cPages;
1622 pVM->pgm.s.cAllPages += cPages;
1623 }
1624#ifdef VBOX_WITH_PGM_NEM_MODE
1625 else
1626 {
1627 int rc = SUPR3PageAlloc(cPages, pVM->pgm.s.fUseLargePages ? SUP_PAGE_ALLOC_F_LARGE_PAGES : 0, &pNew->pvR3);
1628 if (RT_FAILURE(rc))
1629 return rc;
1630
1631 RTGCPHYS iPage = cPages;
1632 while (iPage-- > 0)
1633 PGM_PAGE_INIT(&pNew->aPages[iPage], UINT64_C(0x0000fffffffff000), NIL_GMM_PAGEID,
1634 PGMPAGETYPE_RAM, PGM_PAGE_STATE_ALLOCATED);
1635
1636 /* Update the page count stats. */
1637 pVM->pgm.s.cPrivatePages += cPages;
1638 pVM->pgm.s.cAllPages += cPages;
1639 }
1640#endif
1641
1642 /*
1643 * Link it.
1644 */
1645 pgmR3PhysLinkRamRange(pVM, pNew, pPrev);
1646
1647#ifdef VBOX_WITH_NATIVE_NEM
1648 /*
1649 * Notify NEM now that it has been linked.
1650 */
1651 if (VM_IS_NEM_ENABLED(pVM))
1652 {
1653 uint8_t u2State = UINT8_MAX;
1654 int rc = NEMR3NotifyPhysRamRegister(pVM, GCPhys, pNew->cb, pNew->pvR3, &u2State, &pNew->uNemRange);
1655 if (RT_SUCCESS(rc))
1656 {
1657 if (u2State != UINT8_MAX)
1658 pgmPhysSetNemStateForPages(&pNew->aPages[0], cPages, u2State);
1659 }
1660 else
1661 pgmR3PhysUnlinkRamRange2(pVM, pNew, pPrev);
1662 return rc;
1663 }
1664#endif
1665 return VINF_SUCCESS;
1666}
1667
1668
1669/**
1670 * PGMR3PhysRegisterRam worker that registers a high chunk.
1671 *
1672 * @returns VBox status code.
1673 * @param pVM The cross context VM structure.
1674 * @param GCPhys The address of the RAM.
1675 * @param cRamPages The number of RAM pages to register.
1676 * @param iChunk The chunk number.
1677 * @param pszDesc The RAM range description.
1678 * @param ppPrev Previous RAM range pointer. In/Out.
1679 */
1680static int pgmR3PhysRegisterHighRamChunk(PVM pVM, RTGCPHYS GCPhys, uint32_t cRamPages, uint32_t iChunk,
1681 const char *pszDesc, PPGMRAMRANGE *ppPrev)
1682{
1683 const char *pszDescChunk = iChunk == 0
1684 ? pszDesc
1685 : MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s (#%u)", pszDesc, iChunk + 1);
1686 AssertReturn(pszDescChunk, VERR_NO_MEMORY);
1687
1688 /*
1689 * Allocate memory for the new chunk.
1690 */
1691 size_t const cChunkPages = RT_ALIGN_Z(RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cRamPages]), HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
1692 PSUPPAGE paChunkPages = (PSUPPAGE)RTMemTmpAllocZ(sizeof(SUPPAGE) * cChunkPages);
1693 AssertReturn(paChunkPages, VERR_NO_TMP_MEMORY);
1694 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
1695 void *pvChunk = NULL;
1696 int rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk, &R0PtrChunk, paChunkPages);
1697 if (RT_SUCCESS(rc))
1698 {
1699 Assert(R0PtrChunk != NIL_RTR0PTR || PGM_IS_IN_NEM_MODE(pVM));
1700 memset(pvChunk, 0, cChunkPages << HOST_PAGE_SHIFT);
1701
1702 PPGMRAMRANGE pNew = (PPGMRAMRANGE)pvChunk;
1703
1704 /*
1705 * Ok, init and link the range.
1706 */
1707 rc = pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhys + ((RTGCPHYS)cRamPages << GUEST_PAGE_SHIFT) - 1,
1708 R0PtrChunk, PGM_RAM_RANGE_FLAGS_FLOATING, pszDescChunk, *ppPrev);
1709 if (RT_SUCCESS(rc))
1710 *ppPrev = pNew;
1711
1712 if (RT_FAILURE(rc))
1713 SUPR3PageFreeEx(pvChunk, cChunkPages);
1714 }
1715
1716 RTMemTmpFree(paChunkPages);
1717 return rc;
1718}
1719
1720
1721/**
1722 * Sets up a range RAM.
1723 *
1724 * This will check for conflicting registrations, make a resource
1725 * reservation for the memory (with GMM), and setup the per-page
1726 * tracking structures (PGMPAGE).
1727 *
1728 * @returns VBox status code.
1729 * @param pVM The cross context VM structure.
1730 * @param GCPhys The physical address of the RAM.
1731 * @param cb The size of the RAM.
1732 * @param pszDesc The description - not copied, so, don't free or change it.
1733 */
1734VMMR3DECL(int) PGMR3PhysRegisterRam(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, const char *pszDesc)
1735{
1736 /*
1737 * Validate input.
1738 */
1739 Log(("PGMR3PhysRegisterRam: GCPhys=%RGp cb=%RGp pszDesc=%s\n", GCPhys, cb, pszDesc));
1740 AssertReturn(RT_ALIGN_T(GCPhys, GUEST_PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
1741 AssertReturn(RT_ALIGN_T(cb, GUEST_PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
1742 AssertReturn(cb > 0, VERR_INVALID_PARAMETER);
1743 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
1744 AssertMsgReturn(GCPhysLast > GCPhys, ("The range wraps! GCPhys=%RGp cb=%RGp\n", GCPhys, cb), VERR_INVALID_PARAMETER);
1745 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
1746 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
1747
1748 PGM_LOCK_VOID(pVM);
1749
1750 /*
1751 * Find range location and check for conflicts.
1752 */
1753 PPGMRAMRANGE pPrev = NULL;
1754 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
1755 while (pRam && GCPhysLast >= pRam->GCPhys)
1756 {
1757 AssertLogRelMsgReturnStmt( GCPhysLast < pRam->GCPhys
1758 || GCPhys > pRam->GCPhysLast,
1759 ("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
1760 GCPhys, GCPhysLast, pszDesc, pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
1761 PGM_UNLOCK(pVM), VERR_PGM_RAM_CONFLICT);
1762
1763 /* next */
1764 pPrev = pRam;
1765 pRam = pRam->pNextR3;
1766 }
1767
1768 /*
1769 * Register it with GMM (the API bitches).
1770 */
1771 const RTGCPHYS cPages = cb >> GUEST_PAGE_SHIFT;
1772 int rc = MMR3IncreaseBaseReservation(pVM, cPages);
1773 if (RT_FAILURE(rc))
1774 {
1775 PGM_UNLOCK(pVM);
1776 return rc;
1777 }
1778
1779 if ( GCPhys >= _4G
1780 && cPages > 256)
1781 {
1782 /*
1783 * The PGMRAMRANGE structures for the high memory can get very big.
1784 * There used to be some limitations on SUPR3PageAllocEx allocation
1785 * sizes, so traditionally we limited this to 16MB chunks. These days
1786 * we do ~64 MB chunks each covering 16GB of guest RAM, making sure
1787 * each range is a multiple of 1GB to enable eager hosts to use 1GB
1788 * pages in NEM mode.
1789 *
1790 * See also pgmR3PhysMmio2CalcChunkCount.
1791 */
1792 uint32_t const cPagesPerChunk = _4M;
1793 Assert(RT_ALIGN_32(cPagesPerChunk, X86_PD_PAE_SHIFT - X86_PAGE_SHIFT)); /* NEM large page requirement: 1GB pages. */
1794
1795 RTGCPHYS cPagesLeft = cPages;
1796 RTGCPHYS GCPhysChunk = GCPhys;
1797 uint32_t iChunk = 0;
1798 while (cPagesLeft > 0)
1799 {
1800 uint32_t cPagesInChunk = cPagesLeft;
1801 if (cPagesInChunk > cPagesPerChunk)
1802 cPagesInChunk = cPagesPerChunk;
1803
1804 rc = pgmR3PhysRegisterHighRamChunk(pVM, GCPhysChunk, cPagesInChunk, iChunk, pszDesc, &pPrev);
1805 AssertRCReturn(rc, rc);
1806
1807 /* advance */
1808 GCPhysChunk += (RTGCPHYS)cPagesInChunk << GUEST_PAGE_SHIFT;
1809 cPagesLeft -= cPagesInChunk;
1810 iChunk++;
1811 }
1812 }
1813 else
1814 {
1815 /*
1816 * Allocate, initialize and link the new RAM range.
1817 */
1818 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
1819 PPGMRAMRANGE pNew = NULL;
1820 RTR0PTR pNewR0 = NIL_RTR0PTR;
1821 rc = SUPR3PageAllocEx(RT_ALIGN_Z(cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT, 0 /*fFlags*/,
1822 (void **)&pNew, &pNewR0, NULL /*paPages*/);
1823 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc cbRamRange=%zu\n", rc, cbRamRange), rc);
1824
1825 rc = pgmR3PhysInitAndLinkRamRange(pVM, pNew, GCPhys, GCPhysLast, pNewR0, 0 /*fFlags*/, pszDesc, pPrev);
1826 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc cbRamRange=%zu\n", rc, cbRamRange), rc);
1827 }
1828 pgmPhysInvalidatePageMapTLB(pVM);
1829
1830 PGM_UNLOCK(pVM);
1831 return rc;
1832}
1833
1834
1835/**
1836 * Worker called by PGMR3InitFinalize if we're configured to pre-allocate RAM.
1837 *
1838 * We do this late in the init process so that all the ROM and MMIO ranges have
1839 * been registered already and we don't go wasting memory on them.
1840 *
1841 * @returns VBox status code.
1842 *
1843 * @param pVM The cross context VM structure.
1844 */
1845int pgmR3PhysRamPreAllocate(PVM pVM)
1846{
1847 Assert(pVM->pgm.s.fRamPreAlloc);
1848 Log(("pgmR3PhysRamPreAllocate: enter\n"));
1849#ifdef VBOX_WITH_PGM_NEM_MODE
1850 AssertLogRelReturn(!pVM->pgm.s.fNemMode, VERR_PGM_NOT_SUPPORTED_FOR_NEM_MODE);
1851#endif
1852
1853 /*
1854 * Walk the RAM ranges and allocate all RAM pages, halt at
1855 * the first allocation error.
1856 */
1857 uint64_t cPages = 0;
1858 uint64_t NanoTS = RTTimeNanoTS();
1859 PGM_LOCK_VOID(pVM);
1860 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1861 {
1862 PPGMPAGE pPage = &pRam->aPages[0];
1863 RTGCPHYS GCPhys = pRam->GCPhys;
1864 uint32_t cLeft = pRam->cb >> GUEST_PAGE_SHIFT;
1865 while (cLeft-- > 0)
1866 {
1867 if (PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM)
1868 {
1869 switch (PGM_PAGE_GET_STATE(pPage))
1870 {
1871 case PGM_PAGE_STATE_ZERO:
1872 {
1873 int rc = pgmPhysAllocPage(pVM, pPage, GCPhys);
1874 if (RT_FAILURE(rc))
1875 {
1876 LogRel(("PGM: RAM Pre-allocation failed at %RGp (in %s) with rc=%Rrc\n", GCPhys, pRam->pszDesc, rc));
1877 PGM_UNLOCK(pVM);
1878 return rc;
1879 }
1880 cPages++;
1881 break;
1882 }
1883
1884 case PGM_PAGE_STATE_BALLOONED:
1885 case PGM_PAGE_STATE_ALLOCATED:
1886 case PGM_PAGE_STATE_WRITE_MONITORED:
1887 case PGM_PAGE_STATE_SHARED:
1888 /* nothing to do here. */
1889 break;
1890 }
1891 }
1892
1893 /* next */
1894 pPage++;
1895 GCPhys += GUEST_PAGE_SIZE;
1896 }
1897 }
1898 PGM_UNLOCK(pVM);
1899 NanoTS = RTTimeNanoTS() - NanoTS;
1900
1901 LogRel(("PGM: Pre-allocated %llu pages in %llu ms\n", cPages, NanoTS / 1000000));
1902 Log(("pgmR3PhysRamPreAllocate: returns VINF_SUCCESS\n"));
1903 return VINF_SUCCESS;
1904}
1905
1906
1907/**
1908 * Checks shared page checksums.
1909 *
1910 * @param pVM The cross context VM structure.
1911 */
1912void pgmR3PhysAssertSharedPageChecksums(PVM pVM)
1913{
1914#ifdef VBOX_STRICT
1915 PGM_LOCK_VOID(pVM);
1916
1917 if (pVM->pgm.s.cSharedPages > 0)
1918 {
1919 /*
1920 * Walk the ram ranges.
1921 */
1922 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
1923 {
1924 uint32_t iPage = pRam->cb >> GUEST_PAGE_SHIFT;
1925 AssertMsg(((RTGCPHYS)iPage << GUEST_PAGE_SHIFT) == pRam->cb,
1926 ("%RGp %RGp\n", (RTGCPHYS)iPage << GUEST_PAGE_SHIFT, pRam->cb));
1927
1928 while (iPage-- > 0)
1929 {
1930 PPGMPAGE pPage = &pRam->aPages[iPage];
1931 if (PGM_PAGE_IS_SHARED(pPage))
1932 {
1933 uint32_t u32Checksum = pPage->s.u2Unused0/* | ((uint32_t)pPage->s.u2Unused1 << 8)*/;
1934 if (!u32Checksum)
1935 {
1936 RTGCPHYS GCPhysPage = pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT);
1937 void const *pvPage;
1938 int rc = pgmPhysPageMapReadOnly(pVM, pPage, GCPhysPage, &pvPage);
1939 if (RT_SUCCESS(rc))
1940 {
1941 uint32_t u32Checksum2 = RTCrc32(pvPage, GUEST_PAGE_SIZE);
1942# if 0
1943 AssertMsg((u32Checksum2 & /*UINT32_C(0x00000303)*/ 0x3) == u32Checksum, ("GCPhysPage=%RGp\n", GCPhysPage));
1944# else
1945 if ((u32Checksum2 & /*UINT32_C(0x00000303)*/ 0x3) == u32Checksum)
1946 LogFlow(("shpg %#x @ %RGp %#x [OK]\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
1947 else
1948 AssertMsgFailed(("shpg %#x @ %RGp %#x\n", PGM_PAGE_GET_PAGEID(pPage), GCPhysPage, u32Checksum2));
1949# endif
1950 }
1951 else
1952 AssertRC(rc);
1953 }
1954 }
1955
1956 } /* for each page */
1957
1958 } /* for each ram range */
1959 }
1960
1961 PGM_UNLOCK(pVM);
1962#endif /* VBOX_STRICT */
1963 NOREF(pVM);
1964}
1965
1966
1967/**
1968 * Resets the physical memory state.
1969 *
1970 * ASSUMES that the caller owns the PGM lock.
1971 *
1972 * @returns VBox status code.
1973 * @param pVM The cross context VM structure.
1974 */
1975int pgmR3PhysRamReset(PVM pVM)
1976{
1977 PGM_LOCK_ASSERT_OWNER(pVM);
1978
1979 /* Reset the memory balloon. */
1980 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
1981 AssertRC(rc);
1982
1983#ifdef VBOX_WITH_PAGE_SHARING
1984 /* Clear all registered shared modules. */
1985 pgmR3PhysAssertSharedPageChecksums(pVM);
1986 rc = GMMR3ResetSharedModules(pVM);
1987 AssertRC(rc);
1988#endif
1989 /* Reset counters. */
1990 pVM->pgm.s.cReusedSharedPages = 0;
1991 pVM->pgm.s.cBalloonedPages = 0;
1992
1993 return VINF_SUCCESS;
1994}
1995
1996
1997/**
1998 * Resets (zeros) the RAM after all devices and components have been reset.
1999 *
2000 * ASSUMES that the caller owns the PGM lock.
2001 *
2002 * @returns VBox status code.
2003 * @param pVM The cross context VM structure.
2004 */
2005int pgmR3PhysRamZeroAll(PVM pVM)
2006{
2007 PGM_LOCK_ASSERT_OWNER(pVM);
2008
2009 /*
2010 * We batch up pages that should be freed instead of calling GMM for
2011 * each and every one of them.
2012 */
2013 uint32_t cPendingPages = 0;
2014 PGMMFREEPAGESREQ pReq;
2015 int rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2016 AssertLogRelRCReturn(rc, rc);
2017
2018 /*
2019 * Walk the ram ranges.
2020 */
2021 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2022 {
2023 uint32_t iPage = pRam->cb >> GUEST_PAGE_SHIFT;
2024 AssertMsg(((RTGCPHYS)iPage << GUEST_PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << GUEST_PAGE_SHIFT, pRam->cb));
2025
2026 if ( !pVM->pgm.s.fRamPreAlloc
2027#ifdef VBOX_WITH_PGM_NEM_MODE
2028 && !pVM->pgm.s.fNemMode
2029#endif
2030 && pVM->pgm.s.fZeroRamPagesOnReset)
2031 {
2032 /* Replace all RAM pages by ZERO pages. */
2033 while (iPage-- > 0)
2034 {
2035 PPGMPAGE pPage = &pRam->aPages[iPage];
2036 switch (PGM_PAGE_GET_TYPE(pPage))
2037 {
2038 case PGMPAGETYPE_RAM:
2039 /* Do not replace pages part of a 2 MB continuous range
2040 with zero pages, but zero them instead. */
2041 if ( PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE
2042 || PGM_PAGE_GET_PDE_TYPE(pPage) == PGM_PAGE_PDE_TYPE_PDE_DISABLED)
2043 {
2044 void *pvPage;
2045 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), &pvPage);
2046 AssertLogRelRCReturn(rc, rc);
2047 RT_BZERO(pvPage, GUEST_PAGE_SIZE);
2048 }
2049 else if (PGM_PAGE_IS_BALLOONED(pPage))
2050 {
2051 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
2052 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
2053 }
2054 else if (!PGM_PAGE_IS_ZERO(pPage))
2055 {
2056 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage,
2057 pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), PGMPAGETYPE_RAM);
2058 AssertLogRelRCReturn(rc, rc);
2059 }
2060 break;
2061
2062 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2063 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
2064 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT),
2065 pRam, true /*fDoAccounting*/);
2066 break;
2067
2068 case PGMPAGETYPE_MMIO2:
2069 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
2070 case PGMPAGETYPE_ROM:
2071 case PGMPAGETYPE_MMIO:
2072 break;
2073 default:
2074 AssertFailed();
2075 }
2076 } /* for each page */
2077 }
2078 else
2079 {
2080 /* Zero the memory. */
2081 while (iPage-- > 0)
2082 {
2083 PPGMPAGE pPage = &pRam->aPages[iPage];
2084 switch (PGM_PAGE_GET_TYPE(pPage))
2085 {
2086 case PGMPAGETYPE_RAM:
2087 switch (PGM_PAGE_GET_STATE(pPage))
2088 {
2089 case PGM_PAGE_STATE_ZERO:
2090 break;
2091
2092 case PGM_PAGE_STATE_BALLOONED:
2093 /* Turn into a zero page; the balloon status is lost when the VM reboots. */
2094 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
2095 break;
2096
2097 case PGM_PAGE_STATE_SHARED:
2098 case PGM_PAGE_STATE_WRITE_MONITORED:
2099 rc = pgmPhysPageMakeWritable(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT));
2100 AssertLogRelRCReturn(rc, rc);
2101 RT_FALL_THRU();
2102
2103 case PGM_PAGE_STATE_ALLOCATED:
2104 if (pVM->pgm.s.fZeroRamPagesOnReset)
2105 {
2106 void *pvPage;
2107 rc = pgmPhysPageMap(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), &pvPage);
2108 AssertLogRelRCReturn(rc, rc);
2109 RT_BZERO(pvPage, GUEST_PAGE_SIZE);
2110 }
2111 break;
2112 }
2113 break;
2114
2115 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2116 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO: /** @todo perhaps leave the special page alone? I don't think VT-x copes with this code. */
2117 pgmHandlerPhysicalResetAliasedPage(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT),
2118 pRam, true /*fDoAccounting*/);
2119 break;
2120
2121 case PGMPAGETYPE_MMIO2:
2122 case PGMPAGETYPE_ROM_SHADOW:
2123 case PGMPAGETYPE_ROM:
2124 case PGMPAGETYPE_MMIO:
2125 break;
2126 default:
2127 AssertFailed();
2128
2129 }
2130 } /* for each page */
2131 }
2132
2133 }
2134
2135 /*
2136 * Finish off any pages pending freeing.
2137 */
2138 if (cPendingPages)
2139 {
2140 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2141 AssertLogRelRCReturn(rc, rc);
2142 }
2143 GMMR3FreePagesCleanup(pReq);
2144 return VINF_SUCCESS;
2145}
2146
2147
2148/**
2149 * Frees all RAM during VM termination
2150 *
2151 * ASSUMES that the caller owns the PGM lock.
2152 *
2153 * @returns VBox status code.
2154 * @param pVM The cross context VM structure.
2155 */
2156int pgmR3PhysRamTerm(PVM pVM)
2157{
2158 PGM_LOCK_ASSERT_OWNER(pVM);
2159
2160 /* Reset the memory balloon. */
2161 int rc = GMMR3BalloonedPages(pVM, GMMBALLOONACTION_RESET, 0);
2162 AssertRC(rc);
2163
2164#ifdef VBOX_WITH_PAGE_SHARING
2165 /*
2166 * Clear all registered shared modules.
2167 */
2168 pgmR3PhysAssertSharedPageChecksums(pVM);
2169 rc = GMMR3ResetSharedModules(pVM);
2170 AssertRC(rc);
2171
2172 /*
2173 * Flush the handy pages updates to make sure no shared pages are hiding
2174 * in there. (Not unlikely if the VM shuts down, apparently.)
2175 */
2176# ifdef VBOX_WITH_PGM_NEM_MODE
2177 if (!pVM->pgm.s.fNemMode)
2178# endif
2179 rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_FLUSH_HANDY_PAGES, 0, NULL);
2180#endif
2181
2182 /*
2183 * We batch up pages that should be freed instead of calling GMM for
2184 * each and every one of them.
2185 */
2186 uint32_t cPendingPages = 0;
2187 PGMMFREEPAGESREQ pReq;
2188 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
2189 AssertLogRelRCReturn(rc, rc);
2190
2191 /*
2192 * Walk the ram ranges.
2193 */
2194 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3; pRam; pRam = pRam->pNextR3)
2195 {
2196 uint32_t iPage = pRam->cb >> GUEST_PAGE_SHIFT;
2197 AssertMsg(((RTGCPHYS)iPage << GUEST_PAGE_SHIFT) == pRam->cb, ("%RGp %RGp\n", (RTGCPHYS)iPage << GUEST_PAGE_SHIFT, pRam->cb));
2198
2199 while (iPage-- > 0)
2200 {
2201 PPGMPAGE pPage = &pRam->aPages[iPage];
2202 switch (PGM_PAGE_GET_TYPE(pPage))
2203 {
2204 case PGMPAGETYPE_RAM:
2205 /* Free all shared pages. Private pages are automatically freed during GMM VM cleanup. */
2206 /** @todo change this to explicitly free private pages here. */
2207 if (PGM_PAGE_IS_SHARED(pPage))
2208 {
2209 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage,
2210 pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), PGMPAGETYPE_RAM);
2211 AssertLogRelRCReturn(rc, rc);
2212 }
2213 break;
2214
2215 case PGMPAGETYPE_MMIO2_ALIAS_MMIO:
2216 case PGMPAGETYPE_SPECIAL_ALIAS_MMIO:
2217 case PGMPAGETYPE_MMIO2:
2218 case PGMPAGETYPE_ROM_SHADOW: /* handled by pgmR3PhysRomReset. */
2219 case PGMPAGETYPE_ROM:
2220 case PGMPAGETYPE_MMIO:
2221 break;
2222 default:
2223 AssertFailed();
2224 }
2225 } /* for each page */
2226 }
2227
2228 /*
2229 * Finish off any pages pending freeing.
2230 */
2231 if (cPendingPages)
2232 {
2233 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
2234 AssertLogRelRCReturn(rc, rc);
2235 }
2236 GMMR3FreePagesCleanup(pReq);
2237 return VINF_SUCCESS;
2238}
2239
2240
2241
2242/*********************************************************************************************************************************
2243* MMIO *
2244*********************************************************************************************************************************/
2245
2246/**
2247 * This is the interface IOM is using to register an MMIO region.
2248 *
2249 * It will check for conflicts and ensure that a RAM range structure
2250 * is present before calling the PGMR3HandlerPhysicalRegister API to
2251 * register the callbacks.
2252 *
2253 * @returns VBox status code.
2254 *
2255 * @param pVM The cross context VM structure.
2256 * @param GCPhys The start of the MMIO region.
2257 * @param cb The size of the MMIO region.
2258 * @param hType The physical access handler type registration.
2259 * @param uUser The user argument.
2260 * @param pszDesc The description of the MMIO region.
2261 */
2262VMMR3DECL(int) PGMR3PhysMMIORegister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMPHYSHANDLERTYPE hType,
2263 uint64_t uUser, const char *pszDesc)
2264{
2265 /*
2266 * Assert on some assumption.
2267 */
2268 VM_ASSERT_EMT(pVM);
2269 AssertReturn(!(cb & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2270 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2271 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2272 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
2273#ifdef VBOX_STRICT
2274 PCPGMPHYSHANDLERTYPEINT pType = pgmHandlerPhysicalTypeHandleToPtr(pVM, hType);
2275 Assert(pType);
2276 Assert(pType->enmKind == PGMPHYSHANDLERKIND_MMIO);
2277#endif
2278
2279 int rc = PGM_LOCK(pVM);
2280 AssertRCReturn(rc, rc);
2281
2282 /*
2283 * Make sure there's a RAM range structure for the region.
2284 */
2285 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2286 bool fRamExists = false;
2287 PPGMRAMRANGE pRamPrev = NULL;
2288 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2289 while (pRam && GCPhysLast >= pRam->GCPhys)
2290 {
2291 if ( GCPhysLast >= pRam->GCPhys
2292 && GCPhys <= pRam->GCPhysLast)
2293 {
2294 /* Simplification: all within the same range. */
2295 AssertLogRelMsgReturnStmt( GCPhys >= pRam->GCPhys
2296 && GCPhysLast <= pRam->GCPhysLast,
2297 ("%RGp-%RGp (MMIO/%s) falls partly outside %RGp-%RGp (%s)\n",
2298 GCPhys, GCPhysLast, pszDesc,
2299 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
2300 PGM_UNLOCK(pVM),
2301 VERR_PGM_RAM_CONFLICT);
2302
2303 /* Check that it's all RAM or MMIO pages. */
2304 PCPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
2305 uint32_t cLeft = cb >> GUEST_PAGE_SHIFT;
2306 while (cLeft-- > 0)
2307 {
2308 AssertLogRelMsgReturnStmt( PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM
2309 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO,
2310 ("%RGp-%RGp (MMIO/%s): %RGp is not a RAM or MMIO page - type=%d desc=%s\n",
2311 GCPhys, GCPhysLast, pszDesc, pRam->GCPhys, PGM_PAGE_GET_TYPE(pPage), pRam->pszDesc),
2312 PGM_UNLOCK(pVM),
2313 VERR_PGM_RAM_CONFLICT);
2314 pPage++;
2315 }
2316
2317 /* Looks good. */
2318 fRamExists = true;
2319 break;
2320 }
2321
2322 /* next */
2323 pRamPrev = pRam;
2324 pRam = pRam->pNextR3;
2325 }
2326 PPGMRAMRANGE pNew;
2327 if (fRamExists)
2328 {
2329 pNew = NULL;
2330
2331 /*
2332 * Make all the pages in the range MMIO/ZERO pages, freeing any
2333 * RAM pages currently mapped here. This might not be 100% correct
2334 * for PCI memory, but we're doing the same thing for MMIO2 pages.
2335 */
2336 rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, NULL);
2337 AssertRCReturnStmt(rc, PGM_UNLOCK(pVM), rc);
2338
2339 /* Force a PGM pool flush as guest ram references have been changed. */
2340 /** @todo not entirely SMP safe; assuming for now the guest takes
2341 * care of this internally (not touch mapped mmio while changing the
2342 * mapping). */
2343 PVMCPU pVCpu = VMMGetCpu(pVM);
2344 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2345 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2346 }
2347 else
2348 {
2349 /*
2350 * No RAM range, insert an ad hoc one.
2351 *
2352 * Note that we don't have to tell REM about this range because
2353 * PGMHandlerPhysicalRegisterEx will do that for us.
2354 */
2355 Log(("PGMR3PhysMMIORegister: Adding ad hoc MMIO range for %RGp-%RGp %s\n", GCPhys, GCPhysLast, pszDesc));
2356
2357 /* Alloc. */
2358 const uint32_t cPages = cb >> GUEST_PAGE_SHIFT;
2359 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
2360 const size_t cRangePages = RT_ALIGN_Z(cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
2361 RTR0PTR pNewR0 = NIL_RTR0PTR;
2362 rc = SUPR3PageAllocEx(cRangePages, 0 /*fFlags*/, (void **)&pNew, &pNewR0, NULL /*paPages*/);
2363 AssertLogRelMsgRCReturnStmt(rc, ("cbRamRange=%zu\n", cbRamRange), PGM_UNLOCK(pVM), rc);
2364
2365#ifdef VBOX_WITH_NATIVE_NEM
2366 /* Notify NEM. */
2367 uint8_t u2State = 0; /* (must have valid state as there can't be anything to preserve) */
2368 if (VM_IS_NEM_ENABLED(pVM))
2369 {
2370 rc = NEMR3NotifyPhysMmioExMapEarly(pVM, GCPhys, cPages << GUEST_PAGE_SHIFT, 0 /*fFlags*/, NULL, NULL,
2371 &u2State, &pNew->uNemRange);
2372 AssertLogRelRCReturnStmt(rc, SUPR3PageFreeEx(pNew, cRangePages), rc);
2373 }
2374#endif
2375
2376 /* Initialize the range. */
2377 pNew->pSelfR0 = pNewR0;
2378 pNew->GCPhys = GCPhys;
2379 pNew->GCPhysLast = GCPhysLast;
2380 pNew->cb = cb;
2381 pNew->pszDesc = pszDesc;
2382 pNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO;
2383 pNew->pvR3 = NULL;
2384 pNew->paLSPages = NULL;
2385
2386 uint32_t iPage = cPages;
2387 while (iPage-- > 0)
2388 {
2389 PGM_PAGE_INIT_ZERO(&pNew->aPages[iPage], pVM, PGMPAGETYPE_MMIO);
2390#ifdef VBOX_WITH_NATIVE_NEM
2391 PGM_PAGE_SET_NEM_STATE(&pNew->aPages[iPage], u2State);
2392#endif
2393 }
2394 Assert(PGM_PAGE_GET_TYPE(&pNew->aPages[0]) == PGMPAGETYPE_MMIO);
2395
2396 /* update the page count stats. */
2397 pVM->pgm.s.cPureMmioPages += cPages;
2398 pVM->pgm.s.cAllPages += cPages;
2399
2400 /* link it */
2401 pgmR3PhysLinkRamRange(pVM, pNew, pRamPrev);
2402 }
2403
2404 /*
2405 * Register the access handler.
2406 */
2407 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, hType, uUser, pszDesc);
2408 if (RT_SUCCESS(rc))
2409 {
2410#ifdef VBOX_WITH_NATIVE_NEM
2411 /* Late NEM notification. */
2412 if (VM_IS_NEM_ENABLED(pVM))
2413 {
2414 uint32_t const fNemNotify = (fRamExists ? NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE : 0);
2415 rc = NEMR3NotifyPhysMmioExMapLate(pVM, GCPhys, GCPhysLast - GCPhys + 1, fNemNotify,
2416 fRamExists ? (uint8_t *)pRam->pvR3 + (uintptr_t)(GCPhys - pRam->GCPhys) : NULL,
2417 NULL, !fRamExists ? &pRam->uNemRange : NULL);
2418 AssertLogRelRCReturn(rc, rc);
2419 }
2420#endif
2421 }
2422 /** @todo the phys handler failure handling isn't complete, esp. wrt NEM. */
2423 else if (!fRamExists)
2424 {
2425 pVM->pgm.s.cPureMmioPages -= cb >> GUEST_PAGE_SHIFT;
2426 pVM->pgm.s.cAllPages -= cb >> GUEST_PAGE_SHIFT;
2427
2428 /* remove the ad hoc range. */
2429 pgmR3PhysUnlinkRamRange2(pVM, pNew, pRamPrev);
2430 pNew->cb = pNew->GCPhys = pNew->GCPhysLast = NIL_RTGCPHYS;
2431 SUPR3PageFreeEx(pRam, RT_ALIGN_Z(RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cb >> GUEST_PAGE_SHIFT]),
2432 HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT);
2433 }
2434 pgmPhysInvalidatePageMapTLB(pVM);
2435
2436 PGM_UNLOCK(pVM);
2437 return rc;
2438}
2439
2440
2441/**
2442 * This is the interface IOM is using to register an MMIO region.
2443 *
2444 * It will take care of calling PGMHandlerPhysicalDeregister and clean up
2445 * any ad hoc PGMRAMRANGE left behind.
2446 *
2447 * @returns VBox status code.
2448 * @param pVM The cross context VM structure.
2449 * @param GCPhys The start of the MMIO region.
2450 * @param cb The size of the MMIO region.
2451 */
2452VMMR3DECL(int) PGMR3PhysMMIODeregister(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb)
2453{
2454 VM_ASSERT_EMT(pVM);
2455
2456 int rc = PGM_LOCK(pVM);
2457 AssertRCReturn(rc, rc);
2458
2459 /*
2460 * First deregister the handler, then check if we should remove the ram range.
2461 */
2462 rc = PGMHandlerPhysicalDeregister(pVM, GCPhys);
2463 if (RT_SUCCESS(rc))
2464 {
2465 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
2466 PPGMRAMRANGE pRamPrev = NULL;
2467 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
2468 while (pRam && GCPhysLast >= pRam->GCPhys)
2469 {
2470 /** @todo We're being a bit too careful here. rewrite. */
2471 if ( GCPhysLast == pRam->GCPhysLast
2472 && GCPhys == pRam->GCPhys)
2473 {
2474 Assert(pRam->cb == cb);
2475
2476 /*
2477 * See if all the pages are dead MMIO pages.
2478 */
2479 uint32_t const cGuestPages = cb >> GUEST_PAGE_SHIFT;
2480 bool fAllMMIO = true;
2481 uint32_t iPage = 0;
2482 uint32_t cLeft = cGuestPages;
2483 while (cLeft-- > 0)
2484 {
2485 PPGMPAGE pPage = &pRam->aPages[iPage];
2486 if ( !PGM_PAGE_IS_MMIO_OR_ALIAS(pPage)
2487 /*|| not-out-of-action later */)
2488 {
2489 fAllMMIO = false;
2490 AssertMsgFailed(("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), pPage));
2491 break;
2492 }
2493 Assert( PGM_PAGE_IS_ZERO(pPage)
2494 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2_ALIAS_MMIO
2495 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_SPECIAL_ALIAS_MMIO);
2496 pPage++;
2497 }
2498 if (fAllMMIO)
2499 {
2500 /*
2501 * Ad-hoc range, unlink and free it.
2502 */
2503 Log(("PGMR3PhysMMIODeregister: Freeing ad hoc MMIO range for %RGp-%RGp %s\n",
2504 GCPhys, GCPhysLast, pRam->pszDesc));
2505 /** @todo check the ad-hoc flags? */
2506
2507#ifdef VBOX_WITH_NATIVE_NEM
2508 if (VM_IS_NEM_ENABLED(pVM)) /* Notify REM before we unlink the range. */
2509 {
2510 rc = NEMR3NotifyPhysMmioExUnmap(pVM, GCPhys, GCPhysLast - GCPhys + 1, 0 /*fFlags*/,
2511 NULL, NULL, NULL, &pRam->uNemRange);
2512 AssertLogRelRCReturn(rc, rc);
2513 }
2514#endif
2515
2516 pVM->pgm.s.cAllPages -= cGuestPages;
2517 pVM->pgm.s.cPureMmioPages -= cGuestPages;
2518
2519 pgmR3PhysUnlinkRamRange2(pVM, pRam, pRamPrev);
2520 const uint32_t cPages = pRam->cb >> GUEST_PAGE_SHIFT;
2521 const size_t cbRamRange = RT_UOFFSETOF_DYN(PGMRAMRANGE, aPages[cPages]);
2522 pRam->cb = pRam->GCPhys = pRam->GCPhysLast = NIL_RTGCPHYS;
2523 SUPR3PageFreeEx(pRam, RT_ALIGN_Z(cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT);
2524 break;
2525 }
2526 }
2527
2528 /*
2529 * Range match? It will all be within one range (see PGMAllHandler.cpp).
2530 */
2531 if ( GCPhysLast >= pRam->GCPhys
2532 && GCPhys <= pRam->GCPhysLast)
2533 {
2534 Assert(GCPhys >= pRam->GCPhys);
2535 Assert(GCPhysLast <= pRam->GCPhysLast);
2536
2537 /*
2538 * Turn the pages back into RAM pages.
2539 */
2540 uint32_t iPage = (GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT;
2541 uint32_t cLeft = cb >> GUEST_PAGE_SHIFT;
2542 while (cLeft--)
2543 {
2544 PPGMPAGE pPage = &pRam->aPages[iPage];
2545 AssertMsg( (PGM_PAGE_IS_MMIO(pPage) && PGM_PAGE_IS_ZERO(pPage))
2546 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_MMIO2_ALIAS_MMIO
2547 || PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_SPECIAL_ALIAS_MMIO,
2548 ("%RGp %R[pgmpage]\n", pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), pPage));
2549 if (PGM_PAGE_IS_MMIO_OR_ALIAS(pPage))
2550 PGM_PAGE_SET_TYPE(pVM, pPage, PGMPAGETYPE_RAM);
2551 iPage++;
2552 }
2553
2554#ifdef VBOX_WITH_NATIVE_NEM
2555 /* Notify REM (failure will probably leave things in a non-working state). */
2556 if (VM_IS_NEM_ENABLED(pVM))
2557 {
2558 uint8_t u2State = UINT8_MAX;
2559 rc = NEMR3NotifyPhysMmioExUnmap(pVM, GCPhys, GCPhysLast - GCPhys + 1, NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE,
2560 pRam->pvR3 ? (uint8_t *)pRam->pvR3 + GCPhys - pRam->GCPhys : NULL,
2561 NULL, &u2State, &pRam->uNemRange);
2562 AssertLogRelRCReturn(rc, rc);
2563 if (u2State != UINT8_MAX)
2564 pgmPhysSetNemStateForPages(&pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT],
2565 cb >> GUEST_PAGE_SHIFT, u2State);
2566 }
2567#endif
2568 break;
2569 }
2570
2571 /* next */
2572 pRamPrev = pRam;
2573 pRam = pRam->pNextR3;
2574 }
2575 }
2576
2577 /* Force a PGM pool flush as guest ram references have been changed. */
2578 /** @todo Not entirely SMP safe; assuming for now the guest takes care of
2579 * this internally (not touch mapped mmio while changing the mapping). */
2580 PVMCPU pVCpu = VMMGetCpu(pVM);
2581 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
2582 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
2583
2584 pgmPhysInvalidatePageMapTLB(pVM);
2585 pgmPhysInvalidRamRangeTlbs(pVM);
2586 PGM_UNLOCK(pVM);
2587 return rc;
2588}
2589
2590
2591
2592/*********************************************************************************************************************************
2593* MMIO2 *
2594*********************************************************************************************************************************/
2595
2596/**
2597 * Locate a MMIO2 range.
2598 *
2599 * @returns Pointer to the MMIO2 range.
2600 * @param pVM The cross context VM structure.
2601 * @param pDevIns The device instance owning the region.
2602 * @param iSubDev The sub-device number.
2603 * @param iRegion The region.
2604 * @param hMmio2 Handle to look up. If NIL, use the @a iSubDev and
2605 * @a iRegion.
2606 */
2607DECLINLINE(PPGMREGMMIO2RANGE) pgmR3PhysMmio2Find(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev,
2608 uint32_t iRegion, PGMMMIO2HANDLE hMmio2)
2609{
2610 if (hMmio2 != NIL_PGMMMIO2HANDLE)
2611 {
2612 if (hMmio2 <= RT_ELEMENTS(pVM->pgm.s.apMmio2RangesR3) && hMmio2 != 0)
2613 {
2614 PPGMREGMMIO2RANGE pCur = pVM->pgm.s.apMmio2RangesR3[hMmio2 - 1];
2615 if (pCur && pCur->pDevInsR3 == pDevIns)
2616 {
2617 Assert(pCur->idMmio2 == hMmio2);
2618 AssertReturn(pCur->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK, NULL);
2619 return pCur;
2620 }
2621 Assert(!pCur);
2622 }
2623 for (PPGMREGMMIO2RANGE pCur = pVM->pgm.s.pRegMmioRangesR3; pCur; pCur = pCur->pNextR3)
2624 if (pCur->idMmio2 == hMmio2)
2625 {
2626 AssertBreak(pCur->pDevInsR3 == pDevIns);
2627 AssertReturn(pCur->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK, NULL);
2628 return pCur;
2629 }
2630 }
2631 else
2632 {
2633 /*
2634 * Search the list. There shouldn't be many entries.
2635 */
2636 /** @todo Optimize this lookup! There may now be many entries and it'll
2637 * become really slow when doing MMR3HyperMapMMIO2 and similar. */
2638 for (PPGMREGMMIO2RANGE pCur = pVM->pgm.s.pRegMmioRangesR3; pCur; pCur = pCur->pNextR3)
2639 if ( pCur->pDevInsR3 == pDevIns
2640 && pCur->iRegion == iRegion
2641 && pCur->iSubDev == iSubDev)
2642 return pCur;
2643 }
2644 return NULL;
2645}
2646
2647
2648/**
2649 * Worker for PGMR3PhysMmio2ControlDirtyPageTracking and PGMR3PhysMmio2Map.
2650 */
2651static int pgmR3PhysMmio2EnableDirtyPageTracing(PVM pVM, PPGMREGMMIO2RANGE pFirstMmio2)
2652{
2653 int rc = VINF_SUCCESS;
2654 for (PPGMREGMMIO2RANGE pCurMmio2 = pFirstMmio2; pCurMmio2; pCurMmio2 = pCurMmio2->pNextR3)
2655 {
2656 Assert(!(pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_IS_TRACKING));
2657 int rc2 = pgmHandlerPhysicalExRegister(pVM, pCurMmio2->pPhysHandlerR3, pCurMmio2->RamRange.GCPhys,
2658 pCurMmio2->RamRange.GCPhysLast);
2659 AssertLogRelMsgRC(rc2, ("%#RGp-%#RGp %s failed -> %Rrc\n", pCurMmio2->RamRange.GCPhys, pCurMmio2->RamRange.GCPhysLast,
2660 pCurMmio2->RamRange.pszDesc, rc2));
2661 if (RT_SUCCESS(rc2))
2662 pCurMmio2->fFlags |= PGMREGMMIO2RANGE_F_IS_TRACKING;
2663 else if (RT_SUCCESS(rc))
2664 rc = rc2;
2665 if (pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2666 return rc;
2667 }
2668 AssertFailed();
2669 return rc;
2670}
2671
2672
2673/**
2674 * Worker for PGMR3PhysMmio2ControlDirtyPageTracking and PGMR3PhysMmio2Unmap.
2675 */
2676static int pgmR3PhysMmio2DisableDirtyPageTracing(PVM pVM, PPGMREGMMIO2RANGE pFirstMmio2)
2677{
2678 for (PPGMREGMMIO2RANGE pCurMmio2 = pFirstMmio2; pCurMmio2; pCurMmio2 = pCurMmio2->pNextR3)
2679 {
2680 if (pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_IS_TRACKING)
2681 {
2682 int rc2 = pgmHandlerPhysicalExDeregister(pVM, pCurMmio2->pPhysHandlerR3);
2683 AssertLogRelMsgRC(rc2, ("%#RGp-%#RGp %s failed -> %Rrc\n", pCurMmio2->RamRange.GCPhys, pCurMmio2->RamRange.GCPhysLast,
2684 pCurMmio2->RamRange.pszDesc, rc2));
2685 pCurMmio2->fFlags &= ~PGMREGMMIO2RANGE_F_IS_TRACKING;
2686 }
2687 if (pCurMmio2->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2688 return VINF_SUCCESS;
2689 }
2690 AssertFailed();
2691 return VINF_SUCCESS;
2692
2693}
2694
2695
2696/**
2697 * Calculates the number of chunks
2698 *
2699 * @returns Number of registration chunk needed.
2700 * @param pVM The cross context VM structure.
2701 * @param cb The size of the MMIO/MMIO2 range.
2702 * @param pcPagesPerChunk Where to return the number of pages tracked by each
2703 * chunk. Optional.
2704 * @param pcbChunk Where to return the guest mapping size for a chunk.
2705 */
2706static uint16_t pgmR3PhysMmio2CalcChunkCount(PVM pVM, RTGCPHYS cb, uint32_t *pcPagesPerChunk, uint32_t *pcbChunk)
2707{
2708 RT_NOREF_PV(pVM); /* without raw mode */
2709
2710 /*
2711 * This is the same calculation as PGMR3PhysRegisterRam does, except we'll be
2712 * needing a few bytes extra the PGMREGMMIO2RANGE structure.
2713 *
2714 * Note! In additions, we've got a 24 bit sub-page range for MMIO2 ranges, leaving
2715 * us with an absolute maximum of 16777215 pages per chunk (close to 64 GB).
2716 */
2717 uint32_t const cPagesPerChunk = _4M;
2718 Assert(RT_ALIGN_32(cPagesPerChunk, X86_PD_PAE_SHIFT - X86_PAGE_SHIFT)); /* NEM large page requirement: 1GB pages. */
2719 uint32_t const cbChunk = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE, RamRange.aPages[cPagesPerChunk]);
2720 AssertRelease(cPagesPerChunk < _16M);
2721
2722 if (pcbChunk)
2723 *pcbChunk = cbChunk;
2724 if (pcPagesPerChunk)
2725 *pcPagesPerChunk = cPagesPerChunk;
2726
2727 /* Calc the number of chunks we need. */
2728 RTGCPHYS const cGuestPages = cb >> GUEST_PAGE_SHIFT;
2729 uint16_t cChunks = (uint16_t)((cGuestPages + cPagesPerChunk - 1) / cPagesPerChunk);
2730 AssertRelease((RTGCPHYS)cChunks * cPagesPerChunk >= cGuestPages);
2731 return cChunks;
2732}
2733
2734
2735/**
2736 * Worker for PGMR3PhysMMIO2Register that allocates and the PGMREGMMIO2RANGE
2737 * structures and does basic initialization.
2738 *
2739 * Caller must set type specfic members and initialize the PGMPAGE structures.
2740 *
2741 * This was previously also used by PGMR3PhysMmio2PreRegister, a function for
2742 * pre-registering MMIO that was later (6.1) replaced by a new handle based IOM
2743 * interface. The reference to caller and type above is purely historical.
2744 *
2745 * @returns VBox status code.
2746 * @param pVM The cross context VM structure.
2747 * @param pDevIns The device instance owning the region.
2748 * @param iSubDev The sub-device number (internal PCI config number).
2749 * @param iRegion The region number. If the MMIO2 memory is a PCI
2750 * I/O region this number has to be the number of that
2751 * region. Otherwise it can be any number safe
2752 * UINT8_MAX.
2753 * @param cb The size of the region. Must be page aligned.
2754 * @param fFlags PGMPHYS_MMIO2_FLAGS_XXX.
2755 * @param idMmio2 The MMIO2 ID for the first chunk.
2756 * @param pszDesc The description.
2757 * @param ppHeadRet Where to return the pointer to the first
2758 * registration chunk.
2759 *
2760 * @thread EMT
2761 */
2762static int pgmR3PhysMmio2Create(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cb, uint32_t fFlags,
2763 uint8_t idMmio2, const char *pszDesc, PPGMREGMMIO2RANGE *ppHeadRet)
2764{
2765 /*
2766 * Figure out how many chunks we need and of which size.
2767 */
2768 uint32_t cPagesPerChunk;
2769 uint16_t cChunks = pgmR3PhysMmio2CalcChunkCount(pVM, cb, &cPagesPerChunk, NULL);
2770 AssertReturn(cChunks, VERR_PGM_PHYS_MMIO_EX_IPE);
2771
2772 /*
2773 * Allocate the chunks.
2774 */
2775 PPGMREGMMIO2RANGE *ppNext = ppHeadRet;
2776 *ppNext = NULL;
2777
2778 int rc = VINF_SUCCESS;
2779 uint32_t cPagesLeft = cb >> GUEST_PAGE_SHIFT;
2780 for (uint16_t iChunk = 0; iChunk < cChunks && RT_SUCCESS(rc); iChunk++, idMmio2++)
2781 {
2782 /*
2783 * We currently do a single RAM range for the whole thing. This will
2784 * probably have to change once someone needs really large MMIO regions,
2785 * as we will be running into SUPR3PageAllocEx limitations and such.
2786 */
2787 const uint32_t cPagesTrackedByChunk = RT_MIN(cPagesLeft, cPagesPerChunk);
2788 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE, RamRange.aPages[cPagesTrackedByChunk]);
2789 PPGMREGMMIO2RANGE pNew = NULL;
2790
2791 /*
2792 * Allocate memory for the registration structure.
2793 */
2794 size_t const cChunkPages = RT_ALIGN_Z(cbRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
2795 size_t const cbChunk = (1 + cChunkPages + 1) << HOST_PAGE_SHIFT;
2796 AssertLogRelBreakStmt(cbChunk == (uint32_t)cbChunk, rc = VERR_OUT_OF_RANGE);
2797 RTR0PTR R0PtrChunk = NIL_RTR0PTR;
2798 void *pvChunk = NULL;
2799 rc = SUPR3PageAllocEx(cChunkPages, 0 /*fFlags*/, &pvChunk, &R0PtrChunk, NULL /*paPages*/);
2800 AssertLogRelMsgRCBreak(rc, ("rc=%Rrc, cChunkPages=%#zx\n", rc, cChunkPages));
2801
2802 Assert(R0PtrChunk != NIL_RTR0PTR || PGM_IS_IN_NEM_MODE(pVM));
2803 RT_BZERO(pvChunk, cChunkPages << HOST_PAGE_SHIFT);
2804
2805 pNew = (PPGMREGMMIO2RANGE)pvChunk;
2806 pNew->RamRange.fFlags = PGM_RAM_RANGE_FLAGS_FLOATING;
2807 pNew->RamRange.pSelfR0 = R0PtrChunk + RT_UOFFSETOF(PGMREGMMIO2RANGE, RamRange);
2808
2809 /*
2810 * Initialize the registration structure (caller does specific bits).
2811 */
2812 pNew->pDevInsR3 = pDevIns;
2813 //pNew->pvR3 = NULL;
2814 //pNew->pNext = NULL;
2815 if (iChunk == 0)
2816 pNew->fFlags |= PGMREGMMIO2RANGE_F_FIRST_CHUNK;
2817 if (iChunk + 1 == cChunks)
2818 pNew->fFlags |= PGMREGMMIO2RANGE_F_LAST_CHUNK;
2819 if (fFlags & PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES)
2820 pNew->fFlags |= PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES;
2821 pNew->iSubDev = iSubDev;
2822 pNew->iRegion = iRegion;
2823 pNew->idSavedState = UINT8_MAX;
2824 pNew->idMmio2 = idMmio2;
2825 //pNew->pPhysHandlerR3 = NULL;
2826 //pNew->paLSPages = NULL;
2827 pNew->RamRange.GCPhys = NIL_RTGCPHYS;
2828 pNew->RamRange.GCPhysLast = NIL_RTGCPHYS;
2829 pNew->RamRange.pszDesc = pszDesc;
2830 pNew->RamRange.cb = pNew->cbReal = (RTGCPHYS)cPagesTrackedByChunk << X86_PAGE_SHIFT;
2831 pNew->RamRange.fFlags |= PGM_RAM_RANGE_FLAGS_AD_HOC_MMIO_EX;
2832 pNew->RamRange.uNemRange = UINT32_MAX;
2833 //pNew->RamRange.pvR3 = NULL;
2834 //pNew->RamRange.paLSPages = NULL;
2835
2836 *ppNext = pNew;
2837 ASMCompilerBarrier();
2838 cPagesLeft -= cPagesTrackedByChunk;
2839 ppNext = &pNew->pNextR3;
2840
2841 /*
2842 * Pre-allocate a handler if we're tracking dirty pages, unless NEM takes care of this.
2843 */
2844 if ( (fFlags & PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES)
2845#ifdef VBOX_WITH_PGM_NEM_MODE
2846 && (!VM_IS_NEM_ENABLED(pVM) || !NEMR3IsMmio2DirtyPageTrackingSupported(pVM))
2847#endif
2848 )
2849
2850 {
2851 rc = pgmHandlerPhysicalExCreate(pVM, pVM->pgm.s.hMmio2DirtyPhysHandlerType, idMmio2, pszDesc, &pNew->pPhysHandlerR3);
2852 AssertLogRelMsgRCBreak(rc, ("idMmio2=%zu\n", idMmio2));
2853 }
2854 }
2855 Assert(cPagesLeft == 0);
2856
2857 if (RT_SUCCESS(rc))
2858 {
2859 Assert((*ppHeadRet)->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
2860 return VINF_SUCCESS;
2861 }
2862
2863 /*
2864 * Free floating ranges.
2865 */
2866 while (*ppHeadRet)
2867 {
2868 PPGMREGMMIO2RANGE pFree = *ppHeadRet;
2869 *ppHeadRet = pFree->pNextR3;
2870
2871 if (pFree->pPhysHandlerR3)
2872 {
2873 pgmHandlerPhysicalExDestroy(pVM, pFree->pPhysHandlerR3);
2874 pFree->pPhysHandlerR3 = NULL;
2875 }
2876
2877 if (pFree->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
2878 {
2879 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE,
2880 RamRange.aPages[pFree->RamRange.cb >> X86_PAGE_SHIFT]);
2881 size_t const cChunkPages = RT_ALIGN_Z(cbRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
2882 SUPR3PageFreeEx(pFree, cChunkPages);
2883 }
2884 }
2885
2886 return rc;
2887}
2888
2889
2890/**
2891 * Common worker PGMR3PhysMmio2PreRegister & PGMR3PhysMMIO2Register that links a
2892 * complete registration entry into the lists and lookup tables.
2893 *
2894 * @param pVM The cross context VM structure.
2895 * @param pNew The new MMIO / MMIO2 registration to link.
2896 */
2897static void pgmR3PhysMmio2Link(PVM pVM, PPGMREGMMIO2RANGE pNew)
2898{
2899 Assert(pNew->idMmio2 != UINT8_MAX);
2900
2901 /*
2902 * Link it into the list (order doesn't matter, so insert it at the head).
2903 *
2904 * Note! The range we're linking may consist of multiple chunks, so we
2905 * have to find the last one.
2906 */
2907 PPGMREGMMIO2RANGE pLast = pNew;
2908 for (pLast = pNew; ; pLast = pLast->pNextR3)
2909 {
2910 if (pLast->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2911 break;
2912 Assert(pLast->pNextR3);
2913 Assert(pLast->pNextR3->pDevInsR3 == pNew->pDevInsR3);
2914 Assert(pLast->pNextR3->iSubDev == pNew->iSubDev);
2915 Assert(pLast->pNextR3->iRegion == pNew->iRegion);
2916 Assert(pLast->pNextR3->idMmio2 == pLast->idMmio2 + 1);
2917 }
2918
2919 PGM_LOCK_VOID(pVM);
2920
2921 /* Link in the chain of ranges at the head of the list. */
2922 pLast->pNextR3 = pVM->pgm.s.pRegMmioRangesR3;
2923 pVM->pgm.s.pRegMmioRangesR3 = pNew;
2924
2925 /* Insert the MMIO2 range/page IDs. */
2926 uint8_t idMmio2 = pNew->idMmio2;
2927 for (;;)
2928 {
2929 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == NULL);
2930 Assert(pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] == NIL_RTR0PTR);
2931 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = pNew;
2932 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = pNew->RamRange.pSelfR0 - RT_UOFFSETOF(PGMREGMMIO2RANGE, RamRange);
2933 if (pNew->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
2934 break;
2935 pNew = pNew->pNextR3;
2936 idMmio2++;
2937 }
2938
2939 pgmPhysInvalidatePageMapTLB(pVM);
2940 PGM_UNLOCK(pVM);
2941}
2942
2943
2944/**
2945 * Allocate and register an MMIO2 region.
2946 *
2947 * As mentioned elsewhere, MMIO2 is just RAM spelled differently. It's RAM
2948 * associated with a device. It is also non-shared memory with a permanent
2949 * ring-3 mapping and page backing (presently).
2950 *
2951 * A MMIO2 range may overlap with base memory if a lot of RAM is configured for
2952 * the VM, in which case we'll drop the base memory pages. Presently we will
2953 * make no attempt to preserve anything that happens to be present in the base
2954 * memory that is replaced, this is of course incorrect but it's too much
2955 * effort.
2956 *
2957 * @returns VBox status code.
2958 * @retval VINF_SUCCESS on success, *ppv pointing to the R3 mapping of the
2959 * memory.
2960 * @retval VERR_ALREADY_EXISTS if the region already exists.
2961 *
2962 * @param pVM The cross context VM structure.
2963 * @param pDevIns The device instance owning the region.
2964 * @param iSubDev The sub-device number.
2965 * @param iRegion The region number. If the MMIO2 memory is a PCI
2966 * I/O region this number has to be the number of that
2967 * region. Otherwise it can be any number save
2968 * UINT8_MAX.
2969 * @param cb The size of the region. Must be page aligned.
2970 * @param fFlags Reserved for future use, must be zero.
2971 * @param pszDesc The description.
2972 * @param ppv Where to store the pointer to the ring-3 mapping of
2973 * the memory.
2974 * @param phRegion Where to return the MMIO2 region handle. Optional.
2975 * @thread EMT
2976 */
2977VMMR3_INT_DECL(int) PGMR3PhysMmio2Register(PVM pVM, PPDMDEVINS pDevIns, uint32_t iSubDev, uint32_t iRegion, RTGCPHYS cb,
2978 uint32_t fFlags, const char *pszDesc, void **ppv, PGMMMIO2HANDLE *phRegion)
2979{
2980 /*
2981 * Validate input.
2982 */
2983 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
2984 *ppv = NULL;
2985 if (phRegion)
2986 {
2987 AssertPtrReturn(phRegion, VERR_INVALID_POINTER);
2988 *phRegion = NIL_PGMMMIO2HANDLE;
2989 }
2990 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
2991 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
2992 AssertReturn(iSubDev <= UINT8_MAX, VERR_INVALID_PARAMETER);
2993 AssertReturn(iRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
2994 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
2995 AssertReturn(*pszDesc, VERR_INVALID_PARAMETER);
2996 AssertReturn(pgmR3PhysMmio2Find(pVM, pDevIns, iSubDev, iRegion, NIL_PGMMMIO2HANDLE) == NULL, VERR_ALREADY_EXISTS);
2997 AssertReturn(!(cb & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2998 AssertReturn(cb, VERR_INVALID_PARAMETER);
2999 AssertReturn(!(fFlags & ~PGMPHYS_MMIO2_FLAGS_VALID_MASK), VERR_INVALID_FLAGS);
3000
3001 const uint32_t cGuestPages = cb >> GUEST_PAGE_SHIFT;
3002 AssertLogRelReturn(((RTGCPHYS)cGuestPages << GUEST_PAGE_SHIFT) == cb, VERR_INVALID_PARAMETER);
3003 AssertLogRelReturn(cGuestPages <= (MM_MMIO_64_MAX >> X86_PAGE_SHIFT), VERR_OUT_OF_RANGE);
3004 AssertLogRelReturn(cGuestPages <= PGM_MMIO2_MAX_PAGE_COUNT, VERR_OUT_OF_RANGE);
3005
3006 /*
3007 * For the 2nd+ instance, mangle the description string so it's unique.
3008 */
3009 if (pDevIns->iInstance > 0) /** @todo Move to PDMDevHlp.cpp and use a real string cache. */
3010 {
3011 pszDesc = MMR3HeapAPrintf(pVM, MM_TAG_PGM_PHYS, "%s [%u]", pszDesc, pDevIns->iInstance);
3012 if (!pszDesc)
3013 return VERR_NO_MEMORY;
3014 }
3015
3016 /*
3017 * Allocate an MMIO2 range ID (not freed on failure).
3018 *
3019 * The zero ID is not used as it could be confused with NIL_GMM_PAGEID, so
3020 * the IDs goes from 1 thru PGM_MMIO2_MAX_RANGES.
3021 */
3022 unsigned cChunks = pgmR3PhysMmio2CalcChunkCount(pVM, cb, NULL, NULL);
3023
3024 PGM_LOCK_VOID(pVM);
3025 AssertCompile(PGM_MMIO2_MAX_RANGES < 255);
3026 uint8_t const idMmio2 = pVM->pgm.s.cMmio2Regions + 1;
3027 unsigned const cNewMmio2Regions = pVM->pgm.s.cMmio2Regions + cChunks;
3028 if (cNewMmio2Regions > PGM_MMIO2_MAX_RANGES)
3029 {
3030 PGM_UNLOCK(pVM);
3031 AssertLogRelFailedReturn(VERR_PGM_TOO_MANY_MMIO2_RANGES);
3032 }
3033 pVM->pgm.s.cMmio2Regions = cNewMmio2Regions;
3034 PGM_UNLOCK(pVM);
3035
3036 /*
3037 * Try reserve and allocate the backing memory first as this is what is
3038 * most likely to fail.
3039 */
3040 int rc = MMR3AdjustFixedReservation(pVM, cGuestPages, pszDesc);
3041 if (RT_SUCCESS(rc))
3042 {
3043 const uint32_t cHostPages = RT_ALIGN_T(cb, HOST_PAGE_SIZE, RTGCPHYS) >> HOST_PAGE_SHIFT;
3044 PSUPPAGE paPages = (PSUPPAGE)RTMemTmpAlloc(cHostPages * sizeof(SUPPAGE));
3045 if (RT_SUCCESS(rc))
3046 {
3047 void *pvPages = NULL;
3048#ifndef VBOX_WITH_LINEAR_HOST_PHYS_MEM
3049 RTR0PTR pvPagesR0 = NIL_RTR0PTR;
3050#endif
3051#ifdef VBOX_WITH_PGM_NEM_MODE
3052 if (PGM_IS_IN_NEM_MODE(pVM))
3053 {
3054 for (uint32_t i = 0; i < cHostPages; i++)
3055 {
3056 paPages[i].Phys = UINT64_C(0x0000fffffffff000);
3057 paPages[i].uReserved = 0;
3058 }
3059 rc = SUPR3PageAlloc(cHostPages, pVM->pgm.s.fUseLargePages ? SUP_PAGE_ALLOC_F_LARGE_PAGES : 0, &pvPages);
3060 }
3061 else
3062#endif
3063 {
3064#ifndef VBOX_WITH_LINEAR_HOST_PHYS_MEM
3065 rc = SUPR3PageAllocEx(cHostPages, 0 /*fFlags*/, &pvPages, &pvPagesR0, paPages);
3066#else
3067 rc = SUPR3PageAllocEx(cHostPages, 0 /*fFlags*/, &pvPages, NULL /*pR0Ptr*/, paPages);
3068#endif
3069 }
3070 if (RT_SUCCESS(rc))
3071 {
3072 memset(pvPages, 0, cGuestPages * GUEST_PAGE_SIZE);
3073
3074 /*
3075 * Create the registered MMIO range record for it.
3076 */
3077 PPGMREGMMIO2RANGE pNew;
3078 rc = pgmR3PhysMmio2Create(pVM, pDevIns, iSubDev, iRegion, cb, fFlags, idMmio2, pszDesc, &pNew);
3079 if (RT_SUCCESS(rc))
3080 {
3081 if (phRegion)
3082 *phRegion = idMmio2; /* The ID of the first chunk. */
3083
3084 uint32_t iSrcPage = 0;
3085 uint8_t *pbCurPages = (uint8_t *)pvPages;
3086 for (PPGMREGMMIO2RANGE pCur = pNew; pCur; pCur = pCur->pNextR3)
3087 {
3088 pCur->pvR3 = pbCurPages;
3089#ifndef VBOX_WITH_LINEAR_HOST_PHYS_MEM
3090 pCur->pvR0 = pvPagesR0 + (iSrcPage << GUEST_PAGE_SHIFT);
3091#endif
3092 pCur->RamRange.pvR3 = pbCurPages;
3093
3094 uint32_t iDstPage = pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3095 while (iDstPage-- > 0)
3096 {
3097 PGM_PAGE_INIT(&pNew->RamRange.aPages[iDstPage],
3098 paPages[iDstPage + iSrcPage].Phys,
3099 PGM_MMIO2_PAGEID_MAKE(idMmio2, iDstPage),
3100 PGMPAGETYPE_MMIO2, PGM_PAGE_STATE_ALLOCATED);
3101 }
3102
3103 /* advance. */
3104 iSrcPage += pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3105 pbCurPages += pCur->RamRange.cb;
3106 }
3107
3108 RTMemTmpFree(paPages);
3109
3110 /*
3111 * Update the page count stats, link the registration and we're done.
3112 */
3113 pVM->pgm.s.cAllPages += cGuestPages;
3114 pVM->pgm.s.cPrivatePages += cGuestPages;
3115
3116 pgmR3PhysMmio2Link(pVM, pNew);
3117
3118 *ppv = pvPages;
3119 return VINF_SUCCESS;
3120 }
3121
3122 SUPR3PageFreeEx(pvPages, cHostPages);
3123 }
3124 }
3125 RTMemTmpFree(paPages);
3126 MMR3AdjustFixedReservation(pVM, -(int32_t)cGuestPages, pszDesc);
3127 }
3128 if (pDevIns->iInstance > 0)
3129 MMR3HeapFree((void *)pszDesc);
3130 return rc;
3131}
3132
3133
3134/**
3135 * Deregisters and frees an MMIO2 region.
3136 *
3137 * Any physical access handlers registered for the region must be deregistered
3138 * before calling this function.
3139 *
3140 * @returns VBox status code.
3141 * @param pVM The cross context VM structure.
3142 * @param pDevIns The device instance owning the region.
3143 * @param hMmio2 The MMIO2 handle to deregister, or NIL if all
3144 * regions for the given device is to be deregistered.
3145 */
3146VMMR3_INT_DECL(int) PGMR3PhysMmio2Deregister(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2)
3147{
3148 /*
3149 * Validate input.
3150 */
3151 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3152 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3153
3154 /*
3155 * The loop here scanning all registrations will make sure that multi-chunk ranges
3156 * get properly deregistered, though it's original purpose was the wildcard iRegion.
3157 */
3158 PGM_LOCK_VOID(pVM);
3159 int rc = VINF_SUCCESS;
3160 unsigned cFound = 0;
3161 PPGMREGMMIO2RANGE pPrev = NULL;
3162 PPGMREGMMIO2RANGE pCur = pVM->pgm.s.pRegMmioRangesR3;
3163 while (pCur)
3164 {
3165 uint32_t const fFlags = pCur->fFlags;
3166 if ( pCur->pDevInsR3 == pDevIns
3167 && ( hMmio2 == NIL_PGMMMIO2HANDLE
3168 || pCur->idMmio2 == hMmio2))
3169 {
3170 cFound++;
3171
3172 /*
3173 * Unmap it if it's mapped.
3174 */
3175 if (fFlags & PGMREGMMIO2RANGE_F_MAPPED)
3176 {
3177 int rc2 = PGMR3PhysMmio2Unmap(pVM, pCur->pDevInsR3, pCur->idMmio2, pCur->RamRange.GCPhys);
3178 AssertRC(rc2);
3179 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3180 rc = rc2;
3181 }
3182
3183 /*
3184 * Unlink it
3185 */
3186 PPGMREGMMIO2RANGE pNext = pCur->pNextR3;
3187 if (pPrev)
3188 pPrev->pNextR3 = pNext;
3189 else
3190 pVM->pgm.s.pRegMmioRangesR3 = pNext;
3191 pCur->pNextR3 = NULL;
3192
3193 uint8_t idMmio2 = pCur->idMmio2;
3194 Assert(idMmio2 <= RT_ELEMENTS(pVM->pgm.s.apMmio2RangesR3));
3195 if (idMmio2 <= RT_ELEMENTS(pVM->pgm.s.apMmio2RangesR3))
3196 {
3197 Assert(pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] == pCur);
3198 pVM->pgm.s.apMmio2RangesR3[idMmio2 - 1] = NULL;
3199 pVM->pgm.s.apMmio2RangesR0[idMmio2 - 1] = NIL_RTR0PTR;
3200 }
3201
3202 /*
3203 * Free the memory.
3204 */
3205 uint32_t const cGuestPages = pCur->cbReal >> GUEST_PAGE_SHIFT;
3206 uint32_t const cHostPages = RT_ALIGN_T(pCur->cbReal, HOST_PAGE_SIZE, RTGCPHYS) >> HOST_PAGE_SHIFT;
3207#ifdef VBOX_WITH_PGM_NEM_MODE
3208 if (!pVM->pgm.s.fNemMode)
3209#endif
3210 {
3211 int rc2 = SUPR3PageFreeEx(pCur->pvR3, cHostPages);
3212 AssertRC(rc2);
3213 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3214 rc = rc2;
3215
3216 rc2 = MMR3AdjustFixedReservation(pVM, -(int32_t)cGuestPages, pCur->RamRange.pszDesc);
3217 AssertRC(rc2);
3218 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3219 rc = rc2;
3220 }
3221#ifdef VBOX_WITH_PGM_NEM_MODE
3222 else
3223 {
3224 int rc2 = SUPR3PageFreeEx(pCur->pvR3, cHostPages);
3225 AssertRC(rc2);
3226 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3227 rc = rc2;
3228 }
3229#endif
3230
3231 if (pCur->pPhysHandlerR3)
3232 {
3233 pgmHandlerPhysicalExDestroy(pVM, pCur->pPhysHandlerR3);
3234 pCur->pPhysHandlerR3 = NULL;
3235 }
3236
3237 /* we're leaking hyper memory here if done at runtime. */
3238#ifdef VBOX_STRICT
3239 VMSTATE const enmState = VMR3GetState(pVM);
3240 AssertMsg( enmState == VMSTATE_POWERING_OFF
3241 || enmState == VMSTATE_POWERING_OFF_LS
3242 || enmState == VMSTATE_OFF
3243 || enmState == VMSTATE_OFF_LS
3244 || enmState == VMSTATE_DESTROYING
3245 || enmState == VMSTATE_TERMINATED
3246 || enmState == VMSTATE_CREATING
3247 , ("%s\n", VMR3GetStateName(enmState)));
3248#endif
3249
3250 if (pCur->RamRange.fFlags & PGM_RAM_RANGE_FLAGS_FLOATING)
3251 {
3252 const size_t cbRange = RT_UOFFSETOF_DYN(PGMREGMMIO2RANGE, RamRange.aPages[cGuestPages]);
3253 size_t const cChunkPages = RT_ALIGN_Z(cbRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
3254 SUPR3PageFreeEx(pCur, cChunkPages);
3255 }
3256 /*else
3257 {
3258 rc = MMHyperFree(pVM, pCur); - does not work, see the alloc call.
3259 AssertRCReturn(rc, rc);
3260 } */
3261
3262
3263 /* update page count stats */
3264 pVM->pgm.s.cAllPages -= cGuestPages;
3265 pVM->pgm.s.cPrivatePages -= cGuestPages;
3266
3267 /* next */
3268 pCur = pNext;
3269 if (hMmio2 != NIL_PGMMMIO2HANDLE)
3270 {
3271 if (fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3272 break;
3273 hMmio2++;
3274 Assert(pCur->idMmio2 == hMmio2);
3275 Assert(pCur->pDevInsR3 == pDevIns);
3276 Assert(!(pCur->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK));
3277 }
3278 }
3279 else
3280 {
3281 pPrev = pCur;
3282 pCur = pCur->pNextR3;
3283 }
3284 }
3285 pgmPhysInvalidatePageMapTLB(pVM);
3286 PGM_UNLOCK(pVM);
3287 return !cFound && hMmio2 != NIL_PGMMMIO2HANDLE ? VERR_NOT_FOUND : rc;
3288}
3289
3290
3291/**
3292 * Maps a MMIO2 region.
3293 *
3294 * This is typically done when a guest / the bios / state loading changes the
3295 * PCI config. The replacing of base memory has the same restrictions as during
3296 * registration, of course.
3297 *
3298 * @returns VBox status code.
3299 *
3300 * @param pVM The cross context VM structure.
3301 * @param pDevIns The device instance owning the region.
3302 * @param hMmio2 The handle of the region to map.
3303 * @param GCPhys The guest-physical address to be remapped.
3304 */
3305VMMR3_INT_DECL(int) PGMR3PhysMmio2Map(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, RTGCPHYS GCPhys)
3306{
3307 /*
3308 * Validate input.
3309 *
3310 * Note! It's safe to walk the MMIO/MMIO2 list since registrations only
3311 * happens during VM construction.
3312 */
3313 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3314 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3315 AssertReturn(GCPhys != NIL_RTGCPHYS, VERR_INVALID_PARAMETER);
3316 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
3317 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3318 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
3319
3320 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3321 AssertReturn(pFirstMmio, VERR_NOT_FOUND);
3322 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
3323
3324 PPGMREGMMIO2RANGE pLastMmio = pFirstMmio;
3325 RTGCPHYS cbRange = 0;
3326 for (;;)
3327 {
3328 AssertReturn(!(pLastMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED), VERR_WRONG_ORDER);
3329 Assert(pLastMmio->RamRange.GCPhys == NIL_RTGCPHYS);
3330 Assert(pLastMmio->RamRange.GCPhysLast == NIL_RTGCPHYS);
3331 Assert(pLastMmio->pDevInsR3 == pFirstMmio->pDevInsR3);
3332 Assert(pLastMmio->iSubDev == pFirstMmio->iSubDev);
3333 Assert(pLastMmio->iRegion == pFirstMmio->iRegion);
3334 cbRange += pLastMmio->RamRange.cb;
3335 if (pLastMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3336 break;
3337 pLastMmio = pLastMmio->pNextR3;
3338 }
3339
3340 RTGCPHYS GCPhysLast = GCPhys + cbRange - 1;
3341 AssertLogRelReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
3342
3343 /*
3344 * Find our location in the ram range list, checking for restriction
3345 * we don't bother implementing yet (partially overlapping, multiple
3346 * ram ranges).
3347 */
3348 PGM_LOCK_VOID(pVM);
3349
3350 AssertReturnStmt(!(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED), PGM_UNLOCK(pVM), VERR_WRONG_ORDER);
3351
3352 bool fRamExists = false;
3353 PPGMRAMRANGE pRamPrev = NULL;
3354 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3355 while (pRam && GCPhysLast >= pRam->GCPhys)
3356 {
3357 if ( GCPhys <= pRam->GCPhysLast
3358 && GCPhysLast >= pRam->GCPhys)
3359 {
3360 /* Completely within? */
3361 AssertLogRelMsgReturnStmt( GCPhys >= pRam->GCPhys
3362 && GCPhysLast <= pRam->GCPhysLast,
3363 ("%RGp-%RGp (MMIOEx/%s) falls partly outside %RGp-%RGp (%s)\n",
3364 GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc,
3365 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
3366 PGM_UNLOCK(pVM),
3367 VERR_PGM_RAM_CONFLICT);
3368
3369 /* Check that all the pages are RAM pages. */
3370 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
3371 uint32_t cPagesLeft = cbRange >> GUEST_PAGE_SHIFT;
3372 while (cPagesLeft-- > 0)
3373 {
3374 AssertLogRelMsgReturnStmt(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
3375 ("%RGp isn't a RAM page (%d) - mapping %RGp-%RGp (MMIO2/%s).\n",
3376 GCPhys, PGM_PAGE_GET_TYPE(pPage), GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc),
3377 PGM_UNLOCK(pVM),
3378 VERR_PGM_RAM_CONFLICT);
3379 pPage++;
3380 }
3381
3382 /* There can only be one MMIO/MMIO2 chunk matching here! */
3383 AssertLogRelMsgReturnStmt(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK,
3384 ("%RGp-%RGp (MMIOEx/%s, flags %#X) consists of multiple chunks whereas the RAM somehow doesn't!\n",
3385 GCPhys, GCPhysLast, pFirstMmio->RamRange.pszDesc, pFirstMmio->fFlags),
3386 PGM_UNLOCK(pVM),
3387 VERR_PGM_PHYS_MMIO_EX_IPE);
3388
3389 fRamExists = true;
3390 break;
3391 }
3392
3393 /* next */
3394 pRamPrev = pRam;
3395 pRam = pRam->pNextR3;
3396 }
3397 Log(("PGMR3PhysMmio2Map: %RGp-%RGp fRamExists=%RTbool %s\n", GCPhys, GCPhysLast, fRamExists, pFirstMmio->RamRange.pszDesc));
3398
3399
3400 /*
3401 * Make the changes.
3402 */
3403 RTGCPHYS GCPhysCur = GCPhys;
3404 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3405 {
3406 pCurMmio->RamRange.GCPhys = GCPhysCur;
3407 pCurMmio->RamRange.GCPhysLast = GCPhysCur + pCurMmio->RamRange.cb - 1;
3408 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3409 {
3410 Assert(pCurMmio->RamRange.GCPhysLast == GCPhysLast);
3411 break;
3412 }
3413 GCPhysCur += pCurMmio->RamRange.cb;
3414 }
3415
3416 if (fRamExists)
3417 {
3418 /*
3419 * Make all the pages in the range MMIO/ZERO pages, freeing any
3420 * RAM pages currently mapped here. This might not be 100% correct
3421 * for PCI memory, but we're doing the same thing for MMIO2 pages.
3422 *
3423 * We replace these MMIO/ZERO pages with real pages in the MMIO2 case.
3424 */
3425 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK); /* Only one chunk */
3426 Assert(pFirstMmio->pvR3 == pFirstMmio->RamRange.pvR3);
3427 Assert(pFirstMmio->RamRange.pvR3 != NULL);
3428
3429#ifdef VBOX_WITH_PGM_NEM_MODE
3430 /* We cannot mix MMIO2 into a RAM range in simplified memory mode because pRam->pvR3 can't point
3431 both at the RAM and MMIO2, so we won't ever write & read from the actual MMIO2 memory if we try. */
3432 AssertLogRelMsgReturn(!pVM->pgm.s.fNemMode, ("%s at %RGp-%RGp\n", pFirstMmio->RamRange.pszDesc, GCPhys, GCPhysLast),
3433 VERR_PGM_NOT_SUPPORTED_FOR_NEM_MODE);
3434#endif
3435
3436 int rc = pgmR3PhysFreePageRange(pVM, pRam, GCPhys, GCPhysLast, pFirstMmio->RamRange.pvR3);
3437 AssertRCReturnStmt(rc, PGM_UNLOCK(pVM), rc);
3438
3439 /* Replace the pages, freeing all present RAM pages. */
3440 PPGMPAGE pPageSrc = &pFirstMmio->RamRange.aPages[0];
3441 PPGMPAGE pPageDst = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
3442 uint32_t cPagesLeft = pFirstMmio->RamRange.cb >> GUEST_PAGE_SHIFT;
3443 while (cPagesLeft-- > 0)
3444 {
3445 Assert(PGM_PAGE_IS_MMIO(pPageDst));
3446
3447 RTHCPHYS const HCPhys = PGM_PAGE_GET_HCPHYS(pPageSrc);
3448 uint32_t const idPage = PGM_PAGE_GET_PAGEID(pPageSrc);
3449 PGM_PAGE_SET_PAGEID(pVM, pPageDst, idPage);
3450 PGM_PAGE_SET_HCPHYS(pVM, pPageDst, HCPhys);
3451 PGM_PAGE_SET_TYPE(pVM, pPageDst, PGMPAGETYPE_MMIO2);
3452 PGM_PAGE_SET_STATE(pVM, pPageDst, PGM_PAGE_STATE_ALLOCATED);
3453 PGM_PAGE_SET_PDE_TYPE(pVM, pPageDst, PGM_PAGE_PDE_TYPE_DONTCARE);
3454 PGM_PAGE_SET_PTE_INDEX(pVM, pPageDst, 0);
3455 PGM_PAGE_SET_TRACKING(pVM, pPageDst, 0);
3456 /* NEM state is set by pgmR3PhysFreePageRange. */
3457
3458 pVM->pgm.s.cZeroPages--;
3459 GCPhys += GUEST_PAGE_SIZE;
3460 pPageSrc++;
3461 pPageDst++;
3462 }
3463
3464 /* Flush physical page map TLB. */
3465 pgmPhysInvalidatePageMapTLB(pVM);
3466
3467 /* Force a PGM pool flush as guest ram references have been changed. */
3468 /** @todo not entirely SMP safe; assuming for now the guest takes care of
3469 * this internally (not touch mapped mmio while changing the mapping). */
3470 PVMCPU pVCpu = VMMGetCpu(pVM);
3471 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
3472 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3473 }
3474 else
3475 {
3476 /*
3477 * No RAM range, insert the ones prepared during registration.
3478 */
3479 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3480 {
3481#ifdef VBOX_WITH_NATIVE_NEM
3482 /* Tell NEM and get the new NEM state for the pages. */
3483 uint8_t u2NemState = 0;
3484 if (VM_IS_NEM_ENABLED(pVM))
3485 {
3486 int rc = NEMR3NotifyPhysMmioExMapEarly(pVM, pCurMmio->RamRange.GCPhys,
3487 pCurMmio->RamRange.GCPhysLast - pCurMmio->RamRange.GCPhys + 1,
3488 NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2
3489 | (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES
3490 ? NEM_NOTIFY_PHYS_MMIO_EX_F_TRACK_DIRTY_PAGES : 0),
3491 NULL /*pvRam*/, pCurMmio->RamRange.pvR3,
3492 &u2NemState, &pCurMmio->RamRange.uNemRange);
3493 AssertLogRelRCReturnStmt(rc, PGM_UNLOCK(pVM), rc);
3494 }
3495#endif
3496
3497 /* Clear the tracking data of pages we're going to reactivate. */
3498 PPGMPAGE pPageSrc = &pCurMmio->RamRange.aPages[0];
3499 uint32_t cPagesLeft = pCurMmio->RamRange.cb >> GUEST_PAGE_SHIFT;
3500 while (cPagesLeft-- > 0)
3501 {
3502 PGM_PAGE_SET_TRACKING(pVM, pPageSrc, 0);
3503 PGM_PAGE_SET_PTE_INDEX(pVM, pPageSrc, 0);
3504#ifdef VBOX_WITH_NATIVE_NEM
3505 PGM_PAGE_SET_NEM_STATE(pPageSrc, u2NemState);
3506#endif
3507 pPageSrc++;
3508 }
3509
3510 /* link in the ram range */
3511 pgmR3PhysLinkRamRange(pVM, &pCurMmio->RamRange, pRamPrev);
3512
3513 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3514 {
3515 Assert(pCurMmio->RamRange.GCPhysLast == GCPhysLast);
3516 break;
3517 }
3518 pRamPrev = &pCurMmio->RamRange;
3519 }
3520 }
3521
3522 /*
3523 * If the range have dirty page monitoring enabled, enable that.
3524 *
3525 * We ignore failures here for now because if we fail, the whole mapping
3526 * will have to be reversed and we'll end up with nothing at all on the
3527 * screen and a grumpy guest, whereas if we just go on, we'll only have
3528 * visual distortions to gripe about. There will be something in the
3529 * release log.
3530 */
3531 if ( pFirstMmio->pPhysHandlerR3
3532 && (pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3533 pgmR3PhysMmio2EnableDirtyPageTracing(pVM, pFirstMmio);
3534
3535 /*
3536 * We're good, set the flags and invalid the mapping TLB.
3537 */
3538 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3539 {
3540 pCurMmio->fFlags |= PGMREGMMIO2RANGE_F_MAPPED;
3541 if (fRamExists)
3542 pCurMmio->fFlags |= PGMREGMMIO2RANGE_F_OVERLAPPING;
3543 else
3544 pCurMmio->fFlags &= ~PGMREGMMIO2RANGE_F_OVERLAPPING;
3545 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3546 break;
3547 }
3548 pgmPhysInvalidatePageMapTLB(pVM);
3549
3550#ifdef VBOX_WITH_NATIVE_NEM
3551 /*
3552 * Late NEM notification.
3553 */
3554 if (VM_IS_NEM_ENABLED(pVM))
3555 {
3556 int rc;
3557 uint32_t fNemFlags = NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2;
3558 if (pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES)
3559 fNemFlags |= NEM_NOTIFY_PHYS_MMIO_EX_F_TRACK_DIRTY_PAGES;
3560 if (fRamExists)
3561 rc = NEMR3NotifyPhysMmioExMapLate(pVM, GCPhys, GCPhysLast - GCPhys + 1, fNemFlags | NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE,
3562 pRam->pvR3 ? (uint8_t *)pRam->pvR3 + GCPhys - pRam->GCPhys : NULL, pFirstMmio->pvR3,
3563 NULL /*puNemRange*/);
3564 else
3565 {
3566 rc = VINF_SUCCESS;
3567 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3568 {
3569 rc = NEMR3NotifyPhysMmioExMapLate(pVM, pCurMmio->RamRange.GCPhys, pCurMmio->RamRange.cb, fNemFlags,
3570 NULL, pCurMmio->RamRange.pvR3, &pCurMmio->RamRange.uNemRange);
3571 if ((pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK) || RT_FAILURE(rc))
3572 break;
3573 }
3574 }
3575 AssertLogRelRCReturnStmt(rc, PGMR3PhysMmio2Unmap(pVM, pDevIns, hMmio2, GCPhys); PGM_UNLOCK(pVM), rc);
3576 }
3577#endif
3578
3579 PGM_UNLOCK(pVM);
3580
3581 return VINF_SUCCESS;
3582}
3583
3584
3585/**
3586 * Unmaps an MMIO2 region.
3587 *
3588 * This is typically done when a guest / the bios / state loading changes the
3589 * PCI config. The replacing of base memory has the same restrictions as during
3590 * registration, of course.
3591 */
3592VMMR3_INT_DECL(int) PGMR3PhysMmio2Unmap(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, RTGCPHYS GCPhys)
3593{
3594 /*
3595 * Validate input
3596 */
3597 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3598 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3599 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
3600 if (GCPhys != NIL_RTGCPHYS)
3601 {
3602 AssertReturn(GCPhys != 0, VERR_INVALID_PARAMETER);
3603 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3604 }
3605
3606 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3607 AssertReturn(pFirstMmio, VERR_NOT_FOUND);
3608 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
3609
3610 int rc = PGM_LOCK(pVM);
3611 AssertRCReturn(rc, rc);
3612
3613 PPGMREGMMIO2RANGE pLastMmio = pFirstMmio;
3614 RTGCPHYS cbRange = 0;
3615 for (;;)
3616 {
3617 AssertReturnStmt(pLastMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED, PGM_UNLOCK(pVM), VERR_WRONG_ORDER);
3618 AssertReturnStmt(pLastMmio->RamRange.GCPhys == GCPhys + cbRange || GCPhys == NIL_RTGCPHYS, PGM_UNLOCK(pVM), VERR_INVALID_PARAMETER);
3619 Assert(pLastMmio->pDevInsR3 == pFirstMmio->pDevInsR3);
3620 Assert(pLastMmio->iSubDev == pFirstMmio->iSubDev);
3621 Assert(pLastMmio->iRegion == pFirstMmio->iRegion);
3622 cbRange += pLastMmio->RamRange.cb;
3623 if (pLastMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3624 break;
3625 pLastMmio = pLastMmio->pNextR3;
3626 }
3627
3628 Log(("PGMR3PhysMmio2Unmap: %RGp-%RGp %s\n",
3629 pFirstMmio->RamRange.GCPhys, pLastMmio->RamRange.GCPhysLast, pFirstMmio->RamRange.pszDesc));
3630
3631 uint16_t const fOldFlags = pFirstMmio->fFlags;
3632 AssertReturnStmt(fOldFlags & PGMREGMMIO2RANGE_F_MAPPED, PGM_UNLOCK(pVM), VERR_WRONG_ORDER);
3633
3634 /*
3635 * If monitoring dirty pages, we must deregister the handlers first.
3636 */
3637 if ( pFirstMmio->pPhysHandlerR3
3638 && (fOldFlags & PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3639 pgmR3PhysMmio2DisableDirtyPageTracing(pVM, pFirstMmio);
3640
3641 /*
3642 * Unmap it.
3643 */
3644 int rcRet = VINF_SUCCESS;
3645#ifdef VBOX_WITH_NATIVE_NEM
3646 uint32_t const fNemFlags = NEM_NOTIFY_PHYS_MMIO_EX_F_MMIO2
3647 | (fOldFlags & PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES
3648 ? NEM_NOTIFY_PHYS_MMIO_EX_F_TRACK_DIRTY_PAGES : 0);
3649#endif
3650 if (fOldFlags & PGMREGMMIO2RANGE_F_OVERLAPPING)
3651 {
3652 /*
3653 * We've replaced RAM, replace with zero pages.
3654 *
3655 * Note! This is where we might differ a little from a real system, because
3656 * it's likely to just show the RAM pages as they were before the
3657 * MMIO/MMIO2 region was mapped here.
3658 */
3659 /* Only one chunk allowed when overlapping! */
3660 Assert(fOldFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK);
3661
3662 /* Restore the RAM pages we've replaced. */
3663 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
3664 while (pRam->GCPhys > pFirstMmio->RamRange.GCPhysLast)
3665 pRam = pRam->pNextR3;
3666
3667 PPGMPAGE pPageDst = &pRam->aPages[(pFirstMmio->RamRange.GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
3668 uint32_t cPagesLeft = pFirstMmio->RamRange.cb >> GUEST_PAGE_SHIFT;
3669 pVM->pgm.s.cZeroPages += cPagesLeft; /** @todo not correct for NEM mode */
3670
3671#ifdef VBOX_WITH_NATIVE_NEM
3672 if (VM_IS_NEM_ENABLED(pVM)) /* Notify NEM. Note! we cannot be here in simple memory mode, see mapping function. */
3673 {
3674 uint8_t u2State = UINT8_MAX;
3675 rc = NEMR3NotifyPhysMmioExUnmap(pVM, pFirstMmio->RamRange.GCPhys, pFirstMmio->RamRange.cb,
3676 fNemFlags | NEM_NOTIFY_PHYS_MMIO_EX_F_REPLACE,
3677 pRam->pvR3
3678 ? (uint8_t *)pRam->pvR3 + pFirstMmio->RamRange.GCPhys - pRam->GCPhys : NULL,
3679 pFirstMmio->pvR3, &u2State, &pRam->uNemRange);
3680 AssertRCStmt(rc, rcRet = rc);
3681 if (u2State != UINT8_MAX)
3682 pgmPhysSetNemStateForPages(pPageDst, cPagesLeft, u2State);
3683 }
3684#endif
3685
3686 while (cPagesLeft-- > 0)
3687 {
3688 PGM_PAGE_INIT_ZERO(pPageDst, pVM, PGMPAGETYPE_RAM);
3689 pPageDst++;
3690 }
3691
3692 /* Flush physical page map TLB. */
3693 pgmPhysInvalidatePageMapTLB(pVM);
3694
3695 /* Update range state. */
3696 pFirstMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3697 pFirstMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3698 pFirstMmio->fFlags &= ~(PGMREGMMIO2RANGE_F_OVERLAPPING | PGMREGMMIO2RANGE_F_MAPPED);
3699 }
3700 else
3701 {
3702 /*
3703 * Unlink the chunks related to the MMIO/MMIO2 region.
3704 */
3705 for (PPGMREGMMIO2RANGE pCurMmio = pFirstMmio; ; pCurMmio = pCurMmio->pNextR3)
3706 {
3707#ifdef VBOX_WITH_NATIVE_NEM
3708 if (VM_IS_NEM_ENABLED(pVM)) /* Notify NEM. */
3709 {
3710 uint8_t u2State = UINT8_MAX;
3711 rc = NEMR3NotifyPhysMmioExUnmap(pVM, pCurMmio->RamRange.GCPhys, pCurMmio->RamRange.cb, fNemFlags,
3712 NULL, pCurMmio->pvR3, &u2State, &pCurMmio->RamRange.uNemRange);
3713 AssertRCStmt(rc, rcRet = rc);
3714 if (u2State != UINT8_MAX)
3715 pgmPhysSetNemStateForPages(pCurMmio->RamRange.aPages, pCurMmio->RamRange.cb >> GUEST_PAGE_SHIFT, u2State);
3716 }
3717#endif
3718 pgmR3PhysUnlinkRamRange(pVM, &pCurMmio->RamRange);
3719 pCurMmio->RamRange.GCPhys = NIL_RTGCPHYS;
3720 pCurMmio->RamRange.GCPhysLast = NIL_RTGCPHYS;
3721 pCurMmio->fFlags &= ~(PGMREGMMIO2RANGE_F_OVERLAPPING | PGMREGMMIO2RANGE_F_MAPPED);
3722 if (pCurMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3723 break;
3724 }
3725 }
3726
3727 /* Force a PGM pool flush as guest ram references have been changed. */
3728 /** @todo not entirely SMP safe; assuming for now the guest takes care
3729 * of this internally (not touch mapped mmio while changing the
3730 * mapping). */
3731 PVMCPU pVCpu = VMMGetCpu(pVM);
3732 pVCpu->pgm.s.fSyncFlags |= PGM_SYNC_CLEAR_PGM_POOL;
3733 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
3734
3735 pgmPhysInvalidatePageMapTLB(pVM);
3736 pgmPhysInvalidRamRangeTlbs(pVM);
3737
3738 PGM_UNLOCK(pVM);
3739 return rcRet;
3740}
3741
3742
3743/**
3744 * Reduces the mapping size of a MMIO2 region.
3745 *
3746 * This is mainly for dealing with old saved states after changing the default
3747 * size of a mapping region. See PGMDevHlpMMIOExReduce and
3748 * PDMPCIDEV::pfnRegionLoadChangeHookR3.
3749 *
3750 * The region must not currently be mapped when making this call. The VM state
3751 * must be state restore or VM construction.
3752 *
3753 * @returns VBox status code.
3754 * @param pVM The cross context VM structure.
3755 * @param pDevIns The device instance owning the region.
3756 * @param hMmio2 The handle of the region to reduce.
3757 * @param cbRegion The new mapping size.
3758 */
3759VMMR3_INT_DECL(int) PGMR3PhysMmio2Reduce(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, RTGCPHYS cbRegion)
3760{
3761 /*
3762 * Validate input
3763 */
3764 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3765 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
3766 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
3767 AssertReturn(cbRegion >= X86_PAGE_SIZE, VERR_INVALID_PARAMETER);
3768 AssertReturn(!(cbRegion & X86_PAGE_OFFSET_MASK), VERR_UNSUPPORTED_ALIGNMENT);
3769 VMSTATE enmVmState = VMR3GetState(pVM);
3770 AssertLogRelMsgReturn( enmVmState == VMSTATE_CREATING
3771 || enmVmState == VMSTATE_LOADING,
3772 ("enmVmState=%d (%s)\n", enmVmState, VMR3GetStateName(enmVmState)),
3773 VERR_VM_INVALID_VM_STATE);
3774
3775 int rc = PGM_LOCK(pVM);
3776 AssertRCReturn(rc, rc);
3777
3778 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3779 if (pFirstMmio)
3780 {
3781 Assert(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK);
3782 if (!(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED))
3783 {
3784 /*
3785 * NOTE! Current implementation does not support multiple ranges.
3786 * Implement when there is a real world need and thus a testcase.
3787 */
3788 AssertLogRelMsgStmt(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK,
3789 ("%s: %#x\n", pFirstMmio->RamRange.pszDesc, pFirstMmio->fFlags),
3790 rc = VERR_NOT_SUPPORTED);
3791 if (RT_SUCCESS(rc))
3792 {
3793 /*
3794 * Make the change.
3795 */
3796 Log(("PGMR3PhysMmio2Reduce: %s changes from %RGp bytes (%RGp) to %RGp bytes.\n",
3797 pFirstMmio->RamRange.pszDesc, pFirstMmio->RamRange.cb, pFirstMmio->cbReal, cbRegion));
3798
3799 AssertLogRelMsgStmt(cbRegion <= pFirstMmio->cbReal,
3800 ("%s: cbRegion=%#RGp cbReal=%#RGp\n", pFirstMmio->RamRange.pszDesc, cbRegion, pFirstMmio->cbReal),
3801 rc = VERR_OUT_OF_RANGE);
3802 if (RT_SUCCESS(rc))
3803 {
3804 pFirstMmio->RamRange.cb = cbRegion;
3805 }
3806 }
3807 }
3808 else
3809 rc = VERR_WRONG_ORDER;
3810 }
3811 else
3812 rc = VERR_NOT_FOUND;
3813
3814 PGM_UNLOCK(pVM);
3815 return rc;
3816}
3817
3818
3819/**
3820 * Validates @a hMmio2, making sure it belongs to @a pDevIns.
3821 *
3822 * @returns VBox status code.
3823 * @param pVM The cross context VM structure.
3824 * @param pDevIns The device which allegedly owns @a hMmio2.
3825 * @param hMmio2 The handle to validate.
3826 */
3827VMMR3_INT_DECL(int) PGMR3PhysMmio2ValidateHandle(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2)
3828{
3829 /*
3830 * Validate input
3831 */
3832 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
3833 AssertPtrReturn(pDevIns, VERR_INVALID_POINTER);
3834
3835 /*
3836 * Just do this the simple way. No need for locking as this is only taken at
3837 */
3838 PGM_LOCK_VOID(pVM);
3839 PPGMREGMMIO2RANGE pFirstMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3840 PGM_UNLOCK(pVM);
3841 AssertReturn(pFirstMmio, VERR_INVALID_HANDLE);
3842 AssertReturn(pFirstMmio->fFlags & PGMREGMMIO2RANGE_F_FIRST_CHUNK, VERR_INVALID_HANDLE);
3843 return VINF_SUCCESS;
3844}
3845
3846
3847/**
3848 * Gets the mapping address of an MMIO2 region.
3849 *
3850 * @returns Mapping address, NIL_RTGCPHYS if not mapped or invalid handle.
3851 *
3852 * @param pVM The cross context VM structure.
3853 * @param pDevIns The device owning the MMIO2 handle.
3854 * @param hMmio2 The region handle.
3855 */
3856VMMR3_INT_DECL(RTGCPHYS) PGMR3PhysMmio2GetMappingAddress(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2)
3857{
3858 AssertPtrReturn(pDevIns, NIL_RTGCPHYS);
3859
3860 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3861 AssertReturn(pFirstRegMmio, NIL_RTGCPHYS);
3862
3863 if (pFirstRegMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED)
3864 return pFirstRegMmio->RamRange.GCPhys;
3865 return NIL_RTGCPHYS;
3866}
3867
3868
3869/**
3870 * Worker for PGMR3PhysMmio2QueryAndResetDirtyBitmap.
3871 *
3872 * Called holding the PGM lock.
3873 */
3874static int pgmR3PhysMmio2QueryAndResetDirtyBitmapLocked(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2,
3875 void *pvBitmap, size_t cbBitmap)
3876{
3877 /*
3878 * Continue validation.
3879 */
3880 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
3881 AssertReturn(pFirstRegMmio, VERR_INVALID_HANDLE);
3882 AssertReturn( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
3883 == (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK),
3884 VERR_INVALID_FUNCTION);
3885 AssertReturn(pDevIns == pFirstRegMmio->pDevInsR3, VERR_NOT_OWNER);
3886
3887 RTGCPHYS cbTotal = 0;
3888 uint16_t fTotalDirty = 0;
3889 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio;;)
3890 {
3891 cbTotal += pCur->RamRange.cb; /* Not using cbReal here, because NEM is not in on the creating, only the mapping. */
3892 fTotalDirty |= pCur->fFlags;
3893 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3894 break;
3895 pCur = pCur->pNextR3;
3896 AssertPtrReturn(pCur, VERR_INTERNAL_ERROR_5);
3897 AssertReturn( (pCur->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
3898 == PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES,
3899 VERR_INTERNAL_ERROR_4);
3900 }
3901 size_t const cbTotalBitmap = RT_ALIGN_T(cbTotal, GUEST_PAGE_SIZE * 64, RTGCPHYS) / GUEST_PAGE_SIZE / 8;
3902
3903 if (cbBitmap)
3904 {
3905 AssertPtrReturn(pvBitmap, VERR_INVALID_POINTER);
3906 AssertReturn(RT_ALIGN_P(pvBitmap, sizeof(uint64_t)) == pvBitmap, VERR_INVALID_POINTER);
3907 AssertReturn(cbBitmap == cbTotalBitmap, VERR_INVALID_PARAMETER);
3908 }
3909
3910 /*
3911 * Do the work.
3912 */
3913 int rc = VINF_SUCCESS;
3914 if (pvBitmap)
3915 {
3916#ifdef VBOX_WITH_PGM_NEM_MODE
3917 if (pFirstRegMmio->pPhysHandlerR3 == NULL)
3918 {
3919 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_INTERNAL_ERROR_4);
3920 uint8_t *pbBitmap = (uint8_t *)pvBitmap;
3921 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
3922 {
3923 size_t const cbBitmapChunk = pCur->RamRange.cb / GUEST_PAGE_SIZE / 8;
3924 Assert((RTGCPHYS)cbBitmapChunk * GUEST_PAGE_SIZE * 8 == pCur->RamRange.cb);
3925 int rc2 = NEMR3PhysMmio2QueryAndResetDirtyBitmap(pVM, pCur->RamRange.GCPhys, pCur->RamRange.cb,
3926 pCur->RamRange.uNemRange, pbBitmap, cbBitmapChunk);
3927 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3928 rc = rc2;
3929 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3930 break;
3931 pbBitmap += pCur->RamRange.cb / GUEST_PAGE_SIZE / 8;
3932 }
3933 }
3934 else
3935#endif
3936 if (fTotalDirty & PGMREGMMIO2RANGE_F_IS_DIRTY)
3937 {
3938 if ( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3939 == (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3940 {
3941 /*
3942 * Reset each chunk, gathering dirty bits.
3943 */
3944 RT_BZERO(pvBitmap, cbBitmap); /* simpler for now. */
3945 uint32_t iPageNo = 0;
3946 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
3947 {
3948 if (pCur->fFlags & PGMREGMMIO2RANGE_F_IS_DIRTY)
3949 {
3950 int rc2 = pgmHandlerPhysicalResetMmio2WithBitmap(pVM, pCur->RamRange.GCPhys, pvBitmap, iPageNo);
3951 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
3952 rc = rc2;
3953 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_IS_DIRTY;
3954 }
3955 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3956 break;
3957 iPageNo += pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3958 }
3959 }
3960 else
3961 {
3962 /*
3963 * If not mapped or tracking is disabled, we return the
3964 * PGMREGMMIO2RANGE_F_IS_DIRTY status for all pages. We cannot
3965 * get more accurate data than that after unmapping or disabling.
3966 */
3967 RT_BZERO(pvBitmap, cbBitmap);
3968 uint32_t iPageNo = 0;
3969 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
3970 {
3971 if (pCur->fFlags & PGMREGMMIO2RANGE_F_IS_DIRTY)
3972 {
3973 ASMBitSetRange(pvBitmap, iPageNo, iPageNo + (pCur->RamRange.cb >> GUEST_PAGE_SHIFT));
3974 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_IS_DIRTY;
3975 }
3976 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
3977 break;
3978 iPageNo += pCur->RamRange.cb >> GUEST_PAGE_SHIFT;
3979 }
3980 }
3981 }
3982 /*
3983 * No dirty chunks.
3984 */
3985 else
3986 RT_BZERO(pvBitmap, cbBitmap);
3987 }
3988 /*
3989 * No bitmap. Reset the region if tracking is currently enabled.
3990 */
3991 else if ( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3992 == (PGMREGMMIO2RANGE_F_MAPPED | PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
3993 {
3994#ifdef VBOX_WITH_PGM_NEM_MODE
3995 if (pFirstRegMmio->pPhysHandlerR3 == NULL)
3996 {
3997 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_INTERNAL_ERROR_4);
3998 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
3999 {
4000 int rc2 = NEMR3PhysMmio2QueryAndResetDirtyBitmap(pVM, pCur->RamRange.GCPhys, pCur->RamRange.cb,
4001 pCur->RamRange.uNemRange, NULL, 0);
4002 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
4003 rc = rc2;
4004 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
4005 break;
4006 }
4007 }
4008 else
4009#endif
4010 {
4011 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio; pCur; pCur = pCur->pNextR3)
4012 {
4013 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_IS_DIRTY;
4014 int rc2 = PGMHandlerPhysicalReset(pVM, pCur->RamRange.GCPhys);
4015 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
4016 rc = rc2;
4017 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
4018 break;
4019 }
4020 }
4021 }
4022
4023 return rc;
4024}
4025
4026
4027/**
4028 * Queries the dirty page bitmap and resets the monitoring.
4029 *
4030 * The PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES flag must be specified when
4031 * creating the range for this to work.
4032 *
4033 * @returns VBox status code.
4034 * @retval VERR_INVALID_FUNCTION if not created using
4035 * PGMPHYS_MMIO2_FLAGS_TRACK_DIRTY_PAGES.
4036 * @param pVM The cross context VM structure.
4037 * @param pDevIns The device owning the MMIO2 handle.
4038 * @param hMmio2 The region handle.
4039 * @param pvBitmap The output bitmap. Must be 8-byte aligned. Ignored
4040 * when @a cbBitmap is zero.
4041 * @param cbBitmap The size of the bitmap. Must be the size of the whole
4042 * MMIO2 range, rounded up to the nearest 8 bytes.
4043 * When zero only a reset is done.
4044 */
4045VMMR3_INT_DECL(int) PGMR3PhysMmio2QueryAndResetDirtyBitmap(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2,
4046 void *pvBitmap, size_t cbBitmap)
4047{
4048 /*
4049 * Do some basic validation before grapping the PGM lock and continuing.
4050 */
4051 AssertPtrReturn(pDevIns, VERR_INVALID_POINTER);
4052 AssertReturn(RT_ALIGN_Z(cbBitmap, sizeof(uint64_t)) == cbBitmap, VERR_INVALID_PARAMETER);
4053 int rc = PGM_LOCK(pVM);
4054 if (RT_SUCCESS(rc))
4055 {
4056 STAM_PROFILE_START(&pVM->pgm.s.StatMmio2QueryAndResetDirtyBitmap, a);
4057 rc = pgmR3PhysMmio2QueryAndResetDirtyBitmapLocked(pVM, pDevIns, hMmio2, pvBitmap, cbBitmap);
4058 STAM_PROFILE_STOP(&pVM->pgm.s.StatMmio2QueryAndResetDirtyBitmap, a);
4059 PGM_UNLOCK(pVM);
4060 }
4061 return rc;
4062}
4063
4064/**
4065 * Worker for PGMR3PhysMmio2ControlDirtyPageTracking
4066 *
4067 * Called owning the PGM lock.
4068 */
4069static int pgmR3PhysMmio2ControlDirtyPageTrackingLocked(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, bool fEnabled)
4070{
4071 /*
4072 * Continue validation.
4073 */
4074 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
4075 AssertReturn(pFirstRegMmio, VERR_INVALID_HANDLE);
4076 AssertReturn( (pFirstRegMmio->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
4077 == (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK)
4078 , VERR_INVALID_FUNCTION);
4079 AssertReturn(pDevIns == pFirstRegMmio->pDevInsR3, VERR_NOT_OWNER);
4080
4081#ifdef VBOX_WITH_PGM_NEM_MODE
4082 /*
4083 * This is a nop if NEM is responsible for doing the tracking, we simply
4084 * leave the tracking on all the time there.
4085 */
4086 if (pFirstRegMmio->pPhysHandlerR3 == NULL)
4087 {
4088 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_INTERNAL_ERROR_4);
4089 return VINF_SUCCESS;
4090 }
4091#endif
4092
4093 /*
4094 * Anyting needing doing?
4095 */
4096 if (fEnabled != RT_BOOL(pFirstRegMmio->fFlags & PGMREGMMIO2RANGE_F_TRACKING_ENABLED))
4097 {
4098 LogFlowFunc(("fEnabled=%RTbool %s\n", fEnabled, pFirstRegMmio->RamRange.pszDesc));
4099
4100 /*
4101 * Update the PGMREGMMIO2RANGE_F_TRACKING_ENABLED flag.
4102 */
4103 for (PPGMREGMMIO2RANGE pCur = pFirstRegMmio;;)
4104 {
4105 if (fEnabled)
4106 pCur->fFlags |= PGMREGMMIO2RANGE_F_TRACKING_ENABLED;
4107 else
4108 pCur->fFlags &= ~PGMREGMMIO2RANGE_F_TRACKING_ENABLED;
4109 if (pCur->fFlags & PGMREGMMIO2RANGE_F_LAST_CHUNK)
4110 break;
4111 pCur = pCur->pNextR3;
4112 AssertPtrReturn(pCur, VERR_INTERNAL_ERROR_5);
4113 AssertReturn( (pCur->fFlags & (PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES | PGMREGMMIO2RANGE_F_FIRST_CHUNK))
4114 == PGMREGMMIO2RANGE_F_TRACK_DIRTY_PAGES
4115 , VERR_INTERNAL_ERROR_4);
4116 }
4117
4118 /*
4119 * Enable/disable handlers if currently mapped.
4120 *
4121 * We ignore status codes here as we've already changed the flags and
4122 * returning a failure status now would be confusing. Besides, the two
4123 * functions will continue past failures. As argued in the mapping code,
4124 * it's in the release log.
4125 */
4126 if (pFirstRegMmio->fFlags & PGMREGMMIO2RANGE_F_MAPPED)
4127 {
4128 if (fEnabled)
4129 pgmR3PhysMmio2EnableDirtyPageTracing(pVM, pFirstRegMmio);
4130 else
4131 pgmR3PhysMmio2DisableDirtyPageTracing(pVM, pFirstRegMmio);
4132 }
4133 }
4134 else
4135 LogFlowFunc(("fEnabled=%RTbool %s - no change\n", fEnabled, pFirstRegMmio->RamRange.pszDesc));
4136
4137 return VINF_SUCCESS;
4138}
4139
4140
4141/**
4142 * Controls the dirty page tracking for an MMIO2 range.
4143 *
4144 * @returns VBox status code.
4145 * @param pVM The cross context VM structure.
4146 * @param pDevIns The device owning the MMIO2 memory.
4147 * @param hMmio2 The handle of the region.
4148 * @param fEnabled The new tracking state.
4149 */
4150VMMR3_INT_DECL(int) PGMR3PhysMmio2ControlDirtyPageTracking(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, bool fEnabled)
4151{
4152 /*
4153 * Do some basic validation before grapping the PGM lock and continuing.
4154 */
4155 AssertPtrReturn(pDevIns, VERR_INVALID_POINTER);
4156 int rc = PGM_LOCK(pVM);
4157 if (RT_SUCCESS(rc))
4158 {
4159 rc = pgmR3PhysMmio2ControlDirtyPageTrackingLocked(pVM, pDevIns, hMmio2, fEnabled);
4160 PGM_UNLOCK(pVM);
4161 }
4162 return rc;
4163}
4164
4165
4166/**
4167 * Changes the region number of an MMIO2 region.
4168 *
4169 * This is only for dealing with save state issues, nothing else.
4170 *
4171 * @return VBox status code.
4172 *
4173 * @param pVM The cross context VM structure.
4174 * @param pDevIns The device owning the MMIO2 memory.
4175 * @param hMmio2 The handle of the region.
4176 * @param iNewRegion The new region index.
4177 *
4178 * @thread EMT(0)
4179 * @sa @bugref{9359}
4180 */
4181VMMR3_INT_DECL(int) PGMR3PhysMmio2ChangeRegionNo(PVM pVM, PPDMDEVINS pDevIns, PGMMMIO2HANDLE hMmio2, uint32_t iNewRegion)
4182{
4183 /*
4184 * Validate input.
4185 */
4186 VM_ASSERT_EMT0_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
4187 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_LOADING, VERR_VM_INVALID_VM_STATE);
4188 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4189 AssertReturn(hMmio2 != NIL_PGMMMIO2HANDLE, VERR_INVALID_HANDLE);
4190 AssertReturn(iNewRegion <= UINT8_MAX, VERR_INVALID_PARAMETER);
4191
4192 AssertReturn(pVM->enmVMState == VMSTATE_LOADING, VERR_INVALID_STATE);
4193
4194 int rc = PGM_LOCK(pVM);
4195 AssertRCReturn(rc, rc);
4196
4197 PPGMREGMMIO2RANGE pFirstRegMmio = pgmR3PhysMmio2Find(pVM, pDevIns, UINT32_MAX, UINT32_MAX, hMmio2);
4198 AssertReturnStmt(pFirstRegMmio, PGM_UNLOCK(pVM), VERR_NOT_FOUND);
4199 AssertReturnStmt(pgmR3PhysMmio2Find(pVM, pDevIns, pFirstRegMmio->iSubDev, iNewRegion, NIL_PGMMMIO2HANDLE) == NULL,
4200 PGM_UNLOCK(pVM), VERR_RESOURCE_IN_USE);
4201
4202 /*
4203 * Make the change.
4204 */
4205 pFirstRegMmio->iRegion = (uint8_t)iNewRegion;
4206
4207 PGM_UNLOCK(pVM);
4208 return VINF_SUCCESS;
4209}
4210
4211
4212
4213/*********************************************************************************************************************************
4214* ROM *
4215*********************************************************************************************************************************/
4216
4217/**
4218 * Worker for PGMR3PhysRomRegister.
4219 *
4220 * This is here to simplify lock management, i.e. the caller does all the
4221 * locking and we can simply return without needing to remember to unlock
4222 * anything first.
4223 *
4224 * @returns VBox status code.
4225 * @param pVM The cross context VM structure.
4226 * @param pDevIns The device instance owning the ROM.
4227 * @param GCPhys First physical address in the range.
4228 * Must be page aligned!
4229 * @param cb The size of the range (in bytes).
4230 * Must be page aligned!
4231 * @param pvBinary Pointer to the binary data backing the ROM image.
4232 * @param cbBinary The size of the binary data pvBinary points to.
4233 * This must be less or equal to @a cb.
4234 * @param fFlags Mask of flags. PGMPHYS_ROM_FLAGS_SHADOWED
4235 * and/or PGMPHYS_ROM_FLAGS_PERMANENT_BINARY.
4236 * @param pszDesc Pointer to description string. This must not be freed.
4237 */
4238static int pgmR3PhysRomRegisterLocked(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
4239 const void *pvBinary, uint32_t cbBinary, uint8_t fFlags, const char *pszDesc)
4240{
4241 /*
4242 * Validate input.
4243 */
4244 AssertPtrReturn(pDevIns, VERR_INVALID_PARAMETER);
4245 AssertReturn(RT_ALIGN_T(GCPhys, GUEST_PAGE_SIZE, RTGCPHYS) == GCPhys, VERR_INVALID_PARAMETER);
4246 AssertReturn(RT_ALIGN_T(cb, GUEST_PAGE_SIZE, RTGCPHYS) == cb, VERR_INVALID_PARAMETER);
4247 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
4248 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
4249 AssertPtrReturn(pvBinary, VERR_INVALID_PARAMETER);
4250 AssertPtrReturn(pszDesc, VERR_INVALID_POINTER);
4251 AssertReturn(!(fFlags & ~PGMPHYS_ROM_FLAGS_VALID_MASK), VERR_INVALID_PARAMETER);
4252 VM_ASSERT_STATE_RETURN(pVM, VMSTATE_CREATING, VERR_VM_INVALID_VM_STATE);
4253
4254 const uint32_t cGuestPages = cb >> GUEST_PAGE_SHIFT;
4255#ifdef VBOX_WITH_PGM_NEM_MODE
4256 const uint32_t cHostPages = RT_ALIGN_T(cb, HOST_PAGE_SIZE, RTGCPHYS) >> HOST_PAGE_SHIFT;
4257#endif
4258
4259 /*
4260 * Find the ROM location in the ROM list first.
4261 */
4262 PPGMROMRANGE pRomPrev = NULL;
4263 PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3;
4264 while (pRom && GCPhysLast >= pRom->GCPhys)
4265 {
4266 if ( GCPhys <= pRom->GCPhysLast
4267 && GCPhysLast >= pRom->GCPhys)
4268 AssertLogRelMsgFailedReturn(("%RGp-%RGp (%s) conflicts with existing %RGp-%RGp (%s)\n",
4269 GCPhys, GCPhysLast, pszDesc,
4270 pRom->GCPhys, pRom->GCPhysLast, pRom->pszDesc),
4271 VERR_PGM_RAM_CONFLICT);
4272 /* next */
4273 pRomPrev = pRom;
4274 pRom = pRom->pNextR3;
4275 }
4276
4277 /*
4278 * Find the RAM location and check for conflicts.
4279 *
4280 * Conflict detection is a bit different than for RAM registration since a
4281 * ROM can be located within a RAM range. So, what we have to check for is
4282 * other memory types (other than RAM that is) and that we don't span more
4283 * than one RAM range (lazy).
4284 */
4285 bool fRamExists = false;
4286 PPGMRAMRANGE pRamPrev = NULL;
4287 PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
4288 while (pRam && GCPhysLast >= pRam->GCPhys)
4289 {
4290 if ( GCPhys <= pRam->GCPhysLast
4291 && GCPhysLast >= pRam->GCPhys)
4292 {
4293 /* completely within? */
4294 AssertLogRelMsgReturn( GCPhys >= pRam->GCPhys
4295 && GCPhysLast <= pRam->GCPhysLast,
4296 ("%RGp-%RGp (%s) falls partly outside %RGp-%RGp (%s)\n",
4297 GCPhys, GCPhysLast, pszDesc,
4298 pRam->GCPhys, pRam->GCPhysLast, pRam->pszDesc),
4299 VERR_PGM_RAM_CONFLICT);
4300 fRamExists = true;
4301 break;
4302 }
4303
4304 /* next */
4305 pRamPrev = pRam;
4306 pRam = pRam->pNextR3;
4307 }
4308 if (fRamExists)
4309 {
4310 PPGMPAGE pPage = &pRam->aPages[(GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT];
4311 uint32_t cPagesLeft = cGuestPages;
4312 while (cPagesLeft-- > 0)
4313 {
4314 AssertLogRelMsgReturn(PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM,
4315 ("%RGp (%R[pgmpage]) isn't a RAM page - registering %RGp-%RGp (%s).\n",
4316 pRam->GCPhys + ((RTGCPHYS)(uintptr_t)(pPage - &pRam->aPages[0]) << GUEST_PAGE_SHIFT),
4317 pPage, GCPhys, GCPhysLast, pszDesc), VERR_PGM_RAM_CONFLICT);
4318 Assert(PGM_PAGE_IS_ZERO(pPage) || PGM_IS_IN_NEM_MODE(pVM));
4319 pPage++;
4320 }
4321 }
4322
4323 /*
4324 * Update the base memory reservation if necessary.
4325 */
4326 uint32_t cExtraBaseCost = fRamExists ? 0 : cGuestPages;
4327 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4328 cExtraBaseCost += cGuestPages;
4329 if (cExtraBaseCost)
4330 {
4331 int rc = MMR3IncreaseBaseReservation(pVM, cExtraBaseCost);
4332 if (RT_FAILURE(rc))
4333 return rc;
4334 }
4335
4336#ifdef VBOX_WITH_NATIVE_NEM
4337 /*
4338 * Early NEM notification before we've made any changes or anything.
4339 */
4340 uint32_t const fNemNotify = (fRamExists ? NEM_NOTIFY_PHYS_ROM_F_REPLACE : 0)
4341 | (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED ? NEM_NOTIFY_PHYS_ROM_F_SHADOW : 0);
4342 uint8_t u2NemState = UINT8_MAX;
4343 uint32_t uNemRange = 0;
4344 if (VM_IS_NEM_ENABLED(pVM))
4345 {
4346 int rc = NEMR3NotifyPhysRomRegisterEarly(pVM, GCPhys, cGuestPages << GUEST_PAGE_SHIFT,
4347 fRamExists ? PGM_RAMRANGE_CALC_PAGE_R3PTR(pRam, GCPhys) : NULL,
4348 fNemNotify, &u2NemState, fRamExists ? &pRam->uNemRange : &uNemRange);
4349 AssertLogRelRCReturn(rc, rc);
4350 }
4351#endif
4352
4353 /*
4354 * Allocate memory for the virgin copy of the RAM. In simplified memory mode,
4355 * we allocate memory for any ad-hoc RAM range and for shadow pages.
4356 */
4357 PGMMALLOCATEPAGESREQ pReq = NULL;
4358#ifdef VBOX_WITH_PGM_NEM_MODE
4359 void *pvRam = NULL;
4360 void *pvAlt = NULL;
4361 if (pVM->pgm.s.fNemMode)
4362 {
4363 if (!fRamExists)
4364 {
4365 int rc = SUPR3PageAlloc(cHostPages, 0, &pvRam);
4366 if (RT_FAILURE(rc))
4367 return rc;
4368 }
4369 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4370 {
4371 int rc = SUPR3PageAlloc(cHostPages, 0, &pvAlt);
4372 if (RT_FAILURE(rc))
4373 {
4374 if (pvRam)
4375 SUPR3PageFree(pvRam, cHostPages);
4376 return rc;
4377 }
4378 }
4379 }
4380 else
4381#endif
4382 {
4383 int rc = GMMR3AllocatePagesPrepare(pVM, &pReq, cGuestPages, GMMACCOUNT_BASE);
4384 AssertRCReturn(rc, rc);
4385
4386 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++)
4387 {
4388 pReq->aPages[iPage].HCPhysGCPhys = GCPhys + (iPage << GUEST_PAGE_SHIFT);
4389 pReq->aPages[iPage].fZeroed = false;
4390 pReq->aPages[iPage].idPage = NIL_GMM_PAGEID;
4391 pReq->aPages[iPage].idSharedPage = NIL_GMM_PAGEID;
4392 }
4393
4394 rc = GMMR3AllocatePagesPerform(pVM, pReq);
4395 if (RT_FAILURE(rc))
4396 {
4397 GMMR3AllocatePagesCleanup(pReq);
4398 return rc;
4399 }
4400 }
4401
4402 /*
4403 * Allocate the new ROM range and RAM range (if necessary).
4404 */
4405 PPGMROMRANGE pRomNew = NULL;
4406 RTR0PTR pRomNewR0 = NIL_RTR0PTR;
4407 size_t const cbRomRange = RT_ALIGN_Z(RT_UOFFSETOF_DYN(PGMROMRANGE, aPages[cGuestPages]), 128);
4408 size_t const cbRamRange = fRamExists ? 0 : RT_UOFFSETOF_DYN(PGMROMRANGE, aPages[cGuestPages]);
4409 size_t const cRangePages = RT_ALIGN_Z(cbRomRange + cbRamRange, HOST_PAGE_SIZE) >> HOST_PAGE_SHIFT;
4410 int rc = SUPR3PageAllocEx(cRangePages, 0 /*fFlags*/, (void **)&pRomNew, &pRomNewR0, NULL /*paPages*/);
4411 if (RT_SUCCESS(rc))
4412 {
4413
4414 /*
4415 * Initialize and insert the RAM range (if required).
4416 */
4417 PPGMRAMRANGE pRamNew;
4418 uint32_t const idxFirstRamPage = fRamExists ? (GCPhys - pRam->GCPhys) >> GUEST_PAGE_SHIFT : 0;
4419 PPGMROMPAGE pRomPage = &pRomNew->aPages[0];
4420 if (!fRamExists)
4421 {
4422 /* New RAM range. */
4423 pRamNew = (PPGMRAMRANGE)((uintptr_t)pRomNew + cbRomRange);
4424 pRamNew->pSelfR0 = !pRomNewR0 ? NIL_RTR0PTR : pRomNewR0 + cbRomRange;
4425 pRamNew->GCPhys = GCPhys;
4426 pRamNew->GCPhysLast = GCPhysLast;
4427 pRamNew->cb = cb;
4428 pRamNew->pszDesc = pszDesc;
4429 pRamNew->fFlags = PGM_RAM_RANGE_FLAGS_AD_HOC_ROM;
4430 pRamNew->pvR3 = NULL;
4431 pRamNew->paLSPages = NULL;
4432#ifdef VBOX_WITH_NATIVE_NEM
4433 pRamNew->uNemRange = uNemRange;
4434#endif
4435
4436 PPGMPAGE pRamPage = &pRamNew->aPages[idxFirstRamPage];
4437#ifdef VBOX_WITH_PGM_NEM_MODE
4438 if (pVM->pgm.s.fNemMode)
4439 {
4440 AssertPtr(pvRam); Assert(pReq == NULL);
4441 pRamNew->pvR3 = pvRam;
4442 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4443 {
4444 PGM_PAGE_INIT(pRamPage, UINT64_C(0x0000fffffffff000), NIL_GMM_PAGEID,
4445 PGMPAGETYPE_ROM, PGM_PAGE_STATE_ALLOCATED);
4446 pRomPage->Virgin = *pRamPage;
4447 }
4448 }
4449 else
4450#endif
4451 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4452 {
4453 PGM_PAGE_INIT(pRamPage,
4454 pReq->aPages[iPage].HCPhysGCPhys,
4455 pReq->aPages[iPage].idPage,
4456 PGMPAGETYPE_ROM,
4457 PGM_PAGE_STATE_ALLOCATED);
4458
4459 pRomPage->Virgin = *pRamPage;
4460 }
4461
4462 pVM->pgm.s.cAllPages += cGuestPages;
4463 pVM->pgm.s.cPrivatePages += cGuestPages;
4464 pgmR3PhysLinkRamRange(pVM, pRamNew, pRamPrev);
4465 }
4466 else
4467 {
4468 /* Existing RAM range. */
4469 PPGMPAGE pRamPage = &pRam->aPages[idxFirstRamPage];
4470#ifdef VBOX_WITH_PGM_NEM_MODE
4471 if (pVM->pgm.s.fNemMode)
4472 {
4473 Assert(pvRam == NULL); Assert(pReq == NULL);
4474 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4475 {
4476 Assert(PGM_PAGE_GET_HCPHYS(pRamPage) == UINT64_C(0x0000fffffffff000));
4477 Assert(PGM_PAGE_GET_PAGEID(pRamPage) == NIL_GMM_PAGEID);
4478 Assert(PGM_PAGE_GET_STATE(pRamPage) == PGM_PAGE_STATE_ALLOCATED);
4479 PGM_PAGE_SET_TYPE(pVM, pRamPage, PGMPAGETYPE_ROM);
4480 PGM_PAGE_SET_STATE(pVM, pRamPage, PGM_PAGE_STATE_ALLOCATED);
4481 PGM_PAGE_SET_PDE_TYPE(pVM, pRamPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4482 PGM_PAGE_SET_PTE_INDEX(pVM, pRamPage, 0);
4483 PGM_PAGE_SET_TRACKING(pVM, pRamPage, 0);
4484
4485 pRomPage->Virgin = *pRamPage;
4486 }
4487 }
4488 else
4489#endif
4490 {
4491 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4492 {
4493 PGM_PAGE_SET_TYPE(pVM, pRamPage, PGMPAGETYPE_ROM);
4494 PGM_PAGE_SET_HCPHYS(pVM, pRamPage, pReq->aPages[iPage].HCPhysGCPhys);
4495 PGM_PAGE_SET_STATE(pVM, pRamPage, PGM_PAGE_STATE_ALLOCATED);
4496 PGM_PAGE_SET_PAGEID(pVM, pRamPage, pReq->aPages[iPage].idPage);
4497 PGM_PAGE_SET_PDE_TYPE(pVM, pRamPage, PGM_PAGE_PDE_TYPE_DONTCARE);
4498 PGM_PAGE_SET_PTE_INDEX(pVM, pRamPage, 0);
4499 PGM_PAGE_SET_TRACKING(pVM, pRamPage, 0);
4500
4501 pRomPage->Virgin = *pRamPage;
4502 }
4503 pVM->pgm.s.cZeroPages -= cGuestPages;
4504 pVM->pgm.s.cPrivatePages += cGuestPages;
4505 }
4506 pRamNew = pRam;
4507 }
4508
4509#ifdef VBOX_WITH_NATIVE_NEM
4510 /* Set the NEM state of the pages if needed. */
4511 if (u2NemState != UINT8_MAX)
4512 pgmPhysSetNemStateForPages(&pRamNew->aPages[idxFirstRamPage], cGuestPages, u2NemState);
4513#endif
4514
4515 /* Flush physical page map TLB. */
4516 pgmPhysInvalidatePageMapTLB(pVM);
4517
4518 /*
4519 * Register the ROM access handler.
4520 */
4521 rc = PGMHandlerPhysicalRegister(pVM, GCPhys, GCPhysLast, pVM->pgm.s.hRomPhysHandlerType, GCPhys, pszDesc);
4522 if (RT_SUCCESS(rc))
4523 {
4524 /*
4525 * Copy the image over to the virgin pages.
4526 * This must be done after linking in the RAM range.
4527 */
4528 size_t cbBinaryLeft = cbBinary;
4529 PPGMPAGE pRamPage = &pRamNew->aPages[idxFirstRamPage];
4530 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++)
4531 {
4532 void *pvDstPage;
4533 rc = pgmPhysPageMap(pVM, pRamPage, GCPhys + (iPage << GUEST_PAGE_SHIFT), &pvDstPage);
4534 if (RT_FAILURE(rc))
4535 {
4536 VMSetError(pVM, rc, RT_SRC_POS, "Failed to map virgin ROM page at %RGp", GCPhys);
4537 break;
4538 }
4539 if (cbBinaryLeft >= GUEST_PAGE_SIZE)
4540 {
4541 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << GUEST_PAGE_SHIFT), GUEST_PAGE_SIZE);
4542 cbBinaryLeft -= GUEST_PAGE_SIZE;
4543 }
4544 else
4545 {
4546 RT_BZERO(pvDstPage, GUEST_PAGE_SIZE); /* (shouldn't be necessary, but can't hurt either) */
4547 if (cbBinaryLeft > 0)
4548 {
4549 memcpy(pvDstPage, (uint8_t const *)pvBinary + ((size_t)iPage << GUEST_PAGE_SHIFT), cbBinaryLeft);
4550 cbBinaryLeft = 0;
4551 }
4552 }
4553 }
4554 if (RT_SUCCESS(rc))
4555 {
4556 /*
4557 * Initialize the ROM range.
4558 * Note that the Virgin member of the pages has already been initialized above.
4559 */
4560 pRomNew->pSelfR0 = pRomNewR0;
4561 pRomNew->GCPhys = GCPhys;
4562 pRomNew->GCPhysLast = GCPhysLast;
4563 pRomNew->cb = cb;
4564 pRomNew->fFlags = fFlags;
4565 pRomNew->idSavedState = UINT8_MAX;
4566 pRomNew->cbOriginal = cbBinary;
4567 pRomNew->pszDesc = pszDesc;
4568#ifdef VBOX_WITH_PGM_NEM_MODE
4569 pRomNew->pbR3Alternate = (uint8_t *)pvAlt;
4570#endif
4571 pRomNew->pvOriginal = fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY
4572 ? pvBinary : RTMemDup(pvBinary, cbBinary);
4573 if (pRomNew->pvOriginal)
4574 {
4575 for (unsigned iPage = 0; iPage < cGuestPages; iPage++)
4576 {
4577 PPGMROMPAGE pPage = &pRomNew->aPages[iPage];
4578 pPage->enmProt = PGMROMPROT_READ_ROM_WRITE_IGNORE;
4579#ifdef VBOX_WITH_PGM_NEM_MODE
4580 if (pVM->pgm.s.fNemMode)
4581 PGM_PAGE_INIT(&pPage->Shadow, UINT64_C(0x0000fffffffff000), NIL_GMM_PAGEID,
4582 PGMPAGETYPE_ROM_SHADOW, PGM_PAGE_STATE_ALLOCATED);
4583 else
4584#endif
4585 PGM_PAGE_INIT_ZERO(&pPage->Shadow, pVM, PGMPAGETYPE_ROM_SHADOW);
4586 }
4587
4588 /* update the page count stats for the shadow pages. */
4589 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4590 {
4591#ifdef VBOX_WITH_PGM_NEM_MODE
4592 if (pVM->pgm.s.fNemMode)
4593 pVM->pgm.s.cPrivatePages += cGuestPages;
4594 else
4595#endif
4596 pVM->pgm.s.cZeroPages += cGuestPages;
4597 pVM->pgm.s.cAllPages += cGuestPages;
4598 }
4599
4600 /*
4601 * Insert the ROM range, tell REM and return successfully.
4602 */
4603 pRomNew->pNextR3 = pRom;
4604 pRomNew->pNextR0 = pRom ? pRom->pSelfR0 : NIL_RTR0PTR;
4605
4606 if (pRomPrev)
4607 {
4608 pRomPrev->pNextR3 = pRomNew;
4609 pRomPrev->pNextR0 = pRomNew->pSelfR0;
4610 }
4611 else
4612 {
4613 pVM->pgm.s.pRomRangesR3 = pRomNew;
4614 pVM->pgm.s.pRomRangesR0 = pRomNew->pSelfR0;
4615 }
4616
4617 pgmPhysInvalidatePageMapTLB(pVM);
4618#ifdef VBOX_WITH_PGM_NEM_MODE
4619 if (!pVM->pgm.s.fNemMode)
4620#endif
4621 GMMR3AllocatePagesCleanup(pReq);
4622
4623#ifdef VBOX_WITH_NATIVE_NEM
4624 /*
4625 * Notify NEM again.
4626 */
4627 if (VM_IS_NEM_ENABLED(pVM))
4628 {
4629 u2NemState = UINT8_MAX;
4630 rc = NEMR3NotifyPhysRomRegisterLate(pVM, GCPhys, cb, PGM_RAMRANGE_CALC_PAGE_R3PTR(pRamNew, GCPhys),
4631 fNemNotify, &u2NemState,
4632 fRamExists ? &pRam->uNemRange : &pRamNew->uNemRange);
4633 if (u2NemState != UINT8_MAX)
4634 pgmPhysSetNemStateForPages(&pRamNew->aPages[idxFirstRamPage], cGuestPages, u2NemState);
4635 if (RT_SUCCESS(rc))
4636 return rc;
4637 }
4638 else
4639#endif
4640 return rc;
4641
4642 /*
4643 * bail out
4644 */
4645#ifdef VBOX_WITH_NATIVE_NEM
4646 /* unlink */
4647 if (pRomPrev)
4648 {
4649 pRomPrev->pNextR3 = pRom;
4650 pRomPrev->pNextR0 = pRom ? pRom->pSelfR0 : NIL_RTR0PTR;
4651 }
4652 else
4653 {
4654 pVM->pgm.s.pRomRangesR3 = pRom;
4655 pVM->pgm.s.pRomRangesR0 = pRom ? pRom->pSelfR0 : NIL_RTR0PTR;
4656 }
4657
4658 if (fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4659 {
4660# ifdef VBOX_WITH_PGM_NEM_MODE
4661 if (pVM->pgm.s.fNemMode)
4662 pVM->pgm.s.cPrivatePages -= cGuestPages;
4663 else
4664# endif
4665 pVM->pgm.s.cZeroPages -= cGuestPages;
4666 pVM->pgm.s.cAllPages -= cGuestPages;
4667 }
4668#endif
4669 }
4670 else
4671 rc = VERR_NO_MEMORY;
4672 }
4673
4674 int rc2 = PGMHandlerPhysicalDeregister(pVM, GCPhys);
4675 AssertRC(rc2);
4676 }
4677
4678 if (!fRamExists)
4679 pgmR3PhysUnlinkRamRange2(pVM, pRamNew, pRamPrev);
4680 else
4681 {
4682 PPGMPAGE pRamPage = &pRam->aPages[idxFirstRamPage];
4683#ifdef VBOX_WITH_PGM_NEM_MODE
4684 if (pVM->pgm.s.fNemMode)
4685 {
4686 Assert(pvRam == NULL); Assert(pReq == NULL);
4687 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++, pRomPage++)
4688 {
4689 Assert(PGM_PAGE_GET_HCPHYS(pRamPage) == UINT64_C(0x0000fffffffff000));
4690 Assert(PGM_PAGE_GET_PAGEID(pRamPage) == NIL_GMM_PAGEID);
4691 Assert(PGM_PAGE_GET_STATE(pRamPage) == PGM_PAGE_STATE_ALLOCATED);
4692 PGM_PAGE_SET_TYPE(pVM, pRamPage, PGMPAGETYPE_RAM);
4693 PGM_PAGE_SET_STATE(pVM, pRamPage, PGM_PAGE_STATE_ALLOCATED);
4694 }
4695 }
4696 else
4697#endif
4698 {
4699 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++, pRamPage++)
4700 PGM_PAGE_INIT_ZERO(pRamPage, pVM, PGMPAGETYPE_RAM);
4701 pVM->pgm.s.cZeroPages += cGuestPages;
4702 pVM->pgm.s.cPrivatePages -= cGuestPages;
4703 }
4704 }
4705
4706 SUPR3PageFreeEx(pRomNew, cRangePages);
4707 }
4708
4709 /** @todo Purge the mapping cache or something... */
4710#ifdef VBOX_WITH_PGM_NEM_MODE
4711 if (pVM->pgm.s.fNemMode)
4712 {
4713 Assert(!pReq);
4714 if (pvRam)
4715 SUPR3PageFree(pvRam, cHostPages);
4716 if (pvAlt)
4717 SUPR3PageFree(pvAlt, cHostPages);
4718 }
4719 else
4720#endif
4721 {
4722 GMMR3FreeAllocatedPages(pVM, pReq);
4723 GMMR3AllocatePagesCleanup(pReq);
4724 }
4725 return rc;
4726}
4727
4728
4729/**
4730 * Registers a ROM image.
4731 *
4732 * Shadowed ROM images requires double the amount of backing memory, so,
4733 * don't use that unless you have to. Shadowing of ROM images is process
4734 * where we can select where the reads go and where the writes go. On real
4735 * hardware the chipset provides means to configure this. We provide
4736 * PGMR3PhysProtectROM() for this purpose.
4737 *
4738 * A read-only copy of the ROM image will always be kept around while we
4739 * will allocate RAM pages for the changes on demand (unless all memory
4740 * is configured to be preallocated).
4741 *
4742 * @returns VBox status code.
4743 * @param pVM The cross context VM structure.
4744 * @param pDevIns The device instance owning the ROM.
4745 * @param GCPhys First physical address in the range.
4746 * Must be page aligned!
4747 * @param cb The size of the range (in bytes).
4748 * Must be page aligned!
4749 * @param pvBinary Pointer to the binary data backing the ROM image.
4750 * @param cbBinary The size of the binary data pvBinary points to.
4751 * This must be less or equal to @a cb.
4752 * @param fFlags Mask of flags, PGMPHYS_ROM_FLAGS_XXX.
4753 * @param pszDesc Pointer to description string. This must not be freed.
4754 *
4755 * @remark There is no way to remove the rom, automatically on device cleanup or
4756 * manually from the device yet. This isn't difficult in any way, it's
4757 * just not something we expect to be necessary for a while.
4758 */
4759VMMR3DECL(int) PGMR3PhysRomRegister(PVM pVM, PPDMDEVINS pDevIns, RTGCPHYS GCPhys, RTGCPHYS cb,
4760 const void *pvBinary, uint32_t cbBinary, uint8_t fFlags, const char *pszDesc)
4761{
4762 Log(("PGMR3PhysRomRegister: pDevIns=%p GCPhys=%RGp(-%RGp) cb=%RGp pvBinary=%p cbBinary=%#x fFlags=%#x pszDesc=%s\n",
4763 pDevIns, GCPhys, GCPhys + cb, cb, pvBinary, cbBinary, fFlags, pszDesc));
4764 PGM_LOCK_VOID(pVM);
4765 int rc = pgmR3PhysRomRegisterLocked(pVM, pDevIns, GCPhys, cb, pvBinary, cbBinary, fFlags, pszDesc);
4766 PGM_UNLOCK(pVM);
4767 return rc;
4768}
4769
4770
4771/**
4772 * Called by PGMR3MemSetup to reset the shadow, switch to the virgin, and verify
4773 * that the virgin part is untouched.
4774 *
4775 * This is done after the normal memory has been cleared.
4776 *
4777 * ASSUMES that the caller owns the PGM lock.
4778 *
4779 * @param pVM The cross context VM structure.
4780 */
4781int pgmR3PhysRomReset(PVM pVM)
4782{
4783 PGM_LOCK_ASSERT_OWNER(pVM);
4784 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4785 {
4786 const uint32_t cGuestPages = pRom->cb >> GUEST_PAGE_SHIFT;
4787
4788 if (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED)
4789 {
4790 /*
4791 * Reset the physical handler.
4792 */
4793 int rc = PGMR3PhysRomProtect(pVM, pRom->GCPhys, pRom->cb, PGMROMPROT_READ_ROM_WRITE_IGNORE);
4794 AssertRCReturn(rc, rc);
4795
4796 /*
4797 * What we do with the shadow pages depends on the memory
4798 * preallocation option. If not enabled, we'll just throw
4799 * out all the dirty pages and replace them by the zero page.
4800 */
4801#ifdef VBOX_WITH_PGM_NEM_MODE
4802 if (pVM->pgm.s.fNemMode)
4803 {
4804 /* Clear all the shadow pages (currently using alternate backing). */
4805 RT_BZERO(pRom->pbR3Alternate, pRom->cb);
4806 }
4807 else
4808#endif
4809 if (!pVM->pgm.s.fRamPreAlloc)
4810 {
4811 /* Free the dirty pages. */
4812 uint32_t cPendingPages = 0;
4813 PGMMFREEPAGESREQ pReq;
4814 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
4815 AssertRCReturn(rc, rc);
4816
4817 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++)
4818 if ( !PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow)
4819 && !PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow))
4820 {
4821 Assert(PGM_PAGE_GET_STATE(&pRom->aPages[iPage].Shadow) == PGM_PAGE_STATE_ALLOCATED);
4822 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, &pRom->aPages[iPage].Shadow,
4823 pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT),
4824 (PGMPAGETYPE)PGM_PAGE_GET_TYPE(&pRom->aPages[iPage].Shadow));
4825 AssertLogRelRCReturn(rc, rc);
4826 }
4827
4828 if (cPendingPages)
4829 {
4830 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
4831 AssertLogRelRCReturn(rc, rc);
4832 }
4833 GMMR3FreePagesCleanup(pReq);
4834 }
4835 else
4836 {
4837 /* clear all the shadow pages. */
4838 for (uint32_t iPage = 0; iPage < cGuestPages; iPage++)
4839 {
4840 if (PGM_PAGE_IS_ZERO(&pRom->aPages[iPage].Shadow))
4841 continue;
4842 Assert(!PGM_PAGE_IS_BALLOONED(&pRom->aPages[iPage].Shadow));
4843 void *pvDstPage;
4844 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT);
4845 rc = pgmPhysPageMakeWritableAndMap(pVM, &pRom->aPages[iPage].Shadow, GCPhys, &pvDstPage);
4846 if (RT_FAILURE(rc))
4847 break;
4848 RT_BZERO(pvDstPage, GUEST_PAGE_SIZE);
4849 }
4850 AssertRCReturn(rc, rc);
4851 }
4852 }
4853
4854 /*
4855 * Restore the original ROM pages after a saved state load.
4856 * Also, in strict builds check that ROM pages remain unmodified.
4857 */
4858#ifndef VBOX_STRICT
4859 if (pVM->pgm.s.fRestoreRomPagesOnReset)
4860#endif
4861 {
4862 size_t cbSrcLeft = pRom->cbOriginal;
4863 uint8_t const *pbSrcPage = (uint8_t const *)pRom->pvOriginal;
4864 uint32_t cRestored = 0;
4865 for (uint32_t iPage = 0; iPage < cGuestPages && cbSrcLeft > 0; iPage++, pbSrcPage += GUEST_PAGE_SIZE)
4866 {
4867 const RTGCPHYS GCPhys = pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT);
4868 PPGMPAGE const pPage = pgmPhysGetPage(pVM, GCPhys);
4869 void const *pvDstPage = NULL;
4870 int rc = pgmPhysPageMapReadOnly(pVM, pPage, GCPhys, &pvDstPage);
4871 if (RT_FAILURE(rc))
4872 break;
4873
4874 if (memcmp(pvDstPage, pbSrcPage, RT_MIN(cbSrcLeft, GUEST_PAGE_SIZE)))
4875 {
4876 if (pVM->pgm.s.fRestoreRomPagesOnReset)
4877 {
4878 void *pvDstPageW = NULL;
4879 rc = pgmPhysPageMap(pVM, pPage, GCPhys, &pvDstPageW);
4880 AssertLogRelRCReturn(rc, rc);
4881 memcpy(pvDstPageW, pbSrcPage, RT_MIN(cbSrcLeft, GUEST_PAGE_SIZE));
4882 cRestored++;
4883 }
4884 else
4885 LogRel(("pgmR3PhysRomReset: %RGp: ROM page changed (%s)\n", GCPhys, pRom->pszDesc));
4886 }
4887 cbSrcLeft -= RT_MIN(cbSrcLeft, GUEST_PAGE_SIZE);
4888 }
4889 if (cRestored > 0)
4890 LogRel(("PGM: ROM \"%s\": Reloaded %u of %u pages.\n", pRom->pszDesc, cRestored, cGuestPages));
4891 }
4892 }
4893
4894 /* Clear the ROM restore flag now as we only need to do this once after
4895 loading saved state. */
4896 pVM->pgm.s.fRestoreRomPagesOnReset = false;
4897
4898 return VINF_SUCCESS;
4899}
4900
4901
4902/**
4903 * Called by PGMR3Term to free resources.
4904 *
4905 * ASSUMES that the caller owns the PGM lock.
4906 *
4907 * @param pVM The cross context VM structure.
4908 */
4909void pgmR3PhysRomTerm(PVM pVM)
4910{
4911 /*
4912 * Free the heap copy of the original bits.
4913 */
4914 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4915 {
4916 if ( pRom->pvOriginal
4917 && !(pRom->fFlags & PGMPHYS_ROM_FLAGS_PERMANENT_BINARY))
4918 {
4919 RTMemFree((void *)pRom->pvOriginal);
4920 pRom->pvOriginal = NULL;
4921 }
4922 }
4923}
4924
4925
4926/**
4927 * Change the shadowing of a range of ROM pages.
4928 *
4929 * This is intended for implementing chipset specific memory registers
4930 * and will not be very strict about the input. It will silently ignore
4931 * any pages that are not the part of a shadowed ROM.
4932 *
4933 * @returns VBox status code.
4934 * @retval VINF_PGM_SYNC_CR3
4935 *
4936 * @param pVM The cross context VM structure.
4937 * @param GCPhys Where to start. Page aligned.
4938 * @param cb How much to change. Page aligned.
4939 * @param enmProt The new ROM protection.
4940 */
4941VMMR3DECL(int) PGMR3PhysRomProtect(PVM pVM, RTGCPHYS GCPhys, RTGCPHYS cb, PGMROMPROT enmProt)
4942{
4943 /*
4944 * Check input
4945 */
4946 if (!cb)
4947 return VINF_SUCCESS;
4948 AssertReturn(!(GCPhys & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
4949 AssertReturn(!(cb & GUEST_PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
4950 RTGCPHYS GCPhysLast = GCPhys + (cb - 1);
4951 AssertReturn(GCPhysLast > GCPhys, VERR_INVALID_PARAMETER);
4952 AssertReturn(enmProt >= PGMROMPROT_INVALID && enmProt <= PGMROMPROT_END, VERR_INVALID_PARAMETER);
4953
4954 /*
4955 * Process the request.
4956 */
4957 PGM_LOCK_VOID(pVM);
4958 int rc = VINF_SUCCESS;
4959 bool fFlushTLB = false;
4960 for (PPGMROMRANGE pRom = pVM->pgm.s.pRomRangesR3; pRom; pRom = pRom->pNextR3)
4961 {
4962 if ( GCPhys <= pRom->GCPhysLast
4963 && GCPhysLast >= pRom->GCPhys
4964 && (pRom->fFlags & PGMPHYS_ROM_FLAGS_SHADOWED))
4965 {
4966 /*
4967 * Iterate the relevant pages and make necessary the changes.
4968 */
4969#ifdef VBOX_WITH_NATIVE_NEM
4970 PPGMRAMRANGE const pRam = pgmPhysGetRange(pVM, GCPhys);
4971 AssertPtrReturn(pRam, VERR_INTERNAL_ERROR_3);
4972#endif
4973 bool fChanges = false;
4974 uint32_t const cPages = pRom->GCPhysLast <= GCPhysLast
4975 ? pRom->cb >> GUEST_PAGE_SHIFT
4976 : (GCPhysLast - pRom->GCPhys + 1) >> GUEST_PAGE_SHIFT;
4977 for (uint32_t iPage = (GCPhys - pRom->GCPhys) >> GUEST_PAGE_SHIFT;
4978 iPage < cPages;
4979 iPage++)
4980 {
4981 PPGMROMPAGE pRomPage = &pRom->aPages[iPage];
4982 if (PGMROMPROT_IS_ROM(pRomPage->enmProt) != PGMROMPROT_IS_ROM(enmProt))
4983 {
4984 fChanges = true;
4985
4986 /* flush references to the page. */
4987 RTGCPHYS const GCPhysPage = pRom->GCPhys + (iPage << GUEST_PAGE_SHIFT);
4988 PPGMPAGE pRamPage = pgmPhysGetPage(pVM, GCPhysPage);
4989 int rc2 = pgmPoolTrackUpdateGCPhys(pVM, GCPhysPage, pRamPage, true /*fFlushPTEs*/, &fFlushTLB);
4990 if (rc2 != VINF_SUCCESS && (rc == VINF_SUCCESS || RT_FAILURE(rc2)))
4991 rc = rc2;
4992#ifdef VBOX_WITH_NATIVE_NEM
4993 uint8_t u2State = PGM_PAGE_GET_NEM_STATE(pRamPage);
4994#endif
4995
4996 PPGMPAGE pOld = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Virgin : &pRomPage->Shadow;
4997 PPGMPAGE pNew = PGMROMPROT_IS_ROM(pRomPage->enmProt) ? &pRomPage->Shadow : &pRomPage->Virgin;
4998
4999 *pOld = *pRamPage;
5000 *pRamPage = *pNew;
5001 /** @todo preserve the volatile flags (handlers) when these have been moved out of HCPhys! */
5002
5003#ifdef VBOX_WITH_NATIVE_NEM
5004# ifdef VBOX_WITH_PGM_NEM_MODE
5005 /* In simplified mode we have to switch the page data around too. */
5006 if (pVM->pgm.s.fNemMode)
5007 {
5008 uint8_t abPage[GUEST_PAGE_SIZE];
5009 uint8_t * const pbRamPage = PGM_RAMRANGE_CALC_PAGE_R3PTR(pRam, GCPhysPage);
5010 memcpy(abPage, &pRom->pbR3Alternate[(size_t)iPage << GUEST_PAGE_SHIFT], sizeof(abPage));
5011 memcpy(&pRom->pbR3Alternate[(size_t)iPage << GUEST_PAGE_SHIFT], pbRamPage, sizeof(abPage));
5012 memcpy(pbRamPage, abPage, sizeof(abPage));
5013 }
5014# endif
5015 /* Tell NEM about the backing and protection change. */
5016 if (VM_IS_NEM_ENABLED(pVM))
5017 {
5018 PGMPAGETYPE enmType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pNew);
5019 NEMHCNotifyPhysPageChanged(pVM, GCPhys, PGM_PAGE_GET_HCPHYS(pOld), PGM_PAGE_GET_HCPHYS(pNew),
5020 PGM_RAMRANGE_CALC_PAGE_R3PTR(pRam, GCPhysPage),
5021 pgmPhysPageCalcNemProtection(pRamPage, enmType), enmType, &u2State);
5022 PGM_PAGE_SET_NEM_STATE(pRamPage, u2State);
5023 }
5024#endif
5025 }
5026 pRomPage->enmProt = enmProt;
5027 }
5028
5029 /*
5030 * Reset the access handler if we made changes, no need
5031 * to optimize this.
5032 */
5033 if (fChanges)
5034 {
5035 int rc2 = PGMHandlerPhysicalReset(pVM, pRom->GCPhys);
5036 if (RT_FAILURE(rc2))
5037 {
5038 PGM_UNLOCK(pVM);
5039 AssertRC(rc);
5040 return rc2;
5041 }
5042 }
5043
5044 /* Advance - cb isn't updated. */
5045 GCPhys = pRom->GCPhys + (cPages << GUEST_PAGE_SHIFT);
5046 }
5047 }
5048 PGM_UNLOCK(pVM);
5049 if (fFlushTLB)
5050 PGM_INVL_ALL_VCPU_TLBS(pVM);
5051
5052 return rc;
5053}
5054
5055
5056
5057/*********************************************************************************************************************************
5058* Ballooning *
5059*********************************************************************************************************************************/
5060
5061#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
5062
5063/**
5064 * Rendezvous callback used by PGMR3ChangeMemBalloon that changes the memory balloon size
5065 *
5066 * This is only called on one of the EMTs while the other ones are waiting for
5067 * it to complete this function.
5068 *
5069 * @returns VINF_SUCCESS (VBox strict status code).
5070 * @param pVM The cross context VM structure.
5071 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
5072 * @param pvUser User parameter
5073 */
5074static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysChangeMemBalloonRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
5075{
5076 uintptr_t *paUser = (uintptr_t *)pvUser;
5077 bool fInflate = !!paUser[0];
5078 unsigned cPages = paUser[1];
5079 RTGCPHYS *paPhysPage = (RTGCPHYS *)paUser[2];
5080 uint32_t cPendingPages = 0;
5081 PGMMFREEPAGESREQ pReq;
5082 int rc;
5083
5084 Log(("pgmR3PhysChangeMemBalloonRendezvous: %s %x pages\n", (fInflate) ? "inflate" : "deflate", cPages));
5085 PGM_LOCK_VOID(pVM);
5086
5087 if (fInflate)
5088 {
5089 /* Flush the PGM pool cache as we might have stale references to pages that we just freed. */
5090 pgmR3PoolClearAllRendezvous(pVM, pVCpu, NULL);
5091
5092 /* Replace pages with ZERO pages. */
5093 rc = GMMR3FreePagesPrepare(pVM, &pReq, PGMPHYS_FREE_PAGE_BATCH_SIZE, GMMACCOUNT_BASE);
5094 if (RT_FAILURE(rc))
5095 {
5096 PGM_UNLOCK(pVM);
5097 AssertLogRelRC(rc);
5098 return rc;
5099 }
5100
5101 /* Iterate the pages. */
5102 for (unsigned i = 0; i < cPages; i++)
5103 {
5104 PPGMPAGE pPage = pgmPhysGetPage(pVM, paPhysPage[i]);
5105 if ( pPage == NULL
5106 || PGM_PAGE_GET_TYPE(pPage) != PGMPAGETYPE_RAM)
5107 {
5108 Log(("pgmR3PhysChangeMemBalloonRendezvous: invalid physical page %RGp pPage->u3Type=%d\n", paPhysPage[i], pPage ? PGM_PAGE_GET_TYPE(pPage) : 0));
5109 break;
5110 }
5111
5112 LogFlow(("balloon page: %RGp\n", paPhysPage[i]));
5113
5114 /* Flush the shadow PT if this page was previously used as a guest page table. */
5115 pgmPoolFlushPageByGCPhys(pVM, paPhysPage[i]);
5116
5117 rc = pgmPhysFreePage(pVM, pReq, &cPendingPages, pPage, paPhysPage[i], (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage));
5118 if (RT_FAILURE(rc))
5119 {
5120 PGM_UNLOCK(pVM);
5121 AssertLogRelRC(rc);
5122 return rc;
5123 }
5124 Assert(PGM_PAGE_IS_ZERO(pPage));
5125 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_BALLOONED);
5126 }
5127
5128 if (cPendingPages)
5129 {
5130 rc = GMMR3FreePagesPerform(pVM, pReq, cPendingPages);
5131 if (RT_FAILURE(rc))
5132 {
5133 PGM_UNLOCK(pVM);
5134 AssertLogRelRC(rc);
5135 return rc;
5136 }
5137 }
5138 GMMR3FreePagesCleanup(pReq);
5139 }
5140 else
5141 {
5142 /* Iterate the pages. */
5143 for (unsigned i = 0; i < cPages; i++)
5144 {
5145 PPGMPAGE pPage = pgmPhysGetPage(pVM, paPhysPage[i]);
5146 AssertBreak(pPage && PGM_PAGE_GET_TYPE(pPage) == PGMPAGETYPE_RAM);
5147
5148 LogFlow(("Free ballooned page: %RGp\n", paPhysPage[i]));
5149
5150 Assert(PGM_PAGE_IS_BALLOONED(pPage));
5151
5152 /* Change back to zero page. (NEM does not need to be informed.) */
5153 PGM_PAGE_SET_STATE(pVM, pPage, PGM_PAGE_STATE_ZERO);
5154 }
5155
5156 /* Note that we currently do not map any ballooned pages in our shadow page tables, so no need to flush the pgm pool. */
5157 }
5158
5159 /* Notify GMM about the balloon change. */
5160 rc = GMMR3BalloonedPages(pVM, (fInflate) ? GMMBALLOONACTION_INFLATE : GMMBALLOONACTION_DEFLATE, cPages);
5161 if (RT_SUCCESS(rc))
5162 {
5163 if (!fInflate)
5164 {
5165 Assert(pVM->pgm.s.cBalloonedPages >= cPages);
5166 pVM->pgm.s.cBalloonedPages -= cPages;
5167 }
5168 else
5169 pVM->pgm.s.cBalloonedPages += cPages;
5170 }
5171
5172 PGM_UNLOCK(pVM);
5173
5174 /* Flush the recompiler's TLB as well. */
5175 for (VMCPUID i = 0; i < pVM->cCpus; i++)
5176 CPUMSetChangedFlags(pVM->apCpusR3[i], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5177
5178 AssertLogRelRC(rc);
5179 return rc;
5180}
5181
5182
5183/**
5184 * Frees a range of ram pages, replacing them with ZERO pages; helper for PGMR3PhysFreeRamPages
5185 *
5186 * @returns VBox status code.
5187 * @param pVM The cross context VM structure.
5188 * @param fInflate Inflate or deflate memory balloon
5189 * @param cPages Number of pages to free
5190 * @param paPhysPage Array of guest physical addresses
5191 */
5192static DECLCALLBACK(void) pgmR3PhysChangeMemBalloonHelper(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
5193{
5194 uintptr_t paUser[3];
5195
5196 paUser[0] = fInflate;
5197 paUser[1] = cPages;
5198 paUser[2] = (uintptr_t)paPhysPage;
5199 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
5200 AssertRC(rc);
5201
5202 /* Made a copy in PGMR3PhysFreeRamPages; free it here. */
5203 RTMemFree(paPhysPage);
5204}
5205
5206#endif /* 64-bit host && (Windows || Solaris || Linux || FreeBSD) */
5207
5208/**
5209 * Inflate or deflate a memory balloon
5210 *
5211 * @returns VBox status code.
5212 * @param pVM The cross context VM structure.
5213 * @param fInflate Inflate or deflate memory balloon
5214 * @param cPages Number of pages to free
5215 * @param paPhysPage Array of guest physical addresses
5216 */
5217VMMR3DECL(int) PGMR3PhysChangeMemBalloon(PVM pVM, bool fInflate, unsigned cPages, RTGCPHYS *paPhysPage)
5218{
5219 /* This must match GMMR0Init; currently we only support memory ballooning on all 64-bit hosts except Mac OS X */
5220#if HC_ARCH_BITS == 64 && (defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
5221 int rc;
5222
5223 /* Older additions (ancient non-functioning balloon code) pass wrong physical addresses. */
5224 AssertReturn(!(paPhysPage[0] & 0xfff), VERR_INVALID_PARAMETER);
5225
5226 /* We own the IOM lock here and could cause a deadlock by waiting for another VCPU that is blocking on the IOM lock.
5227 * In the SMP case we post a request packet to postpone the job.
5228 */
5229 if (pVM->cCpus > 1)
5230 {
5231 unsigned cbPhysPage = cPages * sizeof(paPhysPage[0]);
5232 RTGCPHYS *paPhysPageCopy = (RTGCPHYS *)RTMemAlloc(cbPhysPage);
5233 AssertReturn(paPhysPageCopy, VERR_NO_MEMORY);
5234
5235 memcpy(paPhysPageCopy, paPhysPage, cbPhysPage);
5236
5237 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysChangeMemBalloonHelper, 4, pVM, fInflate, cPages, paPhysPageCopy);
5238 AssertRC(rc);
5239 }
5240 else
5241 {
5242 uintptr_t paUser[3];
5243
5244 paUser[0] = fInflate;
5245 paUser[1] = cPages;
5246 paUser[2] = (uintptr_t)paPhysPage;
5247 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysChangeMemBalloonRendezvous, (void *)paUser);
5248 AssertRC(rc);
5249 }
5250 return rc;
5251
5252#else
5253 NOREF(pVM); NOREF(fInflate); NOREF(cPages); NOREF(paPhysPage);
5254 return VERR_NOT_IMPLEMENTED;
5255#endif
5256}
5257
5258
5259/*********************************************************************************************************************************
5260* Write Monitoring *
5261*********************************************************************************************************************************/
5262
5263/**
5264 * Rendezvous callback used by PGMR3WriteProtectRAM that write protects all
5265 * physical RAM.
5266 *
5267 * This is only called on one of the EMTs while the other ones are waiting for
5268 * it to complete this function.
5269 *
5270 * @returns VINF_SUCCESS (VBox strict status code).
5271 * @param pVM The cross context VM structure.
5272 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
5273 * @param pvUser User parameter, unused.
5274 */
5275static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysWriteProtectRAMRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
5276{
5277 int rc = VINF_SUCCESS;
5278 NOREF(pvUser); NOREF(pVCpu);
5279
5280 PGM_LOCK_VOID(pVM);
5281#ifdef PGMPOOL_WITH_OPTIMIZED_DIRTY_PT
5282 pgmPoolResetDirtyPages(pVM);
5283#endif
5284
5285 /** @todo pointless to write protect the physical page pointed to by RSP. */
5286
5287 for (PPGMRAMRANGE pRam = pVM->pgm.s.CTX_SUFF(pRamRangesX);
5288 pRam;
5289 pRam = pRam->CTX_SUFF(pNext))
5290 {
5291 uint32_t cPages = pRam->cb >> GUEST_PAGE_SHIFT;
5292 for (uint32_t iPage = 0; iPage < cPages; iPage++)
5293 {
5294 PPGMPAGE pPage = &pRam->aPages[iPage];
5295 PGMPAGETYPE enmPageType = (PGMPAGETYPE)PGM_PAGE_GET_TYPE(pPage);
5296
5297 if ( RT_LIKELY(enmPageType == PGMPAGETYPE_RAM)
5298 || enmPageType == PGMPAGETYPE_MMIO2)
5299 {
5300 /*
5301 * A RAM page.
5302 */
5303 switch (PGM_PAGE_GET_STATE(pPage))
5304 {
5305 case PGM_PAGE_STATE_ALLOCATED:
5306 /** @todo Optimize this: Don't always re-enable write
5307 * monitoring if the page is known to be very busy. */
5308 if (PGM_PAGE_IS_WRITTEN_TO(pPage))
5309 PGM_PAGE_CLEAR_WRITTEN_TO(pVM, pPage);
5310
5311 pgmPhysPageWriteMonitor(pVM, pPage, pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT));
5312 break;
5313
5314 case PGM_PAGE_STATE_SHARED:
5315 AssertFailed();
5316 break;
5317
5318 case PGM_PAGE_STATE_WRITE_MONITORED: /* nothing to change. */
5319 default:
5320 break;
5321 }
5322 }
5323 }
5324 }
5325 pgmR3PoolWriteProtectPages(pVM);
5326 PGM_INVL_ALL_VCPU_TLBS(pVM);
5327 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
5328 CPUMSetChangedFlags(pVM->apCpusR3[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5329
5330 PGM_UNLOCK(pVM);
5331 return rc;
5332}
5333
5334/**
5335 * Protect all physical RAM to monitor writes
5336 *
5337 * @returns VBox status code.
5338 * @param pVM The cross context VM structure.
5339 */
5340VMMR3DECL(int) PGMR3PhysWriteProtectRAM(PVM pVM)
5341{
5342 VM_ASSERT_EMT_RETURN(pVM, VERR_VM_THREAD_NOT_EMT);
5343
5344 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysWriteProtectRAMRendezvous, NULL);
5345 AssertRC(rc);
5346 return rc;
5347}
5348
5349
5350/*********************************************************************************************************************************
5351* Stats. *
5352*********************************************************************************************************************************/
5353
5354/**
5355 * Query the amount of free memory inside VMMR0
5356 *
5357 * @returns VBox status code.
5358 * @param pUVM The user mode VM handle.
5359 * @param pcbAllocMem Where to return the amount of memory allocated
5360 * by VMs.
5361 * @param pcbFreeMem Where to return the amount of memory that is
5362 * allocated from the host but not currently used
5363 * by any VMs.
5364 * @param pcbBallonedMem Where to return the sum of memory that is
5365 * currently ballooned by the VMs.
5366 * @param pcbSharedMem Where to return the amount of memory that is
5367 * currently shared.
5368 */
5369VMMR3DECL(int) PGMR3QueryGlobalMemoryStats(PUVM pUVM, uint64_t *pcbAllocMem, uint64_t *pcbFreeMem,
5370 uint64_t *pcbBallonedMem, uint64_t *pcbSharedMem)
5371{
5372 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
5373 VM_ASSERT_VALID_EXT_RETURN(pUVM->pVM, VERR_INVALID_VM_HANDLE);
5374
5375 uint64_t cAllocPages = 0;
5376 uint64_t cFreePages = 0;
5377 uint64_t cBalloonPages = 0;
5378 uint64_t cSharedPages = 0;
5379 if (!SUPR3IsDriverless())
5380 {
5381 int rc = GMMR3QueryHypervisorMemoryStats(pUVM->pVM, &cAllocPages, &cFreePages, &cBalloonPages, &cSharedPages);
5382 AssertRCReturn(rc, rc);
5383 }
5384
5385 if (pcbAllocMem)
5386 *pcbAllocMem = cAllocPages * _4K;
5387
5388 if (pcbFreeMem)
5389 *pcbFreeMem = cFreePages * _4K;
5390
5391 if (pcbBallonedMem)
5392 *pcbBallonedMem = cBalloonPages * _4K;
5393
5394 if (pcbSharedMem)
5395 *pcbSharedMem = cSharedPages * _4K;
5396
5397 Log(("PGMR3QueryVMMMemoryStats: all=%llx free=%llx ballooned=%llx shared=%llx\n",
5398 cAllocPages, cFreePages, cBalloonPages, cSharedPages));
5399 return VINF_SUCCESS;
5400}
5401
5402
5403/**
5404 * Query memory stats for the VM.
5405 *
5406 * @returns VBox status code.
5407 * @param pUVM The user mode VM handle.
5408 * @param pcbTotalMem Where to return total amount memory the VM may
5409 * possibly use.
5410 * @param pcbPrivateMem Where to return the amount of private memory
5411 * currently allocated.
5412 * @param pcbSharedMem Where to return the amount of actually shared
5413 * memory currently used by the VM.
5414 * @param pcbZeroMem Where to return the amount of memory backed by
5415 * zero pages.
5416 *
5417 * @remarks The total mem is normally larger than the sum of the three
5418 * components. There are two reasons for this, first the amount of
5419 * shared memory is what we're sure is shared instead of what could
5420 * possibly be shared with someone. Secondly, because the total may
5421 * include some pure MMIO pages that doesn't go into any of the three
5422 * sub-counts.
5423 *
5424 * @todo Why do we return reused shared pages instead of anything that could
5425 * potentially be shared? Doesn't this mean the first VM gets a much
5426 * lower number of shared pages?
5427 */
5428VMMR3DECL(int) PGMR3QueryMemoryStats(PUVM pUVM, uint64_t *pcbTotalMem, uint64_t *pcbPrivateMem,
5429 uint64_t *pcbSharedMem, uint64_t *pcbZeroMem)
5430{
5431 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
5432 PVM pVM = pUVM->pVM;
5433 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
5434
5435 if (pcbTotalMem)
5436 *pcbTotalMem = (uint64_t)pVM->pgm.s.cAllPages * GUEST_PAGE_SIZE;
5437
5438 if (pcbPrivateMem)
5439 *pcbPrivateMem = (uint64_t)pVM->pgm.s.cPrivatePages * GUEST_PAGE_SIZE;
5440
5441 if (pcbSharedMem)
5442 *pcbSharedMem = (uint64_t)pVM->pgm.s.cReusedSharedPages * GUEST_PAGE_SIZE;
5443
5444 if (pcbZeroMem)
5445 *pcbZeroMem = (uint64_t)pVM->pgm.s.cZeroPages * GUEST_PAGE_SIZE;
5446
5447 Log(("PGMR3QueryMemoryStats: all=%x private=%x reused=%x zero=%x\n", pVM->pgm.s.cAllPages, pVM->pgm.s.cPrivatePages, pVM->pgm.s.cReusedSharedPages, pVM->pgm.s.cZeroPages));
5448 return VINF_SUCCESS;
5449}
5450
5451
5452
5453/*********************************************************************************************************************************
5454* Chunk Mappings and Page Allocation *
5455*********************************************************************************************************************************/
5456
5457/**
5458 * Tree enumeration callback for dealing with age rollover.
5459 * It will perform a simple compression of the current age.
5460 */
5461static DECLCALLBACK(int) pgmR3PhysChunkAgeingRolloverCallback(PAVLU32NODECORE pNode, void *pvUser)
5462{
5463 /* Age compression - ASSUMES iNow == 4. */
5464 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
5465 if (pChunk->iLastUsed >= UINT32_C(0xffffff00))
5466 pChunk->iLastUsed = 3;
5467 else if (pChunk->iLastUsed >= UINT32_C(0xfffff000))
5468 pChunk->iLastUsed = 2;
5469 else if (pChunk->iLastUsed)
5470 pChunk->iLastUsed = 1;
5471 else /* iLastUsed = 0 */
5472 pChunk->iLastUsed = 4;
5473
5474 NOREF(pvUser);
5475 return 0;
5476}
5477
5478
5479/**
5480 * The structure passed in the pvUser argument of pgmR3PhysChunkUnmapCandidateCallback().
5481 */
5482typedef struct PGMR3PHYSCHUNKUNMAPCB
5483{
5484 PVM pVM; /**< Pointer to the VM. */
5485 PPGMCHUNKR3MAP pChunk; /**< The chunk to unmap. */
5486} PGMR3PHYSCHUNKUNMAPCB, *PPGMR3PHYSCHUNKUNMAPCB;
5487
5488
5489/**
5490 * Callback used to find the mapping that's been unused for
5491 * the longest time.
5492 */
5493static DECLCALLBACK(int) pgmR3PhysChunkUnmapCandidateCallback(PAVLU32NODECORE pNode, void *pvUser)
5494{
5495 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)pNode;
5496 PPGMR3PHYSCHUNKUNMAPCB pArg = (PPGMR3PHYSCHUNKUNMAPCB)pvUser;
5497
5498 /*
5499 * Check for locks and compare when last used.
5500 */
5501 if (pChunk->cRefs)
5502 return 0;
5503 if (pChunk->cPermRefs)
5504 return 0;
5505 if ( pArg->pChunk
5506 && pChunk->iLastUsed >= pArg->pChunk->iLastUsed)
5507 return 0;
5508
5509 /*
5510 * Check that it's not in any of the TLBs.
5511 */
5512 PVM pVM = pArg->pVM;
5513 if ( pVM->pgm.s.ChunkR3Map.Tlb.aEntries[PGM_CHUNKR3MAPTLB_IDX(pChunk->Core.Key)].idChunk
5514 == pChunk->Core.Key)
5515 {
5516 pChunk = NULL;
5517 return 0;
5518 }
5519#ifdef VBOX_STRICT
5520 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
5521 {
5522 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk != pChunk);
5523 Assert(pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk != pChunk->Core.Key);
5524 }
5525#endif
5526
5527 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.PhysTlbR3.aEntries); i++)
5528 if (pVM->pgm.s.PhysTlbR3.aEntries[i].pMap == pChunk)
5529 return 0;
5530
5531 pArg->pChunk = pChunk;
5532 return 0;
5533}
5534
5535
5536/**
5537 * Finds a good candidate for unmapping when the ring-3 mapping cache is full.
5538 *
5539 * The candidate will not be part of any TLBs, so no need to flush
5540 * anything afterwards.
5541 *
5542 * @returns Chunk id.
5543 * @param pVM The cross context VM structure.
5544 */
5545static int32_t pgmR3PhysChunkFindUnmapCandidate(PVM pVM)
5546{
5547 PGM_LOCK_ASSERT_OWNER(pVM);
5548
5549 /*
5550 * Enumerate the age tree starting with the left most node.
5551 */
5552 STAM_PROFILE_START(&pVM->pgm.s.Stats.StatChunkFindCandidate, a);
5553 PGMR3PHYSCHUNKUNMAPCB Args;
5554 Args.pVM = pVM;
5555 Args.pChunk = NULL;
5556 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkUnmapCandidateCallback, &Args);
5557 Assert(Args.pChunk);
5558 if (Args.pChunk)
5559 {
5560 Assert(Args.pChunk->cRefs == 0);
5561 Assert(Args.pChunk->cPermRefs == 0);
5562 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkFindCandidate, a);
5563 return Args.pChunk->Core.Key;
5564 }
5565
5566 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkFindCandidate, a);
5567 return INT32_MAX;
5568}
5569
5570
5571/**
5572 * Rendezvous callback used by pgmR3PhysUnmapChunk that unmaps a chunk
5573 *
5574 * This is only called on one of the EMTs while the other ones are waiting for
5575 * it to complete this function.
5576 *
5577 * @returns VINF_SUCCESS (VBox strict status code).
5578 * @param pVM The cross context VM structure.
5579 * @param pVCpu The cross context virtual CPU structure of the calling EMT. Unused.
5580 * @param pvUser User pointer. Unused
5581 *
5582 */
5583static DECLCALLBACK(VBOXSTRICTRC) pgmR3PhysUnmapChunkRendezvous(PVM pVM, PVMCPU pVCpu, void *pvUser)
5584{
5585 int rc = VINF_SUCCESS;
5586 PGM_LOCK_VOID(pVM);
5587 NOREF(pVCpu); NOREF(pvUser);
5588
5589 if (pVM->pgm.s.ChunkR3Map.c >= pVM->pgm.s.ChunkR3Map.cMax)
5590 {
5591 /* Flush the pgm pool cache; call the internal rendezvous handler as we're already in a rendezvous handler here. */
5592 /** @todo also not really efficient to unmap a chunk that contains PD
5593 * or PT pages. */
5594 pgmR3PoolClearAllRendezvous(pVM, pVM->apCpusR3[0], NULL /* no need to flush the REM TLB as we already did that above */);
5595
5596 /*
5597 * Request the ring-0 part to unmap a chunk to make space in the mapping cache.
5598 */
5599 GMMMAPUNMAPCHUNKREQ Req;
5600 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
5601 Req.Hdr.cbReq = sizeof(Req);
5602 Req.pvR3 = NULL;
5603 Req.idChunkMap = NIL_GMM_CHUNKID;
5604 Req.idChunkUnmap = pgmR3PhysChunkFindUnmapCandidate(pVM);
5605 if (Req.idChunkUnmap != INT32_MAX)
5606 {
5607 STAM_PROFILE_START(&pVM->pgm.s.Stats.StatChunkUnmap, a);
5608 rc = VMMR3CallR0(pVM, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
5609 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkUnmap, a);
5610 if (RT_SUCCESS(rc))
5611 {
5612 /*
5613 * Remove the unmapped one.
5614 */
5615 PPGMCHUNKR3MAP pUnmappedChunk = (PPGMCHUNKR3MAP)RTAvlU32Remove(&pVM->pgm.s.ChunkR3Map.pTree, Req.idChunkUnmap);
5616 AssertRelease(pUnmappedChunk);
5617 AssertRelease(!pUnmappedChunk->cRefs);
5618 AssertRelease(!pUnmappedChunk->cPermRefs);
5619 pUnmappedChunk->pv = NULL;
5620 pUnmappedChunk->Core.Key = UINT32_MAX;
5621 MMR3HeapFree(pUnmappedChunk);
5622 pVM->pgm.s.ChunkR3Map.c--;
5623 pVM->pgm.s.cUnmappedChunks++;
5624
5625 /*
5626 * Flush dangling PGM pointers (R3 & R0 ptrs to GC physical addresses).
5627 */
5628 /** @todo We should not flush chunks which include cr3 mappings. */
5629 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
5630 {
5631 PPGMCPU pPGM = &pVM->apCpusR3[idCpu]->pgm.s;
5632
5633 pPGM->pGst32BitPdR3 = NULL;
5634 pPGM->pGstPaePdptR3 = NULL;
5635 pPGM->pGstAmd64Pml4R3 = NULL;
5636 pPGM->pGstEptPml4R3 = NULL;
5637 pPGM->pGst32BitPdR0 = NIL_RTR0PTR;
5638 pPGM->pGstPaePdptR0 = NIL_RTR0PTR;
5639 pPGM->pGstAmd64Pml4R0 = NIL_RTR0PTR;
5640 pPGM->pGstEptPml4R0 = NIL_RTR0PTR;
5641 for (unsigned i = 0; i < RT_ELEMENTS(pPGM->apGstPaePDsR3); i++)
5642 {
5643 pPGM->apGstPaePDsR3[i] = NULL;
5644 pPGM->apGstPaePDsR0[i] = NIL_RTR0PTR;
5645 }
5646
5647 /* Flush REM TLBs. */
5648 CPUMSetChangedFlags(pVM->apCpusR3[idCpu], CPUM_CHANGED_GLOBAL_TLB_FLUSH);
5649 }
5650 }
5651 }
5652 }
5653 PGM_UNLOCK(pVM);
5654 return rc;
5655}
5656
5657/**
5658 * Unmap a chunk to free up virtual address space (request packet handler for pgmR3PhysChunkMap)
5659 *
5660 * @returns VBox status code.
5661 * @param pVM The cross context VM structure.
5662 */
5663static DECLCALLBACK(void) pgmR3PhysUnmapChunk(PVM pVM)
5664{
5665 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, pgmR3PhysUnmapChunkRendezvous, NULL);
5666 AssertRC(rc);
5667}
5668
5669
5670/**
5671 * Maps the given chunk into the ring-3 mapping cache.
5672 *
5673 * This will call ring-0.
5674 *
5675 * @returns VBox status code.
5676 * @param pVM The cross context VM structure.
5677 * @param idChunk The chunk in question.
5678 * @param ppChunk Where to store the chunk tracking structure.
5679 *
5680 * @remarks Called from within the PGM critical section.
5681 * @remarks Can be called from any thread!
5682 */
5683int pgmR3PhysChunkMap(PVM pVM, uint32_t idChunk, PPPGMCHUNKR3MAP ppChunk)
5684{
5685 int rc;
5686
5687 PGM_LOCK_ASSERT_OWNER(pVM);
5688
5689 /*
5690 * Move the chunk time forward.
5691 */
5692 pVM->pgm.s.ChunkR3Map.iNow++;
5693 if (pVM->pgm.s.ChunkR3Map.iNow == 0)
5694 {
5695 pVM->pgm.s.ChunkR3Map.iNow = 4;
5696 RTAvlU32DoWithAll(&pVM->pgm.s.ChunkR3Map.pTree, true /*fFromLeft*/, pgmR3PhysChunkAgeingRolloverCallback, NULL);
5697 }
5698
5699 /*
5700 * Allocate a new tracking structure first.
5701 */
5702 PPGMCHUNKR3MAP pChunk = (PPGMCHUNKR3MAP)MMR3HeapAllocZ(pVM, MM_TAG_PGM_CHUNK_MAPPING, sizeof(*pChunk));
5703 AssertReturn(pChunk, VERR_NO_MEMORY);
5704 pChunk->Core.Key = idChunk;
5705 pChunk->iLastUsed = pVM->pgm.s.ChunkR3Map.iNow;
5706
5707 /*
5708 * Request the ring-0 part to map the chunk in question.
5709 */
5710 GMMMAPUNMAPCHUNKREQ Req;
5711 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
5712 Req.Hdr.cbReq = sizeof(Req);
5713 Req.pvR3 = NULL;
5714 Req.idChunkMap = idChunk;
5715 Req.idChunkUnmap = NIL_GMM_CHUNKID;
5716
5717 /* Must be callable from any thread, so can't use VMMR3CallR0. */
5718 STAM_PROFILE_START(&pVM->pgm.s.Stats.StatChunkMap, a);
5719 rc = SUPR3CallVMMR0Ex(VMCC_GET_VMR0_FOR_CALL(pVM), NIL_VMCPUID, VMMR0_DO_GMM_MAP_UNMAP_CHUNK, 0, &Req.Hdr);
5720 STAM_PROFILE_STOP(&pVM->pgm.s.Stats.StatChunkMap, a);
5721 if (RT_SUCCESS(rc))
5722 {
5723 pChunk->pv = Req.pvR3;
5724
5725 /*
5726 * If we're running out of virtual address space, then we should
5727 * unmap another chunk.
5728 *
5729 * Currently, an unmap operation requires that all other virtual CPUs
5730 * are idling and not by chance making use of the memory we're
5731 * unmapping. So, we create an async unmap operation here.
5732 *
5733 * Now, when creating or restoring a saved state this wont work very
5734 * well since we may want to restore all guest RAM + a little something.
5735 * So, we have to do the unmap synchronously. Fortunately for us
5736 * though, during these operations the other virtual CPUs are inactive
5737 * and it should be safe to do this.
5738 */
5739 /** @todo Eventually we should lock all memory when used and do
5740 * map+unmap as one kernel call without any rendezvous or
5741 * other precautions. */
5742 if (pVM->pgm.s.ChunkR3Map.c + 1 >= pVM->pgm.s.ChunkR3Map.cMax)
5743 {
5744 switch (VMR3GetState(pVM))
5745 {
5746 case VMSTATE_LOADING:
5747 case VMSTATE_SAVING:
5748 {
5749 PVMCPU pVCpu = VMMGetCpu(pVM);
5750 if ( pVCpu
5751 && pVM->pgm.s.cDeprecatedPageLocks == 0)
5752 {
5753 pgmR3PhysUnmapChunkRendezvous(pVM, pVCpu, NULL);
5754 break;
5755 }
5756 }
5757 RT_FALL_THRU();
5758 default:
5759 rc = VMR3ReqCallNoWait(pVM, VMCPUID_ANY_QUEUE, (PFNRT)pgmR3PhysUnmapChunk, 1, pVM);
5760 AssertRC(rc);
5761 break;
5762 }
5763 }
5764
5765 /*
5766 * Update the tree. We must do this after any unmapping to make sure
5767 * the chunk we're going to return isn't unmapped by accident.
5768 */
5769 AssertPtr(Req.pvR3);
5770 bool fRc = RTAvlU32Insert(&pVM->pgm.s.ChunkR3Map.pTree, &pChunk->Core);
5771 AssertRelease(fRc);
5772 pVM->pgm.s.ChunkR3Map.c++;
5773 pVM->pgm.s.cMappedChunks++;
5774 }
5775 else
5776 {
5777 /** @todo this may fail because of /proc/sys/vm/max_map_count, so we
5778 * should probably restrict ourselves on linux. */
5779 AssertRC(rc);
5780 MMR3HeapFree(pChunk);
5781 pChunk = NULL;
5782 }
5783
5784 *ppChunk = pChunk;
5785 return rc;
5786}
5787
5788
5789/**
5790 * Invalidates the TLB for the ring-3 mapping cache.
5791 *
5792 * @param pVM The cross context VM structure.
5793 */
5794VMMR3DECL(void) PGMR3PhysChunkInvalidateTLB(PVM pVM)
5795{
5796 PGM_LOCK_VOID(pVM);
5797 for (unsigned i = 0; i < RT_ELEMENTS(pVM->pgm.s.ChunkR3Map.Tlb.aEntries); i++)
5798 {
5799 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].idChunk = NIL_GMM_CHUNKID;
5800 pVM->pgm.s.ChunkR3Map.Tlb.aEntries[i].pChunk = NULL;
5801 }
5802 /* The page map TLB references chunks, so invalidate that one too. */
5803 pgmPhysInvalidatePageMapTLB(pVM);
5804 PGM_UNLOCK(pVM);
5805}
5806
5807
5808/**
5809 * Response to VM_FF_PGM_NEED_HANDY_PAGES and helper for pgmPhysEnsureHandyPage.
5810 *
5811 * This function will also work the VM_FF_PGM_NO_MEMORY force action flag, to
5812 * signal and clear the out of memory condition. When called, this API is used
5813 * to try clear the condition when the user wants to resume.
5814 *
5815 * @returns The following VBox status codes.
5816 * @retval VINF_SUCCESS on success. FFs cleared.
5817 * @retval VINF_EM_NO_MEMORY if we're out of memory. The FF is not cleared in
5818 * this case and it gets accompanied by VM_FF_PGM_NO_MEMORY.
5819 *
5820 * @param pVM The cross context VM structure.
5821 *
5822 * @remarks The VINF_EM_NO_MEMORY status is for the benefit of the FF processing
5823 * in EM.cpp and shouldn't be propagated outside TRPM, HM, EM and
5824 * pgmPhysEnsureHandyPage. There is one exception to this in the \#PF
5825 * handler.
5826 */
5827VMMR3DECL(int) PGMR3PhysAllocateHandyPages(PVM pVM)
5828{
5829 PGM_LOCK_VOID(pVM);
5830
5831 /*
5832 * Allocate more pages, noting down the index of the first new page.
5833 */
5834 uint32_t iClear = pVM->pgm.s.cHandyPages;
5835 AssertMsgReturn(iClear <= RT_ELEMENTS(pVM->pgm.s.aHandyPages), ("%d", iClear), VERR_PGM_HANDY_PAGE_IPE);
5836 Log(("PGMR3PhysAllocateHandyPages: %d -> %d\n", iClear, RT_ELEMENTS(pVM->pgm.s.aHandyPages)));
5837 int rc = VMMR3CallR0(pVM, VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES, 0, NULL);
5838 /** @todo we should split this up into an allocate and flush operation. sometimes you want to flush and not allocate more (which will trigger the vm account limit error) */
5839 if ( rc == VERR_GMM_HIT_VM_ACCOUNT_LIMIT
5840 && pVM->pgm.s.cHandyPages > 0)
5841 {
5842 /* Still handy pages left, so don't panic. */
5843 rc = VINF_SUCCESS;
5844 }
5845
5846 if (RT_SUCCESS(rc))
5847 {
5848 AssertMsg(rc == VINF_SUCCESS, ("%Rrc\n", rc));
5849 Assert(pVM->pgm.s.cHandyPages > 0);
5850#ifdef VBOX_STRICT
5851 uint32_t i;
5852 for (i = iClear; i < pVM->pgm.s.cHandyPages; i++)
5853 if ( pVM->pgm.s.aHandyPages[i].idPage == NIL_GMM_PAGEID
5854 || pVM->pgm.s.aHandyPages[i].idSharedPage != NIL_GMM_PAGEID
5855 || (pVM->pgm.s.aHandyPages[i].HCPhysGCPhys & GUEST_PAGE_OFFSET_MASK))
5856 break;
5857 if (i != pVM->pgm.s.cHandyPages)
5858 {
5859 RTAssertMsg1Weak(NULL, __LINE__, __FILE__, __FUNCTION__);
5860 RTAssertMsg2Weak("i=%d iClear=%d cHandyPages=%d\n", i, iClear, pVM->pgm.s.cHandyPages);
5861 for (uint32_t j = iClear; j < pVM->pgm.s.cHandyPages; j++)
5862 RTAssertMsg2Add("%03d: idPage=%d HCPhysGCPhys=%RHp idSharedPage=%d%s\n", j,
5863 pVM->pgm.s.aHandyPages[j].idPage,
5864 pVM->pgm.s.aHandyPages[j].HCPhysGCPhys,
5865 pVM->pgm.s.aHandyPages[j].idSharedPage,
5866 j == i ? " <---" : "");
5867 RTAssertPanic();
5868 }
5869#endif
5870 }
5871 else
5872 {
5873 /*
5874 * We should never get here unless there is a genuine shortage of
5875 * memory (or some internal error). Flag the error so the VM can be
5876 * suspended ASAP and the user informed. If we're totally out of
5877 * handy pages we will return failure.
5878 */
5879 /* Report the failure. */
5880 LogRel(("PGM: Failed to procure handy pages; rc=%Rrc cHandyPages=%#x\n"
5881 " cAllPages=%#x cPrivatePages=%#x cSharedPages=%#x cZeroPages=%#x\n",
5882 rc, pVM->pgm.s.cHandyPages,
5883 pVM->pgm.s.cAllPages, pVM->pgm.s.cPrivatePages, pVM->pgm.s.cSharedPages, pVM->pgm.s.cZeroPages));
5884
5885 if ( rc != VERR_NO_MEMORY
5886 && rc != VERR_NO_PHYS_MEMORY
5887 && rc != VERR_LOCK_FAILED)
5888 for (uint32_t i = 0; i < RT_ELEMENTS(pVM->pgm.s.aHandyPages); i++)
5889 {
5890 LogRel(("PGM: aHandyPages[#%#04x] = {.HCPhysGCPhys=%RHp, .idPage=%#08x, .idSharedPage=%#08x}\n",
5891 i, pVM->pgm.s.aHandyPages[i].HCPhysGCPhys, pVM->pgm.s.aHandyPages[i].idPage,
5892 pVM->pgm.s.aHandyPages[i].idSharedPage));
5893 uint32_t const idPage = pVM->pgm.s.aHandyPages[i].idPage;
5894 if (idPage != NIL_GMM_PAGEID)
5895 {
5896 for (PPGMRAMRANGE pRam = pVM->pgm.s.pRamRangesXR3;
5897 pRam;
5898 pRam = pRam->pNextR3)
5899 {
5900 uint32_t const cPages = pRam->cb >> GUEST_PAGE_SHIFT;
5901 for (uint32_t iPage = 0; iPage < cPages; iPage++)
5902 if (PGM_PAGE_GET_PAGEID(&pRam->aPages[iPage]) == idPage)
5903 LogRel(("PGM: Used by %RGp %R[pgmpage] (%s)\n",
5904 pRam->GCPhys + ((RTGCPHYS)iPage << GUEST_PAGE_SHIFT), &pRam->aPages[iPage], pRam->pszDesc));
5905 }
5906 }
5907 }
5908
5909 if (rc == VERR_NO_MEMORY)
5910 {
5911 uint64_t cbHostRamAvail = 0;
5912 int rc2 = RTSystemQueryAvailableRam(&cbHostRamAvail);
5913 if (RT_SUCCESS(rc2))
5914 LogRel(("Host RAM: %RU64MB available\n", cbHostRamAvail / _1M));
5915 else
5916 LogRel(("Cannot determine the amount of available host memory\n"));
5917 }
5918
5919 /* Set the FFs and adjust rc. */
5920 VM_FF_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES);
5921 VM_FF_SET(pVM, VM_FF_PGM_NO_MEMORY);
5922 if ( rc == VERR_NO_MEMORY
5923 || rc == VERR_NO_PHYS_MEMORY
5924 || rc == VERR_LOCK_FAILED)
5925 rc = VINF_EM_NO_MEMORY;
5926 }
5927
5928 PGM_UNLOCK(pVM);
5929 return rc;
5930}
5931
5932
5933/*********************************************************************************************************************************
5934* Other Stuff *
5935*********************************************************************************************************************************/
5936
5937/**
5938 * Sets the Address Gate 20 state.
5939 *
5940 * @param pVCpu The cross context virtual CPU structure.
5941 * @param fEnable True if the gate should be enabled.
5942 * False if the gate should be disabled.
5943 */
5944VMMDECL(void) PGMR3PhysSetA20(PVMCPU pVCpu, bool fEnable)
5945{
5946 LogFlow(("PGMR3PhysSetA20 %d (was %d)\n", fEnable, pVCpu->pgm.s.fA20Enabled));
5947 if (pVCpu->pgm.s.fA20Enabled != fEnable)
5948 {
5949#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5950 PCCPUMCTX pCtx = CPUMQueryGuestCtxPtr(pVCpu);
5951 if ( CPUMIsGuestInVmxRootMode(pCtx)
5952 && !fEnable)
5953 {
5954 Log(("Cannot enter A20M mode while in VMX root mode\n"));
5955 return;
5956 }
5957#endif
5958 pVCpu->pgm.s.fA20Enabled = fEnable;
5959 pVCpu->pgm.s.GCPhysA20Mask = ~((RTGCPHYS)!fEnable << 20);
5960 if (VM_IS_NEM_ENABLED(pVCpu->CTX_SUFF(pVM)))
5961 NEMR3NotifySetA20(pVCpu, fEnable);
5962#ifdef PGM_WITH_A20
5963 VMCPU_FF_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3);
5964 pgmR3RefreshShadowModeAfterA20Change(pVCpu);
5965 HMFlushTlb(pVCpu);
5966#endif
5967 IEMTlbInvalidateAllPhysical(pVCpu);
5968 STAM_REL_COUNTER_INC(&pVCpu->pgm.s.cA20Changes);
5969 }
5970}
5971
Note: See TracBrowser for help on using the repository browser.

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