VirtualBox

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

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

GMMR0: Unused variable.

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