VirtualBox

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

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

Biggest check-in ever. New source code headers for all (C) innotek files.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 18.5 KB
Line 
1/* $Id: MM.cpp 4071 2007-08-07 17:07:59Z 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 * Execute state save operation.
339 *
340 * @returns VBox status code.
341 * @param pVM VM Handle.
342 * @param pSSM SSM operation handle.
343 */
344static DECLCALLBACK(int) mmR3Save(PVM pVM, PSSMHANDLE pSSM)
345{
346 LogFlow(("mmR3Save:\n"));
347
348 /* (PGM saves the physical memory.) */
349 SSMR3PutUInt(pSSM, pVM->mm.s.cbRAMSize);
350 return SSMR3PutUInt(pSSM, pVM->mm.s.cbRamBase);
351}
352
353
354/**
355 * Execute state load operation.
356 *
357 * @returns VBox status code.
358 * @param pVM VM Handle.
359 * @param pSSM SSM operation handle.
360 * @param u32Version Data layout version.
361 */
362static DECLCALLBACK(int) mmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t u32Version)
363{
364 LogFlow(("mmR3Load:\n"));
365
366 /*
367 * Validate version.
368 */
369 if (u32Version != 1)
370 {
371 Log(("mmR3Load: Invalid version u32Version=%d!\n", u32Version));
372 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
373 }
374
375 /*
376 * Check the cbRAMSize and cbRamBase values.
377 */
378 RTUINT cb;
379 int rc = SSMR3GetUInt(pSSM, &cb);
380 if (VBOX_FAILURE(rc))
381 return rc;
382 if (cb != pVM->mm.s.cbRAMSize)
383 {
384 Log(("mmR3Load: Memory configuration has changed. cbRAMSize=%#x save %#x\n", pVM->mm.s.cbRAMSize, cb));
385 return VERR_SSM_LOAD_MEMORY_SIZE_MISMATCH;
386 }
387
388 rc = SSMR3GetUInt(pSSM, &cb);
389 if (VBOX_FAILURE(rc))
390 return rc;
391 if (cb != pVM->mm.s.cbRamBase)
392 {
393 Log(("mmR3Load: Memory configuration has changed. cbRamBase=%#x save %#x\n", pVM->mm.s.cbRamBase, cb));
394 return VERR_SSM_LOAD_MEMORY_SIZE_MISMATCH;
395 }
396
397 /* PGM restores the physical memory. */
398 return rc;
399}
400
401
402/**
403 * Locks physical memory which backs a virtual memory range (HC) adding
404 * the required records to the pLockedMem list.
405 *
406 * @returns VBox status code.
407 * @param pVM The VM handle.
408 * @param pv Pointer to memory range which shall be locked down.
409 * This pointer is page aligned.
410 * @param cb Size of memory range (in bytes). This size is page aligned.
411 * @param eType Memory type.
412 * @param ppLockedMem Where to store the pointer to the created locked memory record.
413 * This is optional, pass NULL if not used.
414 * @param fSilentFailure Don't raise an error when unsuccessful. Upper layer with deal with it.
415 */
416int mmr3LockMem(PVM pVM, void *pv, size_t cb, MMLOCKEDTYPE eType, PMMLOCKEDMEM *ppLockedMem, bool fSilentFailure)
417{
418 Assert(RT_ALIGN_P(pv, PAGE_SIZE) == pv);
419 Assert(RT_ALIGN_Z(cb, PAGE_SIZE) == cb);
420
421 if (ppLockedMem)
422 *ppLockedMem = NULL;
423
424 /*
425 * Allocate locked mem structure.
426 */
427 unsigned cPages = cb >> PAGE_SHIFT;
428 AssertReturn(cPages == (cb >> PAGE_SHIFT), VERR_OUT_OF_RANGE);
429 PMMLOCKEDMEM pLockedMem = (PMMLOCKEDMEM)MMR3HeapAlloc(pVM, MM_TAG_MM, RT_OFFSETOF(MMLOCKEDMEM, aPhysPages[cPages]));
430 if (!pLockedMem)
431 return VERR_NO_MEMORY;
432 pLockedMem->pv = pv;
433 pLockedMem->cb = cb;
434 pLockedMem->eType = eType;
435 memset(&pLockedMem->u, 0, sizeof(pLockedMem->u));
436
437 /*
438 * Lock the memory.
439 */
440 int rc = SUPPageLock(pv, cPages, &pLockedMem->aPhysPages[0]);
441 if (VBOX_SUCCESS(rc))
442 {
443 /*
444 * Setup the reserved field.
445 */
446 PSUPPAGE pPhysPage = &pLockedMem->aPhysPages[0];
447 for (unsigned c = cPages; c > 0; c--, pPhysPage++)
448 pPhysPage->uReserved = (RTHCUINTPTR)pLockedMem;
449
450 /*
451 * Insert into the list.
452 *
453 * ASSUME no protected needed here as only one thread in the system can possibly
454 * be doing this. No other threads will walk this list either we assume.
455 */
456 pLockedMem->pNext = pVM->mm.s.pLockedMem;
457 pVM->mm.s.pLockedMem = pLockedMem;
458 /* Set return value. */
459 if (ppLockedMem)
460 *ppLockedMem = pLockedMem;
461 }
462 else
463 {
464 AssertMsgFailed(("SUPPageLock failed with rc=%d\n", rc));
465 MMR3HeapFree(pLockedMem);
466 if (!fSilentFailure)
467 rc = VMSetError(pVM, rc, RT_SRC_POS, N_("Failed to lock %d bytes of host memory (out of memory)"), cb);
468 }
469
470 return rc;
471}
472
473
474/**
475 * Maps a part of or an entire locked memory region into the guest context.
476 *
477 * @returns VBox status.
478 * God knows what happens if we fail...
479 * @param pVM VM handle.
480 * @param pLockedMem Locked memory structure.
481 * @param Addr GC Address where to start the mapping.
482 * @param iPage Page number in the locked memory region.
483 * @param cPages Number of pages to map.
484 * @param fFlags See the fFlags argument of PGR3Map().
485 */
486int mmr3MapLocked(PVM pVM, PMMLOCKEDMEM pLockedMem, RTGCPTR Addr, unsigned iPage, size_t cPages, unsigned fFlags)
487{
488 /*
489 * Adjust ~0 argument
490 */
491 if (cPages == ~(size_t)0)
492 cPages = (pLockedMem->cb >> PAGE_SHIFT) - iPage;
493 Assert(cPages != ~0U);
494 /* no incorrect arguments are accepted */
495 Assert(RT_ALIGN_GCPT(Addr, PAGE_SIZE, RTGCPTR) == Addr);
496 AssertMsg(iPage < (pLockedMem->cb >> PAGE_SHIFT), ("never even think about giving me a bad iPage(=%d)\n", iPage));
497 AssertMsg(iPage + cPages <= (pLockedMem->cb >> PAGE_SHIFT), ("never even think about giving me a bad cPages(=%d)\n", cPages));
498
499 /*
500 * Map the the pages.
501 */
502 PSUPPAGE pPhysPage = &pLockedMem->aPhysPages[iPage];
503 while (cPages)
504 {
505 RTHCPHYS HCPhys = pPhysPage->Phys;
506 int rc = PGMMap(pVM, Addr, HCPhys, PAGE_SIZE, fFlags);
507 if (VBOX_FAILURE(rc))
508 {
509 /** @todo how the hell can we do a proper bailout here. */
510 return rc;
511 }
512
513 /* next */
514 cPages--;
515 iPage++;
516 pPhysPage++;
517 Addr += PAGE_SIZE;
518 }
519
520 return VINF_SUCCESS;
521}
522
523
524/**
525 * Convert HC Physical address to HC Virtual address.
526 *
527 * @returns VBox status.
528 * @param pVM VM handle.
529 * @param HCPhys The host context virtual address.
530 * @param ppv Where to store the resulting address.
531 * @thread The Emulation Thread.
532 */
533MMR3DECL(int) MMR3HCPhys2HCVirt(PVM pVM, RTHCPHYS HCPhys, void **ppv)
534{
535 /*
536 * Try page tables.
537 */
538 int rc = MMPagePhys2PageTry(pVM, HCPhys, ppv);
539 if (VBOX_SUCCESS(rc))
540 return rc;
541
542 /*
543 * Iterate the locked memory - very slow.
544 */
545 uint32_t off = HCPhys & PAGE_OFFSET_MASK;
546 HCPhys &= X86_PTE_PAE_PG_MASK;
547 for (PMMLOCKEDMEM pCur = pVM->mm.s.pLockedMem; pCur; pCur = pCur->pNext)
548 {
549 size_t iPage = pCur->cb >> PAGE_SHIFT;
550 while (iPage-- > 0)
551 if ((pCur->aPhysPages[iPage].Phys & X86_PTE_PAE_PG_MASK) == HCPhys)
552 {
553 *ppv = (char *)pCur->pv + (iPage << PAGE_SHIFT) + off;
554 return VINF_SUCCESS;
555 }
556 }
557 /* give up */
558 return VERR_INVALID_POINTER;
559}
560
561
562/**
563 * Read memory from GC virtual address using the current guest CR3.
564 *
565 * @returns VBox status.
566 * @param pVM VM handle.
567 * @param pvDst Destination address (HC of course).
568 * @param GCPtr GC virtual address.
569 * @param cb Number of bytes to read.
570 */
571MMR3DECL(int) MMR3ReadGCVirt(PVM pVM, void *pvDst, RTGCPTR GCPtr, size_t cb)
572{
573 if (GCPtr - pVM->mm.s.pvHyperAreaGC < pVM->mm.s.cbHyperArea)
574 return MMR3HyperReadGCVirt(pVM, pvDst, GCPtr, cb);
575 return PGMPhysReadGCPtr(pVM, pvDst, GCPtr, cb);
576}
577
578
579/**
580 * Write to memory at GC virtual address translated using the current guest CR3.
581 *
582 * @returns VBox status.
583 * @param pVM VM handle.
584 * @param GCPtrDst GC virtual address.
585 * @param pvSrc The source address (HC of course).
586 * @param cb Number of bytes to read.
587 */
588MMR3DECL(int) MMR3WriteGCVirt(PVM pVM, RTGCPTR GCPtrDst, const void *pvSrc, size_t cb)
589{
590 if (GCPtrDst - pVM->mm.s.pvHyperAreaGC < pVM->mm.s.cbHyperArea)
591 return VERR_ACCESS_DENIED;
592 return PGMPhysWriteGCPtr(pVM, GCPtrDst, pvSrc, cb);
593}
594
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