VirtualBox

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

Last change on this file since 68010 was 68010, checked in by vboxsync, 7 years ago

VMMR0,PDMR0: Adding GVM parameter and validation thereof to the generic ring-0 device & driver calls. [build fix]

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