VirtualBox

source: vbox/trunk/src/VBox/VMM/MM.cpp@ 4388

Last change on this file since 4388 was 4388, checked in by vboxsync, 17 years ago

Shadow ROM emulation. Clear the RESERVED flag for ROM.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 18.8 KB
Line 
1/* $Id: MM.cpp 4388 2007-08-27 14:26:05Z vboxsync $ */
2/** @file
3 * MM - Memory Monitor(/Manager).
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
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 as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/** @page pg_mm MM - The Memory Monitor/Manager
20 *
21 * It seems like this is going to be the entity taking care of memory allocations
22 * and the locking of physical memory for a VM. MM will track these allocations and
23 * pinnings so pointer conversions, memory read and write, and correct clean up can
24 * be done.
25 *
26 * Memory types:
27 * - Hypervisor Memory Area (HMA).
28 * - Page tables.
29 * - Physical pages.
30 *
31 * The first two types are not accessible using the generic conversion functions
32 * for GC memory, there are special functions for these.
33 *
34 *
35 * A decent structure for this component need to be eveloped as we see usage. One
36 * or two rewrites is probabaly needed to get it right...
37 *
38 *
39 *
40 * @section Hypervisor Memory Area
41 *
42 * The hypervisor is give 4MB of space inside the guest, we assume that we can
43 * steal an page directory entry from the guest OS without cause trouble. In
44 * addition to these 4MB we'll be mapping memory for the graphics emulation,
45 * but that will be an independant mapping.
46 *
47 * The 4MBs are divided into two main parts:
48 * -# The static code and data
49 * -# The shortlived page mappings.
50 *
51 * The first part is used for the VM structure, the core code (VMMSwitch),
52 * GC modules, and the alloc-only-heap. The size will be determined at a
53 * later point but initially we'll say 2MB of locked memory, most of which
54 * is non contiguous physically.
55 *
56 * The second part is used for mapping pages to the hypervisor. We'll be using
57 * a simple round robin when doing these mappings. This means that no-one can
58 * assume that a mapping hangs around for very long, while the managing of the
59 * pages are very simple.
60 *
61 *
62 *
63 * @section Page Pool
64 *
65 * The MM manages a per VM page pool from which other components can allocate
66 * locked, page aligned and page granular memory objects. The pool provides
67 * facilities to convert back and forth between physical and virtual addresses
68 * (within the pool of course). Several specialized interfaces are provided
69 * for the most common alloctions and convertions to save the caller from
70 * bothersome casting and extra parameter passing.
71 *
72 *
73 */
74
75
76
77/*******************************************************************************
78* Header Files *
79*******************************************************************************/
80#define LOG_GROUP LOG_GROUP_MM
81#include <VBox/mm.h>
82#include <VBox/pgm.h>
83#include <VBox/cfgm.h>
84#include <VBox/ssm.h>
85#include "MMInternal.h"
86#include <VBox/vm.h>
87#include <VBox/err.h>
88#include <VBox/param.h>
89
90#include <VBox/log.h>
91#include <iprt/alloc.h>
92#include <iprt/assert.h>
93#include <iprt/string.h>
94
95
96/*******************************************************************************
97* Internal Functions *
98*******************************************************************************/
99static int mmR3Term(PVM pVM, bool fKeepTheHeap);
100static DECLCALLBACK(int) mmR3Save(PVM pVM, PSSMHANDLE pSSM);
101static DECLCALLBACK(int) mmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version);
102
103
104
105/**
106 * Initializes the MM.
107 *
108 * MM is managing the virtual address space (among other things) and
109 * setup the hypvervisor memory area mapping in the VM structure and
110 * the hypvervisor alloc-only-heap. Assuming the current init order
111 * and components the hypvervisor memory area looks like this:
112 * -# VM Structure.
113 * -# Hypervisor alloc only heap (also call Hypervisor memory region).
114 * -# Core code.
115 *
116 * MM determins the virtual address of the hypvervisor memory area by
117 * checking for location at previous run. If that property isn't available
118 * it will choose a default starting location, currently 0xe0000000.
119 *
120 * @returns VBox status code.
121 * @param pVM The VM to operate on.
122 */
123MMR3DECL(int) MMR3Init(PVM pVM)
124{
125 LogFlow(("MMR3Init\n"));
126
127 /*
128 * Assert alignment, sizes and order.
129 */
130 AssertRelease(!(RT_OFFSETOF(VM, mm.s) & 31));
131 AssertRelease(sizeof(pVM->mm.s) <= sizeof(pVM->mm.padding));
132 AssertMsg(pVM->mm.s.offVM == 0, ("Already initialized!\n"));
133
134 /*
135 * Init the structure.
136 */
137 pVM->mm.s.offVM = RT_OFFSETOF(VM, mm);
138 pVM->mm.s.offLookupHyper = NIL_OFFSET;
139
140 /*
141 * Init the heap (may already be initialized already if someone used it).
142 */
143 if (!pVM->mm.s.pHeap)
144 {
145 int rc = mmr3HeapCreate(pVM, &pVM->mm.s.pHeap);
146 if (!VBOX_SUCCESS(rc))
147 return rc;
148 }
149
150 /*
151 * Init the page pool.
152 */
153 int rc = mmr3PagePoolInit(pVM);
154 if (VBOX_SUCCESS(rc))
155 {
156 /*
157 * Init the hypervisor related stuff.
158 */
159 rc = mmr3HyperInit(pVM);
160 if (VBOX_SUCCESS(rc))
161 {
162 /*
163 * Register the saved state data unit.
164 */
165 rc = SSMR3RegisterInternal(pVM, "mm", 1, 1, sizeof(uint32_t) * 2,
166 NULL, mmR3Save, NULL,
167 NULL, mmR3Load, NULL);
168 if (VBOX_SUCCESS(rc))
169 return rc;
170 }
171
172 /* .... failure .... */
173 mmR3Term(pVM, true /* keep the heap */);
174 }
175 else
176 mmr3HeapDestroy(pVM->mm.s.pHeap);
177 return rc;
178}
179
180
181/**
182 * Initializes the MM parts which depends on PGM being initialized.
183 *
184 * @returns VBox status code.
185 * @param pVM The VM to operate on.
186 * @remark No cleanup necessary since MMR3Term() will be called on failure.
187 */
188MMR3DECL(int) MMR3InitPaging(PVM pVM)
189{
190 LogFlow(("MMR3InitPaging:\n"));
191 bool fPreAlloc;
192 int rc = CFGMR3QueryBool(CFGMR3GetRoot(pVM), "RamPreAlloc", &fPreAlloc);
193 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
194 fPreAlloc = false;
195 else
196 AssertMsgRCReturn(rc, ("Configuration error: Failed to query integer \"RamPreAlloc\", rc=%Vrc.\n", rc), rc);
197
198 uint64_t cbRam;
199 rc = CFGMR3QueryU64(CFGMR3GetRoot(pVM), "RamSize", &cbRam);
200 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
201 cbRam = 0;
202 if (VBOX_SUCCESS(rc) || rc == VERR_CFGM_VALUE_NOT_FOUND)
203 {
204 if (cbRam < PAGE_SIZE)
205 {
206 Log(("MM: No RAM configured\n"));
207 return VINF_SUCCESS;
208 }
209#ifdef PGM_DYNAMIC_RAM_ALLOC
210 Log(("MM: %llu bytes of RAM%s\n", cbRam, fPreAlloc ? " (PreAlloc)" : ""));
211 pVM->mm.s.pvRamBaseHC = 0; /** @todo obsolete */
212 pVM->mm.s.cbRamBase = cbRam & PAGE_BASE_GC_MASK;
213 rc = MMR3PhysRegister(pVM, pVM->mm.s.pvRamBaseHC, 0, pVM->mm.s.cbRamBase, MM_RAM_FLAGS_DYNAMIC_ALLOC, "Main Memory");
214 if (VBOX_SUCCESS(rc))
215 {
216 /* Allocate the first chunk, as we'll map ROM ranges there. */
217 rc = PGM3PhysGrowRange(pVM, (RTGCPHYS)0);
218 if (VBOX_SUCCESS(rc))
219 {
220 /* Should we preallocate the entire guest RAM? */
221 if (fPreAlloc)
222 {
223 for (RTGCPHYS GCPhys = PGM_DYNAMIC_CHUNK_SIZE; GCPhys < cbRam; GCPhys += PGM_DYNAMIC_CHUNK_SIZE)
224 {
225 rc = PGM3PhysGrowRange(pVM, GCPhys);
226 if (VBOX_FAILURE(rc))
227 return rc;
228 }
229 }
230 return rc;
231 }
232 }
233#else
234 unsigned cPages = cbRam >> PAGE_SHIFT;
235 Log(("MM: %llu bytes of RAM (%d pages)\n", cbRam, cPages));
236 rc = SUPPageAlloc(cPages, &pVM->mm.s.pvRamBaseHC);
237 if (VBOX_SUCCESS(rc))
238 {
239 pVM->mm.s.cbRamBase = cPages << PAGE_SHIFT;
240 rc = MMR3PhysRegister(pVM, pVM->mm.s.pvRamBaseHC, 0, pVM->mm.s.cbRamBase, 0, "Main Memory");
241 if (VBOX_SUCCESS(rc))
242 return rc;
243 SUPPageFree(pVM->mm.s.pvRamBaseHC);
244 }
245 else
246 LogRel(("MMR3InitPage: Failed to allocate %u bytes of RAM! rc=%Vrc\n", cPages << PAGE_SHIFT));
247#endif
248 }
249 else
250 AssertMsgFailed(("Configuration error: Failed to query integer \"RamSize\", rc=%Vrc.\n", rc));
251
252 LogFlow(("MMR3InitPaging: returns %Vrc\n", rc));
253 return rc;
254}
255
256
257/**
258 * Terminates the MM.
259 *
260 * Termination means cleaning up and freeing all resources,
261 * the VM it self is at this point powered off or suspended.
262 *
263 * @returns VBox status code.
264 * @param pVM The VM to operate on.
265 */
266MMR3DECL(int) MMR3Term(PVM pVM)
267{
268 return mmR3Term(pVM, false /* free the heap */);
269}
270
271
272/**
273 * Worker for MMR3Term and MMR3Init.
274 *
275 * The tricky bit here is that we must not destroy the heap if we're
276 * called from MMR3Init, otherwise we'll get into trouble when
277 * CFGMR3Term is called later in the bailout process.
278 *
279 * @returns VBox status code.
280 * @param pVM The VM to operate on.
281 * @param fKeepTheHeap Whether or not to keep the heap.
282 */
283static int mmR3Term(PVM pVM, bool fKeepTheHeap)
284{
285 /*
286 * Release locked memory.
287 * (Associated record are released by the heap.)
288 */
289 PMMLOCKEDMEM pLockedMem = pVM->mm.s.pLockedMem;
290 while (pLockedMem)
291 {
292 int rc = SUPPageUnlock(pLockedMem->pv);
293 AssertMsgRC(rc, ("SUPPageUnlock(%p) -> rc=%d\n", pLockedMem->pv, rc));
294 switch (pLockedMem->eType)
295 {
296 case MM_LOCKED_TYPE_HYPER:
297 rc = SUPPageFree(pLockedMem->pv, pLockedMem->cb >> PAGE_SHIFT);
298 AssertMsgRC(rc, ("SUPPageFree(%p) -> rc=%d\n", pLockedMem->pv, rc));
299 break;
300 case MM_LOCKED_TYPE_HYPER_NOFREE:
301 case MM_LOCKED_TYPE_HYPER_PAGES:
302 case MM_LOCKED_TYPE_PHYS:
303 /* nothing to do. */
304 break;
305 }
306 /* next */
307 pLockedMem = pLockedMem->pNext;
308 }
309
310 /*
311 * Destroy the page pool.
312 */
313 mmr3PagePoolTerm(pVM);
314
315 /*
316 * Destroy the heap if requested.
317 */
318 if (!fKeepTheHeap)
319 {
320 mmr3HeapDestroy(pVM->mm.s.pHeap);
321 pVM->mm.s.pHeap = NULL;
322 }
323
324 /*
325 * Zero stuff to detect after termination use of the MM interface
326 */
327 pVM->mm.s.offLookupHyper = NIL_OFFSET;
328 pVM->mm.s.pLockedMem = NULL;
329 pVM->mm.s.pHyperHeapHC = NULL; /* freed above. */
330 pVM->mm.s.pHyperHeapGC = 0; /* freed above. */
331 pVM->mm.s.offVM = 0; /* init assertion on this */
332
333 return 0;
334}
335
336
337/**
338 * Reset notification.
339 *
340 * MM will reload shadow ROMs into RAM at this point and make
341 * the ROM writable.
342 *
343 * @param pVM The VM handle.
344 */
345MMR3DECL(void) MMR3Reset(PVM pVM)
346{
347 mmR3PhysRomReset(pVM);
348}
349
350
351/**
352 * Execute state save operation.
353 *
354 * @returns VBox status code.
355 * @param pVM VM Handle.
356 * @param pSSM SSM operation handle.
357 */
358static DECLCALLBACK(int) mmR3Save(PVM pVM, PSSMHANDLE pSSM)
359{
360 LogFlow(("mmR3Save:\n"));
361
362 /* (PGM saves the physical memory.) */
363 SSMR3PutUInt(pSSM, pVM->mm.s.cbRAMSize);
364 return SSMR3PutUInt(pSSM, pVM->mm.s.cbRamBase);
365}
366
367
368/**
369 * Execute state load operation.
370 *
371 * @returns VBox status code.
372 * @param pVM VM Handle.
373 * @param pSSM SSM operation handle.
374 * @param u32Version Data layout version.
375 */
376static DECLCALLBACK(int) mmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
377{
378 LogFlow(("mmR3Load:\n"));
379
380 /*
381 * Validate version.
382 */
383 if (u32Version != 1)
384 {
385 Log(("mmR3Load: Invalid version u32Version=%d!\n", u32Version));
386 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
387 }
388
389 /*
390 * Check the cbRAMSize and cbRamBase values.
391 */
392 RTUINT cb;
393 int rc = SSMR3GetUInt(pSSM, &cb);
394 if (VBOX_FAILURE(rc))
395 return rc;
396 if (cb != pVM->mm.s.cbRAMSize)
397 {
398 Log(("mmR3Load: Memory configuration has changed. cbRAMSize=%#x save %#x\n", pVM->mm.s.cbRAMSize, cb));
399 return VERR_SSM_LOAD_MEMORY_SIZE_MISMATCH;
400 }
401
402 rc = SSMR3GetUInt(pSSM, &cb);
403 if (VBOX_FAILURE(rc))
404 return rc;
405 if (cb != pVM->mm.s.cbRamBase)
406 {
407 Log(("mmR3Load: Memory configuration has changed. cbRamBase=%#x save %#x\n", pVM->mm.s.cbRamBase, cb));
408 return VERR_SSM_LOAD_MEMORY_SIZE_MISMATCH;
409 }
410
411 /* PGM restores the physical memory. */
412 return rc;
413}
414
415
416/**
417 * Locks physical memory which backs a virtual memory range (HC) adding
418 * the required records to the pLockedMem list.
419 *
420 * @returns VBox status code.
421 * @param pVM The VM handle.
422 * @param pv Pointer to memory range which shall be locked down.
423 * This pointer is page aligned.
424 * @param cb Size of memory range (in bytes). This size is page aligned.
425 * @param eType Memory type.
426 * @param ppLockedMem Where to store the pointer to the created locked memory record.
427 * This is optional, pass NULL if not used.
428 * @param fSilentFailure Don't raise an error when unsuccessful. Upper layer with deal with it.
429 */
430int mmr3LockMem(PVM pVM, void *pv, size_t cb, MMLOCKEDTYPE eType, PMMLOCKEDMEM *ppLockedMem, bool fSilentFailure)
431{
432 Assert(RT_ALIGN_P(pv, PAGE_SIZE) == pv);
433 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb);
434
435 if (ppLockedMem)
436 *ppLockedMem = NULL;
437
438 /*
439 * Allocate locked mem structure.
440 */
441 unsigned cPages = cb >> PAGE_SHIFT;
442 AssertReturn(cPages == (cb >> PAGE_SHIFT), VERR_OUT_OF_RANGE);
443 PMMLOCKEDMEM pLockedMem = (PMMLOCKEDMEM)MMR3HeapAlloc(pVM, MM_TAG_MM, RT_OFFSETOF(MMLOCKEDMEM, aPhysPages[cPages]));
444 if (!pLockedMem)
445 return VERR_NO_MEMORY;
446 pLockedMem->pv = pv;
447 pLockedMem->cb = cb;
448 pLockedMem->eType = eType;
449 memset(&pLockedMem->u, 0, sizeof(pLockedMem->u));
450
451 /*
452 * Lock the memory.
453 */
454 int rc = SUPPageLock(pv, cPages, &pLockedMem->aPhysPages[0]);
455 if (VBOX_SUCCESS(rc))
456 {
457 /*
458 * Setup the reserved field.
459 */
460 PSUPPAGE pPhysPage = &pLockedMem->aPhysPages[0];
461 for (unsigned c = cPages; c > 0; c--, pPhysPage++)
462 pPhysPage->uReserved = (RTHCUINTPTR)pLockedMem;
463
464 /*
465 * Insert into the list.
466 *
467 * ASSUME no protected needed here as only one thread in the system can possibly
468 * be doing this. No other threads will walk this list either we assume.
469 */
470 pLockedMem->pNext = pVM->mm.s.pLockedMem;
471 pVM->mm.s.pLockedMem = pLockedMem;
472 /* Set return value. */
473 if (ppLockedMem)
474 *ppLockedMem = pLockedMem;
475 }
476 else
477 {
478 AssertMsgFailed(("SUPPageLock failed with rc=%d\n", rc));
479 MMR3HeapFree(pLockedMem);
480 if (!fSilentFailure)
481 rc = VMSetError(pVM, rc, RT_SRC_POS, N_("Failed to lock %d bytes of host memory (out of memory)"), cb);
482 }
483
484 return rc;
485}
486
487
488/**
489 * Maps a part of or an entire locked memory region into the guest context.
490 *
491 * @returns VBox status.
492 * God knows what happens if we fail...
493 * @param pVM VM handle.
494 * @param pLockedMem Locked memory structure.
495 * @param Addr GC Address where to start the mapping.
496 * @param iPage Page number in the locked memory region.
497 * @param cPages Number of pages to map.
498 * @param fFlags See the fFlags argument of PGR3Map().
499 */
500int mmr3MapLocked(PVM pVM, PMMLOCKEDMEM pLockedMem, RTGCPTR Addr, unsigned iPage, size_t cPages, unsigned fFlags)
501{
502 /*
503 * Adjust ~0 argument
504 */
505 if (cPages == ~(size_t)0)
506 cPages = (pLockedMem->cb >> PAGE_SHIFT) - iPage;
507 Assert(cPages != ~0U);
508 /* no incorrect arguments are accepted */
509 Assert(RT_ALIGN_GCPT(Addr, PAGE_SIZE, RTGCPTR) == Addr);
510 AssertMsg(iPage < (pLockedMem->cb >> PAGE_SHIFT), ("never even think about giving me a bad iPage(=%d)\n", iPage));
511 AssertMsg(iPage + cPages <= (pLockedMem->cb >> PAGE_SHIFT), ("never even think about giving me a bad cPages(=%d)\n", cPages));
512
513 /*
514 * Map the the pages.
515 */
516 PSUPPAGE pPhysPage = &pLockedMem->aPhysPages[iPage];
517 while (cPages)
518 {
519 RTHCPHYS HCPhys = pPhysPage->Phys;
520 int rc = PGMMap(pVM, Addr, HCPhys, PAGE_SIZE, fFlags);
521 if (VBOX_FAILURE(rc))
522 {
523 /** @todo how the hell can we do a proper bailout here. */
524 return rc;
525 }
526
527 /* next */
528 cPages--;
529 iPage++;
530 pPhysPage++;
531 Addr += PAGE_SIZE;
532 }
533
534 return VINF_SUCCESS;
535}
536
537
538/**
539 * Convert HC Physical address to HC Virtual address.
540 *
541 * @returns VBox status.
542 * @param pVM VM handle.
543 * @param HCPhys The host context virtual address.
544 * @param ppv Where to store the resulting address.
545 * @thread The Emulation Thread.
546 */
547MMR3DECL(int) MMR3HCPhys2HCVirt(PVM pVM, RTHCPHYS HCPhys, void **ppv)
548{
549 /*
550 * Try page tables.
551 */
552 int rc = MMPagePhys2PageTry(pVM, HCPhys, ppv);
553 if (VBOX_SUCCESS(rc))
554 return rc;
555
556 /*
557 * Iterate the locked memory - very slow.
558 */
559 uint32_t off = HCPhys & PAGE_OFFSET_MASK;
560 HCPhys &= X86_PTE_PAE_PG_MASK;
561 for (PMMLOCKEDMEM pCur = pVM->mm.s.pLockedMem; pCur; pCur = pCur->pNext)
562 {
563 size_t iPage = pCur->cb >> PAGE_SHIFT;
564 while (iPage-- > 0)
565 if ((pCur->aPhysPages[iPage].Phys & X86_PTE_PAE_PG_MASK) == HCPhys)
566 {
567 *ppv = (char *)pCur->pv + (iPage << PAGE_SHIFT) + off;
568 return VINF_SUCCESS;
569 }
570 }
571 /* give up */
572 return VERR_INVALID_POINTER;
573}
574
575
576/**
577 * Read memory from GC virtual address using the current guest CR3.
578 *
579 * @returns VBox status.
580 * @param pVM VM handle.
581 * @param pvDst Destination address (HC of course).
582 * @param GCPtr GC virtual address.
583 * @param cb Number of bytes to read.
584 */
585MMR3DECL(int) MMR3ReadGCVirt(PVM pVM, void *pvDst, RTGCPTR GCPtr, size_t cb)
586{
587 if (GCPtr - pVM->mm.s.pvHyperAreaGC < pVM->mm.s.cbHyperArea)
588 return MMR3HyperReadGCVirt(pVM, pvDst, GCPtr, cb);
589 return PGMPhysReadGCPtr(pVM, pvDst, GCPtr, cb);
590}
591
592
593/**
594 * Write to memory at GC virtual address translated using the current guest CR3.
595 *
596 * @returns VBox status.
597 * @param pVM VM handle.
598 * @param GCPtrDst GC virtual address.
599 * @param pvSrc The source address (HC of course).
600 * @param cb Number of bytes to read.
601 */
602MMR3DECL(int) MMR3WriteGCVirt(PVM pVM, RTGCPTR GCPtrDst, const void *pvSrc, size_t cb)
603{
604 if (GCPtrDst - pVM->mm.s.pvHyperAreaGC < pVM->mm.s.cbHyperArea)
605 return VERR_ACCESS_DENIED;
606 return PGMPhysWriteGCPtr(pVM, GCPtrDst, pvSrc, cb);
607}
608
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