VirtualBox

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

Last change on this file since 30658 was 30656, checked in by vboxsync, 15 years ago

Missing init

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

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