VirtualBox

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

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

Reregister all shared modules after VM restore

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

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