VirtualBox

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

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

GMMR0: Leave the GMM lock when mapping a chunk into user space, it's expensive.

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