VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/GMMR0.cpp@ 36400

Last change on this file since 36400 was 36400, checked in by vboxsync, 14 years ago

PCI: work on IOMMU notifications

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 151.4 KB
Line 
1/* $Id: GMMR0.cpp 36400 2011-03-24 13:14:26Z vboxsync $ */
2/** @file
3 * GMM - Global Memory Manager.
4 */
5
6/*
7 * Copyright (C) 2007 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/** @page pg_gmm GMM - The Global Memory Manager
20 *
21 * As the name indicates, this component is responsible for global memory
22 * management. Currently only guest RAM is allocated from the GMM, but this
23 * may change to include shadow page tables and other bits later.
24 *
25 * Guest RAM is managed as individual pages, but allocated from the host OS
26 * in chunks for reasons of portability / efficiency. To minimize the memory
27 * footprint all tracking structure must be as small as possible without
28 * unnecessary performance penalties.
29 *
30 * The allocation chunks has fixed sized, the size defined at compile time
31 * by the #GMM_CHUNK_SIZE \#define.
32 *
33 * Each chunk is given an unique ID. Each page also has a unique ID. The
34 * relation ship between the two IDs is:
35 * @code
36 * GMM_CHUNK_SHIFT = log2(GMM_CHUNK_SIZE / PAGE_SIZE);
37 * idPage = (idChunk << GMM_CHUNK_SHIFT) | iPage;
38 * @endcode
39 * Where iPage is the index of the page within the chunk. This ID scheme
40 * permits for efficient chunk and page lookup, but it relies on the chunk size
41 * to be set at compile time. The chunks are organized in an AVL tree with their
42 * IDs being the keys.
43 *
44 * The physical address of each page in an allocation chunk is maintained by
45 * the #RTR0MEMOBJ and obtained using #RTR0MemObjGetPagePhysAddr. There is no
46 * need to duplicate this information (it'll cost 8-bytes per page if we did).
47 *
48 * So what do we need to track per page? Most importantly we need to know
49 * which state the page is in:
50 * - Private - Allocated for (eventually) backing one particular VM page.
51 * - Shared - Readonly page that is used by one or more VMs and treated
52 * as COW by PGM.
53 * - Free - Not used by anyone.
54 *
55 * For the page replacement operations (sharing, defragmenting and freeing)
56 * to be somewhat efficient, private pages needs to be associated with a
57 * particular page in a particular VM.
58 *
59 * Tracking the usage of shared pages is impractical and expensive, so we'll
60 * settle for a reference counting system instead.
61 *
62 * Free pages will be chained on LIFOs
63 *
64 * On 64-bit systems we will use a 64-bit bitfield per page, while on 32-bit
65 * systems a 32-bit bitfield will have to suffice because of address space
66 * limitations. The #GMMPAGE structure shows the details.
67 *
68 *
69 * @section sec_gmm_alloc_strat Page Allocation Strategy
70 *
71 * The strategy for allocating pages has to take fragmentation and shared
72 * pages into account, or we may end up with with 2000 chunks with only
73 * a few pages in each. Shared pages cannot easily be reallocated because
74 * of the inaccurate usage accounting (see above). Private pages can be
75 * reallocated by a defragmentation thread in the same manner that sharing
76 * is done.
77 *
78 * The first approach is to manage the free pages in two sets depending on
79 * whether they are mainly for the allocation of shared or private pages.
80 * In the initial implementation there will be almost no possibility for
81 * mixing shared and private pages in the same chunk (only if we're really
82 * stressed on memory), but when we implement forking of VMs and have to
83 * deal with lots of COW pages it'll start getting kind of interesting.
84 *
85 * The sets are lists of chunks with approximately the same number of
86 * free pages. Say the chunk size is 1MB, meaning 256 pages, and a set
87 * consists of 16 lists. So, the first list will contain the chunks with
88 * 1-7 free pages, the second covers 8-15, and so on. The chunks will be
89 * moved between the lists as pages are freed up or allocated.
90 *
91 *
92 * @section sec_gmm_costs Costs
93 *
94 * The per page cost in kernel space is 32-bit plus whatever RTR0MEMOBJ
95 * entails. In addition there is the chunk cost of approximately
96 * (sizeof(RT0MEMOBJ) + sizeof(CHUNK)) / 2^CHUNK_SHIFT bytes per page.
97 *
98 * On Windows the per page #RTR0MEMOBJ cost is 32-bit on 32-bit windows
99 * and 64-bit on 64-bit windows (a PFN_NUMBER in the MDL). So, 64-bit per page.
100 * The cost on Linux is identical, but here it's because of sizeof(struct page *).
101 *
102 *
103 * @section sec_gmm_legacy Legacy Mode for Non-Tier-1 Platforms
104 *
105 * In legacy mode the page source is locked user pages and not
106 * #RTR0MemObjAllocPhysNC, this means that a page can only be allocated
107 * by the VM that locked it. We will make no attempt at implementing
108 * page sharing on these systems, just do enough to make it all work.
109 *
110 *
111 * @subsection sub_gmm_locking Serializing
112 *
113 * One simple fast mutex will be employed in the initial implementation, not
114 * two as mentioned in @ref subsec_pgmPhys_Serializing.
115 *
116 * @see @ref subsec_pgmPhys_Serializing
117 *
118 *
119 * @section sec_gmm_overcommit Memory Over-Commitment Management
120 *
121 * The GVM will have to do the system wide memory over-commitment
122 * management. My current ideas are:
123 * - Per VM oc policy that indicates how much to initially commit
124 * to it and what to do in a out-of-memory situation.
125 * - Prevent overtaxing the host.
126 *
127 * There are some challenges here, the main ones are configurability and
128 * security. Should we for instance permit anyone to request 100% memory
129 * commitment? Who should be allowed to do runtime adjustments of the
130 * config. And how to prevent these settings from being lost when the last
131 * VM process exits? The solution is probably to have an optional root
132 * daemon the will keep VMMR0.r0 in memory and enable the security measures.
133 *
134 *
135 *
136 * @section sec_gmm_numa NUMA
137 *
138 * NUMA considerations will be designed and implemented a bit later.
139 *
140 * The preliminary guesses is that we will have to try allocate memory as
141 * close as possible to the CPUs the VM is executed on (EMT and additional CPU
142 * threads). Which means it's mostly about allocation and sharing policies.
143 * Both the scheduler and allocator interface will to supply some NUMA info
144 * and we'll need to have a way to calc access costs.
145 *
146 */
147
148
149/*******************************************************************************
150* Header Files *
151*******************************************************************************/
152#define LOG_GROUP LOG_GROUP_GMM
153#include <VBox/rawpci.h>
154#include <VBox/vmm/vm.h>
155#include <VBox/vmm/gmm.h>
156#include "GMMR0Internal.h"
157#include <VBox/vmm/gvm.h>
158#include <VBox/vmm/pgm.h>
159#include <VBox/log.h>
160#include <VBox/param.h>
161#include <VBox/err.h>
162#include <iprt/asm.h>
163#include <iprt/avl.h>
164#include <iprt/mem.h>
165#include <iprt/memobj.h>
166#include <iprt/semaphore.h>
167#include <iprt/string.h>
168
169
170/*******************************************************************************
171* Structures and Typedefs *
172*******************************************************************************/
173/** Pointer to set of free chunks. */
174typedef struct GMMCHUNKFREESET *PGMMCHUNKFREESET;
175
176/** Pointer to a GMM allocation chunk. */
177typedef struct GMMCHUNK *PGMMCHUNK;
178
179/**
180 * The per-page tracking structure employed by the GMM.
181 *
182 * On 32-bit hosts we'll some trickery is necessary to compress all
183 * the information into 32-bits. When the fSharedFree member is set,
184 * the 30th bit decides whether it's a free page or not.
185 *
186 * Because of the different layout on 32-bit and 64-bit hosts, macros
187 * are used to get and set some of the data.
188 */
189typedef union GMMPAGE
190{
191#if HC_ARCH_BITS == 64
192 /** Unsigned integer view. */
193 uint64_t u;
194
195 /** The common view. */
196 struct GMMPAGECOMMON
197 {
198 uint32_t uStuff1 : 32;
199 uint32_t uStuff2 : 30;
200 /** The page state. */
201 uint32_t u2State : 2;
202 } Common;
203
204 /** The view of a private page. */
205 struct GMMPAGEPRIVATE
206 {
207 /** The guest page frame number. (Max addressable: 2 ^ 44 - 16) */
208 uint32_t pfn;
209 /** The GVM handle. (64K VMs) */
210 uint32_t hGVM : 16;
211 /** Reserved. */
212 uint32_t u16Reserved : 14;
213 /** The page state. */
214 uint32_t u2State : 2;
215 } Private;
216
217 /** The view of a shared page. */
218 struct GMMPAGESHARED
219 {
220 /** The host page frame number. (Max addressable: 2 ^ 44 - 16) */
221 uint32_t pfn;
222 /** The reference count (64K VMs). */
223 uint32_t cRefs : 16;
224 /** Reserved. Checksum or something? Two hGVMs for forking? */
225 uint32_t u14Reserved : 14;
226 /** The page state. */
227 uint32_t u2State : 2;
228 } Shared;
229
230 /** The view of a free page. */
231 struct GMMPAGEFREE
232 {
233 /** The index of the next page in the free list. UINT16_MAX is NIL. */
234 uint16_t iNext;
235 /** Reserved. Checksum or something? */
236 uint16_t u16Reserved0;
237 /** Reserved. Checksum or something? */
238 uint32_t u30Reserved1 : 30;
239 /** The page state. */
240 uint32_t u2State : 2;
241 } Free;
242
243#else /* 32-bit */
244 /** Unsigned integer view. */
245 uint32_t u;
246
247 /** The common view. */
248 struct GMMPAGECOMMON
249 {
250 uint32_t uStuff : 30;
251 /** The page state. */
252 uint32_t u2State : 2;
253 } Common;
254
255 /** The view of a private page. */
256 struct GMMPAGEPRIVATE
257 {
258 /** The guest page frame number. (Max addressable: 2 ^ 36) */
259 uint32_t pfn : 24;
260 /** The GVM handle. (127 VMs) */
261 uint32_t hGVM : 7;
262 /** The top page state bit, MBZ. */
263 uint32_t fZero : 1;
264 } Private;
265
266 /** The view of a shared page. */
267 struct GMMPAGESHARED
268 {
269 /** The reference count. */
270 uint32_t cRefs : 30;
271 /** The page state. */
272 uint32_t u2State : 2;
273 } Shared;
274
275 /** The view of a free page. */
276 struct GMMPAGEFREE
277 {
278 /** The index of the next page in the free list. UINT16_MAX is NIL. */
279 uint32_t iNext : 16;
280 /** Reserved. Checksum or something? */
281 uint32_t u14Reserved : 14;
282 /** The page state. */
283 uint32_t u2State : 2;
284 } Free;
285#endif
286} GMMPAGE;
287AssertCompileSize(GMMPAGE, sizeof(RTHCUINTPTR));
288/** Pointer to a GMMPAGE. */
289typedef GMMPAGE *PGMMPAGE;
290
291
292/** @name The Page States.
293 * @{ */
294/** A private page. */
295#define GMM_PAGE_STATE_PRIVATE 0
296/** A private page - alternative value used on the 32-bit implementation.
297 * This will never be used on 64-bit hosts. */
298#define GMM_PAGE_STATE_PRIVATE_32 1
299/** A shared page. */
300#define GMM_PAGE_STATE_SHARED 2
301/** A free page. */
302#define GMM_PAGE_STATE_FREE 3
303/** @} */
304
305
306/** @def GMM_PAGE_IS_PRIVATE
307 *
308 * @returns true if private, false if not.
309 * @param pPage The GMM page.
310 */
311#if HC_ARCH_BITS == 64
312# define GMM_PAGE_IS_PRIVATE(pPage) ( (pPage)->Common.u2State == GMM_PAGE_STATE_PRIVATE )
313#else
314# define GMM_PAGE_IS_PRIVATE(pPage) ( (pPage)->Private.fZero == 0 )
315#endif
316
317/** @def GMM_PAGE_IS_SHARED
318 *
319 * @returns true if shared, false if not.
320 * @param pPage The GMM page.
321 */
322#define GMM_PAGE_IS_SHARED(pPage) ( (pPage)->Common.u2State == GMM_PAGE_STATE_SHARED )
323
324/** @def GMM_PAGE_IS_FREE
325 *
326 * @returns true if free, false if not.
327 * @param pPage The GMM page.
328 */
329#define GMM_PAGE_IS_FREE(pPage) ( (pPage)->Common.u2State == GMM_PAGE_STATE_FREE )
330
331/** @def GMM_PAGE_PFN_LAST
332 * The last valid guest pfn range.
333 * @remark Some of the values outside the range has special meaning,
334 * see GMM_PAGE_PFN_UNSHAREABLE.
335 */
336#if HC_ARCH_BITS == 64
337# define GMM_PAGE_PFN_LAST UINT32_C(0xfffffff0)
338#else
339# define GMM_PAGE_PFN_LAST UINT32_C(0x00fffff0)
340#endif
341AssertCompile(GMM_PAGE_PFN_LAST == (GMM_GCPHYS_LAST >> PAGE_SHIFT));
342
343/** @def GMM_PAGE_PFN_UNSHAREABLE
344 * Indicates that this page isn't used for normal guest memory and thus isn't shareable.
345 */
346#if HC_ARCH_BITS == 64
347# define GMM_PAGE_PFN_UNSHAREABLE UINT32_C(0xfffffff1)
348#else
349# define GMM_PAGE_PFN_UNSHAREABLE UINT32_C(0x00fffff1)
350#endif
351AssertCompile(GMM_PAGE_PFN_UNSHAREABLE == (GMM_GCPHYS_UNSHAREABLE >> PAGE_SHIFT));
352
353
354/**
355 * A GMM allocation chunk ring-3 mapping record.
356 *
357 * This should really be associated with a session and not a VM, but
358 * it's simpler to associated with a VM and cleanup with the VM object
359 * is destroyed.
360 */
361typedef struct GMMCHUNKMAP
362{
363 /** The mapping object. */
364 RTR0MEMOBJ MapObj;
365 /** The VM owning the mapping. */
366 PGVM pGVM;
367} GMMCHUNKMAP;
368/** Pointer to a GMM allocation chunk mapping. */
369typedef struct GMMCHUNKMAP *PGMMCHUNKMAP;
370
371typedef enum GMMCHUNKTYPE
372{
373 GMMCHUNKTYPE_INVALID = 0,
374 GMMCHUNKTYPE_NON_CONTINUOUS = 1, /* 4 kb pages */
375 GMMCHUNKTYPE_CONTINUOUS = 2, /* one 2 MB continuous physical range. */
376 GMMCHUNKTYPE_32BIT_HACK = 0x7fffffff
377} GMMCHUNKTYPE;
378
379
380/**
381 * A GMM allocation chunk.
382 */
383typedef struct GMMCHUNK
384{
385 /** The AVL node core.
386 * The Key is the chunk ID. */
387 AVLU32NODECORE Core;
388 /** The memory object.
389 * Either from RTR0MemObjAllocPhysNC or RTR0MemObjLockUser depending on
390 * what the host can dish up with. */
391 RTR0MEMOBJ MemObj;
392 /** Pointer to the next chunk in the free list. */
393 PGMMCHUNK pFreeNext;
394 /** Pointer to the previous chunk in the free list. */
395 PGMMCHUNK pFreePrev;
396 /** Pointer to the free set this chunk belongs to. NULL for
397 * chunks with no free pages. */
398 PGMMCHUNKFREESET pSet;
399 /** Pointer to an array of mappings. */
400 PGMMCHUNKMAP paMappings;
401 /** The number of mappings. */
402 uint16_t cMappings;
403 /** The head of the list of free pages. UINT16_MAX is the NIL value. */
404 uint16_t iFreeHead;
405 /** The number of free pages. */
406 uint16_t cFree;
407 /** The GVM handle of the VM that first allocated pages from this chunk, this
408 * is used as a preference when there are several chunks to choose from.
409 * When in bound memory mode this isn't a preference any longer. */
410 uint16_t hGVM;
411 /** The number of private pages. */
412 uint16_t cPrivate;
413 /** The number of shared pages. */
414 uint16_t cShared;
415 /** Chunk type */
416 GMMCHUNKTYPE enmType;
417 /** The pages. */
418 GMMPAGE aPages[GMM_CHUNK_SIZE >> PAGE_SHIFT];
419} GMMCHUNK;
420
421
422/**
423 * An allocation chunk TLB entry.
424 */
425typedef struct GMMCHUNKTLBE
426{
427 /** The chunk id. */
428 uint32_t idChunk;
429 /** Pointer to the chunk. */
430 PGMMCHUNK pChunk;
431} GMMCHUNKTLBE;
432/** Pointer to an allocation chunk TLB entry. */
433typedef GMMCHUNKTLBE *PGMMCHUNKTLBE;
434
435
436/** The number of entries tin the allocation chunk TLB. */
437#define GMM_CHUNKTLB_ENTRIES 32
438/** Gets the TLB entry index for the given Chunk ID. */
439#define GMM_CHUNKTLB_IDX(idChunk) ( (idChunk) & (GMM_CHUNKTLB_ENTRIES - 1) )
440
441/**
442 * An allocation chunk TLB.
443 */
444typedef struct GMMCHUNKTLB
445{
446 /** The TLB entries. */
447 GMMCHUNKTLBE aEntries[GMM_CHUNKTLB_ENTRIES];
448} GMMCHUNKTLB;
449/** Pointer to an allocation chunk TLB. */
450typedef GMMCHUNKTLB *PGMMCHUNKTLB;
451
452
453/** The GMMCHUNK::cFree shift count. */
454#define GMM_CHUNK_FREE_SET_SHIFT 4
455/** The GMMCHUNK::cFree mask for use when considering relinking a chunk. */
456#define GMM_CHUNK_FREE_SET_MASK 15
457/** The number of lists in set. */
458#define GMM_CHUNK_FREE_SET_LISTS (GMM_CHUNK_NUM_PAGES >> GMM_CHUNK_FREE_SET_SHIFT)
459
460/**
461 * A set of free chunks.
462 */
463typedef struct GMMCHUNKFREESET
464{
465 /** The number of free pages in the set. */
466 uint64_t cFreePages;
467 /** Chunks ordered by increasing number of free pages. */
468 PGMMCHUNK apLists[GMM_CHUNK_FREE_SET_LISTS];
469} GMMCHUNKFREESET;
470
471
472/**
473 * The GMM instance data.
474 */
475typedef struct GMM
476{
477 /** Magic / eye catcher. GMM_MAGIC */
478 uint32_t u32Magic;
479 /** The fast mutex protecting the GMM.
480 * More fine grained locking can be implemented later if necessary. */
481 RTSEMFASTMUTEX Mtx;
482 /** The chunk tree. */
483 PAVLU32NODECORE pChunks;
484 /** The chunk TLB. */
485 GMMCHUNKTLB ChunkTLB;
486 /** The private free set. */
487 GMMCHUNKFREESET Private;
488 /** The shared free set. */
489 GMMCHUNKFREESET Shared;
490
491 /** Shared module tree (global). */
492 /** @todo separate trees for distinctly different guest OSes. */
493 PAVLGCPTRNODECORE pGlobalSharedModuleTree;
494
495 /** The maximum number of pages we're allowed to allocate.
496 * @gcfgm 64-bit GMM/MaxPages Direct.
497 * @gcfgm 32-bit GMM/PctPages Relative to the number of host pages. */
498 uint64_t cMaxPages;
499 /** The number of pages that has been reserved.
500 * The deal is that cReservedPages - cOverCommittedPages <= cMaxPages. */
501 uint64_t cReservedPages;
502 /** The number of pages that we have over-committed in reservations. */
503 uint64_t cOverCommittedPages;
504 /** The number of actually allocated (committed if you like) pages. */
505 uint64_t cAllocatedPages;
506 /** The number of pages that are shared. A subset of cAllocatedPages. */
507 uint64_t cSharedPages;
508 /** The number of pages that are actually shared between VMs. */
509 uint64_t cDuplicatePages;
510 /** The number of pages that are shared that has been left behind by
511 * VMs not doing proper cleanups. */
512 uint64_t cLeftBehindSharedPages;
513 /** The number of allocation chunks.
514 * (The number of pages we've allocated from the host can be derived from this.) */
515 uint32_t cChunks;
516 /** The number of current ballooned pages. */
517 uint64_t cBalloonedPages;
518
519 /** The legacy allocation mode indicator.
520 * This is determined at initialization time. */
521 bool fLegacyAllocationMode;
522 /** The bound memory mode indicator.
523 * When set, the memory will be bound to a specific VM and never
524 * shared. This is always set if fLegacyAllocationMode is set.
525 * (Also determined at initialization time.) */
526 bool fBoundMemoryMode;
527 /** The number of registered VMs. */
528 uint16_t cRegisteredVMs;
529
530 /** The previous allocated Chunk ID.
531 * Used as a hint to avoid scanning the whole bitmap. */
532 uint32_t idChunkPrev;
533 /** Chunk ID allocation bitmap.
534 * Bits of allocated IDs are set, free ones are clear.
535 * The NIL id (0) is marked allocated. */
536 uint32_t bmChunkId[(GMM_CHUNKID_LAST + 1 + 31) / 32];
537} GMM;
538/** Pointer to the GMM instance. */
539typedef GMM *PGMM;
540
541/** The value of GMM::u32Magic (Katsuhiro Otomo). */
542#define GMM_MAGIC 0x19540414
543
544
545/*******************************************************************************
546* Global Variables *
547*******************************************************************************/
548/** Pointer to the GMM instance data. */
549static PGMM g_pGMM = NULL;
550
551/** Macro for obtaining and validating the g_pGMM pointer.
552 * On failure it will return from the invoking function with the specified return value.
553 *
554 * @param pGMM The name of the pGMM variable.
555 * @param rc The return value on failure. Use VERR_INTERNAL_ERROR for
556 * VBox status codes.
557 */
558#define GMM_GET_VALID_INSTANCE(pGMM, rc) \
559 do { \
560 (pGMM) = g_pGMM; \
561 AssertPtrReturn((pGMM), (rc)); \
562 AssertMsgReturn((pGMM)->u32Magic == GMM_MAGIC, ("%p - %#x\n", (pGMM), (pGMM)->u32Magic), (rc)); \
563 } while (0)
564
565/** Macro for obtaining and validating the g_pGMM pointer, void function variant.
566 * On failure it will return from the invoking function.
567 *
568 * @param pGMM The name of the pGMM variable.
569 */
570#define GMM_GET_VALID_INSTANCE_VOID(pGMM) \
571 do { \
572 (pGMM) = g_pGMM; \
573 AssertPtrReturnVoid((pGMM)); \
574 AssertMsgReturnVoid((pGMM)->u32Magic == GMM_MAGIC, ("%p - %#x\n", (pGMM), (pGMM)->u32Magic)); \
575 } while (0)
576
577
578/** @def GMM_CHECK_SANITY_UPON_ENTERING
579 * Checks the sanity of the GMM instance data before making changes.
580 *
581 * This is macro is a stub by default and must be enabled manually in the code.
582 *
583 * @returns true if sane, false if not.
584 * @param pGMM The name of the pGMM variable.
585 */
586#if defined(VBOX_STRICT) && 0
587# define GMM_CHECK_SANITY_UPON_ENTERING(pGMM) (gmmR0SanityCheck((pGMM), __PRETTY_FUNCTION__, __LINE__) == 0)
588#else
589# define GMM_CHECK_SANITY_UPON_ENTERING(pGMM) (true)
590#endif
591
592/** @def GMM_CHECK_SANITY_UPON_LEAVING
593 * Checks the sanity of the GMM instance data after making changes.
594 *
595 * This is macro is a stub by default and must be enabled manually in the code.
596 *
597 * @returns true if sane, false if not.
598 * @param pGMM The name of the pGMM variable.
599 */
600#if defined(VBOX_STRICT) && 0
601# define GMM_CHECK_SANITY_UPON_LEAVING(pGMM) (gmmR0SanityCheck((pGMM), __PRETTY_FUNCTION__, __LINE__) == 0)
602#else
603# define GMM_CHECK_SANITY_UPON_LEAVING(pGMM) (true)
604#endif
605
606/** @def GMM_CHECK_SANITY_IN_LOOPS
607 * Checks the sanity of the GMM instance in the allocation loops.
608 *
609 * This is macro is a stub by default and must be enabled manually in the code.
610 *
611 * @returns true if sane, false if not.
612 * @param pGMM The name of the pGMM variable.
613 */
614#if defined(VBOX_STRICT) && 0
615# define GMM_CHECK_SANITY_IN_LOOPS(pGMM) (gmmR0SanityCheck((pGMM), __PRETTY_FUNCTION__, __LINE__) == 0)
616#else
617# define GMM_CHECK_SANITY_IN_LOOPS(pGMM) (true)
618#endif
619
620
621/*******************************************************************************
622* Internal Functions *
623*******************************************************************************/
624static DECLCALLBACK(int) gmmR0TermDestroyChunk(PAVLU32NODECORE pNode, void *pvGMM);
625static DECLCALLBACK(int) gmmR0CleanupVMScanChunk(PAVLU32NODECORE pNode, void *pvGMM);
626static DECLCALLBACK(int) gmmR0CleanupSharedModule(PAVLGCPTRNODECORE pNode, void *pvGVM);
627/*static*/ DECLCALLBACK(int) gmmR0CleanupVMDestroyChunk(PAVLU32NODECORE pNode, void *pvGVM);
628DECLINLINE(void) gmmR0LinkChunk(PGMMCHUNK pChunk, PGMMCHUNKFREESET pSet);
629DECLINLINE(void) gmmR0UnlinkChunk(PGMMCHUNK pChunk);
630static uint32_t gmmR0SanityCheck(PGMM pGMM, const char *pszFunction, unsigned uLineNo);
631static void gmmR0FreeChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk);
632static void gmmR0FreeSharedPage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage);
633static int gmmR0UnmapChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk);
634
635
636
637/**
638 * Initializes the GMM component.
639 *
640 * This is called when the VMMR0.r0 module is loaded and protected by the
641 * loader semaphore.
642 *
643 * @returns VBox status code.
644 */
645GMMR0DECL(int) GMMR0Init(void)
646{
647 LogFlow(("GMMInit:\n"));
648
649 /*
650 * Allocate the instance data and the lock(s).
651 */
652 PGMM pGMM = (PGMM)RTMemAllocZ(sizeof(*pGMM));
653 if (!pGMM)
654 return VERR_NO_MEMORY;
655 pGMM->u32Magic = GMM_MAGIC;
656 for (unsigned i = 0; i < RT_ELEMENTS(pGMM->ChunkTLB.aEntries); i++)
657 pGMM->ChunkTLB.aEntries[i].idChunk = NIL_GMM_CHUNKID;
658 ASMBitSet(&pGMM->bmChunkId[0], NIL_GMM_CHUNKID);
659
660 int rc = RTSemFastMutexCreate(&pGMM->Mtx);
661 if (RT_SUCCESS(rc))
662 {
663 /*
664 * Check and see if RTR0MemObjAllocPhysNC works.
665 */
666#if 0 /* later, see #3170. */
667 RTR0MEMOBJ MemObj;
668 rc = RTR0MemObjAllocPhysNC(&MemObj, _64K, NIL_RTHCPHYS);
669 if (RT_SUCCESS(rc))
670 {
671 rc = RTR0MemObjFree(MemObj, true);
672 AssertRC(rc);
673 }
674 else if (rc == VERR_NOT_SUPPORTED)
675 pGMM->fLegacyAllocationMode = pGMM->fBoundMemoryMode = true;
676 else
677 SUPR0Printf("GMMR0Init: RTR0MemObjAllocPhysNC(,64K,Any) -> %d!\n", rc);
678#else
679# if defined(RT_OS_WINDOWS) || (defined(RT_OS_SOLARIS) && ARCH_BITS == 64) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
680 pGMM->fLegacyAllocationMode = false;
681# if ARCH_BITS == 32
682 /* Don't reuse possibly partial chunks because of the virtual address space limitation. */
683 pGMM->fBoundMemoryMode = true;
684# else
685 pGMM->fBoundMemoryMode = false;
686# endif
687# else
688 pGMM->fLegacyAllocationMode = true;
689 pGMM->fBoundMemoryMode = true;
690# endif
691#endif
692
693 /*
694 * Query system page count and guess a reasonable cMaxPages value.
695 */
696 pGMM->cMaxPages = UINT32_MAX; /** @todo IPRT function for query ram size and such. */
697
698 g_pGMM = pGMM;
699 LogFlow(("GMMInit: pGMM=%p fLegacyAllocationMode=%RTbool fBoundMemoryMode=%RTbool\n", pGMM, pGMM->fLegacyAllocationMode, pGMM->fBoundMemoryMode));
700 return VINF_SUCCESS;
701 }
702
703 RTMemFree(pGMM);
704 SUPR0Printf("GMMR0Init: failed! rc=%d\n", rc);
705 return rc;
706}
707
708
709/**
710 * Terminates the GMM component.
711 */
712GMMR0DECL(void) GMMR0Term(void)
713{
714 LogFlow(("GMMTerm:\n"));
715
716 /*
717 * Take care / be paranoid...
718 */
719 PGMM pGMM = g_pGMM;
720 if (!VALID_PTR(pGMM))
721 return;
722 if (pGMM->u32Magic != GMM_MAGIC)
723 {
724 SUPR0Printf("GMMR0Term: u32Magic=%#x\n", pGMM->u32Magic);
725 return;
726 }
727
728 /*
729 * Undo what init did and free all the resources we've acquired.
730 */
731 /* Destroy the fundamentals. */
732 g_pGMM = NULL;
733 pGMM->u32Magic++;
734 RTSemFastMutexDestroy(pGMM->Mtx);
735 pGMM->Mtx = NIL_RTSEMFASTMUTEX;
736
737 /* free any chunks still hanging around. */
738 RTAvlU32Destroy(&pGMM->pChunks, gmmR0TermDestroyChunk, pGMM);
739
740 /* finally the instance data itself. */
741 RTMemFree(pGMM);
742 LogFlow(("GMMTerm: done\n"));
743}
744
745
746/**
747 * RTAvlU32Destroy callback.
748 *
749 * @returns 0
750 * @param pNode The node to destroy.
751 * @param pvGMM The GMM handle.
752 */
753static DECLCALLBACK(int) gmmR0TermDestroyChunk(PAVLU32NODECORE pNode, void *pvGMM)
754{
755 PGMMCHUNK pChunk = (PGMMCHUNK)pNode;
756
757 if (pChunk->cFree != (GMM_CHUNK_SIZE >> PAGE_SHIFT))
758 SUPR0Printf("GMMR0Term: %p/%#x: cFree=%d cPrivate=%d cShared=%d cMappings=%d\n", pChunk,
759 pChunk->Core.Key, pChunk->cFree, pChunk->cPrivate, pChunk->cShared, pChunk->cMappings);
760
761 int rc = RTR0MemObjFree(pChunk->MemObj, true /* fFreeMappings */);
762 if (RT_FAILURE(rc))
763 {
764 SUPR0Printf("GMMR0Term: %p/%#x: RTRMemObjFree(%p,true) -> %d (cMappings=%d)\n", pChunk,
765 pChunk->Core.Key, pChunk->MemObj, rc, pChunk->cMappings);
766 AssertRC(rc);
767 }
768 pChunk->MemObj = NIL_RTR0MEMOBJ;
769
770 RTMemFree(pChunk->paMappings);
771 pChunk->paMappings = NULL;
772
773 RTMemFree(pChunk);
774 NOREF(pvGMM);
775 return 0;
776}
777
778
779/**
780 * Initializes the per-VM data for the GMM.
781 *
782 * This is called from within the GVMM lock (from GVMMR0CreateVM)
783 * and should only initialize the data members so GMMR0CleanupVM
784 * can deal with them. We reserve no memory or anything here,
785 * that's done later in GMMR0InitVM.
786 *
787 * @param pGVM Pointer to the Global VM structure.
788 */
789GMMR0DECL(void) GMMR0InitPerVMData(PGVM pGVM)
790{
791 AssertCompile(RT_SIZEOFMEMB(GVM,gmm.s) <= RT_SIZEOFMEMB(GVM,gmm.padding));
792
793 pGVM->gmm.s.enmPolicy = GMMOCPOLICY_INVALID;
794 pGVM->gmm.s.enmPriority = GMMPRIORITY_INVALID;
795 pGVM->gmm.s.fMayAllocate = false;
796}
797
798
799/**
800 * Cleans up when a VM is terminating.
801 *
802 * @param pGVM Pointer to the Global VM structure.
803 */
804GMMR0DECL(void) GMMR0CleanupVM(PGVM pGVM)
805{
806 LogFlow(("GMMR0CleanupVM: pGVM=%p:{.pVM=%p, .hSelf=%#x}\n", pGVM, pGVM->pVM, pGVM->hSelf));
807
808 PGMM pGMM;
809 GMM_GET_VALID_INSTANCE_VOID(pGMM);
810
811 int rc = RTSemFastMutexRequest(pGMM->Mtx);
812 AssertRC(rc);
813 GMM_CHECK_SANITY_UPON_ENTERING(pGMM);
814
815#ifdef VBOX_WITH_PAGE_SHARING
816 /* Clean up all registered shared modules. */
817 RTAvlGCPtrDestroy(&pGVM->gmm.s.pSharedModuleTree, gmmR0CleanupSharedModule, pGVM);
818#endif
819
820 /*
821 * The policy is 'INVALID' until the initial reservation
822 * request has been serviced.
823 */
824 if ( pGVM->gmm.s.enmPolicy > GMMOCPOLICY_INVALID
825 && pGVM->gmm.s.enmPolicy < GMMOCPOLICY_END)
826 {
827 /*
828 * If it's the last VM around, we can skip walking all the chunk looking
829 * for the pages owned by this VM and instead flush the whole shebang.
830 *
831 * This takes care of the eventuality that a VM has left shared page
832 * references behind (shouldn't happen of course, but you never know).
833 */
834 Assert(pGMM->cRegisteredVMs);
835 pGMM->cRegisteredVMs--;
836#if 0 /* disabled so it won't hide bugs. */
837 if (!pGMM->cRegisteredVMs)
838 {
839 RTAvlU32Destroy(&pGMM->pChunks, gmmR0CleanupVMDestroyChunk, pGMM);
840
841 for (unsigned i = 0; i < RT_ELEMENTS(pGMM->ChunkTLB.aEntries); i++)
842 {
843 pGMM->ChunkTLB.aEntries[i].idChunk = NIL_GMM_CHUNKID;
844 pGMM->ChunkTLB.aEntries[i].pChunk = NULL;
845 }
846
847 memset(&pGMM->Private, 0, sizeof(pGMM->Private));
848 memset(&pGMM->Shared, 0, sizeof(pGMM->Shared));
849
850 memset(&pGMM->bmChunkId[0], 0, sizeof(pGMM->bmChunkId));
851 ASMBitSet(&pGMM->bmChunkId[0], NIL_GMM_CHUNKID);
852
853 pGMM->cReservedPages = 0;
854 pGMM->cOverCommittedPages = 0;
855 pGMM->cAllocatedPages = 0;
856 pGMM->cSharedPages = 0;
857 pGMM->cDuplicatePages = 0;
858 pGMM->cLeftBehindSharedPages = 0;
859 pGMM->cChunks = 0;
860 pGMM->cBalloonedPages = 0;
861 }
862 else
863#endif
864 {
865 /*
866 * Walk the entire pool looking for pages that belong to this VM
867 * and left over mappings. (This'll only catch private pages, shared
868 * pages will be 'left behind'.)
869 */
870 /** @todo this might be kind of expensive with a lot of VMs and
871 * memory hanging around... */
872 uint64_t cPrivatePages = pGVM->gmm.s.cPrivatePages; /* save */
873 RTAvlU32DoWithAll(&pGMM->pChunks, true /* fFromLeft */, gmmR0CleanupVMScanChunk, pGVM);
874 if (pGVM->gmm.s.cPrivatePages)
875 SUPR0Printf("GMMR0CleanupVM: hGVM=%#x has %#x private pages that cannot be found!\n", pGVM->hSelf, pGVM->gmm.s.cPrivatePages);
876 pGMM->cAllocatedPages -= cPrivatePages;
877
878 /* free empty chunks. */
879 if (cPrivatePages)
880 {
881 PGMMCHUNK pCur = pGMM->Private.apLists[RT_ELEMENTS(pGMM->Private.apLists) - 1];
882 while (pCur)
883 {
884 PGMMCHUNK pNext = pCur->pFreeNext;
885 if ( pCur->cFree == GMM_CHUNK_NUM_PAGES
886 && ( !pGMM->fBoundMemoryMode
887 || pCur->hGVM == pGVM->hSelf))
888 gmmR0FreeChunk(pGMM, pGVM, pCur);
889 pCur = pNext;
890 }
891 }
892
893 /* account for shared pages that weren't freed. */
894 if (pGVM->gmm.s.cSharedPages)
895 {
896 Assert(pGMM->cSharedPages >= pGVM->gmm.s.cSharedPages);
897 SUPR0Printf("GMMR0CleanupVM: hGVM=%#x left %#x shared pages behind!\n", pGVM->hSelf, pGVM->gmm.s.cSharedPages);
898 pGMM->cLeftBehindSharedPages += pGVM->gmm.s.cSharedPages;
899 }
900
901 /* Clean up balloon statistics in case the VM process crashed. */
902 Assert(pGMM->cBalloonedPages >= pGVM->gmm.s.cBalloonedPages);
903 pGMM->cBalloonedPages -= pGVM->gmm.s.cBalloonedPages;
904
905 /*
906 * Update the over-commitment management statistics.
907 */
908 pGMM->cReservedPages -= pGVM->gmm.s.Reserved.cBasePages
909 + pGVM->gmm.s.Reserved.cFixedPages
910 + pGVM->gmm.s.Reserved.cShadowPages;
911 switch (pGVM->gmm.s.enmPolicy)
912 {
913 case GMMOCPOLICY_NO_OC:
914 break;
915 default:
916 /** @todo Update GMM->cOverCommittedPages */
917 break;
918 }
919 }
920 }
921
922 /* zap the GVM data. */
923 pGVM->gmm.s.enmPolicy = GMMOCPOLICY_INVALID;
924 pGVM->gmm.s.enmPriority = GMMPRIORITY_INVALID;
925 pGVM->gmm.s.fMayAllocate = false;
926
927 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
928 RTSemFastMutexRelease(pGMM->Mtx);
929
930 LogFlow(("GMMR0CleanupVM: returns\n"));
931}
932
933
934/**
935 * RTAvlU32DoWithAll callback.
936 *
937 * @returns 0
938 * @param pNode The node to search.
939 * @param pvGVM Pointer to the shared VM structure.
940 */
941static DECLCALLBACK(int) gmmR0CleanupVMScanChunk(PAVLU32NODECORE pNode, void *pvGVM)
942{
943 PGMMCHUNK pChunk = (PGMMCHUNK)pNode;
944 PGVM pGVM = (PGVM)pvGVM;
945
946 /*
947 * Look for pages belonging to the VM.
948 * (Perform some internal checks while we're scanning.)
949 */
950#ifndef VBOX_STRICT
951 if (pChunk->cFree != (GMM_CHUNK_SIZE >> PAGE_SHIFT))
952#endif
953 {
954 unsigned cPrivate = 0;
955 unsigned cShared = 0;
956 unsigned cFree = 0;
957
958 gmmR0UnlinkChunk(pChunk); /* avoiding cFreePages updates. */
959
960 uint16_t hGVM = pGVM->hSelf;
961 unsigned iPage = (GMM_CHUNK_SIZE >> PAGE_SHIFT);
962 while (iPage-- > 0)
963 if (GMM_PAGE_IS_PRIVATE(&pChunk->aPages[iPage]))
964 {
965 if (pChunk->aPages[iPage].Private.hGVM == hGVM)
966 {
967 /*
968 * Free the page.
969 *
970 * The reason for not using gmmR0FreePrivatePage here is that we
971 * must *not* cause the chunk to be freed from under us - we're in
972 * an AVL tree walk here.
973 */
974 pChunk->aPages[iPage].u = 0;
975 pChunk->aPages[iPage].Free.iNext = pChunk->iFreeHead;
976 pChunk->aPages[iPage].Free.u2State = GMM_PAGE_STATE_FREE;
977 pChunk->iFreeHead = iPage;
978 pChunk->cPrivate--;
979 pChunk->cFree++;
980 pGVM->gmm.s.cPrivatePages--;
981 cFree++;
982 }
983 else
984 cPrivate++;
985 }
986 else if (GMM_PAGE_IS_FREE(&pChunk->aPages[iPage]))
987 cFree++;
988 else
989 cShared++;
990
991 gmmR0LinkChunk(pChunk, pChunk->cShared ? &g_pGMM->Shared : &g_pGMM->Private);
992
993 /*
994 * Did it add up?
995 */
996 if (RT_UNLIKELY( pChunk->cFree != cFree
997 || pChunk->cPrivate != cPrivate
998 || pChunk->cShared != cShared))
999 {
1000 SUPR0Printf("gmmR0CleanupVMScanChunk: Chunk %p/%#x has bogus stats - free=%d/%d private=%d/%d shared=%d/%d\n",
1001 pChunk->cFree, cFree, pChunk->cPrivate, cPrivate, pChunk->cShared, cShared);
1002 pChunk->cFree = cFree;
1003 pChunk->cPrivate = cPrivate;
1004 pChunk->cShared = cShared;
1005 }
1006 }
1007
1008 /*
1009 * Look for the mapping belonging to the terminating VM.
1010 */
1011 for (unsigned i = 0; i < pChunk->cMappings; i++)
1012 if (pChunk->paMappings[i].pGVM == pGVM)
1013 {
1014 RTR0MEMOBJ MemObj = pChunk->paMappings[i].MapObj;
1015
1016 pChunk->cMappings--;
1017 if (i < pChunk->cMappings)
1018 pChunk->paMappings[i] = pChunk->paMappings[pChunk->cMappings];
1019 pChunk->paMappings[pChunk->cMappings].pGVM = NULL;
1020 pChunk->paMappings[pChunk->cMappings].MapObj = NIL_RTR0MEMOBJ;
1021
1022 int rc = RTR0MemObjFree(MemObj, false /* fFreeMappings (NA) */);
1023 if (RT_FAILURE(rc))
1024 {
1025 SUPR0Printf("gmmR0CleanupVMScanChunk: %p/%#x: mapping #%x: RTRMemObjFree(%p,false) -> %d \n",
1026 pChunk, pChunk->Core.Key, i, MemObj, rc);
1027 AssertRC(rc);
1028 }
1029 break;
1030 }
1031
1032 /*
1033 * If not in bound memory mode, we should reset the hGVM field
1034 * if it has our handle in it.
1035 */
1036 if (pChunk->hGVM == pGVM->hSelf)
1037 {
1038 if (!g_pGMM->fBoundMemoryMode)
1039 pChunk->hGVM = NIL_GVM_HANDLE;
1040 else if (pChunk->cFree != GMM_CHUNK_NUM_PAGES)
1041 {
1042 SUPR0Printf("gmmR0CleanupVMScanChunk: %p/%#x: cFree=%#x - it should be 0 in bound mode!\n",
1043 pChunk, pChunk->Core.Key, pChunk->cFree);
1044 AssertMsgFailed(("%p/%#x: cFree=%#x - it should be 0 in bound mode!\n", pChunk, pChunk->Core.Key, pChunk->cFree));
1045
1046 gmmR0UnlinkChunk(pChunk);
1047 pChunk->cFree = GMM_CHUNK_NUM_PAGES;
1048 gmmR0LinkChunk(pChunk, pChunk->cShared ? &g_pGMM->Shared : &g_pGMM->Private);
1049 }
1050 }
1051
1052 return 0;
1053}
1054
1055
1056/**
1057 * RTAvlU32Destroy callback for GMMR0CleanupVM.
1058 *
1059 * @returns 0
1060 * @param pNode The node (allocation chunk) to destroy.
1061 * @param pvGVM Pointer to the shared VM structure.
1062 */
1063/*static*/ DECLCALLBACK(int) gmmR0CleanupVMDestroyChunk(PAVLU32NODECORE pNode, void *pvGVM)
1064{
1065 PGMMCHUNK pChunk = (PGMMCHUNK)pNode;
1066 PGVM pGVM = (PGVM)pvGVM;
1067
1068 for (unsigned i = 0; i < pChunk->cMappings; i++)
1069 {
1070 if (pChunk->paMappings[i].pGVM != pGVM)
1071 SUPR0Printf("gmmR0CleanupVMDestroyChunk: %p/%#x: mapping #%x: pGVM=%p exepcted %p\n", pChunk,
1072 pChunk->Core.Key, i, pChunk->paMappings[i].pGVM, pGVM);
1073 int rc = RTR0MemObjFree(pChunk->paMappings[i].MapObj, false /* fFreeMappings (NA) */);
1074 if (RT_FAILURE(rc))
1075 {
1076 SUPR0Printf("gmmR0CleanupVMDestroyChunk: %p/%#x: mapping #%x: RTRMemObjFree(%p,false) -> %d \n", pChunk,
1077 pChunk->Core.Key, i, pChunk->paMappings[i].MapObj, rc);
1078 AssertRC(rc);
1079 }
1080 }
1081
1082 int rc = RTR0MemObjFree(pChunk->MemObj, true /* fFreeMappings */);
1083 if (RT_FAILURE(rc))
1084 {
1085 SUPR0Printf("gmmR0CleanupVMDestroyChunk: %p/%#x: RTRMemObjFree(%p,true) -> %d (cMappings=%d)\n", pChunk,
1086 pChunk->Core.Key, pChunk->MemObj, rc, pChunk->cMappings);
1087 AssertRC(rc);
1088 }
1089 pChunk->MemObj = NIL_RTR0MEMOBJ;
1090
1091 RTMemFree(pChunk->paMappings);
1092 pChunk->paMappings = NULL;
1093
1094 RTMemFree(pChunk);
1095 return 0;
1096}
1097
1098
1099/**
1100 * The initial resource reservations.
1101 *
1102 * This will make memory reservations according to policy and priority. If there aren't
1103 * sufficient resources available to sustain the VM this function will fail and all
1104 * future allocations requests will fail as well.
1105 *
1106 * These are just the initial reservations made very very early during the VM creation
1107 * process and will be adjusted later in the GMMR0UpdateReservation call after the
1108 * ring-3 init has completed.
1109 *
1110 * @returns VBox status code.
1111 * @retval VERR_GMM_MEMORY_RESERVATION_DECLINED
1112 * @retval VERR_GMM_
1113 *
1114 * @param pVM Pointer to the shared VM structure.
1115 * @param idCpu VCPU id
1116 * @param cBasePages The number of pages that may be allocated for the base RAM and ROMs.
1117 * This does not include MMIO2 and similar.
1118 * @param cShadowPages The number of pages that may be allocated for shadow paging structures.
1119 * @param cFixedPages The number of pages that may be allocated for fixed objects like the
1120 * hyper heap, MMIO2 and similar.
1121 * @param enmPolicy The OC policy to use on this VM.
1122 * @param enmPriority The priority in an out-of-memory situation.
1123 *
1124 * @thread The creator thread / EMT.
1125 */
1126GMMR0DECL(int) GMMR0InitialReservation(PVM pVM, VMCPUID idCpu, uint64_t cBasePages, uint32_t cShadowPages, uint32_t cFixedPages,
1127 GMMOCPOLICY enmPolicy, GMMPRIORITY enmPriority)
1128{
1129 LogFlow(("GMMR0InitialReservation: pVM=%p cBasePages=%#llx cShadowPages=%#x cFixedPages=%#x enmPolicy=%d enmPriority=%d\n",
1130 pVM, cBasePages, cShadowPages, cFixedPages, enmPolicy, enmPriority));
1131
1132 /*
1133 * Validate, get basics and take the semaphore.
1134 */
1135 PGMM pGMM;
1136 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
1137 PGVM pGVM;
1138 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
1139 if (RT_FAILURE(rc))
1140 return rc;
1141
1142 AssertReturn(cBasePages, VERR_INVALID_PARAMETER);
1143 AssertReturn(cShadowPages, VERR_INVALID_PARAMETER);
1144 AssertReturn(cFixedPages, VERR_INVALID_PARAMETER);
1145 AssertReturn(enmPolicy > GMMOCPOLICY_INVALID && enmPolicy < GMMOCPOLICY_END, VERR_INVALID_PARAMETER);
1146 AssertReturn(enmPriority > GMMPRIORITY_INVALID && enmPriority < GMMPRIORITY_END, VERR_INVALID_PARAMETER);
1147
1148 rc = RTSemFastMutexRequest(pGMM->Mtx);
1149 AssertRC(rc);
1150 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
1151 {
1152 if ( !pGVM->gmm.s.Reserved.cBasePages
1153 && !pGVM->gmm.s.Reserved.cFixedPages
1154 && !pGVM->gmm.s.Reserved.cShadowPages)
1155 {
1156 /*
1157 * Check if we can accommodate this.
1158 */
1159 /* ... later ... */
1160 if (RT_SUCCESS(rc))
1161 {
1162 /*
1163 * Update the records.
1164 */
1165 pGVM->gmm.s.Reserved.cBasePages = cBasePages;
1166 pGVM->gmm.s.Reserved.cFixedPages = cFixedPages;
1167 pGVM->gmm.s.Reserved.cShadowPages = cShadowPages;
1168 pGVM->gmm.s.enmPolicy = enmPolicy;
1169 pGVM->gmm.s.enmPriority = enmPriority;
1170 pGVM->gmm.s.fMayAllocate = true;
1171
1172 pGMM->cReservedPages += cBasePages + cFixedPages + cShadowPages;
1173 pGMM->cRegisteredVMs++;
1174 }
1175 }
1176 else
1177 rc = VERR_WRONG_ORDER;
1178 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
1179 }
1180 else
1181 rc = VERR_INTERNAL_ERROR_5;
1182 RTSemFastMutexRelease(pGMM->Mtx);
1183 LogFlow(("GMMR0InitialReservation: returns %Rrc\n", rc));
1184 return rc;
1185}
1186
1187
1188/**
1189 * VMMR0 request wrapper for GMMR0InitialReservation.
1190 *
1191 * @returns see GMMR0InitialReservation.
1192 * @param pVM Pointer to the shared VM structure.
1193 * @param idCpu VCPU id
1194 * @param pReq The request packet.
1195 */
1196GMMR0DECL(int) GMMR0InitialReservationReq(PVM pVM, VMCPUID idCpu, PGMMINITIALRESERVATIONREQ pReq)
1197{
1198 /*
1199 * Validate input and pass it on.
1200 */
1201 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1202 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1203 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
1204
1205 return GMMR0InitialReservation(pVM, idCpu, pReq->cBasePages, pReq->cShadowPages, pReq->cFixedPages, pReq->enmPolicy, pReq->enmPriority);
1206}
1207
1208
1209/**
1210 * This updates the memory reservation with the additional MMIO2 and ROM pages.
1211 *
1212 * @returns VBox status code.
1213 * @retval VERR_GMM_MEMORY_RESERVATION_DECLINED
1214 *
1215 * @param pVM Pointer to the shared VM structure.
1216 * @param idCpu VCPU id
1217 * @param cBasePages The number of pages that may be allocated for the base RAM and ROMs.
1218 * This does not include MMIO2 and similar.
1219 * @param cShadowPages The number of pages that may be allocated for shadow paging structures.
1220 * @param cFixedPages The number of pages that may be allocated for fixed objects like the
1221 * hyper heap, MMIO2 and similar.
1222 *
1223 * @thread EMT.
1224 */
1225GMMR0DECL(int) GMMR0UpdateReservation(PVM pVM, VMCPUID idCpu, uint64_t cBasePages, uint32_t cShadowPages, uint32_t cFixedPages)
1226{
1227 LogFlow(("GMMR0UpdateReservation: pVM=%p cBasePages=%#llx cShadowPages=%#x cFixedPages=%#x\n",
1228 pVM, cBasePages, cShadowPages, cFixedPages));
1229
1230 /*
1231 * Validate, get basics and take the semaphore.
1232 */
1233 PGMM pGMM;
1234 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
1235 PGVM pGVM;
1236 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
1237 if (RT_FAILURE(rc))
1238 return rc;
1239
1240 AssertReturn(cBasePages, VERR_INVALID_PARAMETER);
1241 AssertReturn(cShadowPages, VERR_INVALID_PARAMETER);
1242 AssertReturn(cFixedPages, VERR_INVALID_PARAMETER);
1243
1244 rc = RTSemFastMutexRequest(pGMM->Mtx);
1245 AssertRC(rc);
1246 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
1247 {
1248 if ( pGVM->gmm.s.Reserved.cBasePages
1249 && pGVM->gmm.s.Reserved.cFixedPages
1250 && pGVM->gmm.s.Reserved.cShadowPages)
1251 {
1252 /*
1253 * Check if we can accommodate this.
1254 */
1255 /* ... later ... */
1256 if (RT_SUCCESS(rc))
1257 {
1258 /*
1259 * Update the records.
1260 */
1261 pGMM->cReservedPages -= pGVM->gmm.s.Reserved.cBasePages
1262 + pGVM->gmm.s.Reserved.cFixedPages
1263 + pGVM->gmm.s.Reserved.cShadowPages;
1264 pGMM->cReservedPages += cBasePages + cFixedPages + cShadowPages;
1265
1266 pGVM->gmm.s.Reserved.cBasePages = cBasePages;
1267 pGVM->gmm.s.Reserved.cFixedPages = cFixedPages;
1268 pGVM->gmm.s.Reserved.cShadowPages = cShadowPages;
1269 }
1270 }
1271 else
1272 rc = VERR_WRONG_ORDER;
1273 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
1274 }
1275 else
1276 rc = VERR_INTERNAL_ERROR_5;
1277 RTSemFastMutexRelease(pGMM->Mtx);
1278 LogFlow(("GMMR0UpdateReservation: returns %Rrc\n", rc));
1279 return rc;
1280}
1281
1282
1283/**
1284 * VMMR0 request wrapper for GMMR0UpdateReservation.
1285 *
1286 * @returns see GMMR0UpdateReservation.
1287 * @param pVM Pointer to the shared VM structure.
1288 * @param idCpu VCPU id
1289 * @param pReq The request packet.
1290 */
1291GMMR0DECL(int) GMMR0UpdateReservationReq(PVM pVM, VMCPUID idCpu, PGMMUPDATERESERVATIONREQ pReq)
1292{
1293 /*
1294 * Validate input and pass it on.
1295 */
1296 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1297 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1298 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
1299
1300 return GMMR0UpdateReservation(pVM, idCpu, pReq->cBasePages, pReq->cShadowPages, pReq->cFixedPages);
1301}
1302
1303
1304/**
1305 * Performs sanity checks on a free set.
1306 *
1307 * @returns Error count.
1308 *
1309 * @param pGMM Pointer to the GMM instance.
1310 * @param pSet Pointer to the set.
1311 * @param pszSetName The set name.
1312 * @param pszFunction The function from which it was called.
1313 * @param uLine The line number.
1314 */
1315static uint32_t gmmR0SanityCheckSet(PGMM pGMM, PGMMCHUNKFREESET pSet, const char *pszSetName,
1316 const char *pszFunction, unsigned uLineNo)
1317{
1318 uint32_t cErrors = 0;
1319
1320 /*
1321 * Count the free pages in all the chunks and match it against pSet->cFreePages.
1322 */
1323 uint32_t cPages = 0;
1324 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists); i++)
1325 {
1326 for (PGMMCHUNK pCur = pSet->apLists[i]; pCur; pCur = pCur->pFreeNext)
1327 {
1328 /** @todo check that the chunk is hash into the right set. */
1329 cPages += pCur->cFree;
1330 }
1331 }
1332 if (RT_UNLIKELY(cPages != pSet->cFreePages))
1333 {
1334 SUPR0Printf("GMM insanity: found %#x pages in the %s set, expected %#x. (%s, line %u)\n",
1335 cPages, pszSetName, pSet->cFreePages, pszFunction, uLineNo);
1336 cErrors++;
1337 }
1338
1339 return cErrors;
1340}
1341
1342
1343/**
1344 * Performs some sanity checks on the GMM while owning lock.
1345 *
1346 * @returns Error count.
1347 *
1348 * @param pGMM Pointer to the GMM instance.
1349 * @param pszFunction The function from which it is called.
1350 * @param uLineNo The line number.
1351 */
1352static uint32_t gmmR0SanityCheck(PGMM pGMM, const char *pszFunction, unsigned uLineNo)
1353{
1354 uint32_t cErrors = 0;
1355
1356 cErrors += gmmR0SanityCheckSet(pGMM, &pGMM->Private, "private", pszFunction, uLineNo);
1357 cErrors += gmmR0SanityCheckSet(pGMM, &pGMM->Shared, "shared", pszFunction, uLineNo);
1358 /** @todo add more sanity checks. */
1359
1360 return cErrors;
1361}
1362
1363
1364/**
1365 * Looks up a chunk in the tree and fill in the TLB entry for it.
1366 *
1367 * This is not expected to fail and will bitch if it does.
1368 *
1369 * @returns Pointer to the allocation chunk, NULL if not found.
1370 * @param pGMM Pointer to the GMM instance.
1371 * @param idChunk The ID of the chunk to find.
1372 * @param pTlbe Pointer to the TLB entry.
1373 */
1374static PGMMCHUNK gmmR0GetChunkSlow(PGMM pGMM, uint32_t idChunk, PGMMCHUNKTLBE pTlbe)
1375{
1376 PGMMCHUNK pChunk = (PGMMCHUNK)RTAvlU32Get(&pGMM->pChunks, idChunk);
1377 AssertMsgReturn(pChunk, ("Chunk %#x not found!\n", idChunk), NULL);
1378 pTlbe->idChunk = idChunk;
1379 pTlbe->pChunk = pChunk;
1380 return pChunk;
1381}
1382
1383
1384/**
1385 * Finds a allocation chunk.
1386 *
1387 * This is not expected to fail and will bitch if it does.
1388 *
1389 * @returns Pointer to the allocation chunk, NULL if not found.
1390 * @param pGMM Pointer to the GMM instance.
1391 * @param idChunk The ID of the chunk to find.
1392 */
1393DECLINLINE(PGMMCHUNK) gmmR0GetChunk(PGMM pGMM, uint32_t idChunk)
1394{
1395 /*
1396 * Do a TLB lookup, branch if not in the TLB.
1397 */
1398 PGMMCHUNKTLBE pTlbe = &pGMM->ChunkTLB.aEntries[GMM_CHUNKTLB_IDX(idChunk)];
1399 if ( pTlbe->idChunk != idChunk
1400 || !pTlbe->pChunk)
1401 return gmmR0GetChunkSlow(pGMM, idChunk, pTlbe);
1402 return pTlbe->pChunk;
1403}
1404
1405
1406/**
1407 * Finds a page.
1408 *
1409 * This is not expected to fail and will bitch if it does.
1410 *
1411 * @returns Pointer to the page, NULL if not found.
1412 * @param pGMM Pointer to the GMM instance.
1413 * @param idPage The ID of the page to find.
1414 */
1415DECLINLINE(PGMMPAGE) gmmR0GetPage(PGMM pGMM, uint32_t idPage)
1416{
1417 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
1418 if (RT_LIKELY(pChunk))
1419 return &pChunk->aPages[idPage & GMM_PAGEID_IDX_MASK];
1420 return NULL;
1421}
1422
1423
1424/**
1425 * Unlinks the chunk from the free list it's currently on (if any).
1426 *
1427 * @param pChunk The allocation chunk.
1428 */
1429DECLINLINE(void) gmmR0UnlinkChunk(PGMMCHUNK pChunk)
1430{
1431 PGMMCHUNKFREESET pSet = pChunk->pSet;
1432 if (RT_LIKELY(pSet))
1433 {
1434 pSet->cFreePages -= pChunk->cFree;
1435
1436 PGMMCHUNK pPrev = pChunk->pFreePrev;
1437 PGMMCHUNK pNext = pChunk->pFreeNext;
1438 if (pPrev)
1439 pPrev->pFreeNext = pNext;
1440 else
1441 pSet->apLists[(pChunk->cFree - 1) >> GMM_CHUNK_FREE_SET_SHIFT] = pNext;
1442 if (pNext)
1443 pNext->pFreePrev = pPrev;
1444
1445 pChunk->pSet = NULL;
1446 pChunk->pFreeNext = NULL;
1447 pChunk->pFreePrev = NULL;
1448 }
1449 else
1450 {
1451 Assert(!pChunk->pFreeNext);
1452 Assert(!pChunk->pFreePrev);
1453 Assert(!pChunk->cFree);
1454 }
1455}
1456
1457
1458/**
1459 * Links the chunk onto the appropriate free list in the specified free set.
1460 *
1461 * If no free entries, it's not linked into any list.
1462 *
1463 * @param pChunk The allocation chunk.
1464 * @param pSet The free set.
1465 */
1466DECLINLINE(void) gmmR0LinkChunk(PGMMCHUNK pChunk, PGMMCHUNKFREESET pSet)
1467{
1468 Assert(!pChunk->pSet);
1469 Assert(!pChunk->pFreeNext);
1470 Assert(!pChunk->pFreePrev);
1471
1472 if (pChunk->cFree > 0)
1473 {
1474 pChunk->pSet = pSet;
1475 pChunk->pFreePrev = NULL;
1476 unsigned iList = (pChunk->cFree - 1) >> GMM_CHUNK_FREE_SET_SHIFT;
1477 pChunk->pFreeNext = pSet->apLists[iList];
1478 if (pChunk->pFreeNext)
1479 pChunk->pFreeNext->pFreePrev = pChunk;
1480 pSet->apLists[iList] = pChunk;
1481
1482 pSet->cFreePages += pChunk->cFree;
1483 }
1484}
1485
1486
1487/**
1488 * Frees a Chunk ID.
1489 *
1490 * @param pGMM Pointer to the GMM instance.
1491 * @param idChunk The Chunk ID to free.
1492 */
1493static void gmmR0FreeChunkId(PGMM pGMM, uint32_t idChunk)
1494{
1495 AssertReturnVoid(idChunk != NIL_GMM_CHUNKID);
1496 AssertMsg(ASMBitTest(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk));
1497 ASMAtomicBitClear(&pGMM->bmChunkId[0], idChunk);
1498}
1499
1500
1501/**
1502 * Allocates a new Chunk ID.
1503 *
1504 * @returns The Chunk ID.
1505 * @param pGMM Pointer to the GMM instance.
1506 */
1507static uint32_t gmmR0AllocateChunkId(PGMM pGMM)
1508{
1509 AssertCompile(!((GMM_CHUNKID_LAST + 1) & 31)); /* must be a multiple of 32 */
1510 AssertCompile(NIL_GMM_CHUNKID == 0);
1511
1512 /*
1513 * Try the next sequential one.
1514 */
1515 int32_t idChunk = ++pGMM->idChunkPrev;
1516#if 0 /* test the fallback first */
1517 if ( idChunk <= GMM_CHUNKID_LAST
1518 && idChunk > NIL_GMM_CHUNKID
1519 && !ASMAtomicBitTestAndSet(&pVMM->bmChunkId[0], idChunk))
1520 return idChunk;
1521#endif
1522
1523 /*
1524 * Scan sequentially from the last one.
1525 */
1526 if ( (uint32_t)idChunk < GMM_CHUNKID_LAST
1527 && idChunk > NIL_GMM_CHUNKID)
1528 {
1529 idChunk = ASMBitNextClear(&pGMM->bmChunkId[0], GMM_CHUNKID_LAST + 1, idChunk);
1530 if (idChunk > NIL_GMM_CHUNKID)
1531 {
1532 AssertMsgReturn(!ASMAtomicBitTestAndSet(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk), NIL_GMM_CHUNKID);
1533 return pGMM->idChunkPrev = idChunk;
1534 }
1535 }
1536
1537 /*
1538 * Ok, scan from the start.
1539 * We're not racing anyone, so there is no need to expect failures or have restart loops.
1540 */
1541 idChunk = ASMBitFirstClear(&pGMM->bmChunkId[0], GMM_CHUNKID_LAST + 1);
1542 AssertMsgReturn(idChunk > NIL_GMM_CHUNKID, ("%#x\n", idChunk), NIL_GVM_HANDLE);
1543 AssertMsgReturn(!ASMAtomicBitTestAndSet(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk), NIL_GMM_CHUNKID);
1544
1545 return pGMM->idChunkPrev = idChunk;
1546}
1547
1548
1549/**
1550 * Registers a new chunk of memory.
1551 *
1552 * This is called by both gmmR0AllocateOneChunk and GMMR0SeedChunk. The caller
1553 * must own the global lock.
1554 *
1555 * @returns VBox status code.
1556 * @param pGMM Pointer to the GMM instance.
1557 * @param pSet Pointer to the set.
1558 * @param MemObj The memory object for the chunk.
1559 * @param hGVM The affinity of the chunk. NIL_GVM_HANDLE for no
1560 * affinity.
1561 * @param enmChunkType Chunk type (continuous or non-continuous)
1562 * @param ppChunk Chunk address (out)
1563 */
1564static int gmmR0RegisterChunk(PGMM pGMM, PGMMCHUNKFREESET pSet, RTR0MEMOBJ MemObj, uint16_t hGVM, GMMCHUNKTYPE enmChunkType, PGMMCHUNK *ppChunk = NULL)
1565{
1566 Assert(hGVM != NIL_GVM_HANDLE || pGMM->fBoundMemoryMode);
1567
1568 int rc;
1569 PGMMCHUNK pChunk = (PGMMCHUNK)RTMemAllocZ(sizeof(*pChunk));
1570 if (pChunk)
1571 {
1572 /*
1573 * Initialize it.
1574 */
1575 pChunk->MemObj = MemObj;
1576 pChunk->cFree = GMM_CHUNK_NUM_PAGES;
1577 pChunk->hGVM = hGVM;
1578 pChunk->iFreeHead = 0;
1579 pChunk->enmType = enmChunkType;
1580 for (unsigned iPage = 0; iPage < RT_ELEMENTS(pChunk->aPages) - 1; iPage++)
1581 {
1582 pChunk->aPages[iPage].Free.u2State = GMM_PAGE_STATE_FREE;
1583 pChunk->aPages[iPage].Free.iNext = iPage + 1;
1584 }
1585 pChunk->aPages[RT_ELEMENTS(pChunk->aPages) - 1].Free.u2State = GMM_PAGE_STATE_FREE;
1586 pChunk->aPages[RT_ELEMENTS(pChunk->aPages) - 1].Free.iNext = UINT16_MAX;
1587
1588 /*
1589 * Allocate a Chunk ID and insert it into the tree.
1590 * This has to be done behind the mutex of course.
1591 */
1592 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
1593 {
1594 pChunk->Core.Key = gmmR0AllocateChunkId(pGMM);
1595 if ( pChunk->Core.Key != NIL_GMM_CHUNKID
1596 && pChunk->Core.Key <= GMM_CHUNKID_LAST
1597 && RTAvlU32Insert(&pGMM->pChunks, &pChunk->Core))
1598 {
1599 pGMM->cChunks++;
1600 gmmR0LinkChunk(pChunk, pSet);
1601 LogFlow(("gmmR0RegisterChunk: pChunk=%p id=%#x cChunks=%d\n", pChunk, pChunk->Core.Key, pGMM->cChunks));
1602
1603 if (ppChunk)
1604 *ppChunk = pChunk;
1605
1606 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
1607 return VINF_SUCCESS;
1608 }
1609
1610 /* bail out */
1611 rc = VERR_INTERNAL_ERROR;
1612 }
1613 else
1614 rc = VERR_INTERNAL_ERROR_5;
1615
1616 RTMemFree(pChunk);
1617 }
1618 else
1619 rc = VERR_NO_MEMORY;
1620 return rc;
1621}
1622
1623
1624/**
1625 * Allocate one new chunk and add it to the specified free set.
1626 *
1627 * @returns VBox status code.
1628 * @param pGMM Pointer to the GMM instance.
1629 * @param pSet Pointer to the set.
1630 * @param hGVM The affinity of the new chunk.
1631 * @param enmChunkType Chunk type (continuous or non-continuous)
1632 * @param ppChunk Chunk address (out)
1633 *
1634 * @remarks Called without owning the mutex.
1635 */
1636static int gmmR0AllocateOneChunk(PGMM pGMM, PGMMCHUNKFREESET pSet, uint16_t hGVM, GMMCHUNKTYPE enmChunkType, PGMMCHUNK *ppChunk = NULL)
1637{
1638 /*
1639 * Allocate the memory.
1640 */
1641 RTR0MEMOBJ MemObj;
1642 int rc;
1643
1644 AssertCompile(GMM_CHUNK_SIZE == _2M);
1645 AssertReturn(enmChunkType == GMMCHUNKTYPE_NON_CONTINUOUS || enmChunkType == GMMCHUNKTYPE_CONTINUOUS, VERR_INVALID_PARAMETER);
1646
1647 /* Leave the lock temporarily as the allocation might take long. */
1648 RTSemFastMutexRelease(pGMM->Mtx);
1649 if (enmChunkType == GMMCHUNKTYPE_NON_CONTINUOUS)
1650 rc = RTR0MemObjAllocPhysNC(&MemObj, GMM_CHUNK_SIZE, NIL_RTHCPHYS);
1651 else
1652 rc = RTR0MemObjAllocPhysEx(&MemObj, GMM_CHUNK_SIZE, NIL_RTHCPHYS, GMM_CHUNK_SIZE);
1653
1654 /* Grab the lock again. */
1655 int rc2 = RTSemFastMutexRequest(pGMM->Mtx);
1656 AssertRCReturn(rc2, rc2);
1657
1658 if (RT_SUCCESS(rc))
1659 {
1660 rc = gmmR0RegisterChunk(pGMM, pSet, MemObj, hGVM, enmChunkType, ppChunk);
1661 if (RT_FAILURE(rc))
1662 RTR0MemObjFree(MemObj, false /* fFreeMappings */);
1663 }
1664 /** @todo Check that RTR0MemObjAllocPhysNC always returns VERR_NO_MEMORY on
1665 * allocation failure. */
1666 return rc;
1667}
1668
1669
1670/**
1671 * Attempts to allocate more pages until the requested amount is met.
1672 *
1673 * @returns VBox status code.
1674 * @param pGMM Pointer to the GMM instance data.
1675 * @param pGVM The calling VM.
1676 * @param pSet Pointer to the free set to grow.
1677 * @param cPages The number of pages needed.
1678 *
1679 * @remarks Called owning the mutex, but will leave it temporarily while
1680 * allocating the memory!
1681 */
1682static int gmmR0AllocateMoreChunks(PGMM pGMM, PGVM pGVM, PGMMCHUNKFREESET pSet, uint32_t cPages)
1683{
1684 Assert(!pGMM->fLegacyAllocationMode);
1685
1686 if (!GMM_CHECK_SANITY_IN_LOOPS(pGMM))
1687 return VERR_INTERNAL_ERROR_4;
1688
1689 if (!pGMM->fBoundMemoryMode)
1690 {
1691 /*
1692 * Try steal free chunks from the other set first. (Only take 100% free chunks.)
1693 */
1694 PGMMCHUNKFREESET pOtherSet = pSet == &pGMM->Private ? &pGMM->Shared : &pGMM->Private;
1695 while ( pSet->cFreePages < cPages
1696 && pOtherSet->cFreePages >= GMM_CHUNK_NUM_PAGES)
1697 {
1698 PGMMCHUNK pChunk = pOtherSet->apLists[GMM_CHUNK_FREE_SET_LISTS - 1];
1699 while (pChunk && pChunk->cFree != GMM_CHUNK_NUM_PAGES)
1700 pChunk = pChunk->pFreeNext;
1701 if (!pChunk)
1702 break;
1703
1704 gmmR0UnlinkChunk(pChunk);
1705 gmmR0LinkChunk(pChunk, pSet);
1706 }
1707
1708 /*
1709 * If we need still more pages, allocate new chunks.
1710 * Note! We will leave the mutex while doing the allocation,
1711 */
1712 while (pSet->cFreePages < cPages)
1713 {
1714 int rc = gmmR0AllocateOneChunk(pGMM, pSet, pGVM->hSelf, GMMCHUNKTYPE_NON_CONTINUOUS);
1715 if (RT_FAILURE(rc))
1716 return rc;
1717 if (!GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
1718 return VERR_INTERNAL_ERROR_5;
1719 }
1720 }
1721 else
1722 {
1723 /*
1724 * The memory is bound to the VM allocating it, so we have to count
1725 * the free pages carefully as well as making sure we brand them with
1726 * our VM handle.
1727 *
1728 * Note! We will leave the mutex while doing the allocation,
1729 */
1730 uint16_t const hGVM = pGVM->hSelf;
1731 for (;;)
1732 {
1733 /* Count and see if we've reached the goal. */
1734 uint32_t cPagesFound = 0;
1735 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists); i++)
1736 for (PGMMCHUNK pCur = pSet->apLists[i]; pCur; pCur = pCur->pFreeNext)
1737 if (pCur->hGVM == hGVM)
1738 {
1739 cPagesFound += pCur->cFree;
1740 if (cPagesFound >= cPages)
1741 break;
1742 }
1743 if (cPagesFound >= cPages)
1744 break;
1745
1746 /* Allocate more. */
1747 int rc = gmmR0AllocateOneChunk(pGMM, pSet, hGVM, GMMCHUNKTYPE_NON_CONTINUOUS);
1748 if (RT_FAILURE(rc))
1749 return rc;
1750 if (!GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
1751 return VERR_INTERNAL_ERROR_5;
1752 }
1753 }
1754
1755 return VINF_SUCCESS;
1756}
1757
1758
1759/**
1760 * Allocates one private page.
1761 *
1762 * Worker for gmmR0AllocatePages.
1763 *
1764 * @param pGMM Pointer to the GMM instance data.
1765 * @param hGVM The GVM handle of the VM requesting memory.
1766 * @param pChunk The chunk to allocate it from.
1767 * @param pPageDesc The page descriptor.
1768 */
1769static void gmmR0AllocatePage(PGMM pGMM, uint32_t hGVM, PGMMCHUNK pChunk, PGMMPAGEDESC pPageDesc)
1770{
1771 /* update the chunk stats. */
1772 if (pChunk->hGVM == NIL_GVM_HANDLE)
1773 pChunk->hGVM = hGVM;
1774 Assert(pChunk->cFree);
1775 pChunk->cFree--;
1776 pChunk->cPrivate++;
1777
1778 /* unlink the first free page. */
1779 const uint32_t iPage = pChunk->iFreeHead;
1780 AssertReleaseMsg(iPage < RT_ELEMENTS(pChunk->aPages), ("%d\n", iPage));
1781 PGMMPAGE pPage = &pChunk->aPages[iPage];
1782 Assert(GMM_PAGE_IS_FREE(pPage));
1783 pChunk->iFreeHead = pPage->Free.iNext;
1784 Log3(("A pPage=%p iPage=%#x/%#x u2State=%d iFreeHead=%#x iNext=%#x\n",
1785 pPage, iPage, (pChunk->Core.Key << GMM_CHUNKID_SHIFT) | iPage,
1786 pPage->Common.u2State, pChunk->iFreeHead, pPage->Free.iNext));
1787
1788 /* make the page private. */
1789 pPage->u = 0;
1790 AssertCompile(GMM_PAGE_STATE_PRIVATE == 0);
1791 pPage->Private.hGVM = hGVM;
1792 AssertCompile(NIL_RTHCPHYS >= GMM_GCPHYS_LAST);
1793 AssertCompile(GMM_GCPHYS_UNSHAREABLE >= GMM_GCPHYS_LAST);
1794 if (pPageDesc->HCPhysGCPhys <= GMM_GCPHYS_LAST)
1795 pPage->Private.pfn = pPageDesc->HCPhysGCPhys >> PAGE_SHIFT;
1796 else
1797 pPage->Private.pfn = GMM_PAGE_PFN_UNSHAREABLE; /* unshareable / unassigned - same thing. */
1798
1799 /* update the page descriptor. */
1800 pPageDesc->HCPhysGCPhys = RTR0MemObjGetPagePhysAddr(pChunk->MemObj, iPage);
1801 Assert(pPageDesc->HCPhysGCPhys != NIL_RTHCPHYS);
1802 pPageDesc->idPage = (pChunk->Core.Key << GMM_CHUNKID_SHIFT) | iPage;
1803 pPageDesc->idSharedPage = NIL_GMM_PAGEID;
1804}
1805
1806
1807/**
1808 * Common worker for GMMR0AllocateHandyPages and GMMR0AllocatePages.
1809 *
1810 * @returns VBox status code:
1811 * @retval VINF_SUCCESS on success.
1812 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk or
1813 * gmmR0AllocateMoreChunks is necessary.
1814 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
1815 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
1816 * that is we're trying to allocate more than we've reserved.
1817 *
1818 * @param pGMM Pointer to the GMM instance data.
1819 * @param pGVM Pointer to the shared VM structure.
1820 * @param cPages The number of pages to allocate.
1821 * @param paPages Pointer to the page descriptors.
1822 * See GMMPAGEDESC for details on what is expected on input.
1823 * @param enmAccount The account to charge.
1824 */
1825static int gmmR0AllocatePages(PGMM pGMM, PGVM pGVM, uint32_t cPages, PGMMPAGEDESC paPages, GMMACCOUNT enmAccount)
1826{
1827 /*
1828 * Check allocation limits.
1829 */
1830 if (RT_UNLIKELY(pGMM->cAllocatedPages + cPages > pGMM->cMaxPages))
1831 return VERR_GMM_HIT_GLOBAL_LIMIT;
1832
1833 switch (enmAccount)
1834 {
1835 case GMMACCOUNT_BASE:
1836 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages + pGVM->gmm.s.cBalloonedPages + cPages > pGVM->gmm.s.Reserved.cBasePages))
1837 {
1838 Log(("gmmR0AllocatePages:Base: Reserved=%#llx Allocated+Ballooned+Requested=%#llx+%#llx+%#x!\n",
1839 pGVM->gmm.s.Reserved.cBasePages, pGVM->gmm.s.Allocated.cBasePages, pGVM->gmm.s.cBalloonedPages, cPages));
1840 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1841 }
1842 break;
1843 case GMMACCOUNT_SHADOW:
1844 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cShadowPages + cPages > pGVM->gmm.s.Reserved.cShadowPages))
1845 {
1846 Log(("gmmR0AllocatePages:Shadow: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1847 pGVM->gmm.s.Reserved.cShadowPages, pGVM->gmm.s.Allocated.cShadowPages, cPages));
1848 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1849 }
1850 break;
1851 case GMMACCOUNT_FIXED:
1852 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cFixedPages + cPages > pGVM->gmm.s.Reserved.cFixedPages))
1853 {
1854 Log(("gmmR0AllocatePages:Fixed: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1855 pGVM->gmm.s.Reserved.cFixedPages, pGVM->gmm.s.Allocated.cFixedPages, cPages));
1856 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1857 }
1858 break;
1859 default:
1860 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
1861 }
1862
1863 /*
1864 * Check if we need to allocate more memory or not. In bound memory mode this
1865 * is a bit extra work but it's easier to do it upfront than bailing out later.
1866 */
1867 PGMMCHUNKFREESET pSet = &pGMM->Private;
1868 if (pSet->cFreePages < cPages)
1869 return VERR_GMM_SEED_ME;
1870 if (pGMM->fBoundMemoryMode)
1871 {
1872 uint16_t hGVM = pGVM->hSelf;
1873 uint32_t cPagesFound = 0;
1874 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists); i++)
1875 for (PGMMCHUNK pCur = pSet->apLists[i]; pCur; pCur = pCur->pFreeNext)
1876 if (pCur->hGVM == hGVM)
1877 {
1878 cPagesFound += pCur->cFree;
1879 if (cPagesFound >= cPages)
1880 break;
1881 }
1882 if (cPagesFound < cPages)
1883 return VERR_GMM_SEED_ME;
1884 }
1885
1886 /*
1887 * Pick the pages.
1888 * Try make some effort keeping VMs sharing private chunks.
1889 */
1890 uint16_t hGVM = pGVM->hSelf;
1891 uint32_t iPage = 0;
1892
1893 /* first round, pick from chunks with an affinity to the VM. */
1894 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists) && iPage < cPages; i++)
1895 {
1896 PGMMCHUNK pCurFree = NULL;
1897 PGMMCHUNK pCur = pSet->apLists[i];
1898 while (pCur && iPage < cPages)
1899 {
1900 PGMMCHUNK pNext = pCur->pFreeNext;
1901
1902 if ( pCur->hGVM == hGVM
1903 && pCur->cFree < GMM_CHUNK_NUM_PAGES)
1904 {
1905 gmmR0UnlinkChunk(pCur);
1906 for (; pCur->cFree && iPage < cPages; iPage++)
1907 gmmR0AllocatePage(pGMM, hGVM, pCur, &paPages[iPage]);
1908 gmmR0LinkChunk(pCur, pSet);
1909 }
1910
1911 pCur = pNext;
1912 }
1913 }
1914
1915 if (iPage < cPages)
1916 {
1917 /* second round, pick pages from the 100% empty chunks we just skipped above. */
1918 PGMMCHUNK pCurFree = NULL;
1919 PGMMCHUNK pCur = pSet->apLists[RT_ELEMENTS(pSet->apLists) - 1];
1920 while (pCur && iPage < cPages)
1921 {
1922 PGMMCHUNK pNext = pCur->pFreeNext;
1923
1924 if ( pCur->cFree == GMM_CHUNK_NUM_PAGES
1925 && ( pCur->hGVM == hGVM
1926 || !pGMM->fBoundMemoryMode))
1927 {
1928 gmmR0UnlinkChunk(pCur);
1929 for (; pCur->cFree && iPage < cPages; iPage++)
1930 gmmR0AllocatePage(pGMM, hGVM, pCur, &paPages[iPage]);
1931 gmmR0LinkChunk(pCur, pSet);
1932 }
1933
1934 pCur = pNext;
1935 }
1936 }
1937
1938 if ( iPage < cPages
1939 && !pGMM->fBoundMemoryMode)
1940 {
1941 /* third round, disregard affinity. */
1942 unsigned i = RT_ELEMENTS(pSet->apLists);
1943 while (i-- > 0 && iPage < cPages)
1944 {
1945 PGMMCHUNK pCurFree = NULL;
1946 PGMMCHUNK pCur = pSet->apLists[i];
1947 while (pCur && iPage < cPages)
1948 {
1949 PGMMCHUNK pNext = pCur->pFreeNext;
1950
1951 if ( pCur->cFree > GMM_CHUNK_NUM_PAGES / 2
1952 && cPages >= GMM_CHUNK_NUM_PAGES / 2)
1953 pCur->hGVM = hGVM; /* change chunk affinity */
1954
1955 gmmR0UnlinkChunk(pCur);
1956 for (; pCur->cFree && iPage < cPages; iPage++)
1957 gmmR0AllocatePage(pGMM, hGVM, pCur, &paPages[iPage]);
1958 gmmR0LinkChunk(pCur, pSet);
1959
1960 pCur = pNext;
1961 }
1962 }
1963 }
1964
1965 /*
1966 * Update the account.
1967 */
1968 switch (enmAccount)
1969 {
1970 case GMMACCOUNT_BASE: pGVM->gmm.s.Allocated.cBasePages += iPage; break;
1971 case GMMACCOUNT_SHADOW: pGVM->gmm.s.Allocated.cShadowPages += iPage; break;
1972 case GMMACCOUNT_FIXED: pGVM->gmm.s.Allocated.cFixedPages += iPage; break;
1973 default:
1974 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
1975 }
1976 pGVM->gmm.s.cPrivatePages += iPage;
1977 pGMM->cAllocatedPages += iPage;
1978
1979 AssertMsgReturn(iPage == cPages, ("%u != %u\n", iPage, cPages), VERR_INTERNAL_ERROR);
1980
1981 /*
1982 * Check if we've reached some threshold and should kick one or two VMs and tell
1983 * them to inflate their balloons a bit more... later.
1984 */
1985
1986 return VINF_SUCCESS;
1987}
1988
1989
1990/**
1991 * Updates the previous allocations and allocates more pages.
1992 *
1993 * The handy pages are always taken from the 'base' memory account.
1994 * The allocated pages are not cleared and will contains random garbage.
1995 *
1996 * @returns VBox status code:
1997 * @retval VINF_SUCCESS on success.
1998 * @retval VERR_NOT_OWNER if the caller is not an EMT.
1999 * @retval VERR_GMM_PAGE_NOT_FOUND if one of the pages to update wasn't found.
2000 * @retval VERR_GMM_PAGE_NOT_PRIVATE if one of the pages to update wasn't a
2001 * private page.
2002 * @retval VERR_GMM_PAGE_NOT_SHARED if one of the pages to update wasn't a
2003 * shared page.
2004 * @retval VERR_GMM_NOT_PAGE_OWNER if one of the pages to be updated wasn't
2005 * owned by the VM.
2006 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
2007 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
2008 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
2009 * that is we're trying to allocate more than we've reserved.
2010 *
2011 * @param pVM Pointer to the shared VM structure.
2012 * @param idCpu VCPU id
2013 * @param cPagesToUpdate The number of pages to update (starting from the head).
2014 * @param cPagesToAlloc The number of pages to allocate (starting from the head).
2015 * @param paPages The array of page descriptors.
2016 * See GMMPAGEDESC for details on what is expected on input.
2017 * @thread EMT.
2018 */
2019GMMR0DECL(int) GMMR0AllocateHandyPages(PVM pVM, VMCPUID idCpu, uint32_t cPagesToUpdate, uint32_t cPagesToAlloc, PGMMPAGEDESC paPages)
2020{
2021 LogFlow(("GMMR0AllocateHandyPages: pVM=%p cPagesToUpdate=%#x cPagesToAlloc=%#x paPages=%p\n",
2022 pVM, cPagesToUpdate, cPagesToAlloc, paPages));
2023
2024 /*
2025 * Validate, get basics and take the semaphore.
2026 * (This is a relatively busy path, so make predictions where possible.)
2027 */
2028 PGMM pGMM;
2029 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2030 PGVM pGVM;
2031 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2032 if (RT_FAILURE(rc))
2033 return rc;
2034
2035 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2036 AssertMsgReturn( (cPagesToUpdate && cPagesToUpdate < 1024)
2037 || (cPagesToAlloc && cPagesToAlloc < 1024),
2038 ("cPagesToUpdate=%#x cPagesToAlloc=%#x\n", cPagesToUpdate, cPagesToAlloc),
2039 VERR_INVALID_PARAMETER);
2040
2041 unsigned iPage = 0;
2042 for (; iPage < cPagesToUpdate; iPage++)
2043 {
2044 AssertMsgReturn( ( paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST
2045 && !(paPages[iPage].HCPhysGCPhys & PAGE_OFFSET_MASK))
2046 || paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS
2047 || paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE,
2048 ("#%#x: %RHp\n", iPage, paPages[iPage].HCPhysGCPhys),
2049 VERR_INVALID_PARAMETER);
2050 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
2051 /*|| paPages[iPage].idPage == NIL_GMM_PAGEID*/,
2052 ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2053 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
2054 /*|| paPages[iPage].idSharedPage == NIL_GMM_PAGEID*/,
2055 ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
2056 }
2057
2058 for (; iPage < cPagesToAlloc; iPage++)
2059 {
2060 AssertMsgReturn(paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS, ("#%#x: %RHp\n", iPage, paPages[iPage].HCPhysGCPhys), VERR_INVALID_PARAMETER);
2061 AssertMsgReturn(paPages[iPage].idPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2062 AssertMsgReturn(paPages[iPage].idSharedPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
2063 }
2064
2065 rc = RTSemFastMutexRequest(pGMM->Mtx);
2066 AssertRC(rc);
2067 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2068 {
2069 /* No allocations before the initial reservation has been made! */
2070 if (RT_LIKELY( pGVM->gmm.s.Reserved.cBasePages
2071 && pGVM->gmm.s.Reserved.cFixedPages
2072 && pGVM->gmm.s.Reserved.cShadowPages))
2073 {
2074 /*
2075 * Perform the updates.
2076 * Stop on the first error.
2077 */
2078 for (iPage = 0; iPage < cPagesToUpdate; iPage++)
2079 {
2080 if (paPages[iPage].idPage != NIL_GMM_PAGEID)
2081 {
2082 PGMMPAGE pPage = gmmR0GetPage(pGMM, paPages[iPage].idPage);
2083 if (RT_LIKELY(pPage))
2084 {
2085 if (RT_LIKELY(GMM_PAGE_IS_PRIVATE(pPage)))
2086 {
2087 if (RT_LIKELY(pPage->Private.hGVM == pGVM->hSelf))
2088 {
2089 AssertCompile(NIL_RTHCPHYS > GMM_GCPHYS_LAST && GMM_GCPHYS_UNSHAREABLE > GMM_GCPHYS_LAST);
2090 if (RT_LIKELY(paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST))
2091 pPage->Private.pfn = paPages[iPage].HCPhysGCPhys >> PAGE_SHIFT;
2092 else if (paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE)
2093 pPage->Private.pfn = GMM_PAGE_PFN_UNSHAREABLE;
2094 /* else: NIL_RTHCPHYS nothing */
2095#if 0
2096#ifdef VBOX_WITH_PCI_PASSTHROUGH
2097 if (pVM->rawpci.s.pfnContigMemInfo)
2098 pVM->rawpci.s.pfnContigMemInfo(pVM, paPages[iPage].HCPhysGCPhys, 0, PAGE_SIZE, PCIRAW_MEMINFO_MAP);
2099#endif
2100#endif
2101
2102 paPages[iPage].idPage = NIL_GMM_PAGEID;
2103 paPages[iPage].HCPhysGCPhys = NIL_RTHCPHYS;
2104 }
2105 else
2106 {
2107 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not owner! hGVM=%#x hSelf=%#x\n",
2108 iPage, paPages[iPage].idPage, pPage->Private.hGVM, pGVM->hSelf));
2109 rc = VERR_GMM_NOT_PAGE_OWNER;
2110 break;
2111 }
2112 }
2113 else
2114 {
2115 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not private! %.*Rhxs (type %d)\n", iPage, paPages[iPage].idPage, sizeof(*pPage), pPage, pPage->Common.u2State));
2116 rc = VERR_GMM_PAGE_NOT_PRIVATE;
2117 break;
2118 }
2119 }
2120 else
2121 {
2122 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not found! (private)\n", iPage, paPages[iPage].idPage));
2123 rc = VERR_GMM_PAGE_NOT_FOUND;
2124 break;
2125 }
2126 }
2127
2128 if (paPages[iPage].idSharedPage != NIL_GMM_PAGEID)
2129 {
2130 PGMMPAGE pPage = gmmR0GetPage(pGMM, paPages[iPage].idSharedPage);
2131 if (RT_LIKELY(pPage))
2132 {
2133 if (RT_LIKELY(GMM_PAGE_IS_SHARED(pPage)))
2134 {
2135 AssertCompile(NIL_RTHCPHYS > GMM_GCPHYS_LAST && GMM_GCPHYS_UNSHAREABLE > GMM_GCPHYS_LAST);
2136 Assert(pPage->Shared.cRefs);
2137 Assert(pGVM->gmm.s.cSharedPages);
2138 Assert(pGVM->gmm.s.Allocated.cBasePages);
2139
2140 Log(("GMMR0AllocateHandyPages: free shared page %x cRefs=%d\n", paPages[iPage].idSharedPage, pPage->Shared.cRefs));
2141 pGVM->gmm.s.cSharedPages--;
2142 pGVM->gmm.s.Allocated.cBasePages--;
2143 if (!--pPage->Shared.cRefs)
2144 {
2145 gmmR0FreeSharedPage(pGMM, paPages[iPage].idSharedPage, pPage);
2146 }
2147 else
2148 {
2149 Assert(pGMM->cDuplicatePages);
2150 pGMM->cDuplicatePages--;
2151 }
2152
2153 paPages[iPage].idSharedPage = NIL_GMM_PAGEID;
2154 }
2155 else
2156 {
2157 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not shared!\n", iPage, paPages[iPage].idSharedPage));
2158 rc = VERR_GMM_PAGE_NOT_SHARED;
2159 break;
2160 }
2161 }
2162 else
2163 {
2164 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not found! (shared)\n", iPage, paPages[iPage].idSharedPage));
2165 rc = VERR_GMM_PAGE_NOT_FOUND;
2166 break;
2167 }
2168 }
2169 }
2170
2171 /*
2172 * Join paths with GMMR0AllocatePages for the allocation.
2173 * Note! gmmR0AllocateMoreChunks may leave the protection of the mutex!
2174 */
2175 while (RT_SUCCESS(rc))
2176 {
2177 rc = gmmR0AllocatePages(pGMM, pGVM, cPagesToAlloc, paPages, GMMACCOUNT_BASE);
2178 if ( rc != VERR_GMM_SEED_ME
2179 || pGMM->fLegacyAllocationMode)
2180 break;
2181 rc = gmmR0AllocateMoreChunks(pGMM, pGVM, &pGMM->Private, cPagesToAlloc);
2182 }
2183 }
2184 else
2185 rc = VERR_WRONG_ORDER;
2186 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
2187 }
2188 else
2189 rc = VERR_INTERNAL_ERROR_5;
2190 RTSemFastMutexRelease(pGMM->Mtx);
2191 LogFlow(("GMMR0AllocateHandyPages: returns %Rrc\n", rc));
2192 return rc;
2193}
2194
2195
2196/**
2197 * Allocate one or more pages.
2198 *
2199 * This is typically used for ROMs and MMIO2 (VRAM) during VM creation.
2200 * The allocated pages are not cleared and will contains random garbage.
2201 *
2202 * @returns VBox status code:
2203 * @retval VINF_SUCCESS on success.
2204 * @retval VERR_NOT_OWNER if the caller is not an EMT.
2205 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
2206 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
2207 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
2208 * that is we're trying to allocate more than we've reserved.
2209 *
2210 * @param pVM Pointer to the shared VM structure.
2211 * @param idCpu VCPU id
2212 * @param cPages The number of pages to allocate.
2213 * @param paPages Pointer to the page descriptors.
2214 * See GMMPAGEDESC for details on what is expected on input.
2215 * @param enmAccount The account to charge.
2216 *
2217 * @thread EMT.
2218 */
2219GMMR0DECL(int) GMMR0AllocatePages(PVM pVM, VMCPUID idCpu, uint32_t cPages, PGMMPAGEDESC paPages, GMMACCOUNT enmAccount)
2220{
2221 LogFlow(("GMMR0AllocatePages: pVM=%p cPages=%#x paPages=%p enmAccount=%d\n", pVM, cPages, paPages, enmAccount));
2222
2223 /*
2224 * Validate, get basics and take the semaphore.
2225 */
2226 PGMM pGMM;
2227 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2228 PGVM pGVM;
2229 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2230 if (RT_FAILURE(rc))
2231 return rc;
2232
2233 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2234 AssertMsgReturn(enmAccount > GMMACCOUNT_INVALID && enmAccount < GMMACCOUNT_END, ("%d\n", enmAccount), VERR_INVALID_PARAMETER);
2235 AssertMsgReturn(cPages > 0 && cPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cPages), VERR_INVALID_PARAMETER);
2236
2237 for (unsigned iPage = 0; iPage < cPages; iPage++)
2238 {
2239 AssertMsgReturn( paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS
2240 || paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE
2241 || ( enmAccount == GMMACCOUNT_BASE
2242 && paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST
2243 && !(paPages[iPage].HCPhysGCPhys & PAGE_OFFSET_MASK)),
2244 ("#%#x: %RHp enmAccount=%d\n", iPage, paPages[iPage].HCPhysGCPhys, enmAccount),
2245 VERR_INVALID_PARAMETER);
2246 AssertMsgReturn(paPages[iPage].idPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2247 AssertMsgReturn(paPages[iPage].idSharedPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
2248 }
2249
2250 rc = RTSemFastMutexRequest(pGMM->Mtx);
2251 AssertRC(rc);
2252 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2253 {
2254
2255 /* No allocations before the initial reservation has been made! */
2256 if (RT_LIKELY( pGVM->gmm.s.Reserved.cBasePages
2257 && pGVM->gmm.s.Reserved.cFixedPages
2258 && pGVM->gmm.s.Reserved.cShadowPages))
2259 {
2260 /*
2261 * gmmR0AllocatePages seed loop.
2262 * Note! gmmR0AllocateMoreChunks may leave the protection of the mutex!
2263 */
2264 while (RT_SUCCESS(rc))
2265 {
2266 rc = gmmR0AllocatePages(pGMM, pGVM, cPages, paPages, enmAccount);
2267 if ( rc != VERR_GMM_SEED_ME
2268 || pGMM->fLegacyAllocationMode)
2269 break;
2270 rc = gmmR0AllocateMoreChunks(pGMM, pGVM, &pGMM->Private, cPages);
2271 }
2272 }
2273 else
2274 rc = VERR_WRONG_ORDER;
2275 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
2276 }
2277 else
2278 rc = VERR_INTERNAL_ERROR_5;
2279 RTSemFastMutexRelease(pGMM->Mtx);
2280 LogFlow(("GMMR0AllocatePages: returns %Rrc\n", rc));
2281 return rc;
2282}
2283
2284
2285/**
2286 * VMMR0 request wrapper for GMMR0AllocatePages.
2287 *
2288 * @returns see GMMR0AllocatePages.
2289 * @param pVM Pointer to the shared VM structure.
2290 * @param idCpu VCPU id
2291 * @param pReq The request packet.
2292 */
2293GMMR0DECL(int) GMMR0AllocatePagesReq(PVM pVM, VMCPUID idCpu, PGMMALLOCATEPAGESREQ pReq)
2294{
2295 /*
2296 * Validate input and pass it on.
2297 */
2298 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2299 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2300 AssertMsgReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[0]),
2301 ("%#x < %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[0])),
2302 VERR_INVALID_PARAMETER);
2303 AssertMsgReturn(pReq->Hdr.cbReq == RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[pReq->cPages]),
2304 ("%#x != %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[pReq->cPages])),
2305 VERR_INVALID_PARAMETER);
2306
2307 return GMMR0AllocatePages(pVM, idCpu, pReq->cPages, &pReq->aPages[0], pReq->enmAccount);
2308}
2309
2310/**
2311 * Allocate a large page to represent guest RAM
2312 *
2313 * The allocated pages are not cleared and will contains random garbage.
2314 *
2315 * @returns VBox status code:
2316 * @retval VINF_SUCCESS on success.
2317 * @retval VERR_NOT_OWNER if the caller is not an EMT.
2318 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
2319 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
2320 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
2321 * that is we're trying to allocate more than we've reserved.
2322 * @returns see GMMR0AllocatePages.
2323 * @param pVM Pointer to the shared VM structure.
2324 * @param idCpu VCPU id
2325 * @param cbPage Large page size
2326 */
2327GMMR0DECL(int) GMMR0AllocateLargePage(PVM pVM, VMCPUID idCpu, uint32_t cbPage, uint32_t *pIdPage, RTHCPHYS *pHCPhys)
2328{
2329 LogFlow(("GMMR0AllocateLargePage: pVM=%p cbPage=%x\n", pVM, cbPage));
2330
2331 AssertReturn(cbPage == GMM_CHUNK_SIZE, VERR_INVALID_PARAMETER);
2332 AssertPtrReturn(pIdPage, VERR_INVALID_PARAMETER);
2333 AssertPtrReturn(pHCPhys, VERR_INVALID_PARAMETER);
2334
2335 /*
2336 * Validate, get basics and take the semaphore.
2337 */
2338 PGMM pGMM;
2339 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2340 PGVM pGVM;
2341 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2342 if (RT_FAILURE(rc))
2343 return rc;
2344
2345 /* Not supported in legacy mode where we allocate the memory in ring 3 and lock it in ring 0. */
2346 if (pGMM->fLegacyAllocationMode)
2347 return VERR_NOT_SUPPORTED;
2348
2349 *pHCPhys = NIL_RTHCPHYS;
2350 *pIdPage = NIL_GMM_PAGEID;
2351
2352 rc = RTSemFastMutexRequest(pGMM->Mtx);
2353 AssertRCReturn(rc, rc);
2354 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2355 {
2356 const unsigned cPages = (GMM_CHUNK_SIZE >> PAGE_SHIFT);
2357 PGMMCHUNK pChunk;
2358 GMMPAGEDESC PageDesc;
2359
2360 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages + pGVM->gmm.s.cBalloonedPages + cPages > pGVM->gmm.s.Reserved.cBasePages))
2361 {
2362 Log(("GMMR0AllocateLargePage: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
2363 pGVM->gmm.s.Reserved.cBasePages, pGVM->gmm.s.Allocated.cBasePages, cPages));
2364 RTSemFastMutexRelease(pGMM->Mtx);
2365 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
2366 }
2367
2368 /* Allocate a new continuous chunk. */
2369 rc = gmmR0AllocateOneChunk(pGMM, &pGMM->Private, pGVM->hSelf, GMMCHUNKTYPE_CONTINUOUS, &pChunk);
2370 if (RT_FAILURE(rc))
2371 {
2372 RTSemFastMutexRelease(pGMM->Mtx);
2373 return rc;
2374 }
2375
2376 /* Unlink the new chunk from the free list. */
2377 gmmR0UnlinkChunk(pChunk);
2378
2379 /* Allocate all pages. */
2380 gmmR0AllocatePage(pGMM, pGVM->hSelf, pChunk, &PageDesc);
2381 /* Return the first page as we'll use the whole chunk as one big page. */
2382 *pIdPage = PageDesc.idPage;
2383 *pHCPhys = PageDesc.HCPhysGCPhys;
2384
2385 for (unsigned i = 1; i < cPages; i++)
2386 gmmR0AllocatePage(pGMM, pGVM->hSelf, pChunk, &PageDesc);
2387
2388 /* Update accounting. */
2389 pGVM->gmm.s.Allocated.cBasePages += cPages;
2390 pGVM->gmm.s.cPrivatePages += cPages;
2391 pGMM->cAllocatedPages += cPages;
2392
2393 gmmR0LinkChunk(pChunk, &pGMM->Private);
2394 }
2395 else
2396 rc = VERR_INTERNAL_ERROR_5;
2397
2398 RTSemFastMutexRelease(pGMM->Mtx);
2399 LogFlow(("GMMR0AllocateLargePage: returns %Rrc\n", rc));
2400 return rc;
2401}
2402
2403
2404/**
2405 * Free a large page
2406 *
2407 * @returns VBox status code:
2408 * @param pVM Pointer to the shared VM structure.
2409 * @param idCpu VCPU id
2410 * @param idPage Large page id
2411 */
2412GMMR0DECL(int) GMMR0FreeLargePage(PVM pVM, VMCPUID idCpu, uint32_t idPage)
2413{
2414 LogFlow(("GMMR0FreeLargePage: pVM=%p idPage=%x\n", pVM, idPage));
2415
2416 /*
2417 * Validate, get basics and take the semaphore.
2418 */
2419 PGMM pGMM;
2420 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2421 PGVM pGVM;
2422 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2423 if (RT_FAILURE(rc))
2424 return rc;
2425
2426 /* Not supported in legacy mode where we allocate the memory in ring 3 and lock it in ring 0. */
2427 if (pGMM->fLegacyAllocationMode)
2428 return VERR_NOT_SUPPORTED;
2429
2430 rc = RTSemFastMutexRequest(pGMM->Mtx);
2431 AssertRC(rc);
2432 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2433 {
2434 const unsigned cPages = (GMM_CHUNK_SIZE >> PAGE_SHIFT);
2435
2436 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages < cPages))
2437 {
2438 Log(("GMMR0FreeLargePage: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cBasePages, cPages));
2439 RTSemFastMutexRelease(pGMM->Mtx);
2440 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2441 }
2442
2443 PGMMPAGE pPage = gmmR0GetPage(pGMM, idPage);
2444 if ( RT_LIKELY(pPage)
2445 && RT_LIKELY(GMM_PAGE_IS_PRIVATE(pPage)))
2446 {
2447 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2448 Assert(pChunk);
2449 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2450 Assert(pChunk->cPrivate > 0);
2451
2452 /* Release the memory immediately. */
2453 gmmR0FreeChunk(pGMM, NULL, pChunk);
2454
2455 /* Update accounting. */
2456 pGVM->gmm.s.Allocated.cBasePages -= cPages;
2457 pGVM->gmm.s.cPrivatePages -= cPages;
2458 pGMM->cAllocatedPages -= cPages;
2459 }
2460 else
2461 rc = VERR_GMM_PAGE_NOT_FOUND;
2462 }
2463 else
2464 rc = VERR_INTERNAL_ERROR_5;
2465
2466 RTSemFastMutexRelease(pGMM->Mtx);
2467 LogFlow(("GMMR0FreeLargePage: returns %Rrc\n", rc));
2468 return rc;
2469}
2470
2471
2472/**
2473 * VMMR0 request wrapper for GMMR0FreeLargePage.
2474 *
2475 * @returns see GMMR0FreeLargePage.
2476 * @param pVM Pointer to the shared VM structure.
2477 * @param idCpu VCPU id
2478 * @param pReq The request packet.
2479 */
2480GMMR0DECL(int) GMMR0FreeLargePageReq(PVM pVM, VMCPUID idCpu, PGMMFREELARGEPAGEREQ pReq)
2481{
2482 /*
2483 * Validate input and pass it on.
2484 */
2485 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2486 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2487 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(GMMFREEPAGESREQ),
2488 ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(GMMFREEPAGESREQ)),
2489 VERR_INVALID_PARAMETER);
2490
2491 return GMMR0FreeLargePage(pVM, idCpu, pReq->idPage);
2492}
2493
2494/**
2495 * Frees a chunk, giving it back to the host OS.
2496 *
2497 * @param pGMM Pointer to the GMM instance.
2498 * @param pGVM This is set when called from GMMR0CleanupVM so we can
2499 * unmap and free the chunk in one go.
2500 * @param pChunk The chunk to free.
2501 */
2502static void gmmR0FreeChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk)
2503{
2504 Assert(pChunk->Core.Key != NIL_GMM_CHUNKID);
2505
2506 /*
2507 * Cleanup hack! Unmap the chunk from the callers address space.
2508 */
2509 if ( pChunk->cMappings
2510 && pGVM)
2511 gmmR0UnmapChunk(pGMM, pGVM, pChunk);
2512
2513 /*
2514 * If there are current mappings of the chunk, then request the
2515 * VMs to unmap them. Reposition the chunk in the free list so
2516 * it won't be a likely candidate for allocations.
2517 */
2518 if (pChunk->cMappings)
2519 {
2520 /** @todo R0 -> VM request */
2521 /* The chunk can be owned by more than one VM if fBoundMemoryMode is false! */
2522 Log(("gmmR0FreeChunk: chunk still has %d mappings; don't free!\n", pChunk->cMappings));
2523 }
2524 else
2525 {
2526 /*
2527 * Try free the memory object.
2528 */
2529 int rc = RTR0MemObjFree(pChunk->MemObj, false /* fFreeMappings */);
2530 if (RT_SUCCESS(rc))
2531 {
2532 pChunk->MemObj = NIL_RTR0MEMOBJ;
2533
2534 /*
2535 * Unlink it from everywhere.
2536 */
2537 gmmR0UnlinkChunk(pChunk);
2538
2539 PAVLU32NODECORE pCore = RTAvlU32Remove(&pGMM->pChunks, pChunk->Core.Key);
2540 Assert(pCore == &pChunk->Core); NOREF(pCore);
2541
2542 PGMMCHUNKTLBE pTlbe = &pGMM->ChunkTLB.aEntries[GMM_CHUNKTLB_IDX(pChunk->Core.Key)];
2543 if (pTlbe->pChunk == pChunk)
2544 {
2545 pTlbe->idChunk = NIL_GMM_CHUNKID;
2546 pTlbe->pChunk = NULL;
2547 }
2548
2549 Assert(pGMM->cChunks > 0);
2550 pGMM->cChunks--;
2551
2552 /*
2553 * Free the Chunk ID and struct.
2554 */
2555 gmmR0FreeChunkId(pGMM, pChunk->Core.Key);
2556 pChunk->Core.Key = NIL_GMM_CHUNKID;
2557
2558 RTMemFree(pChunk->paMappings);
2559 pChunk->paMappings = NULL;
2560
2561 RTMemFree(pChunk);
2562 }
2563 else
2564 AssertRC(rc);
2565 }
2566}
2567
2568
2569/**
2570 * Free page worker.
2571 *
2572 * The caller does all the statistic decrementing, we do all the incrementing.
2573 *
2574 * @param pGMM Pointer to the GMM instance data.
2575 * @param pChunk Pointer to the chunk this page belongs to.
2576 * @param idPage The Page ID.
2577 * @param pPage Pointer to the page.
2578 */
2579static void gmmR0FreePageWorker(PGMM pGMM, PGMMCHUNK pChunk, uint32_t idPage, PGMMPAGE pPage)
2580{
2581 Log3(("F pPage=%p iPage=%#x/%#x u2State=%d iFreeHead=%#x\n",
2582 pPage, pPage - &pChunk->aPages[0], idPage, pPage->Common.u2State, pChunk->iFreeHead)); NOREF(idPage);
2583
2584 /*
2585 * Put the page on the free list.
2586 */
2587 pPage->u = 0;
2588 pPage->Free.u2State = GMM_PAGE_STATE_FREE;
2589 Assert(pChunk->iFreeHead < RT_ELEMENTS(pChunk->aPages) || pChunk->iFreeHead == UINT16_MAX);
2590 pPage->Free.iNext = pChunk->iFreeHead;
2591 pChunk->iFreeHead = pPage - &pChunk->aPages[0];
2592
2593 /*
2594 * Update statistics (the cShared/cPrivate stats are up to date already),
2595 * and relink the chunk if necessary.
2596 */
2597 if ((pChunk->cFree & GMM_CHUNK_FREE_SET_MASK) == 0)
2598 {
2599 gmmR0UnlinkChunk(pChunk);
2600 pChunk->cFree++;
2601 gmmR0LinkChunk(pChunk, pChunk->cShared ? &pGMM->Shared : &pGMM->Private);
2602 }
2603 else
2604 {
2605 pChunk->cFree++;
2606 pChunk->pSet->cFreePages++;
2607
2608 /*
2609 * If the chunk becomes empty, consider giving memory back to the host OS.
2610 *
2611 * The current strategy is to try give it back if there are other chunks
2612 * in this free list, meaning if there are at least 240 free pages in this
2613 * category. Note that since there are probably mappings of the chunk,
2614 * it won't be freed up instantly, which probably screws up this logic
2615 * a bit...
2616 */
2617 if (RT_UNLIKELY( pChunk->cFree == GMM_CHUNK_NUM_PAGES
2618 && pChunk->pFreeNext
2619 && pChunk->pFreePrev
2620 && !pGMM->fLegacyAllocationMode))
2621 gmmR0FreeChunk(pGMM, NULL, pChunk);
2622 }
2623}
2624
2625
2626/**
2627 * Frees a shared page, the page is known to exist and be valid and such.
2628 *
2629 * @param pGMM Pointer to the GMM instance.
2630 * @param idPage The Page ID
2631 * @param pPage The page structure.
2632 */
2633DECLINLINE(void) gmmR0FreeSharedPage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage)
2634{
2635 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2636 Assert(pChunk);
2637 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2638 Assert(pChunk->cShared > 0);
2639 Assert(pGMM->cSharedPages > 0);
2640 Assert(pGMM->cAllocatedPages > 0);
2641 Assert(!pPage->Shared.cRefs);
2642
2643 pChunk->cShared--;
2644 pGMM->cAllocatedPages--;
2645 pGMM->cSharedPages--;
2646 gmmR0FreePageWorker(pGMM, pChunk, idPage, pPage);
2647}
2648
2649#ifdef VBOX_WITH_PAGE_SHARING
2650/**
2651 * Converts a private page to a shared page, the page is known to exist and be valid and such.
2652 *
2653 * @param pGMM Pointer to the GMM instance.
2654 * @param pGVM Pointer to the GVM instance.
2655 * @param HCPhys Host physical address
2656 * @param idPage The Page ID
2657 * @param pPage The page structure.
2658 */
2659DECLINLINE(void) gmmR0ConvertToSharedPage(PGMM pGMM, PGVM pGVM, RTHCPHYS HCPhys, uint32_t idPage, PGMMPAGE pPage)
2660{
2661 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2662 Assert(pChunk);
2663 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2664 Assert(GMM_PAGE_IS_PRIVATE(pPage));
2665
2666 pChunk->cPrivate--;
2667 pChunk->cShared++;
2668
2669 pGMM->cSharedPages++;
2670
2671 pGVM->gmm.s.cSharedPages++;
2672 pGVM->gmm.s.cPrivatePages--;
2673
2674 /* Modify the page structure. */
2675 pPage->Shared.pfn = (uint32_t)(uint64_t)(HCPhys >> PAGE_SHIFT);
2676 pPage->Shared.cRefs = 1;
2677 pPage->Common.u2State = GMM_PAGE_STATE_SHARED;
2678}
2679
2680/**
2681 * Increase the use count of a shared page, the page is known to exist and be valid and such.
2682 *
2683 * @param pGMM Pointer to the GMM instance.
2684 * @param pGVM Pointer to the GVM instance.
2685 * @param pPage The page structure.
2686 */
2687DECLINLINE(void) gmmR0UseSharedPage(PGMM pGMM, PGVM pGVM, PGMMPAGE pPage)
2688{
2689 Assert(pGMM->cSharedPages > 0);
2690 Assert(pGMM->cAllocatedPages > 0);
2691
2692 pGMM->cDuplicatePages++;
2693
2694 pPage->Shared.cRefs++;
2695 pGVM->gmm.s.cSharedPages++;
2696 pGVM->gmm.s.Allocated.cBasePages++;
2697}
2698#endif
2699
2700/**
2701 * Frees a private page, the page is known to exist and be valid and such.
2702 *
2703 * @param pGMM Pointer to the GMM instance.
2704 * @param idPage The Page ID
2705 * @param pPage The page structure.
2706 */
2707DECLINLINE(void) gmmR0FreePrivatePage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage)
2708{
2709 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2710 Assert(pChunk);
2711 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2712 Assert(pChunk->cPrivate > 0);
2713 Assert(pGMM->cAllocatedPages > 0);
2714
2715 pChunk->cPrivate--;
2716 pGMM->cAllocatedPages--;
2717 gmmR0FreePageWorker(pGMM, pChunk, idPage, pPage);
2718}
2719
2720/**
2721 * Common worker for GMMR0FreePages and GMMR0BalloonedPages.
2722 *
2723 * @returns VBox status code:
2724 * @retval xxx
2725 *
2726 * @param pGMM Pointer to the GMM instance data.
2727 * @param pGVM Pointer to the shared VM structure.
2728 * @param cPages The number of pages to free.
2729 * @param paPages Pointer to the page descriptors.
2730 * @param enmAccount The account this relates to.
2731 */
2732static int gmmR0FreePages(PGMM pGMM, PGVM pGVM, uint32_t cPages, PGMMFREEPAGEDESC paPages, GMMACCOUNT enmAccount)
2733{
2734 /*
2735 * Check that the request isn't impossible wrt to the account status.
2736 */
2737 switch (enmAccount)
2738 {
2739 case GMMACCOUNT_BASE:
2740 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages < cPages))
2741 {
2742 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cBasePages, cPages));
2743 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2744 }
2745 break;
2746 case GMMACCOUNT_SHADOW:
2747 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cShadowPages < cPages))
2748 {
2749 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cShadowPages, cPages));
2750 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2751 }
2752 break;
2753 case GMMACCOUNT_FIXED:
2754 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cFixedPages < cPages))
2755 {
2756 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cFixedPages, cPages));
2757 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2758 }
2759 break;
2760 default:
2761 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
2762 }
2763
2764 /*
2765 * Walk the descriptors and free the pages.
2766 *
2767 * Statistics (except the account) are being updated as we go along,
2768 * unlike the alloc code. Also, stop on the first error.
2769 */
2770 int rc = VINF_SUCCESS;
2771 uint32_t iPage;
2772 for (iPage = 0; iPage < cPages; iPage++)
2773 {
2774 uint32_t idPage = paPages[iPage].idPage;
2775 PGMMPAGE pPage = gmmR0GetPage(pGMM, idPage);
2776 if (RT_LIKELY(pPage))
2777 {
2778 if (RT_LIKELY(GMM_PAGE_IS_PRIVATE(pPage)))
2779 {
2780 if (RT_LIKELY(pPage->Private.hGVM == pGVM->hSelf))
2781 {
2782 Assert(pGVM->gmm.s.cPrivatePages);
2783 pGVM->gmm.s.cPrivatePages--;
2784 gmmR0FreePrivatePage(pGMM, idPage, pPage);
2785 }
2786 else
2787 {
2788 Log(("gmmR0AllocatePages: #%#x/%#x: not owner! hGVM=%#x hSelf=%#x\n", iPage, idPage,
2789 pPage->Private.hGVM, pGVM->hSelf));
2790 rc = VERR_GMM_NOT_PAGE_OWNER;
2791 break;
2792 }
2793 }
2794 else if (RT_LIKELY(GMM_PAGE_IS_SHARED(pPage)))
2795 {
2796 Assert(pGVM->gmm.s.cSharedPages);
2797 pGVM->gmm.s.cSharedPages--;
2798 Assert(pPage->Shared.cRefs);
2799 if (!--pPage->Shared.cRefs)
2800 {
2801 gmmR0FreeSharedPage(pGMM, idPage, pPage);
2802 }
2803 else
2804 {
2805 Assert(pGMM->cDuplicatePages);
2806 pGMM->cDuplicatePages--;
2807 }
2808 }
2809 else
2810 {
2811 Log(("gmmR0AllocatePages: #%#x/%#x: already free!\n", iPage, idPage));
2812 rc = VERR_GMM_PAGE_ALREADY_FREE;
2813 break;
2814 }
2815 }
2816 else
2817 {
2818 Log(("gmmR0AllocatePages: #%#x/%#x: not found!\n", iPage, idPage));
2819 rc = VERR_GMM_PAGE_NOT_FOUND;
2820 break;
2821 }
2822 paPages[iPage].idPage = NIL_GMM_PAGEID;
2823 }
2824
2825 /*
2826 * Update the account.
2827 */
2828 switch (enmAccount)
2829 {
2830 case GMMACCOUNT_BASE: pGVM->gmm.s.Allocated.cBasePages -= iPage; break;
2831 case GMMACCOUNT_SHADOW: pGVM->gmm.s.Allocated.cShadowPages -= iPage; break;
2832 case GMMACCOUNT_FIXED: pGVM->gmm.s.Allocated.cFixedPages -= iPage; break;
2833 default:
2834 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
2835 }
2836
2837 /*
2838 * Any threshold stuff to be done here?
2839 */
2840
2841 return rc;
2842}
2843
2844
2845/**
2846 * Free one or more pages.
2847 *
2848 * This is typically used at reset time or power off.
2849 *
2850 * @returns VBox status code:
2851 * @retval xxx
2852 *
2853 * @param pVM Pointer to the shared VM structure.
2854 * @param idCpu VCPU id
2855 * @param cPages The number of pages to allocate.
2856 * @param paPages Pointer to the page descriptors containing the Page IDs for each page.
2857 * @param enmAccount The account this relates to.
2858 * @thread EMT.
2859 */
2860GMMR0DECL(int) GMMR0FreePages(PVM pVM, VMCPUID idCpu, uint32_t cPages, PGMMFREEPAGEDESC paPages, GMMACCOUNT enmAccount)
2861{
2862 LogFlow(("GMMR0FreePages: pVM=%p cPages=%#x paPages=%p enmAccount=%d\n", pVM, cPages, paPages, enmAccount));
2863
2864 /*
2865 * Validate input and get the basics.
2866 */
2867 PGMM pGMM;
2868 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2869 PGVM pGVM;
2870 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2871 if (RT_FAILURE(rc))
2872 return rc;
2873
2874 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2875 AssertMsgReturn(enmAccount > GMMACCOUNT_INVALID && enmAccount < GMMACCOUNT_END, ("%d\n", enmAccount), VERR_INVALID_PARAMETER);
2876 AssertMsgReturn(cPages > 0 && cPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cPages), VERR_INVALID_PARAMETER);
2877
2878 for (unsigned iPage = 0; iPage < cPages; iPage++)
2879 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
2880 /*|| paPages[iPage].idPage == NIL_GMM_PAGEID*/,
2881 ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2882
2883 /*
2884 * Take the semaphore and call the worker function.
2885 */
2886 rc = RTSemFastMutexRequest(pGMM->Mtx);
2887 AssertRC(rc);
2888 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2889 {
2890 rc = gmmR0FreePages(pGMM, pGVM, cPages, paPages, enmAccount);
2891 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
2892 }
2893 else
2894 rc = VERR_INTERNAL_ERROR_5;
2895 RTSemFastMutexRelease(pGMM->Mtx);
2896 LogFlow(("GMMR0FreePages: returns %Rrc\n", rc));
2897 return rc;
2898}
2899
2900
2901/**
2902 * VMMR0 request wrapper for GMMR0FreePages.
2903 *
2904 * @returns see GMMR0FreePages.
2905 * @param pVM Pointer to the shared VM structure.
2906 * @param idCpu VCPU id
2907 * @param pReq The request packet.
2908 */
2909GMMR0DECL(int) GMMR0FreePagesReq(PVM pVM, VMCPUID idCpu, PGMMFREEPAGESREQ pReq)
2910{
2911 /*
2912 * Validate input and pass it on.
2913 */
2914 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2915 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2916 AssertMsgReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[0]),
2917 ("%#x < %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[0])),
2918 VERR_INVALID_PARAMETER);
2919 AssertMsgReturn(pReq->Hdr.cbReq == RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[pReq->cPages]),
2920 ("%#x != %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[pReq->cPages])),
2921 VERR_INVALID_PARAMETER);
2922
2923 return GMMR0FreePages(pVM, idCpu, pReq->cPages, &pReq->aPages[0], pReq->enmAccount);
2924}
2925
2926
2927/**
2928 * Report back on a memory ballooning request.
2929 *
2930 * The request may or may not have been initiated by the GMM. If it was initiated
2931 * by the GMM it is important that this function is called even if no pages were
2932 * ballooned.
2933 *
2934 * @returns VBox status code:
2935 * @retval VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH
2936 * @retval VERR_GMM_ATTEMPT_TO_DEFLATE_TOO_MUCH
2937 * @retval VERR_GMM_OVERCOMMITTED_TRY_AGAIN_IN_A_BIT - reset condition
2938 * indicating that we won't necessarily have sufficient RAM to boot
2939 * the VM again and that it should pause until this changes (we'll try
2940 * balloon some other VM). (For standard deflate we have little choice
2941 * but to hope the VM won't use the memory that was returned to it.)
2942 *
2943 * @param pVM Pointer to the shared VM structure.
2944 * @param idCpu VCPU id
2945 * @param enmAction Inflate/deflate/reset
2946 * @param cBalloonedPages The number of pages that was ballooned.
2947 *
2948 * @thread EMT.
2949 */
2950GMMR0DECL(int) GMMR0BalloonedPages(PVM pVM, VMCPUID idCpu, GMMBALLOONACTION enmAction, uint32_t cBalloonedPages)
2951{
2952 LogFlow(("GMMR0BalloonedPages: pVM=%p enmAction=%d cBalloonedPages=%#x\n",
2953 pVM, enmAction, cBalloonedPages));
2954
2955 AssertMsgReturn(cBalloonedPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cBalloonedPages), VERR_INVALID_PARAMETER);
2956
2957 /*
2958 * Validate input and get the basics.
2959 */
2960 PGMM pGMM;
2961 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2962 PGVM pGVM;
2963 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2964 if (RT_FAILURE(rc))
2965 return rc;
2966
2967 /*
2968 * Take the semaphore and do some more validations.
2969 */
2970 rc = RTSemFastMutexRequest(pGMM->Mtx);
2971 AssertRC(rc);
2972 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2973 {
2974 switch (enmAction)
2975 {
2976 case GMMBALLOONACTION_INFLATE:
2977 {
2978 if (RT_LIKELY(pGVM->gmm.s.Allocated.cBasePages + pGVM->gmm.s.cBalloonedPages + cBalloonedPages <= pGVM->gmm.s.Reserved.cBasePages))
2979 {
2980 /*
2981 * Record the ballooned memory.
2982 */
2983 pGMM->cBalloonedPages += cBalloonedPages;
2984 if (pGVM->gmm.s.cReqBalloonedPages)
2985 {
2986 /* Codepath never taken. Might be interesting in the future to request ballooned memory from guests in low memory conditions.. */
2987 AssertFailed();
2988
2989 pGVM->gmm.s.cBalloonedPages += cBalloonedPages;
2990 pGVM->gmm.s.cReqActuallyBalloonedPages += cBalloonedPages;
2991 Log(("GMMR0BalloonedPages: +%#x - Global=%#llx / VM: Total=%#llx Req=%#llx Actual=%#llx (pending)\n", cBalloonedPages,
2992 pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages, pGVM->gmm.s.cReqBalloonedPages, pGVM->gmm.s.cReqActuallyBalloonedPages));
2993 }
2994 else
2995 {
2996 pGVM->gmm.s.cBalloonedPages += cBalloonedPages;
2997 Log(("GMMR0BalloonedPages: +%#x - Global=%#llx / VM: Total=%#llx (user)\n",
2998 cBalloonedPages, pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages));
2999 }
3000 }
3001 else
3002 {
3003 Log(("GMMR0BalloonedPages: cBasePages=%#llx Total=%#llx cBalloonedPages=%#llx Reserved=%#llx\n",
3004 pGVM->gmm.s.Allocated.cBasePages, pGVM->gmm.s.cBalloonedPages, cBalloonedPages, pGVM->gmm.s.Reserved.cBasePages));
3005 rc = VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
3006 }
3007 break;
3008 }
3009
3010 case GMMBALLOONACTION_DEFLATE:
3011 {
3012 /* Deflate. */
3013 if (pGVM->gmm.s.cBalloonedPages >= cBalloonedPages)
3014 {
3015 /*
3016 * Record the ballooned memory.
3017 */
3018 Assert(pGMM->cBalloonedPages >= cBalloonedPages);
3019 pGMM->cBalloonedPages -= cBalloonedPages;
3020 pGVM->gmm.s.cBalloonedPages -= cBalloonedPages;
3021 if (pGVM->gmm.s.cReqDeflatePages)
3022 {
3023 AssertFailed(); /* This is path is for later. */
3024 Log(("GMMR0BalloonedPages: -%#x - Global=%#llx / VM: Total=%#llx Req=%#llx\n",
3025 cBalloonedPages, pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages, pGVM->gmm.s.cReqDeflatePages));
3026
3027 /*
3028 * Anything we need to do here now when the request has been completed?
3029 */
3030 pGVM->gmm.s.cReqDeflatePages = 0;
3031 }
3032 else
3033 Log(("GMMR0BalloonedPages: -%#x - Global=%#llx / VM: Total=%#llx (user)\n",
3034 cBalloonedPages, pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages));
3035 }
3036 else
3037 {
3038 Log(("GMMR0BalloonedPages: Total=%#llx cBalloonedPages=%#llx\n", pGVM->gmm.s.cBalloonedPages, cBalloonedPages));
3039 rc = VERR_GMM_ATTEMPT_TO_DEFLATE_TOO_MUCH;
3040 }
3041 break;
3042 }
3043
3044 case GMMBALLOONACTION_RESET:
3045 {
3046 /* Reset to an empty balloon. */
3047 Assert(pGMM->cBalloonedPages >= pGVM->gmm.s.cBalloonedPages);
3048
3049 pGMM->cBalloonedPages -= pGVM->gmm.s.cBalloonedPages;
3050 pGVM->gmm.s.cBalloonedPages = 0;
3051 break;
3052 }
3053
3054 default:
3055 rc = VERR_INVALID_PARAMETER;
3056 break;
3057 }
3058 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
3059 }
3060 else
3061 rc = VERR_INTERNAL_ERROR_5;
3062
3063 RTSemFastMutexRelease(pGMM->Mtx);
3064 LogFlow(("GMMR0BalloonedPages: returns %Rrc\n", rc));
3065 return rc;
3066}
3067
3068
3069/**
3070 * VMMR0 request wrapper for GMMR0BalloonedPages.
3071 *
3072 * @returns see GMMR0BalloonedPages.
3073 * @param pVM Pointer to the shared VM structure.
3074 * @param idCpu VCPU id
3075 * @param pReq The request packet.
3076 */
3077GMMR0DECL(int) GMMR0BalloonedPagesReq(PVM pVM, VMCPUID idCpu, PGMMBALLOONEDPAGESREQ pReq)
3078{
3079 /*
3080 * Validate input and pass it on.
3081 */
3082 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
3083 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
3084 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(GMMBALLOONEDPAGESREQ),
3085 ("%#x < %#x\n", pReq->Hdr.cbReq, sizeof(GMMBALLOONEDPAGESREQ)),
3086 VERR_INVALID_PARAMETER);
3087
3088 return GMMR0BalloonedPages(pVM, idCpu, pReq->enmAction, pReq->cBalloonedPages);
3089}
3090
3091/**
3092 * Return memory statistics for the hypervisor
3093 *
3094 * @returns VBox status code:
3095 * @param pVM Pointer to the shared VM structure.
3096 * @param pReq The request packet.
3097 */
3098GMMR0DECL(int) GMMR0QueryHypervisorMemoryStatsReq(PVM pVM, PGMMMEMSTATSREQ pReq)
3099{
3100 /*
3101 * Validate input and pass it on.
3102 */
3103 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
3104 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
3105 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(GMMMEMSTATSREQ),
3106 ("%#x < %#x\n", pReq->Hdr.cbReq, sizeof(GMMMEMSTATSREQ)),
3107 VERR_INVALID_PARAMETER);
3108
3109 /*
3110 * Validate input and get the basics.
3111 */
3112 PGMM pGMM;
3113 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
3114 pReq->cAllocPages = pGMM->cAllocatedPages;
3115 pReq->cFreePages = (pGMM->cChunks << (GMM_CHUNK_SHIFT- PAGE_SHIFT)) - pGMM->cAllocatedPages;
3116 pReq->cBalloonedPages = pGMM->cBalloonedPages;
3117 pReq->cMaxPages = pGMM->cMaxPages;
3118 pReq->cSharedPages = pGMM->cDuplicatePages;
3119 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
3120
3121 return VINF_SUCCESS;
3122}
3123
3124/**
3125 * Return memory statistics for the VM
3126 *
3127 * @returns VBox status code:
3128 * @param pVM Pointer to the shared VM structure.
3129 * @parma idCpu Cpu id.
3130 * @param pReq The request packet.
3131 */
3132GMMR0DECL(int) GMMR0QueryMemoryStatsReq(PVM pVM, VMCPUID idCpu, PGMMMEMSTATSREQ pReq)
3133{
3134 /*
3135 * Validate input and pass it on.
3136 */
3137 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
3138 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
3139 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(GMMMEMSTATSREQ),
3140 ("%#x < %#x\n", pReq->Hdr.cbReq, sizeof(GMMMEMSTATSREQ)),
3141 VERR_INVALID_PARAMETER);
3142
3143 /*
3144 * Validate input and get the basics.
3145 */
3146 PGMM pGMM;
3147 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
3148 PGVM pGVM;
3149 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
3150 if (RT_FAILURE(rc))
3151 return rc;
3152
3153 /*
3154 * Take the semaphore and do some more validations.
3155 */
3156 rc = RTSemFastMutexRequest(pGMM->Mtx);
3157 AssertRC(rc);
3158 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
3159 {
3160 pReq->cAllocPages = pGVM->gmm.s.Allocated.cBasePages;
3161 pReq->cBalloonedPages = pGVM->gmm.s.cBalloonedPages;
3162 pReq->cMaxPages = pGVM->gmm.s.Reserved.cBasePages;
3163 pReq->cFreePages = pReq->cMaxPages - pReq->cAllocPages;
3164 }
3165 else
3166 rc = VERR_INTERNAL_ERROR_5;
3167
3168 RTSemFastMutexRelease(pGMM->Mtx);
3169 LogFlow(("GMMR3QueryVMMemoryStats: returns %Rrc\n", rc));
3170 return rc;
3171}
3172
3173/**
3174 * Unmaps a chunk previously mapped into the address space of the current process.
3175 *
3176 * @returns VBox status code.
3177 * @param pGMM Pointer to the GMM instance data.
3178 * @param pGVM Pointer to the Global VM structure.
3179 * @param pChunk Pointer to the chunk to be unmapped.
3180 */
3181static int gmmR0UnmapChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk)
3182{
3183 if (!pGMM->fLegacyAllocationMode)
3184 {
3185 /*
3186 * Find the mapping and try unmapping it.
3187 */
3188 for (uint32_t i = 0; i < pChunk->cMappings; i++)
3189 {
3190 Assert(pChunk->paMappings[i].pGVM && pChunk->paMappings[i].MapObj != NIL_RTR0MEMOBJ);
3191 if (pChunk->paMappings[i].pGVM == pGVM)
3192 {
3193 /* unmap */
3194 int rc = RTR0MemObjFree(pChunk->paMappings[i].MapObj, false /* fFreeMappings (NA) */);
3195 if (RT_SUCCESS(rc))
3196 {
3197 /* update the record. */
3198 pChunk->cMappings--;
3199 if (i < pChunk->cMappings)
3200 pChunk->paMappings[i] = pChunk->paMappings[pChunk->cMappings];
3201 pChunk->paMappings[pChunk->cMappings].MapObj = NIL_RTR0MEMOBJ;
3202 pChunk->paMappings[pChunk->cMappings].pGVM = NULL;
3203 }
3204 return rc;
3205 }
3206 }
3207 }
3208 else if (pChunk->hGVM == pGVM->hSelf)
3209 return VINF_SUCCESS;
3210
3211 Log(("gmmR0UnmapChunk: Chunk %#x is not mapped into pGVM=%p/%#x\n", pChunk->Core.Key, pGVM, pGVM->hSelf));
3212 return VERR_GMM_CHUNK_NOT_MAPPED;
3213}
3214
3215
3216/**
3217 * Maps a chunk into the user address space of the current process.
3218 *
3219 * @returns VBox status code.
3220 * @param pGMM Pointer to the GMM instance data.
3221 * @param pGVM Pointer to the Global VM structure.
3222 * @param pChunk Pointer to the chunk to be mapped.
3223 * @param ppvR3 Where to store the ring-3 address of the mapping.
3224 * In the VERR_GMM_CHUNK_ALREADY_MAPPED case, this will be
3225 * contain the address of the existing mapping.
3226 */
3227static int gmmR0MapChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk, PRTR3PTR ppvR3)
3228{
3229 /*
3230 * If we're in legacy mode this is simple.
3231 */
3232 if (pGMM->fLegacyAllocationMode)
3233 {
3234 if (pChunk->hGVM != pGVM->hSelf)
3235 {
3236 Log(("gmmR0MapChunk: chunk %#x is already mapped at %p!\n", pChunk->Core.Key, *ppvR3));
3237 return VERR_GMM_CHUNK_NOT_FOUND;
3238 }
3239
3240 *ppvR3 = RTR0MemObjAddressR3(pChunk->MemObj);
3241 return VINF_SUCCESS;
3242 }
3243
3244 /*
3245 * Check to see if the chunk is already mapped.
3246 */
3247 for (uint32_t i = 0; i < pChunk->cMappings; i++)
3248 {
3249 Assert(pChunk->paMappings[i].pGVM && pChunk->paMappings[i].MapObj != NIL_RTR0MEMOBJ);
3250 if (pChunk->paMappings[i].pGVM == pGVM)
3251 {
3252 *ppvR3 = RTR0MemObjAddressR3(pChunk->paMappings[i].MapObj);
3253 Log(("gmmR0MapChunk: chunk %#x is already mapped at %p!\n", pChunk->Core.Key, *ppvR3));
3254#ifdef VBOX_WITH_PAGE_SHARING
3255 /* The ring-3 chunk cache can be out of sync; don't fail. */
3256 return VINF_SUCCESS;
3257#else
3258 return VERR_GMM_CHUNK_ALREADY_MAPPED;
3259#endif
3260 }
3261 }
3262
3263 /*
3264 * Do the mapping.
3265 */
3266 RTR0MEMOBJ MapObj;
3267 int rc = RTR0MemObjMapUser(&MapObj, pChunk->MemObj, (RTR3PTR)-1, 0, RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
3268 if (RT_SUCCESS(rc))
3269 {
3270 /* reallocate the array? */
3271 if ((pChunk->cMappings & 1 /*7*/) == 0)
3272 {
3273 void *pvMappings = RTMemRealloc(pChunk->paMappings, (pChunk->cMappings + 2 /*8*/) * sizeof(pChunk->paMappings[0]));
3274 if (RT_UNLIKELY(!pvMappings))
3275 {
3276 rc = RTR0MemObjFree(MapObj, false /* fFreeMappings (NA) */);
3277 AssertRC(rc);
3278 return VERR_NO_MEMORY;
3279 }
3280 pChunk->paMappings = (PGMMCHUNKMAP)pvMappings;
3281 }
3282
3283 /* insert new entry */
3284 pChunk->paMappings[pChunk->cMappings].MapObj = MapObj;
3285 pChunk->paMappings[pChunk->cMappings].pGVM = pGVM;
3286 pChunk->cMappings++;
3287
3288 *ppvR3 = RTR0MemObjAddressR3(MapObj);
3289 }
3290
3291 return rc;
3292}
3293
3294/**
3295 * Check if a chunk is mapped into the specified VM
3296 *
3297 * @returns mapped yes/no
3298 * @param pGVM Pointer to the Global VM structure.
3299 * @param pChunk Pointer to the chunk to be mapped.
3300 * @param ppvR3 Where to store the ring-3 address of the mapping.
3301 */
3302static int gmmR0IsChunkMapped(PGVM pGVM, PGMMCHUNK pChunk, PRTR3PTR ppvR3)
3303{
3304 /*
3305 * Check to see if the chunk is already mapped.
3306 */
3307 for (uint32_t i = 0; i < pChunk->cMappings; i++)
3308 {
3309 Assert(pChunk->paMappings[i].pGVM && pChunk->paMappings[i].MapObj != NIL_RTR0MEMOBJ);
3310 if (pChunk->paMappings[i].pGVM == pGVM)
3311 {
3312 *ppvR3 = RTR0MemObjAddressR3(pChunk->paMappings[i].MapObj);
3313 return true;
3314 }
3315 }
3316 *ppvR3 = NULL;
3317 return false;
3318}
3319
3320/**
3321 * Map a chunk and/or unmap another chunk.
3322 *
3323 * The mapping and unmapping applies to the current process.
3324 *
3325 * This API does two things because it saves a kernel call per mapping when
3326 * when the ring-3 mapping cache is full.
3327 *
3328 * @returns VBox status code.
3329 * @param pVM The VM.
3330 * @param idChunkMap The chunk to map. NIL_GMM_CHUNKID if nothing to map.
3331 * @param idChunkUnmap The chunk to unmap. NIL_GMM_CHUNKID if nothing to unmap.
3332 * @param ppvR3 Where to store the address of the mapped chunk. NULL is ok if nothing to map.
3333 * @thread EMT
3334 */
3335GMMR0DECL(int) GMMR0MapUnmapChunk(PVM pVM, uint32_t idChunkMap, uint32_t idChunkUnmap, PRTR3PTR ppvR3)
3336{
3337 LogFlow(("GMMR0MapUnmapChunk: pVM=%p idChunkMap=%#x idChunkUnmap=%#x ppvR3=%p\n",
3338 pVM, idChunkMap, idChunkUnmap, ppvR3));
3339
3340 /*
3341 * Validate input and get the basics.
3342 */
3343 PGMM pGMM;
3344 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
3345 PGVM pGVM;
3346 int rc = GVMMR0ByVM(pVM, &pGVM);
3347 if (RT_FAILURE(rc))
3348 return rc;
3349
3350 AssertCompile(NIL_GMM_CHUNKID == 0);
3351 AssertMsgReturn(idChunkMap <= GMM_CHUNKID_LAST, ("%#x\n", idChunkMap), VERR_INVALID_PARAMETER);
3352 AssertMsgReturn(idChunkUnmap <= GMM_CHUNKID_LAST, ("%#x\n", idChunkUnmap), VERR_INVALID_PARAMETER);
3353
3354 if ( idChunkMap == NIL_GMM_CHUNKID
3355 && idChunkUnmap == NIL_GMM_CHUNKID)
3356 return VERR_INVALID_PARAMETER;
3357
3358 if (idChunkMap != NIL_GMM_CHUNKID)
3359 {
3360 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
3361 *ppvR3 = NIL_RTR3PTR;
3362 }
3363
3364 /*
3365 * Take the semaphore and do the work.
3366 *
3367 * The unmapping is done last since it's easier to undo a mapping than
3368 * undoing an unmapping. The ring-3 mapping cache cannot not be so big
3369 * that it pushes the user virtual address space to within a chunk of
3370 * it it's limits, so, no problem here.
3371 */
3372 rc = RTSemFastMutexRequest(pGMM->Mtx);
3373 AssertRC(rc);
3374 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
3375 {
3376 PGMMCHUNK pMap = NULL;
3377 if (idChunkMap != NIL_GVM_HANDLE)
3378 {
3379 pMap = gmmR0GetChunk(pGMM, idChunkMap);
3380 if (RT_LIKELY(pMap))
3381 rc = gmmR0MapChunk(pGMM, pGVM, pMap, ppvR3);
3382 else
3383 {
3384 Log(("GMMR0MapUnmapChunk: idChunkMap=%#x\n", idChunkMap));
3385 rc = VERR_GMM_CHUNK_NOT_FOUND;
3386 }
3387 }
3388
3389 if ( idChunkUnmap != NIL_GMM_CHUNKID
3390 && RT_SUCCESS(rc))
3391 {
3392 PGMMCHUNK pUnmap = gmmR0GetChunk(pGMM, idChunkUnmap);
3393 if (RT_LIKELY(pUnmap))
3394 rc = gmmR0UnmapChunk(pGMM, pGVM, pUnmap);
3395 else
3396 {
3397 Log(("GMMR0MapUnmapChunk: idChunkUnmap=%#x\n", idChunkUnmap));
3398 rc = VERR_GMM_CHUNK_NOT_FOUND;
3399 }
3400
3401 if (RT_FAILURE(rc) && pMap)
3402 gmmR0UnmapChunk(pGMM, pGVM, pMap);
3403 }
3404
3405 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
3406 }
3407 else
3408 rc = VERR_INTERNAL_ERROR_5;
3409 RTSemFastMutexRelease(pGMM->Mtx);
3410
3411 LogFlow(("GMMR0MapUnmapChunk: returns %Rrc\n", rc));
3412 return rc;
3413}
3414
3415
3416/**
3417 * VMMR0 request wrapper for GMMR0MapUnmapChunk.
3418 *
3419 * @returns see GMMR0MapUnmapChunk.
3420 * @param pVM Pointer to the shared VM structure.
3421 * @param pReq The request packet.
3422 */
3423GMMR0DECL(int) GMMR0MapUnmapChunkReq(PVM pVM, PGMMMAPUNMAPCHUNKREQ pReq)
3424{
3425 /*
3426 * Validate input and pass it on.
3427 */
3428 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
3429 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
3430 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
3431
3432 return GMMR0MapUnmapChunk(pVM, pReq->idChunkMap, pReq->idChunkUnmap, &pReq->pvR3);
3433}
3434
3435
3436/**
3437 * Legacy mode API for supplying pages.
3438 *
3439 * The specified user address points to a allocation chunk sized block that
3440 * will be locked down and used by the GMM when the GM asks for pages.
3441 *
3442 * @returns VBox status code.
3443 * @param pVM The VM.
3444 * @param idCpu VCPU id
3445 * @param pvR3 Pointer to the chunk size memory block to lock down.
3446 */
3447GMMR0DECL(int) GMMR0SeedChunk(PVM pVM, VMCPUID idCpu, RTR3PTR pvR3)
3448{
3449 /*
3450 * Validate input and get the basics.
3451 */
3452 PGMM pGMM;
3453 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
3454 PGVM pGVM;
3455 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
3456 if (RT_FAILURE(rc))
3457 return rc;
3458
3459 AssertPtrReturn(pvR3, VERR_INVALID_POINTER);
3460 AssertReturn(!(PAGE_OFFSET_MASK & pvR3), VERR_INVALID_POINTER);
3461
3462 if (!pGMM->fLegacyAllocationMode)
3463 {
3464 Log(("GMMR0SeedChunk: not in legacy allocation mode!\n"));
3465 return VERR_NOT_SUPPORTED;
3466 }
3467
3468 /*
3469 * Lock the memory before taking the semaphore.
3470 */
3471 RTR0MEMOBJ MemObj;
3472 rc = RTR0MemObjLockUser(&MemObj, pvR3, GMM_CHUNK_SIZE, RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
3473 if (RT_SUCCESS(rc))
3474 {
3475 /* Grab the lock. */
3476 rc = RTSemFastMutexRequest(pGMM->Mtx);
3477 AssertRC(rc);
3478 if (RT_SUCCESS(rc))
3479 {
3480 /*
3481 * Add a new chunk with our hGVM.
3482 */
3483 rc = gmmR0RegisterChunk(pGMM, &pGMM->Private, MemObj, pGVM->hSelf, GMMCHUNKTYPE_NON_CONTINUOUS);
3484 RTSemFastMutexRelease(pGMM->Mtx);
3485 }
3486
3487 if (RT_FAILURE(rc))
3488 RTR0MemObjFree(MemObj, false /* fFreeMappings */);
3489 }
3490
3491 LogFlow(("GMMR0SeedChunk: rc=%d (pvR3=%p)\n", rc, pvR3));
3492 return rc;
3493}
3494
3495typedef struct
3496{
3497 PAVLGCPTRNODECORE pNode;
3498 char *pszModuleName;
3499 char *pszVersion;
3500 VBOXOSFAMILY enmGuestOS;
3501} GMMFINDMODULEBYNAME, *PGMMFINDMODULEBYNAME;
3502
3503/**
3504 * Tree enumeration callback for finding identical modules by name and version
3505 */
3506DECLCALLBACK(int) gmmR0CheckForIdenticalModule(PAVLGCPTRNODECORE pNode, void *pvUser)
3507{
3508 PGMMFINDMODULEBYNAME pInfo = (PGMMFINDMODULEBYNAME)pvUser;
3509 PGMMSHAREDMODULE pModule = (PGMMSHAREDMODULE)pNode;
3510
3511 if ( pInfo
3512 && pInfo->enmGuestOS == pModule->enmGuestOS
3513 /** @todo replace with RTStrNCmp */
3514 && !strcmp(pModule->szName, pInfo->pszModuleName)
3515 && !strcmp(pModule->szVersion, pInfo->pszVersion))
3516 {
3517 pInfo->pNode = pNode;
3518 return 1; /* stop search */
3519 }
3520 return 0;
3521}
3522
3523
3524/**
3525 * Registers a new shared module for the VM
3526 *
3527 * @returns VBox status code.
3528 * @param pVM VM handle
3529 * @param idCpu VCPU id
3530 * @param enmGuestOS Guest OS type
3531 * @param pszModuleName Module name
3532 * @param pszVersion Module version
3533 * @param GCBaseAddr Module base address
3534 * @param cbModule Module size
3535 * @param cRegions Number of shared region descriptors
3536 * @param pRegions Shared region(s)
3537 */
3538GMMR0DECL(int) GMMR0RegisterSharedModule(PVM pVM, VMCPUID idCpu, VBOXOSFAMILY enmGuestOS, char *pszModuleName, char *pszVersion, RTGCPTR GCBaseAddr, uint32_t cbModule,
3539 unsigned cRegions, VMMDEVSHAREDREGIONDESC *pRegions)
3540{
3541#ifdef VBOX_WITH_PAGE_SHARING
3542 /*
3543 * Validate input and get the basics.
3544 */
3545 PGMM pGMM;
3546 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
3547 PGVM pGVM;
3548 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
3549 if (RT_FAILURE(rc))
3550 return rc;
3551
3552 Log(("GMMR0RegisterSharedModule %s %s base %RGv size %x\n", pszModuleName, pszVersion, GCBaseAddr, cbModule));
3553
3554 /*
3555 * Take the semaphore and do some more validations.
3556 */
3557 rc = RTSemFastMutexRequest(pGMM->Mtx);
3558 AssertRC(rc);
3559 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
3560 {
3561 bool fNewModule = false;
3562
3563 /* Check if this module is already locally registered. */
3564 PGMMSHAREDMODULEPERVM pRecVM = (PGMMSHAREDMODULEPERVM)RTAvlGCPtrGet(&pGVM->gmm.s.pSharedModuleTree, GCBaseAddr);
3565 if (!pRecVM)
3566 {
3567 pRecVM = (PGMMSHAREDMODULEPERVM)RTMemAllocZ(RT_OFFSETOF(GMMSHAREDMODULEPERVM, aRegions[cRegions]));
3568 if (!pRecVM)
3569 {
3570 AssertFailed();
3571 rc = VERR_NO_MEMORY;
3572 goto end;
3573 }
3574 pRecVM->Core.Key = GCBaseAddr;
3575 pRecVM->cRegions = cRegions;
3576
3577 /* Save the region data as they can differ between VMs (address space scrambling or simply different loading order) */
3578 for (unsigned i = 0; i < cRegions; i++)
3579 {
3580 pRecVM->aRegions[i].GCRegionAddr = pRegions[i].GCRegionAddr;
3581 pRecVM->aRegions[i].cbRegion = RT_ALIGN_T(pRegions[i].cbRegion, PAGE_SIZE, uint32_t);
3582 pRecVM->aRegions[i].u32Alignment = 0;
3583 pRecVM->aRegions[i].paHCPhysPageID = NULL; /* unused */
3584 }
3585
3586 bool ret = RTAvlGCPtrInsert(&pGVM->gmm.s.pSharedModuleTree, &pRecVM->Core);
3587 Assert(ret);
3588
3589 Log(("GMMR0RegisterSharedModule: new local module %s\n", pszModuleName));
3590 fNewModule = true;
3591 }
3592 else
3593 rc = VINF_PGM_SHARED_MODULE_ALREADY_REGISTERED;
3594
3595 /* Check if this module is already globally registered. */
3596 PGMMSHAREDMODULE pGlobalModule = (PGMMSHAREDMODULE)RTAvlGCPtrGet(&pGMM->pGlobalSharedModuleTree, GCBaseAddr);
3597 if ( !pGlobalModule
3598 && enmGuestOS == VBOXOSFAMILY_Windows64)
3599 {
3600 /* Two identical copies of e.g. Win7 x64 will typically not have a similar virtual address space layout for dlls or kernel modules.
3601 * Try to find identical binaries based on name and version.
3602 */
3603 GMMFINDMODULEBYNAME Info;
3604
3605 Info.pNode = NULL;
3606 Info.pszVersion = pszVersion;
3607 Info.pszModuleName = pszModuleName;
3608 Info.enmGuestOS = enmGuestOS;
3609
3610 Log(("Try to find identical module %s\n", pszModuleName));
3611 int ret = RTAvlGCPtrDoWithAll(&pGMM->pGlobalSharedModuleTree, true /* fFromLeft */, gmmR0CheckForIdenticalModule, &Info);
3612 if (ret == 1)
3613 {
3614 Assert(Info.pNode);
3615 pGlobalModule = (PGMMSHAREDMODULE)Info.pNode;
3616 Log(("Found identical module at %RGv\n", pGlobalModule->Core.Key));
3617 }
3618 }
3619
3620 if (!pGlobalModule)
3621 {
3622 Assert(fNewModule);
3623 Assert(!pRecVM->fCollision);
3624
3625 pGlobalModule = (PGMMSHAREDMODULE)RTMemAllocZ(RT_OFFSETOF(GMMSHAREDMODULE, aRegions[cRegions]));
3626 if (!pGlobalModule)
3627 {
3628 AssertFailed();
3629 rc = VERR_NO_MEMORY;
3630 goto end;
3631 }
3632
3633 pGlobalModule->Core.Key = GCBaseAddr;
3634 pGlobalModule->cbModule = cbModule;
3635 /* Input limit already safe; no need to check again. */
3636 /** @todo replace with RTStrCopy */
3637 strcpy(pGlobalModule->szName, pszModuleName);
3638 strcpy(pGlobalModule->szVersion, pszVersion);
3639
3640 pGlobalModule->enmGuestOS = enmGuestOS;
3641 pGlobalModule->cRegions = cRegions;
3642
3643 for (unsigned i = 0; i < cRegions; i++)
3644 {
3645 Log(("New region %d base=%RGv size %x\n", i, pRegions[i].GCRegionAddr, pRegions[i].cbRegion));
3646 pGlobalModule->aRegions[i].GCRegionAddr = pRegions[i].GCRegionAddr;
3647 pGlobalModule->aRegions[i].cbRegion = RT_ALIGN_T(pRegions[i].cbRegion, PAGE_SIZE, uint32_t);
3648 pGlobalModule->aRegions[i].u32Alignment = 0;
3649 pGlobalModule->aRegions[i].paHCPhysPageID = NULL; /* uninitialized. */
3650 }
3651
3652 /* Save reference. */
3653 pRecVM->pGlobalModule = pGlobalModule;
3654 pRecVM->fCollision = false;
3655 pGlobalModule->cUsers++;
3656 rc = VINF_SUCCESS;
3657
3658 bool ret = RTAvlGCPtrInsert(&pGMM->pGlobalSharedModuleTree, &pGlobalModule->Core);
3659 Assert(ret);
3660
3661 Log(("GMMR0RegisterSharedModule: new global module %s\n", pszModuleName));
3662 }
3663 else
3664 {
3665 Assert(pGlobalModule->cUsers > 0);
3666
3667 /* Make sure the name and version are identical. */
3668 /** @todo replace with RTStrNCmp */
3669 if ( !strcmp(pGlobalModule->szName, pszModuleName)
3670 && !strcmp(pGlobalModule->szVersion, pszVersion))
3671 {
3672 /* Save reference. */
3673 pRecVM->pGlobalModule = pGlobalModule;
3674 if ( fNewModule
3675 || pRecVM->fCollision == true) /* colliding module unregistered and new one registered since the last check */
3676 {
3677 pGlobalModule->cUsers++;
3678 Log(("GMMR0RegisterSharedModule: using existing module %s cUser=%d!\n", pszModuleName, pGlobalModule->cUsers));
3679 }
3680 pRecVM->fCollision = false;
3681 rc = VINF_SUCCESS;
3682 }
3683 else
3684 {
3685 Log(("GMMR0RegisterSharedModule: module %s collision!\n", pszModuleName));
3686 pRecVM->fCollision = true;
3687 rc = VINF_PGM_SHARED_MODULE_COLLISION;
3688 goto end;
3689 }
3690 }
3691
3692 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
3693 }
3694 else
3695 rc = VERR_INTERNAL_ERROR_5;
3696
3697end:
3698 RTSemFastMutexRelease(pGMM->Mtx);
3699 return rc;
3700#else
3701 return VERR_NOT_IMPLEMENTED;
3702#endif
3703}
3704
3705
3706/**
3707 * VMMR0 request wrapper for GMMR0RegisterSharedModule.
3708 *
3709 * @returns see GMMR0RegisterSharedModule.
3710 * @param pVM Pointer to the shared VM structure.
3711 * @param idCpu VCPU id
3712 * @param pReq The request packet.
3713 */
3714GMMR0DECL(int) GMMR0RegisterSharedModuleReq(PVM pVM, VMCPUID idCpu, PGMMREGISTERSHAREDMODULEREQ pReq)
3715{
3716 /*
3717 * Validate input and pass it on.
3718 */
3719 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
3720 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
3721 AssertMsgReturn(pReq->Hdr.cbReq >= sizeof(*pReq) && pReq->Hdr.cbReq == RT_UOFFSETOF(GMMREGISTERSHAREDMODULEREQ, aRegions[pReq->cRegions]), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
3722
3723 /* Pass back return code in the request packet to preserve informational codes. (VMMR3CallR0 chokes on them) */
3724 pReq->rc = GMMR0RegisterSharedModule(pVM, idCpu, pReq->enmGuestOS, pReq->szName, pReq->szVersion, pReq->GCBaseAddr, pReq->cbModule, pReq->cRegions, pReq->aRegions);
3725 return VINF_SUCCESS;
3726}
3727
3728/**
3729 * Unregisters a shared module for the VM
3730 *
3731 * @returns VBox status code.
3732 * @param pVM VM handle
3733 * @param idCpu VCPU id
3734 * @param pszModuleName Module name
3735 * @param pszVersion Module version
3736 * @param GCBaseAddr Module base address
3737 * @param cbModule Module size
3738 */
3739GMMR0DECL(int) GMMR0UnregisterSharedModule(PVM pVM, VMCPUID idCpu, char *pszModuleName, char *pszVersion, RTGCPTR GCBaseAddr, uint32_t cbModule)
3740{
3741#ifdef VBOX_WITH_PAGE_SHARING
3742 /*
3743 * Validate input and get the basics.
3744 */
3745 PGMM pGMM;
3746 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
3747 PGVM pGVM;
3748 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
3749 if (RT_FAILURE(rc))
3750 return rc;
3751
3752 Log(("GMMR0UnregisterSharedModule %s %s base=%RGv size %x\n", pszModuleName, pszVersion, GCBaseAddr, cbModule));
3753
3754 /*
3755 * Take the semaphore and do some more validations.
3756 */
3757 rc = RTSemFastMutexRequest(pGMM->Mtx);
3758 AssertRC(rc);
3759 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
3760 {
3761 PGMMSHAREDMODULEPERVM pRecVM = (PGMMSHAREDMODULEPERVM)RTAvlGCPtrGet(&pGVM->gmm.s.pSharedModuleTree, GCBaseAddr);
3762 if (pRecVM)
3763 {
3764 /* Remove reference to global shared module. */
3765 if (!pRecVM->fCollision)
3766 {
3767 PGMMSHAREDMODULE pRec = pRecVM->pGlobalModule;
3768 Assert(pRec);
3769
3770 if (pRec) /* paranoia */
3771 {
3772 Assert(pRec->cUsers);
3773 pRec->cUsers--;
3774 if (pRec->cUsers == 0)
3775 {
3776 /* Free the ranges, but leave the pages intact as there might still be references; they will be cleared by the COW mechanism. */
3777 for (unsigned i = 0; i < pRec->cRegions; i++)
3778 if (pRec->aRegions[i].paHCPhysPageID)
3779 RTMemFree(pRec->aRegions[i].paHCPhysPageID);
3780
3781 Assert(pRec->Core.Key == GCBaseAddr || pRec->enmGuestOS == VBOXOSFAMILY_Windows64);
3782 Assert(pRec->cRegions == pRecVM->cRegions);
3783#ifdef VBOX_STRICT
3784 for (unsigned i = 0; i < pRecVM->cRegions; i++)
3785 {
3786 Assert(pRecVM->aRegions[i].GCRegionAddr == pRec->aRegions[i].GCRegionAddr);
3787 Assert(pRecVM->aRegions[i].cbRegion == pRec->aRegions[i].cbRegion);
3788 }
3789#endif
3790
3791 /* Remove from the tree and free memory. */
3792 RTAvlGCPtrRemove(&pGMM->pGlobalSharedModuleTree, pRec->Core.Key);
3793 RTMemFree(pRec);
3794 }
3795 }
3796 else
3797 rc = VERR_PGM_SHARED_MODULE_REGISTRATION_INCONSISTENCY;
3798 }
3799 else
3800 Assert(!pRecVM->pGlobalModule);
3801
3802 /* Remove from the tree and free memory. */
3803 RTAvlGCPtrRemove(&pGVM->gmm.s.pSharedModuleTree, GCBaseAddr);
3804 RTMemFree(pRecVM);
3805 }
3806 else
3807 rc = VERR_PGM_SHARED_MODULE_NOT_FOUND;
3808
3809 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
3810 }
3811 else
3812 rc = VERR_INTERNAL_ERROR_5;
3813
3814 RTSemFastMutexRelease(pGMM->Mtx);
3815 return rc;
3816#else
3817 return VERR_NOT_IMPLEMENTED;
3818#endif
3819}
3820
3821/**
3822 * VMMR0 request wrapper for GMMR0UnregisterSharedModule.
3823 *
3824 * @returns see GMMR0UnregisterSharedModule.
3825 * @param pVM Pointer to the shared VM structure.
3826 * @param idCpu VCPU id
3827 * @param pReq The request packet.
3828 */
3829GMMR0DECL(int) GMMR0UnregisterSharedModuleReq(PVM pVM, VMCPUID idCpu, PGMMUNREGISTERSHAREDMODULEREQ pReq)
3830{
3831 /*
3832 * Validate input and pass it on.
3833 */
3834 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
3835 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
3836 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
3837
3838 return GMMR0UnregisterSharedModule(pVM, idCpu, pReq->szName, pReq->szVersion, pReq->GCBaseAddr, pReq->cbModule);
3839}
3840
3841
3842#ifdef VBOX_WITH_PAGE_SHARING
3843/**
3844 * Checks specified shared module range for changes
3845 *
3846 * Performs the following tasks:
3847 * - If a shared page is new, then it changes the GMM page type to shared and
3848 * returns it in the pPageDesc descriptor.
3849 * - If a shared page already exists, then it checks if the VM page is
3850 * identical and if so frees the VM page and returns the shared page in
3851 * pPageDesc descriptor.
3852 *
3853 * @remarks ASSUMES the caller has acquired the GMM semaphore!!
3854 *
3855 * @returns VBox status code.
3856 * @param pGMM Pointer to the GMM instance data.
3857 * @param pGVM Pointer to the GVM instance data.
3858 * @param pModule Module description
3859 * @param idxRegion Region index
3860 * @param idxPage Page index
3861 * @param paPageDesc Page descriptor
3862 */
3863GMMR0DECL(int) GMMR0SharedModuleCheckPage(PGVM pGVM, PGMMSHAREDMODULE pModule, unsigned idxRegion, unsigned idxPage,
3864 PGMMSHAREDPAGEDESC pPageDesc)
3865{
3866 int rc = VINF_SUCCESS;
3867 PGMM pGMM;
3868 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
3869 unsigned cPages = pModule->aRegions[idxRegion].cbRegion >> PAGE_SHIFT;
3870
3871 AssertReturn(idxRegion < pModule->cRegions, VERR_INVALID_PARAMETER);
3872 AssertReturn(idxPage < cPages, VERR_INVALID_PARAMETER);
3873
3874 LogFlow(("GMMR0SharedModuleCheckRange %s base %RGv region %d idxPage %d\n", pModule->szName, pModule->Core.Key, idxRegion, idxPage));
3875
3876 PGMMSHAREDREGIONDESC pGlobalRegion = &pModule->aRegions[idxRegion];
3877 if (!pGlobalRegion->paHCPhysPageID)
3878 {
3879 /* First time; create a page descriptor array. */
3880 Log(("Allocate page descriptor array for %d pages\n", cPages));
3881 pGlobalRegion->paHCPhysPageID = (uint32_t *)RTMemAlloc(cPages * sizeof(*pGlobalRegion->paHCPhysPageID));
3882 if (!pGlobalRegion->paHCPhysPageID)
3883 {
3884 AssertFailed();
3885 rc = VERR_NO_MEMORY;
3886 goto end;
3887 }
3888 /* Invalidate all descriptors. */
3889 for (unsigned i = 0; i < cPages; i++)
3890 pGlobalRegion->paHCPhysPageID[i] = NIL_GMM_PAGEID;
3891 }
3892
3893 /* We've seen this shared page for the first time? */
3894 if (pGlobalRegion->paHCPhysPageID[idxPage] == NIL_GMM_PAGEID)
3895 {
3896new_shared_page:
3897 Log(("New shared page guest %RGp host %RHp\n", pPageDesc->GCPhys, pPageDesc->HCPhys));
3898
3899 /* Easy case: just change the internal page type. */
3900 PGMMPAGE pPage = gmmR0GetPage(pGMM, pPageDesc->uHCPhysPageId);
3901 if (!pPage)
3902 {
3903 Log(("GMMR0SharedModuleCheckPage: Invalid idPage=%#x #1 (GCPhys=%RGp HCPhys=%RHp idxRegion=%#x idxPage=%#x)\n",
3904 pPageDesc->uHCPhysPageId, pPageDesc->GCPhys, pPageDesc->HCPhys, idxRegion, idxPage));
3905 AssertFailed();
3906 rc = VERR_PGM_PHYS_INVALID_PAGE_ID;
3907 goto end;
3908 }
3909
3910 AssertMsg(pPageDesc->GCPhys == (pPage->Private.pfn << 12), ("desc %RGp gmm %RGp\n", pPageDesc->HCPhys, (pPage->Private.pfn << 12)));
3911
3912 gmmR0ConvertToSharedPage(pGMM, pGVM, pPageDesc->HCPhys, pPageDesc->uHCPhysPageId, pPage);
3913
3914 /* Keep track of these references. */
3915 pGlobalRegion->paHCPhysPageID[idxPage] = pPageDesc->uHCPhysPageId;
3916 }
3917 else
3918 {
3919 uint8_t *pbLocalPage, *pbSharedPage;
3920 uint8_t *pbChunk;
3921 PGMMCHUNK pChunk;
3922
3923 Assert(pPageDesc->uHCPhysPageId != pGlobalRegion->paHCPhysPageID[idxPage]);
3924
3925 Log(("Replace existing page guest %RGp host %RHp id %x -> id %x\n", pPageDesc->GCPhys, pPageDesc->HCPhys, pPageDesc->uHCPhysPageId, pGlobalRegion->paHCPhysPageID[idxPage]));
3926
3927 /* Get the shared page source. */
3928 PGMMPAGE pPage = gmmR0GetPage(pGMM, pGlobalRegion->paHCPhysPageID[idxPage]);
3929 if (!pPage)
3930 {
3931 Log(("GMMR0SharedModuleCheckPage: Invalid idPage=%#x #2 (idxRegion=%#x idxPage=%#x)\n",
3932 pPageDesc->uHCPhysPageId, idxRegion, idxPage));
3933 AssertFailed();
3934 rc = VERR_PGM_PHYS_INVALID_PAGE_ID;
3935 goto end;
3936 }
3937 if (pPage->Common.u2State != GMM_PAGE_STATE_SHARED)
3938 {
3939 /* Page was freed at some point; invalidate this entry. */
3940 /** @todo this isn't really bullet proof. */
3941 Log(("Old shared page was freed -> create a new one\n"));
3942 pGlobalRegion->paHCPhysPageID[idxPage] = NIL_GMM_PAGEID;
3943 goto new_shared_page; /* ugly goto */
3944 }
3945
3946 Log(("Replace existing page guest host %RHp -> %RHp\n", pPageDesc->HCPhys, ((uint64_t)pPage->Shared.pfn) << PAGE_SHIFT));
3947
3948 /* Calculate the virtual address of the local page. */
3949 pChunk = gmmR0GetChunk(pGMM, pPageDesc->uHCPhysPageId >> GMM_CHUNKID_SHIFT);
3950 if (pChunk)
3951 {
3952 if (!gmmR0IsChunkMapped(pGVM, pChunk, (PRTR3PTR)&pbChunk))
3953 {
3954 Log(("GMMR0SharedModuleCheckPage: Invalid idPage=%#x #3\n", pPageDesc->uHCPhysPageId));
3955 AssertFailed();
3956 rc = VERR_PGM_PHYS_INVALID_PAGE_ID;
3957 goto end;
3958 }
3959 pbLocalPage = pbChunk + ((pPageDesc->uHCPhysPageId & GMM_PAGEID_IDX_MASK) << PAGE_SHIFT);
3960 }
3961 else
3962 {
3963 Log(("GMMR0SharedModuleCheckPage: Invalid idPage=%#x #4\n", pPageDesc->uHCPhysPageId));
3964 AssertFailed();
3965 rc = VERR_PGM_PHYS_INVALID_PAGE_ID;
3966 goto end;
3967 }
3968
3969 /* Calculate the virtual address of the shared page. */
3970 pChunk = gmmR0GetChunk(pGMM, pGlobalRegion->paHCPhysPageID[idxPage] >> GMM_CHUNKID_SHIFT);
3971 Assert(pChunk); /* can't fail as gmmR0GetPage succeeded. */
3972
3973 /* Get the virtual address of the physical page; map the chunk into the VM process if not already done. */
3974 if (!gmmR0IsChunkMapped(pGVM, pChunk, (PRTR3PTR)&pbChunk))
3975 {
3976 Log(("Map chunk into process!\n"));
3977 rc = gmmR0MapChunk(pGMM, pGVM, pChunk, (PRTR3PTR)&pbChunk);
3978 if (rc != VINF_SUCCESS)
3979 {
3980 AssertRC(rc);
3981 goto end;
3982 }
3983 }
3984 pbSharedPage = pbChunk + ((pGlobalRegion->paHCPhysPageID[idxPage] & GMM_PAGEID_IDX_MASK) << PAGE_SHIFT);
3985
3986 /** @todo write ASMMemComparePage. */
3987 if (memcmp(pbSharedPage, pbLocalPage, PAGE_SIZE))
3988 {
3989 Log(("Unexpected differences found between local and shared page; skip\n"));
3990 /* Signal to the caller that this one hasn't changed. */
3991 pPageDesc->uHCPhysPageId = NIL_GMM_PAGEID;
3992 goto end;
3993 }
3994
3995 /* Free the old local page. */
3996 GMMFREEPAGEDESC PageDesc;
3997
3998 PageDesc.idPage = pPageDesc->uHCPhysPageId;
3999 rc = gmmR0FreePages(pGMM, pGVM, 1, &PageDesc, GMMACCOUNT_BASE);
4000 AssertRCReturn(rc, rc);
4001
4002 gmmR0UseSharedPage(pGMM, pGVM, pPage);
4003
4004 /* Pass along the new physical address & page id. */
4005 pPageDesc->HCPhys = ((uint64_t)pPage->Shared.pfn) << PAGE_SHIFT;
4006 pPageDesc->uHCPhysPageId = pGlobalRegion->paHCPhysPageID[idxPage];
4007 }
4008end:
4009 return rc;
4010}
4011
4012/**
4013 * RTAvlU32Destroy callback.
4014 *
4015 * @returns 0
4016 * @param pNode The node to destroy.
4017 * @param pvGVM The GVM handle.
4018 */
4019static DECLCALLBACK(int) gmmR0CleanupSharedModule(PAVLGCPTRNODECORE pNode, void *pvGVM)
4020{
4021 PGVM pGVM = (PGVM)pvGVM;
4022 PGMMSHAREDMODULEPERVM pRecVM = (PGMMSHAREDMODULEPERVM)pNode;
4023 PGMM pGMM;
4024 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
4025
4026 Assert(pRecVM->pGlobalModule || pRecVM->fCollision);
4027 if (pRecVM->pGlobalModule)
4028 {
4029 PGMMSHAREDMODULE pRec = pRecVM->pGlobalModule;
4030 Assert(pRec);
4031 Assert(pRec->cUsers);
4032
4033 Log(("gmmR0CleanupSharedModule: %s %s cUsers=%d\n", pRec->szName, pRec->szVersion, pRec->cUsers));
4034 pRec->cUsers--;
4035 if (pRec->cUsers == 0)
4036 {
4037 for (unsigned i = 0; i < pRec->cRegions; i++)
4038 if (pRec->aRegions[i].paHCPhysPageID)
4039 RTMemFree(pRec->aRegions[i].paHCPhysPageID);
4040
4041 /* Remove from the tree and free memory. */
4042 RTAvlGCPtrRemove(&pGMM->pGlobalSharedModuleTree, pRec->Core.Key);
4043 RTMemFree(pRec);
4044 }
4045 }
4046 RTMemFree(pRecVM);
4047 return 0;
4048}
4049#endif
4050
4051/**
4052 * Removes all shared modules for the specified VM
4053 *
4054 * @returns VBox status code.
4055 * @param pVM VM handle
4056 * @param idCpu VCPU id
4057 */
4058GMMR0DECL(int) GMMR0ResetSharedModules(PVM pVM, VMCPUID idCpu)
4059{
4060#ifdef VBOX_WITH_PAGE_SHARING
4061 /*
4062 * Validate input and get the basics.
4063 */
4064 PGMM pGMM;
4065 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
4066 PGVM pGVM;
4067 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
4068 if (RT_FAILURE(rc))
4069 return rc;
4070
4071 /*
4072 * Take the semaphore and do some more validations.
4073 */
4074 rc = RTSemFastMutexRequest(pGMM->Mtx);
4075 AssertRC(rc);
4076 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
4077 {
4078 Log(("GMMR0ResetSharedModules\n"));
4079 RTAvlGCPtrDestroy(&pGVM->gmm.s.pSharedModuleTree, gmmR0CleanupSharedModule, pGVM);
4080
4081 rc = VINF_SUCCESS;
4082 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
4083 }
4084 else
4085 rc = VERR_INTERNAL_ERROR_5;
4086
4087 RTSemFastMutexRelease(pGMM->Mtx);
4088 return rc;
4089#else
4090 return VERR_NOT_IMPLEMENTED;
4091#endif
4092}
4093
4094#ifdef VBOX_WITH_PAGE_SHARING
4095typedef struct
4096{
4097 PGVM pGVM;
4098 VMCPUID idCpu;
4099 int rc;
4100} GMMCHECKSHAREDMODULEINFO, *PGMMCHECKSHAREDMODULEINFO;
4101
4102/**
4103 * Tree enumeration callback for checking a shared module.
4104 */
4105DECLCALLBACK(int) gmmR0CheckSharedModule(PAVLGCPTRNODECORE pNode, void *pvUser)
4106{
4107 PGMMCHECKSHAREDMODULEINFO pInfo = (PGMMCHECKSHAREDMODULEINFO)pvUser;
4108 PGMMSHAREDMODULEPERVM pLocalModule = (PGMMSHAREDMODULEPERVM)pNode;
4109 PGMMSHAREDMODULE pGlobalModule = pLocalModule->pGlobalModule;
4110
4111 if ( !pLocalModule->fCollision
4112 && pGlobalModule)
4113 {
4114 Log(("gmmR0CheckSharedModule: check %s %s base=%RGv size=%x collision=%d\n", pGlobalModule->szName, pGlobalModule->szVersion, pGlobalModule->Core.Key, pGlobalModule->cbModule, pLocalModule->fCollision));
4115 pInfo->rc = PGMR0SharedModuleCheck(pInfo->pGVM->pVM, pInfo->pGVM, pInfo->idCpu, pGlobalModule, pLocalModule->cRegions, pLocalModule->aRegions);
4116 if (RT_FAILURE(pInfo->rc))
4117 return 1; /* stop enumeration. */
4118 }
4119 return 0;
4120}
4121#endif
4122
4123#ifdef DEBUG_sandervl
4124/**
4125 * Setup for a GMMR0CheckSharedModules call (to allow log flush jumps back to ring 3)
4126 *
4127 * @returns VBox status code.
4128 * @param pVM VM handle
4129 */
4130GMMR0DECL(int) GMMR0CheckSharedModulesStart(PVM pVM)
4131{
4132 /*
4133 * Validate input and get the basics.
4134 */
4135 PGMM pGMM;
4136 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
4137
4138 /*
4139 * Take the semaphore and do some more validations.
4140 */
4141 int rc = RTSemFastMutexRequest(pGMM->Mtx);
4142 AssertRC(rc);
4143 if (!GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
4144 rc = VERR_INTERNAL_ERROR_5;
4145 else
4146 rc = VINF_SUCCESS;
4147
4148 return rc;
4149}
4150
4151/**
4152 * Clean up after a GMMR0CheckSharedModules call (to allow log flush jumps back to ring 3)
4153 *
4154 * @returns VBox status code.
4155 * @param pVM VM handle
4156 */
4157GMMR0DECL(int) GMMR0CheckSharedModulesEnd(PVM pVM)
4158{
4159 /*
4160 * Validate input and get the basics.
4161 */
4162 PGMM pGMM;
4163 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
4164
4165 RTSemFastMutexRelease(pGMM->Mtx);
4166 return VINF_SUCCESS;
4167}
4168#endif
4169
4170/**
4171 * Check all shared modules for the specified VM
4172 *
4173 * @returns VBox status code.
4174 * @param pVM VM handle
4175 * @param pVCpu VMCPU handle
4176 */
4177GMMR0DECL(int) GMMR0CheckSharedModules(PVM pVM, PVMCPU pVCpu)
4178{
4179#ifdef VBOX_WITH_PAGE_SHARING
4180 /*
4181 * Validate input and get the basics.
4182 */
4183 PGMM pGMM;
4184 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
4185 PGVM pGVM;
4186 int rc = GVMMR0ByVMAndEMT(pVM, pVCpu->idCpu, &pGVM);
4187 if (RT_FAILURE(rc))
4188 return rc;
4189
4190# ifndef DEBUG_sandervl
4191 /*
4192 * Take the semaphore and do some more validations.
4193 */
4194 rc = RTSemFastMutexRequest(pGMM->Mtx);
4195 AssertRC(rc);
4196# endif
4197 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
4198 {
4199 GMMCHECKSHAREDMODULEINFO Info;
4200
4201 Log(("GMMR0CheckSharedModules\n"));
4202 Info.pGVM = pGVM;
4203 Info.idCpu = pVCpu->idCpu;
4204 Info.rc = VINF_SUCCESS;
4205
4206 RTAvlGCPtrDoWithAll(&pGVM->gmm.s.pSharedModuleTree, true /* fFromLeft */, gmmR0CheckSharedModule, &Info);
4207
4208 rc = Info.rc;
4209
4210 Log(("GMMR0CheckSharedModules done!\n"));
4211
4212 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
4213 }
4214 else
4215 rc = VERR_INTERNAL_ERROR_5;
4216
4217# ifndef DEBUG_sandervl
4218 RTSemFastMutexRelease(pGMM->Mtx);
4219# endif
4220 return rc;
4221#else
4222 return VERR_NOT_IMPLEMENTED;
4223#endif
4224}
4225
4226#if defined(VBOX_STRICT) && HC_ARCH_BITS == 64
4227typedef struct
4228{
4229 PGVM pGVM;
4230 PGMM pGMM;
4231 uint8_t *pSourcePage;
4232 bool fFoundDuplicate;
4233} GMMFINDDUPPAGEINFO, *PGMMFINDDUPPAGEINFO;
4234
4235/**
4236 * RTAvlU32DoWithAll callback.
4237 *
4238 * @returns 0
4239 * @param pNode The node to search.
4240 * @param pvInfo Pointer to the input parameters
4241 */
4242static DECLCALLBACK(int) gmmR0FindDupPageInChunk(PAVLU32NODECORE pNode, void *pvInfo)
4243{
4244 PGMMCHUNK pChunk = (PGMMCHUNK)pNode;
4245 PGMMFINDDUPPAGEINFO pInfo = (PGMMFINDDUPPAGEINFO)pvInfo;
4246 PGVM pGVM = pInfo->pGVM;
4247 PGMM pGMM = pInfo->pGMM;
4248 uint8_t *pbChunk;
4249
4250 /* Only take chunks not mapped into this VM process; not entirely correct. */
4251 if (!gmmR0IsChunkMapped(pGVM, pChunk, (PRTR3PTR)&pbChunk))
4252 {
4253 int rc = gmmR0MapChunk(pGMM, pGVM, pChunk, (PRTR3PTR)&pbChunk);
4254 if (rc != VINF_SUCCESS)
4255 goto end;
4256
4257 /*
4258 * Look for duplicate pages
4259 */
4260 unsigned iPage = (GMM_CHUNK_SIZE >> PAGE_SHIFT);
4261 while (iPage-- > 0)
4262 {
4263 if (GMM_PAGE_IS_PRIVATE(&pChunk->aPages[iPage]))
4264 {
4265 uint8_t *pbDestPage = pbChunk + (iPage << PAGE_SHIFT);
4266
4267 if (!memcmp(pInfo->pSourcePage, pbDestPage, PAGE_SIZE))
4268 {
4269 pInfo->fFoundDuplicate = true;
4270 break;
4271 }
4272 }
4273 }
4274 gmmR0UnmapChunk(pGMM, pGVM, pChunk);
4275 }
4276end:
4277 if (pInfo->fFoundDuplicate)
4278 return 1; /* stop search */
4279 else
4280 return 0;
4281}
4282
4283/**
4284 * Find a duplicate of the specified page in other active VMs
4285 *
4286 * @returns VBox status code.
4287 * @param pVM VM handle
4288 * @param pReq Request packet
4289 */
4290GMMR0DECL(int) GMMR0FindDuplicatePageReq(PVM pVM, PGMMFINDDUPLICATEPAGEREQ pReq)
4291{
4292 /*
4293 * Validate input and pass it on.
4294 */
4295 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
4296 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
4297 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
4298
4299 PGMM pGMM;
4300 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
4301
4302 /*
4303 * Take the semaphore and do some more validations.
4304 */
4305 int rc = RTSemFastMutexRequest(pGMM->Mtx);
4306 AssertRC(rc);
4307 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
4308 {
4309 PGVM pGVM;
4310 rc = GVMMR0ByVM(pVM, &pGVM);
4311 if (RT_FAILURE(rc))
4312 goto end;
4313
4314 uint8_t *pbChunk;
4315 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, pReq->idPage >> GMM_CHUNKID_SHIFT);
4316 if (!pChunk)
4317 {
4318 AssertFailed();
4319 goto end;
4320 }
4321
4322 if (!gmmR0IsChunkMapped(pGVM, pChunk, (PRTR3PTR)&pbChunk))
4323 {
4324 AssertFailed();
4325 goto end;
4326 }
4327
4328 uint8_t *pbSourcePage = pbChunk + ((pReq->idPage & GMM_PAGEID_IDX_MASK) << PAGE_SHIFT);
4329
4330 PGMMPAGE pPage = gmmR0GetPage(pGMM, pReq->idPage);
4331 if (!pPage)
4332 {
4333 AssertFailed();
4334 rc = VERR_PGM_PHYS_INVALID_PAGE_ID;
4335 goto end;
4336 }
4337 GMMFINDDUPPAGEINFO Info;
4338
4339 Info.pGVM = pGVM;
4340 Info.pGMM = pGMM;
4341 Info.pSourcePage = pbSourcePage;
4342 Info.fFoundDuplicate = false;
4343 RTAvlU32DoWithAll(&pGMM->pChunks, true /* fFromLeft */, gmmR0FindDupPageInChunk, &Info);
4344
4345 pReq->fDuplicate = Info.fFoundDuplicate;
4346 }
4347 else
4348 rc = VERR_INTERNAL_ERROR_5;
4349
4350end:
4351 RTSemFastMutexRelease(pGMM->Mtx);
4352 return rc;
4353}
4354
4355#endif /* VBOX_STRICT && HC_ARCH_BITS == 64 */
4356
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