VirtualBox

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

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

FreeBSD: Enable new allocation mode using the PhysNC allocator

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 114.9 KB
Line 
1/* $Id: GMMR0.cpp 27147 2010-03-07 16:55:49Z vboxsync $ */
2/** @file
3 * GMM - Global Memory Manager.
4 */
5
6/*
7 * Copyright (C) 2007 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22
23/** @page pg_gmm GMM - The Global Memory Manager
24 *
25 * As the name indicates, this component is responsible for global memory
26 * management. Currently only guest RAM is allocated from the GMM, but this
27 * may change to include shadow page tables and other bits later.
28 *
29 * Guest RAM is managed as individual pages, but allocated from the host OS
30 * in chunks for reasons of portability / efficiency. To minimize the memory
31 * footprint all tracking structure must be as small as possible without
32 * unnecessary performance penalties.
33 *
34 * The allocation chunks has fixed sized, the size defined at compile time
35 * by the #GMM_CHUNK_SIZE \#define.
36 *
37 * Each chunk is given an unquie ID. Each page also has a unique ID. The
38 * relation ship between the two IDs is:
39 * @code
40 * GMM_CHUNK_SHIFT = log2(GMM_CHUNK_SIZE / PAGE_SIZE);
41 * idPage = (idChunk << GMM_CHUNK_SHIFT) | iPage;
42 * @endcode
43 * Where iPage is the index of the page within the chunk. This ID scheme
44 * permits for efficient chunk and page lookup, but it relies on the chunk size
45 * to be set at compile time. The chunks are organized in an AVL tree with their
46 * IDs being the keys.
47 *
48 * The physical address of each page in an allocation chunk is maintained by
49 * the #RTR0MEMOBJ and obtained using #RTR0MemObjGetPagePhysAddr. There is no
50 * need to duplicate this information (it'll cost 8-bytes per page if we did).
51 *
52 * So what do we need to track per page? Most importantly we need to know
53 * which state the page is in:
54 * - Private - Allocated for (eventually) backing one particular VM page.
55 * - Shared - Readonly page that is used by one or more VMs and treated
56 * as COW by PGM.
57 * - Free - Not used by anyone.
58 *
59 * For the page replacement operations (sharing, defragmenting and freeing)
60 * to be somewhat efficient, private pages needs to be associated with a
61 * particular page in a particular VM.
62 *
63 * Tracking the usage of shared pages is impractical and expensive, so we'll
64 * settle for a reference counting system instead.
65 *
66 * Free pages will be chained on LIFOs
67 *
68 * On 64-bit systems we will use a 64-bit bitfield per page, while on 32-bit
69 * systems a 32-bit bitfield will have to suffice because of address space
70 * limitations. The #GMMPAGE structure shows the details.
71 *
72 *
73 * @section sec_gmm_alloc_strat Page Allocation Strategy
74 *
75 * The strategy for allocating pages has to take fragmentation and shared
76 * pages into account, or we may end up with with 2000 chunks with only
77 * a few pages in each. Shared pages cannot easily be reallocated because
78 * of the inaccurate usage accounting (see above). Private pages can be
79 * reallocated by a defragmentation thread in the same manner that sharing
80 * is done.
81 *
82 * The first approach is to manage the free pages in two sets depending on
83 * whether they are mainly for the allocation of shared or private pages.
84 * In the initial implementation there will be almost no possibility for
85 * mixing shared and private pages in the same chunk (only if we're really
86 * stressed on memory), but when we implement forking of VMs and have to
87 * deal with lots of COW pages it'll start getting kind of interesting.
88 *
89 * The sets are lists of chunks with approximately the same number of
90 * free pages. Say the chunk size is 1MB, meaning 256 pages, and a set
91 * consists of 16 lists. So, the first list will contain the chunks with
92 * 1-7 free pages, the second covers 8-15, and so on. The chunks will be
93 * moved between the lists as pages are freed up or allocated.
94 *
95 *
96 * @section sec_gmm_costs Costs
97 *
98 * The per page cost in kernel space is 32-bit plus whatever RTR0MEMOBJ
99 * entails. In addition there is the chunk cost of approximately
100 * (sizeof(RT0MEMOBJ) + sizof(CHUNK)) / 2^CHUNK_SHIFT bytes per page.
101 *
102 * On Windows the per page #RTR0MEMOBJ cost is 32-bit on 32-bit windows
103 * and 64-bit on 64-bit windows (a PFN_NUMBER in the MDL). So, 64-bit per page.
104 * The cost on Linux is identical, but here it's because of sizeof(struct page *).
105 *
106 *
107 * @section sec_gmm_legacy Legacy Mode for Non-Tier-1 Platforms
108 *
109 * In legacy mode the page source is locked user pages and not
110 * #RTR0MemObjAllocPhysNC, this means that a page can only be allocated
111 * by the VM that locked it. We will make no attempt at implementing
112 * page sharing on these systems, just do enough to make it all work.
113 *
114 *
115 * @subsection sub_gmm_locking Serializing
116 *
117 * One simple fast mutex will be employed in the initial implementation, not
118 * two as metioned in @ref subsec_pgmPhys_Serializing.
119 *
120 * @see @ref subsec_pgmPhys_Serializing
121 *
122 *
123 * @section sec_gmm_overcommit Memory Over-Commitment Management
124 *
125 * The GVM will have to do the system wide memory over-commitment
126 * management. My current ideas are:
127 * - Per VM oc policy that indicates how much to initially commit
128 * to it and what to do in a out-of-memory situation.
129 * - Prevent overtaxing the host.
130 *
131 * There are some challenges here, the main ones are configurability and
132 * security. Should we for instance permit anyone to request 100% memory
133 * commitment? Who should be allowed to do runtime adjustments of the
134 * config. And how to prevent these settings from being lost when the last
135 * VM process exits? The solution is probably to have an optional root
136 * daemon the will keep VMMR0.r0 in memory and enable the security measures.
137 *
138 *
139 *
140 * @section sec_gmm_numa NUMA
141 *
142 * NUMA considerations will be designed and implemented a bit later.
143 *
144 * The preliminary guesses is that we will have to try allocate memory as
145 * close as possible to the CPUs the VM is executed on (EMT and additional CPU
146 * threads). Which means it's mostly about allocation and sharing policies.
147 * Both the scheduler and allocator interface will to supply some NUMA info
148 * and we'll need to have a way to calc access costs.
149 *
150 */
151
152
153/*******************************************************************************
154* Header Files *
155*******************************************************************************/
156#define LOG_GROUP LOG_GROUP_GMM
157#include <VBox/gmm.h>
158#include "GMMR0Internal.h"
159#include <VBox/gvm.h>
160#include <VBox/log.h>
161#include <VBox/param.h>
162#include <VBox/err.h>
163#include <iprt/avl.h>
164#include <iprt/mem.h>
165#include <iprt/memobj.h>
166#include <iprt/semaphore.h>
167#include <iprt/string.h>
168
169
170/*******************************************************************************
171* Structures and Typedefs *
172*******************************************************************************/
173/** Pointer to set of free chunks. */
174typedef struct GMMCHUNKFREESET *PGMMCHUNKFREESET;
175
176/** Pointer to a GMM allocation chunk. */
177typedef struct GMMCHUNK *PGMMCHUNK;
178
179/**
180 * The per-page tracking structure employed by the GMM.
181 *
182 * On 32-bit hosts we'll some trickery is necessary to compress all
183 * the information into 32-bits. When the fSharedFree member is set,
184 * the 30th bit decides whether it's a free page or not.
185 *
186 * Because of the different layout on 32-bit and 64-bit hosts, macros
187 * are used to get and set some of the data.
188 */
189typedef union GMMPAGE
190{
191#if HC_ARCH_BITS == 64
192 /** Unsigned integer view. */
193 uint64_t u;
194
195 /** The common view. */
196 struct GMMPAGECOMMON
197 {
198 uint32_t uStuff1 : 32;
199 uint32_t uStuff2 : 30;
200 /** The page state. */
201 uint32_t u2State : 2;
202 } Common;
203
204 /** The view of a private page. */
205 struct GMMPAGEPRIVATE
206 {
207 /** The guest page frame number. (Max addressable: 2 ^ 44 - 16) */
208 uint32_t pfn;
209 /** The GVM handle. (64K VMs) */
210 uint32_t hGVM : 16;
211 /** Reserved. */
212 uint32_t u16Reserved : 14;
213 /** The page state. */
214 uint32_t u2State : 2;
215 } Private;
216
217 /** The view of a shared page. */
218 struct GMMPAGESHARED
219 {
220 /** The reference count. */
221 uint32_t cRefs;
222 /** Reserved. Checksum or something? Two hGVMs for forking? */
223 uint32_t u30Reserved : 30;
224 /** The page state. */
225 uint32_t u2State : 2;
226 } Shared;
227
228 /** The view of a free page. */
229 struct GMMPAGEFREE
230 {
231 /** The index of the next page in the free list. UINT16_MAX is NIL. */
232 uint16_t iNext;
233 /** Reserved. Checksum or something? */
234 uint16_t u16Reserved0;
235 /** Reserved. Checksum or something? */
236 uint32_t u30Reserved1 : 30;
237 /** The page state. */
238 uint32_t u2State : 2;
239 } Free;
240
241#else /* 32-bit */
242 /** Unsigned integer view. */
243 uint32_t u;
244
245 /** The common view. */
246 struct GMMPAGECOMMON
247 {
248 uint32_t uStuff : 30;
249 /** The page state. */
250 uint32_t u2State : 2;
251 } Common;
252
253 /** The view of a private page. */
254 struct GMMPAGEPRIVATE
255 {
256 /** The guest page frame number. (Max addressable: 2 ^ 36) */
257 uint32_t pfn : 24;
258 /** The GVM handle. (127 VMs) */
259 uint32_t hGVM : 7;
260 /** The top page state bit, MBZ. */
261 uint32_t fZero : 1;
262 } Private;
263
264 /** The view of a shared page. */
265 struct GMMPAGESHARED
266 {
267 /** The reference count. */
268 uint32_t cRefs : 30;
269 /** The page state. */
270 uint32_t u2State : 2;
271 } Shared;
272
273 /** The view of a free page. */
274 struct GMMPAGEFREE
275 {
276 /** The index of the next page in the free list. UINT16_MAX is NIL. */
277 uint32_t iNext : 16;
278 /** Reserved. Checksum or something? */
279 uint32_t u14Reserved : 14;
280 /** The page state. */
281 uint32_t u2State : 2;
282 } Free;
283#endif
284} GMMPAGE;
285AssertCompileSize(GMMPAGE, sizeof(RTHCUINTPTR));
286/** Pointer to a GMMPAGE. */
287typedef GMMPAGE *PGMMPAGE;
288
289
290/** @name The Page States.
291 * @{ */
292/** A private page. */
293#define GMM_PAGE_STATE_PRIVATE 0
294/** A private page - alternative value used on the 32-bit implemenation.
295 * This will never be used on 64-bit hosts. */
296#define GMM_PAGE_STATE_PRIVATE_32 1
297/** A shared page. */
298#define GMM_PAGE_STATE_SHARED 2
299/** A free page. */
300#define GMM_PAGE_STATE_FREE 3
301/** @} */
302
303
304/** @def GMM_PAGE_IS_PRIVATE
305 *
306 * @returns true if private, false if not.
307 * @param pPage The GMM page.
308 */
309#if HC_ARCH_BITS == 64
310# define GMM_PAGE_IS_PRIVATE(pPage) ( (pPage)->Common.u2State == GMM_PAGE_STATE_PRIVATE )
311#else
312# define GMM_PAGE_IS_PRIVATE(pPage) ( (pPage)->Private.fZero == 0 )
313#endif
314
315/** @def GMM_PAGE_IS_SHARED
316 *
317 * @returns true if shared, false if not.
318 * @param pPage The GMM page.
319 */
320#define GMM_PAGE_IS_SHARED(pPage) ( (pPage)->Common.u2State == GMM_PAGE_STATE_SHARED )
321
322/** @def GMM_PAGE_IS_FREE
323 *
324 * @returns true if free, false if not.
325 * @param pPage The GMM page.
326 */
327#define GMM_PAGE_IS_FREE(pPage) ( (pPage)->Common.u2State == GMM_PAGE_STATE_FREE )
328
329/** @def GMM_PAGE_PFN_LAST
330 * The last valid guest pfn range.
331 * @remark Some of the values outside the range has special meaning,
332 * see GMM_PAGE_PFN_UNSHAREABLE.
333 */
334#if HC_ARCH_BITS == 64
335# define GMM_PAGE_PFN_LAST UINT32_C(0xfffffff0)
336#else
337# define GMM_PAGE_PFN_LAST UINT32_C(0x00fffff0)
338#endif
339AssertCompile(GMM_PAGE_PFN_LAST == (GMM_GCPHYS_LAST >> PAGE_SHIFT));
340
341/** @def GMM_PAGE_PFN_UNSHAREABLE
342 * Indicates that this page isn't used for normal guest memory and thus isn't shareable.
343 */
344#if HC_ARCH_BITS == 64
345# define GMM_PAGE_PFN_UNSHAREABLE UINT32_C(0xfffffff1)
346#else
347# define GMM_PAGE_PFN_UNSHAREABLE UINT32_C(0x00fffff1)
348#endif
349AssertCompile(GMM_PAGE_PFN_UNSHAREABLE == (GMM_GCPHYS_UNSHAREABLE >> PAGE_SHIFT));
350
351
352/**
353 * A GMM allocation chunk ring-3 mapping record.
354 *
355 * This should really be associated with a session and not a VM, but
356 * it's simpler to associated with a VM and cleanup with the VM object
357 * is destroyed.
358 */
359typedef struct GMMCHUNKMAP
360{
361 /** The mapping object. */
362 RTR0MEMOBJ MapObj;
363 /** The VM owning the mapping. */
364 PGVM pGVM;
365} GMMCHUNKMAP;
366/** Pointer to a GMM allocation chunk mapping. */
367typedef struct GMMCHUNKMAP *PGMMCHUNKMAP;
368
369typedef enum GMMCHUNKTYPE
370{
371 GMMCHUNKTYPE_INVALID = 0,
372 GMMCHUNKTYPE_NON_CONTINUOUS = 1, /* 4 kb pages */
373 GMMCHUNKTYPE_CONTINUOUS = 2, /* one 2 MB continuous physical range. */
374 GMMCHUNKTYPE_32BIT_HACK = 0x7fffffff
375} GMMCHUNKTYPE;
376
377
378/**
379 * A GMM allocation chunk.
380 */
381typedef struct GMMCHUNK
382{
383 /** The AVL node core.
384 * The Key is the chunk ID. */
385 AVLU32NODECORE Core;
386 /** The memory object.
387 * Either from RTR0MemObjAllocPhysNC or RTR0MemObjLockUser depending on
388 * what the host can dish up with. */
389 RTR0MEMOBJ MemObj;
390 /** Pointer to the next chunk in the free list. */
391 PGMMCHUNK pFreeNext;
392 /** Pointer to the previous chunk in the free list. */
393 PGMMCHUNK pFreePrev;
394 /** Pointer to the free set this chunk belongs to. NULL for
395 * chunks with no free pages. */
396 PGMMCHUNKFREESET pSet;
397 /** Pointer to an array of mappings. */
398 PGMMCHUNKMAP paMappings;
399 /** The number of mappings. */
400 uint16_t cMappings;
401 /** The head of the list of free pages. UINT16_MAX is the NIL value. */
402 uint16_t iFreeHead;
403 /** The number of free pages. */
404 uint16_t cFree;
405 /** The GVM handle of the VM that first allocated pages from this chunk, this
406 * is used as a preference when there are several chunks to choose from.
407 * When in bound memory mode this isn't a preference any longer. */
408 uint16_t hGVM;
409 /** The number of private pages. */
410 uint16_t cPrivate;
411 /** The number of shared pages. */
412 uint16_t cShared;
413 /** Chunk type */
414 GMMCHUNKTYPE enmType;
415 /** The pages. */
416 GMMPAGE aPages[GMM_CHUNK_SIZE >> PAGE_SHIFT];
417} GMMCHUNK;
418
419
420/**
421 * An allocation chunk TLB entry.
422 */
423typedef struct GMMCHUNKTLBE
424{
425 /** The chunk id. */
426 uint32_t idChunk;
427 /** Pointer to the chunk. */
428 PGMMCHUNK pChunk;
429} GMMCHUNKTLBE;
430/** Pointer to an allocation chunk TLB entry. */
431typedef GMMCHUNKTLBE *PGMMCHUNKTLBE;
432
433
434/** The number of entries tin the allocation chunk TLB. */
435#define GMM_CHUNKTLB_ENTRIES 32
436/** Gets the TLB entry index for the given Chunk ID. */
437#define GMM_CHUNKTLB_IDX(idChunk) ( (idChunk) & (GMM_CHUNKTLB_ENTRIES - 1) )
438
439/**
440 * An allocation chunk TLB.
441 */
442typedef struct GMMCHUNKTLB
443{
444 /** The TLB entries. */
445 GMMCHUNKTLBE aEntries[GMM_CHUNKTLB_ENTRIES];
446} GMMCHUNKTLB;
447/** Pointer to an allocation chunk TLB. */
448typedef GMMCHUNKTLB *PGMMCHUNKTLB;
449
450
451/** The GMMCHUNK::cFree shift count. */
452#define GMM_CHUNK_FREE_SET_SHIFT 4
453/** The GMMCHUNK::cFree mask for use when considering relinking a chunk. */
454#define GMM_CHUNK_FREE_SET_MASK 15
455/** The number of lists in set. */
456#define GMM_CHUNK_FREE_SET_LISTS (GMM_CHUNK_NUM_PAGES >> GMM_CHUNK_FREE_SET_SHIFT)
457
458/**
459 * A set of free chunks.
460 */
461typedef struct GMMCHUNKFREESET
462{
463 /** The number of free pages in the set. */
464 uint64_t cFreePages;
465 /** Chunks ordered by increasing number of free pages. */
466 PGMMCHUNK apLists[GMM_CHUNK_FREE_SET_LISTS];
467} GMMCHUNKFREESET;
468
469
470/**
471 * The GMM instance data.
472 */
473typedef struct GMM
474{
475 /** Magic / eye catcher. GMM_MAGIC */
476 uint32_t u32Magic;
477 /** The fast mutex protecting the GMM.
478 * More fine grained locking can be implemented later if necessary. */
479 RTSEMFASTMUTEX Mtx;
480 /** The chunk tree. */
481 PAVLU32NODECORE pChunks;
482 /** The chunk TLB. */
483 GMMCHUNKTLB ChunkTLB;
484 /** The private free set. */
485 GMMCHUNKFREESET Private;
486 /** The shared free set. */
487 GMMCHUNKFREESET Shared;
488
489 /** The maximum number of pages we're allowed to allocate.
490 * @gcfgm 64-bit GMM/MaxPages Direct.
491 * @gcfgm 32-bit GMM/PctPages Relative to the number of host pages. */
492 uint64_t cMaxPages;
493 /** The number of pages that has been reserved.
494 * The deal is that cReservedPages - cOverCommittedPages <= cMaxPages. */
495 uint64_t cReservedPages;
496 /** The number of pages that we have over-committed in reservations. */
497 uint64_t cOverCommittedPages;
498 /** The number of actually allocated (committed if you like) pages. */
499 uint64_t cAllocatedPages;
500 /** The number of pages that are shared. A subset of cAllocatedPages. */
501 uint64_t cSharedPages;
502 /** The number of pages that are shared that has been left behind by
503 * VMs not doing proper cleanups. */
504 uint64_t cLeftBehindSharedPages;
505 /** The number of allocation chunks.
506 * (The number of pages we've allocated from the host can be derived from this.) */
507 uint32_t cChunks;
508 /** The number of current ballooned pages. */
509 uint64_t cBalloonedPages;
510
511 /** The legacy allocation mode indicator.
512 * This is determined at initialization time. */
513 bool fLegacyAllocationMode;
514 /** The bound memory mode indicator.
515 * When set, the memory will be bound to a specific VM and never
516 * shared. This is always set if fLegacyAllocationMode is set.
517 * (Also determined at initialization time.) */
518 bool fBoundMemoryMode;
519 /** The number of registered VMs. */
520 uint16_t cRegisteredVMs;
521
522 /** The previous allocated Chunk ID.
523 * Used as a hint to avoid scanning the whole bitmap. */
524 uint32_t idChunkPrev;
525 /** Chunk ID allocation bitmap.
526 * Bits of allocated IDs are set, free ones are clear.
527 * The NIL id (0) is marked allocated. */
528 uint32_t bmChunkId[(GMM_CHUNKID_LAST + 1 + 31) / 32];
529} GMM;
530/** Pointer to the GMM instance. */
531typedef GMM *PGMM;
532
533/** The value of GMM::u32Magic (Katsuhiro Otomo). */
534#define GMM_MAGIC 0x19540414
535
536
537/*******************************************************************************
538* Global Variables *
539*******************************************************************************/
540/** Pointer to the GMM instance data. */
541static PGMM g_pGMM = NULL;
542
543/** Macro for obtaining and validating the g_pGMM pointer.
544 * On failure it will return from the invoking function with the specified return value.
545 *
546 * @param pGMM The name of the pGMM variable.
547 * @param rc The return value on failure. Use VERR_INTERNAL_ERROR for
548 * VBox status codes.
549 */
550#define GMM_GET_VALID_INSTANCE(pGMM, rc) \
551 do { \
552 (pGMM) = g_pGMM; \
553 AssertPtrReturn((pGMM), (rc)); \
554 AssertMsgReturn((pGMM)->u32Magic == GMM_MAGIC, ("%p - %#x\n", (pGMM), (pGMM)->u32Magic), (rc)); \
555 } while (0)
556
557/** Macro for obtaining and validating the g_pGMM pointer, void function variant.
558 * On failure it will return from the invoking function.
559 *
560 * @param pGMM The name of the pGMM variable.
561 */
562#define GMM_GET_VALID_INSTANCE_VOID(pGMM) \
563 do { \
564 (pGMM) = g_pGMM; \
565 AssertPtrReturnVoid((pGMM)); \
566 AssertMsgReturnVoid((pGMM)->u32Magic == GMM_MAGIC, ("%p - %#x\n", (pGMM), (pGMM)->u32Magic)); \
567 } while (0)
568
569
570/** @def GMM_CHECK_SANITY_UPON_ENTERING
571 * Checks the sanity of the GMM instance data before making changes.
572 *
573 * This is macro is a stub by default and must be enabled manually in the code.
574 *
575 * @returns true if sane, false if not.
576 * @param pGMM The name of the pGMM variable.
577 */
578#if defined(VBOX_STRICT) && 0
579# define GMM_CHECK_SANITY_UPON_ENTERING(pGMM) (gmmR0SanityCheck((pGMM), __PRETTY_FUNCTION__, __LINE__) == 0)
580#else
581# define GMM_CHECK_SANITY_UPON_ENTERING(pGMM) (true)
582#endif
583
584/** @def GMM_CHECK_SANITY_UPON_LEAVING
585 * Checks the sanity of the GMM instance data after making changes.
586 *
587 * This is macro is a stub by default and must be enabled manually in the code.
588 *
589 * @returns true if sane, false if not.
590 * @param pGMM The name of the pGMM variable.
591 */
592#if defined(VBOX_STRICT) && 0
593# define GMM_CHECK_SANITY_UPON_LEAVING(pGMM) (gmmR0SanityCheck((pGMM), __PRETTY_FUNCTION__, __LINE__) == 0)
594#else
595# define GMM_CHECK_SANITY_UPON_LEAVING(pGMM) (true)
596#endif
597
598/** @def GMM_CHECK_SANITY_IN_LOOPS
599 * Checks the sanity of the GMM instance in the allocation loops.
600 *
601 * This is macro is a stub by default and must be enabled manually in the code.
602 *
603 * @returns true if sane, false if not.
604 * @param pGMM The name of the pGMM variable.
605 */
606#if defined(VBOX_STRICT) && 0
607# define GMM_CHECK_SANITY_IN_LOOPS(pGMM) (gmmR0SanityCheck((pGMM), __PRETTY_FUNCTION__, __LINE__) == 0)
608#else
609# define GMM_CHECK_SANITY_IN_LOOPS(pGMM) (true)
610#endif
611
612
613/*******************************************************************************
614* Internal Functions *
615*******************************************************************************/
616static DECLCALLBACK(int) gmmR0TermDestroyChunk(PAVLU32NODECORE pNode, void *pvGMM);
617static DECLCALLBACK(int) gmmR0CleanupVMScanChunk(PAVLU32NODECORE pNode, void *pvGMM);
618/*static*/ DECLCALLBACK(int) gmmR0CleanupVMDestroyChunk(PAVLU32NODECORE pNode, void *pvGVM);
619DECLINLINE(void) gmmR0LinkChunk(PGMMCHUNK pChunk, PGMMCHUNKFREESET pSet);
620DECLINLINE(void) gmmR0UnlinkChunk(PGMMCHUNK pChunk);
621static uint32_t gmmR0SanityCheck(PGMM pGMM, const char *pszFunction, unsigned uLineNo);
622static void gmmR0FreeChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk);
623static void gmmR0FreeSharedPage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage);
624static int gmmR0UnmapChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk);
625
626
627
628/**
629 * Initializes the GMM component.
630 *
631 * This is called when the VMMR0.r0 module is loaded and protected by the
632 * loader semaphore.
633 *
634 * @returns VBox status code.
635 */
636GMMR0DECL(int) GMMR0Init(void)
637{
638 LogFlow(("GMMInit:\n"));
639
640 /*
641 * Allocate the instance data and the lock(s).
642 */
643 PGMM pGMM = (PGMM)RTMemAllocZ(sizeof(*pGMM));
644 if (!pGMM)
645 return VERR_NO_MEMORY;
646 pGMM->u32Magic = GMM_MAGIC;
647 for (unsigned i = 0; i < RT_ELEMENTS(pGMM->ChunkTLB.aEntries); i++)
648 pGMM->ChunkTLB.aEntries[i].idChunk = NIL_GMM_CHUNKID;
649 ASMBitSet(&pGMM->bmChunkId[0], NIL_GMM_CHUNKID);
650
651 int rc = RTSemFastMutexCreate(&pGMM->Mtx);
652 if (RT_SUCCESS(rc))
653 {
654 /*
655 * Check and see if RTR0MemObjAllocPhysNC works.
656 */
657#if 0 /* later, see #3170. */
658 RTR0MEMOBJ MemObj;
659 rc = RTR0MemObjAllocPhysNC(&MemObj, _64K, NIL_RTHCPHYS);
660 if (RT_SUCCESS(rc))
661 {
662 rc = RTR0MemObjFree(MemObj, true);
663 AssertRC(rc);
664 }
665 else if (rc == VERR_NOT_SUPPORTED)
666 pGMM->fLegacyAllocationMode = pGMM->fBoundMemoryMode = true;
667 else
668 SUPR0Printf("GMMR0Init: RTR0MemObjAllocPhysNC(,64K,Any) -> %d!\n", rc);
669#else
670# if defined(RT_OS_WINDOWS) || defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
671 pGMM->fLegacyAllocationMode = false;
672# if ARCH_BITS == 32
673 /* Don't reuse possibly partial chunks because of the virtual address space limitation. */
674 pGMM->fBoundMemoryMode = true;
675# else
676 pGMM->fBoundMemoryMode = false;
677# endif
678# else
679 pGMM->fLegacyAllocationMode = true;
680 pGMM->fBoundMemoryMode = true;
681# endif
682#endif
683
684 /*
685 * Query system page count and guess a reasonable cMaxPages value.
686 */
687 pGMM->cMaxPages = UINT32_MAX; /** @todo IPRT function for query ram size and such. */
688
689 g_pGMM = pGMM;
690 LogFlow(("GMMInit: pGMM=%p fLegacyAllocationMode=%RTbool fBoundMemoryMode=%RTbool\n", pGMM, pGMM->fLegacyAllocationMode, pGMM->fBoundMemoryMode));
691 return VINF_SUCCESS;
692 }
693
694 RTMemFree(pGMM);
695 SUPR0Printf("GMMR0Init: failed! rc=%d\n", rc);
696 return rc;
697}
698
699
700/**
701 * Terminates the GMM component.
702 */
703GMMR0DECL(void) GMMR0Term(void)
704{
705 LogFlow(("GMMTerm:\n"));
706
707 /*
708 * Take care / be paranoid...
709 */
710 PGMM pGMM = g_pGMM;
711 if (!VALID_PTR(pGMM))
712 return;
713 if (pGMM->u32Magic != GMM_MAGIC)
714 {
715 SUPR0Printf("GMMR0Term: u32Magic=%#x\n", pGMM->u32Magic);
716 return;
717 }
718
719 /*
720 * Undo what init did and free all the resources we've acquired.
721 */
722 /* Destroy the fundamentals. */
723 g_pGMM = NULL;
724 pGMM->u32Magic++;
725 RTSemFastMutexDestroy(pGMM->Mtx);
726 pGMM->Mtx = NIL_RTSEMFASTMUTEX;
727
728 /* free any chunks still hanging around. */
729 RTAvlU32Destroy(&pGMM->pChunks, gmmR0TermDestroyChunk, pGMM);
730
731 /* finally the instance data itself. */
732 RTMemFree(pGMM);
733 LogFlow(("GMMTerm: done\n"));
734}
735
736
737/**
738 * RTAvlU32Destroy callback.
739 *
740 * @returns 0
741 * @param pNode The node to destroy.
742 * @param pvGMM The GMM handle.
743 */
744static DECLCALLBACK(int) gmmR0TermDestroyChunk(PAVLU32NODECORE pNode, void *pvGMM)
745{
746 PGMMCHUNK pChunk = (PGMMCHUNK)pNode;
747
748 if (pChunk->cFree != (GMM_CHUNK_SIZE >> PAGE_SHIFT))
749 SUPR0Printf("GMMR0Term: %p/%#x: cFree=%d cPrivate=%d cShared=%d cMappings=%d\n", pChunk,
750 pChunk->Core.Key, pChunk->cFree, pChunk->cPrivate, pChunk->cShared, pChunk->cMappings);
751
752 int rc = RTR0MemObjFree(pChunk->MemObj, true /* fFreeMappings */);
753 if (RT_FAILURE(rc))
754 {
755 SUPR0Printf("GMMR0Term: %p/%#x: RTRMemObjFree(%p,true) -> %d (cMappings=%d)\n", pChunk,
756 pChunk->Core.Key, pChunk->MemObj, rc, pChunk->cMappings);
757 AssertRC(rc);
758 }
759 pChunk->MemObj = NIL_RTR0MEMOBJ;
760
761 RTMemFree(pChunk->paMappings);
762 pChunk->paMappings = NULL;
763
764 RTMemFree(pChunk);
765 NOREF(pvGMM);
766 return 0;
767}
768
769
770/**
771 * Initializes the per-VM data for the GMM.
772 *
773 * This is called from within the GVMM lock (from GVMMR0CreateVM)
774 * and should only initialize the data members so GMMR0CleanupVM
775 * can deal with them. We reserve no memory or anything here,
776 * that's done later in GMMR0InitVM.
777 *
778 * @param pGVM Pointer to the Global VM structure.
779 */
780GMMR0DECL(void) GMMR0InitPerVMData(PGVM pGVM)
781{
782 AssertCompile(RT_SIZEOFMEMB(GVM,gmm.s) <= RT_SIZEOFMEMB(GVM,gmm.padding));
783
784 pGVM->gmm.s.enmPolicy = GMMOCPOLICY_INVALID;
785 pGVM->gmm.s.enmPriority = GMMPRIORITY_INVALID;
786 pGVM->gmm.s.fMayAllocate = false;
787}
788
789
790/**
791 * Cleans up when a VM is terminating.
792 *
793 * @param pGVM Pointer to the Global VM structure.
794 */
795GMMR0DECL(void) GMMR0CleanupVM(PGVM pGVM)
796{
797 LogFlow(("GMMR0CleanupVM: pGVM=%p:{.pVM=%p, .hSelf=%#x}\n", pGVM, pGVM->pVM, pGVM->hSelf));
798
799 PGMM pGMM;
800 GMM_GET_VALID_INSTANCE_VOID(pGMM);
801
802 int rc = RTSemFastMutexRequest(pGMM->Mtx);
803 AssertRC(rc);
804 GMM_CHECK_SANITY_UPON_ENTERING(pGMM);
805
806 /*
807 * The policy is 'INVALID' until the initial reservation
808 * request has been serviced.
809 */
810 if ( pGVM->gmm.s.enmPolicy > GMMOCPOLICY_INVALID
811 && pGVM->gmm.s.enmPolicy < GMMOCPOLICY_END)
812 {
813 /*
814 * If it's the last VM around, we can skip walking all the chunk looking
815 * for the pages owned by this VM and instead flush the whole shebang.
816 *
817 * This takes care of the eventuality that a VM has left shared page
818 * references behind (shouldn't happen of course, but you never know).
819 */
820 Assert(pGMM->cRegisteredVMs);
821 pGMM->cRegisteredVMs--;
822#if 0 /* disabled so it won't hide bugs. */
823 if (!pGMM->cRegisteredVMs)
824 {
825 RTAvlU32Destroy(&pGMM->pChunks, gmmR0CleanupVMDestroyChunk, pGMM);
826
827 for (unsigned i = 0; i < RT_ELEMENTS(pGMM->ChunkTLB.aEntries); i++)
828 {
829 pGMM->ChunkTLB.aEntries[i].idChunk = NIL_GMM_CHUNKID;
830 pGMM->ChunkTLB.aEntries[i].pChunk = NULL;
831 }
832
833 memset(&pGMM->Private, 0, sizeof(pGMM->Private));
834 memset(&pGMM->Shared, 0, sizeof(pGMM->Shared));
835
836 memset(&pGMM->bmChunkId[0], 0, sizeof(pGMM->bmChunkId));
837 ASMBitSet(&pGMM->bmChunkId[0], NIL_GMM_CHUNKID);
838
839 pGMM->cReservedPages = 0;
840 pGMM->cOverCommittedPages = 0;
841 pGMM->cAllocatedPages = 0;
842 pGMM->cSharedPages = 0;
843 pGMM->cLeftBehindSharedPages = 0;
844 pGMM->cChunks = 0;
845 pGMM->cBalloonedPages = 0;
846 }
847 else
848#endif
849 {
850 /*
851 * Walk the entire pool looking for pages that belongs to this VM
852 * and left over mappings. (This'll only catch private pages, shared
853 * pages will be 'left behind'.)
854 */
855 uint64_t cPrivatePages = pGVM->gmm.s.cPrivatePages; /* save */
856 RTAvlU32DoWithAll(&pGMM->pChunks, true /* fFromLeft */, gmmR0CleanupVMScanChunk, pGVM);
857 if (pGVM->gmm.s.cPrivatePages)
858 SUPR0Printf("GMMR0CleanupVM: hGVM=%#x has %#x private pages that cannot be found!\n", pGVM->hSelf, pGVM->gmm.s.cPrivatePages);
859 pGMM->cAllocatedPages -= cPrivatePages;
860
861 /* free empty chunks. */
862 if (cPrivatePages)
863 {
864 PGMMCHUNK pCur = pGMM->Private.apLists[RT_ELEMENTS(pGMM->Private.apLists) - 1];
865 while (pCur)
866 {
867 PGMMCHUNK pNext = pCur->pFreeNext;
868 if ( pCur->cFree == GMM_CHUNK_NUM_PAGES
869 && ( !pGMM->fBoundMemoryMode
870 || pCur->hGVM == pGVM->hSelf))
871 gmmR0FreeChunk(pGMM, pGVM, pCur);
872 pCur = pNext;
873 }
874 }
875
876 /* account for shared pages that weren't freed. */
877 if (pGVM->gmm.s.cSharedPages)
878 {
879 Assert(pGMM->cSharedPages >= pGVM->gmm.s.cSharedPages);
880 SUPR0Printf("GMMR0CleanupVM: hGVM=%#x left %#x shared pages behind!\n", pGVM->hSelf, pGVM->gmm.s.cSharedPages);
881 pGMM->cLeftBehindSharedPages += pGVM->gmm.s.cSharedPages;
882 }
883
884 /*
885 * Update the over-commitment management statistics.
886 */
887 pGMM->cReservedPages -= pGVM->gmm.s.Reserved.cBasePages
888 + pGVM->gmm.s.Reserved.cFixedPages
889 + pGVM->gmm.s.Reserved.cShadowPages;
890 switch (pGVM->gmm.s.enmPolicy)
891 {
892 case GMMOCPOLICY_NO_OC:
893 break;
894 default:
895 /** @todo Update GMM->cOverCommittedPages */
896 break;
897 }
898 }
899 }
900
901 /* zap the GVM data. */
902 pGVM->gmm.s.enmPolicy = GMMOCPOLICY_INVALID;
903 pGVM->gmm.s.enmPriority = GMMPRIORITY_INVALID;
904 pGVM->gmm.s.fMayAllocate = false;
905
906 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
907 RTSemFastMutexRelease(pGMM->Mtx);
908
909 LogFlow(("GMMR0CleanupVM: returns\n"));
910}
911
912
913/**
914 * RTAvlU32DoWithAll callback.
915 *
916 * @returns 0
917 * @param pNode The node to search.
918 * @param pvGVM Pointer to the shared VM structure.
919 */
920static DECLCALLBACK(int) gmmR0CleanupVMScanChunk(PAVLU32NODECORE pNode, void *pvGVM)
921{
922 PGMMCHUNK pChunk = (PGMMCHUNK)pNode;
923 PGVM pGVM = (PGVM)pvGVM;
924
925 /*
926 * Look for pages belonging to the VM.
927 * (Perform some internal checks while we're scanning.)
928 */
929#ifndef VBOX_STRICT
930 if (pChunk->cFree != (GMM_CHUNK_SIZE >> PAGE_SHIFT))
931#endif
932 {
933 unsigned cPrivate = 0;
934 unsigned cShared = 0;
935 unsigned cFree = 0;
936
937 gmmR0UnlinkChunk(pChunk); /* avoiding cFreePages updates. */
938
939 uint16_t hGVM = pGVM->hSelf;
940 unsigned iPage = (GMM_CHUNK_SIZE >> PAGE_SHIFT);
941 while (iPage-- > 0)
942 if (GMM_PAGE_IS_PRIVATE(&pChunk->aPages[iPage]))
943 {
944 if (pChunk->aPages[iPage].Private.hGVM == hGVM)
945 {
946 /*
947 * Free the page.
948 *
949 * The reason for not using gmmR0FreePrivatePage here is that we
950 * must *not* cause the chunk to be freed from under us - we're in
951 * an AVL tree walk here.
952 */
953 pChunk->aPages[iPage].u = 0;
954 pChunk->aPages[iPage].Free.iNext = pChunk->iFreeHead;
955 pChunk->aPages[iPage].Free.u2State = GMM_PAGE_STATE_FREE;
956 pChunk->iFreeHead = iPage;
957 pChunk->cPrivate--;
958 pChunk->cFree++;
959 pGVM->gmm.s.cPrivatePages--;
960 cFree++;
961 }
962 else
963 cPrivate++;
964 }
965 else if (GMM_PAGE_IS_FREE(&pChunk->aPages[iPage]))
966 cFree++;
967 else
968 cShared++;
969
970 gmmR0LinkChunk(pChunk, pChunk->cShared ? &g_pGMM->Shared : &g_pGMM->Private);
971
972 /*
973 * Did it add up?
974 */
975 if (RT_UNLIKELY( pChunk->cFree != cFree
976 || pChunk->cPrivate != cPrivate
977 || pChunk->cShared != cShared))
978 {
979 SUPR0Printf("gmmR0CleanupVMScanChunk: Chunk %p/%#x has bogus stats - free=%d/%d private=%d/%d shared=%d/%d\n",
980 pChunk->cFree, cFree, pChunk->cPrivate, cPrivate, pChunk->cShared, cShared);
981 pChunk->cFree = cFree;
982 pChunk->cPrivate = cPrivate;
983 pChunk->cShared = cShared;
984 }
985 }
986
987 /*
988 * Look for the mapping belonging to the terminating VM.
989 */
990 for (unsigned i = 0; i < pChunk->cMappings; i++)
991 if (pChunk->paMappings[i].pGVM == pGVM)
992 {
993 RTR0MEMOBJ MemObj = pChunk->paMappings[i].MapObj;
994
995 pChunk->cMappings--;
996 if (i < pChunk->cMappings)
997 pChunk->paMappings[i] = pChunk->paMappings[pChunk->cMappings];
998 pChunk->paMappings[pChunk->cMappings].pGVM = NULL;
999 pChunk->paMappings[pChunk->cMappings].MapObj = NIL_RTR0MEMOBJ;
1000
1001 int rc = RTR0MemObjFree(MemObj, false /* fFreeMappings (NA) */);
1002 if (RT_FAILURE(rc))
1003 {
1004 SUPR0Printf("gmmR0CleanupVMScanChunk: %p/%#x: mapping #%x: RTRMemObjFree(%p,false) -> %d \n",
1005 pChunk, pChunk->Core.Key, i, MemObj, rc);
1006 AssertRC(rc);
1007 }
1008 break;
1009 }
1010
1011 /*
1012 * If not in bound memory mode, we should reset the hGVM field
1013 * if it has our handle in it.
1014 */
1015 if (pChunk->hGVM == pGVM->hSelf)
1016 {
1017 if (!g_pGMM->fBoundMemoryMode)
1018 pChunk->hGVM = NIL_GVM_HANDLE;
1019 else if (pChunk->cFree != GMM_CHUNK_NUM_PAGES)
1020 {
1021 SUPR0Printf("gmmR0CleanupVMScanChunk: %p/%#x: cFree=%#x - it should be 0 in bound mode!\n",
1022 pChunk, pChunk->Core.Key, pChunk->cFree);
1023 AssertMsgFailed(("%p/%#x: cFree=%#x - it should be 0 in bound mode!\n", pChunk, pChunk->Core.Key, pChunk->cFree));
1024
1025 gmmR0UnlinkChunk(pChunk);
1026 pChunk->cFree = GMM_CHUNK_NUM_PAGES;
1027 gmmR0LinkChunk(pChunk, pChunk->cShared ? &g_pGMM->Shared : &g_pGMM->Private);
1028 }
1029 }
1030
1031 return 0;
1032}
1033
1034
1035/**
1036 * RTAvlU32Destroy callback for GMMR0CleanupVM.
1037 *
1038 * @returns 0
1039 * @param pNode The node (allocation chunk) to destroy.
1040 * @param pvGVM Pointer to the shared VM structure.
1041 */
1042/*static*/ DECLCALLBACK(int) gmmR0CleanupVMDestroyChunk(PAVLU32NODECORE pNode, void *pvGVM)
1043{
1044 PGMMCHUNK pChunk = (PGMMCHUNK)pNode;
1045 PGVM pGVM = (PGVM)pvGVM;
1046
1047 for (unsigned i = 0; i < pChunk->cMappings; i++)
1048 {
1049 if (pChunk->paMappings[i].pGVM != pGVM)
1050 SUPR0Printf("gmmR0CleanupVMDestroyChunk: %p/%#x: mapping #%x: pGVM=%p exepcted %p\n", pChunk,
1051 pChunk->Core.Key, i, pChunk->paMappings[i].pGVM, pGVM);
1052 int rc = RTR0MemObjFree(pChunk->paMappings[i].MapObj, false /* fFreeMappings (NA) */);
1053 if (RT_FAILURE(rc))
1054 {
1055 SUPR0Printf("gmmR0CleanupVMDestroyChunk: %p/%#x: mapping #%x: RTRMemObjFree(%p,false) -> %d \n", pChunk,
1056 pChunk->Core.Key, i, pChunk->paMappings[i].MapObj, rc);
1057 AssertRC(rc);
1058 }
1059 }
1060
1061 int rc = RTR0MemObjFree(pChunk->MemObj, true /* fFreeMappings */);
1062 if (RT_FAILURE(rc))
1063 {
1064 SUPR0Printf("gmmR0CleanupVMDestroyChunk: %p/%#x: RTRMemObjFree(%p,true) -> %d (cMappings=%d)\n", pChunk,
1065 pChunk->Core.Key, pChunk->MemObj, rc, pChunk->cMappings);
1066 AssertRC(rc);
1067 }
1068 pChunk->MemObj = NIL_RTR0MEMOBJ;
1069
1070 RTMemFree(pChunk->paMappings);
1071 pChunk->paMappings = NULL;
1072
1073 RTMemFree(pChunk);
1074 return 0;
1075}
1076
1077
1078/**
1079 * The initial resource reservations.
1080 *
1081 * This will make memory reservations according to policy and priority. If there aren't
1082 * sufficient resources available to sustain the VM this function will fail and all
1083 * future allocations requests will fail as well.
1084 *
1085 * These are just the initial reservations made very very early during the VM creation
1086 * process and will be adjusted later in the GMMR0UpdateReservation call after the
1087 * ring-3 init has completed.
1088 *
1089 * @returns VBox status code.
1090 * @retval VERR_GMM_MEMORY_RESERVATION_DECLINED
1091 * @retval VERR_GMM_
1092 *
1093 * @param pVM Pointer to the shared VM structure.
1094 * @param idCpu VCPU id
1095 * @param cBasePages The number of pages that may be allocated for the base RAM and ROMs.
1096 * This does not include MMIO2 and similar.
1097 * @param cShadowPages The number of pages that may be allocated for shadow pageing structures.
1098 * @param cFixedPages The number of pages that may be allocated for fixed objects like the
1099 * hyper heap, MMIO2 and similar.
1100 * @param enmPolicy The OC policy to use on this VM.
1101 * @param enmPriority The priority in an out-of-memory situation.
1102 *
1103 * @thread The creator thread / EMT.
1104 */
1105GMMR0DECL(int) GMMR0InitialReservation(PVM pVM, VMCPUID idCpu, uint64_t cBasePages, uint32_t cShadowPages, uint32_t cFixedPages,
1106 GMMOCPOLICY enmPolicy, GMMPRIORITY enmPriority)
1107{
1108 LogFlow(("GMMR0InitialReservation: pVM=%p cBasePages=%#llx cShadowPages=%#x cFixedPages=%#x enmPolicy=%d enmPriority=%d\n",
1109 pVM, cBasePages, cShadowPages, cFixedPages, enmPolicy, enmPriority));
1110
1111 /*
1112 * Validate, get basics and take the semaphore.
1113 */
1114 PGMM pGMM;
1115 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
1116 PGVM pGVM;
1117 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
1118 if (RT_FAILURE(rc))
1119 return rc;
1120
1121 AssertReturn(cBasePages, VERR_INVALID_PARAMETER);
1122 AssertReturn(cShadowPages, VERR_INVALID_PARAMETER);
1123 AssertReturn(cFixedPages, VERR_INVALID_PARAMETER);
1124 AssertReturn(enmPolicy > GMMOCPOLICY_INVALID && enmPolicy < GMMOCPOLICY_END, VERR_INVALID_PARAMETER);
1125 AssertReturn(enmPriority > GMMPRIORITY_INVALID && enmPriority < GMMPRIORITY_END, VERR_INVALID_PARAMETER);
1126
1127 rc = RTSemFastMutexRequest(pGMM->Mtx);
1128 AssertRC(rc);
1129 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
1130 {
1131 if ( !pGVM->gmm.s.Reserved.cBasePages
1132 && !pGVM->gmm.s.Reserved.cFixedPages
1133 && !pGVM->gmm.s.Reserved.cShadowPages)
1134 {
1135 /*
1136 * Check if we can accomodate this.
1137 */
1138 /* ... later ... */
1139 if (RT_SUCCESS(rc))
1140 {
1141 /*
1142 * Update the records.
1143 */
1144 pGVM->gmm.s.Reserved.cBasePages = cBasePages;
1145 pGVM->gmm.s.Reserved.cFixedPages = cFixedPages;
1146 pGVM->gmm.s.Reserved.cShadowPages = cShadowPages;
1147 pGVM->gmm.s.enmPolicy = enmPolicy;
1148 pGVM->gmm.s.enmPriority = enmPriority;
1149 pGVM->gmm.s.fMayAllocate = true;
1150
1151 pGMM->cReservedPages += cBasePages + cFixedPages + cShadowPages;
1152 pGMM->cRegisteredVMs++;
1153 }
1154 }
1155 else
1156 rc = VERR_WRONG_ORDER;
1157 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
1158 }
1159 else
1160 rc = VERR_INTERNAL_ERROR_5;
1161 RTSemFastMutexRelease(pGMM->Mtx);
1162 LogFlow(("GMMR0InitialReservation: returns %Rrc\n", rc));
1163 return rc;
1164}
1165
1166
1167/**
1168 * VMMR0 request wrapper for GMMR0InitialReservation.
1169 *
1170 * @returns see GMMR0InitialReservation.
1171 * @param pVM Pointer to the shared VM structure.
1172 * @param idCpu VCPU id
1173 * @param pReq The request packet.
1174 */
1175GMMR0DECL(int) GMMR0InitialReservationReq(PVM pVM, VMCPUID idCpu, PGMMINITIALRESERVATIONREQ pReq)
1176{
1177 /*
1178 * Validate input and pass it on.
1179 */
1180 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1181 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1182 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
1183
1184 return GMMR0InitialReservation(pVM, idCpu, pReq->cBasePages, pReq->cShadowPages, pReq->cFixedPages, pReq->enmPolicy, pReq->enmPriority);
1185}
1186
1187
1188/**
1189 * This updates the memory reservation with the additional MMIO2 and ROM pages.
1190 *
1191 * @returns VBox status code.
1192 * @retval VERR_GMM_MEMORY_RESERVATION_DECLINED
1193 *
1194 * @param pVM Pointer to the shared VM structure.
1195 * @param idCpu VCPU id
1196 * @param cBasePages The number of pages that may be allocated for the base RAM and ROMs.
1197 * This does not include MMIO2 and similar.
1198 * @param cShadowPages The number of pages that may be allocated for shadow pageing structures.
1199 * @param cFixedPages The number of pages that may be allocated for fixed objects like the
1200 * hyper heap, MMIO2 and similar.
1201 *
1202 * @thread EMT.
1203 */
1204GMMR0DECL(int) GMMR0UpdateReservation(PVM pVM, VMCPUID idCpu, uint64_t cBasePages, uint32_t cShadowPages, uint32_t cFixedPages)
1205{
1206 LogFlow(("GMMR0UpdateReservation: pVM=%p cBasePages=%#llx cShadowPages=%#x cFixedPages=%#x\n",
1207 pVM, cBasePages, cShadowPages, cFixedPages));
1208
1209 /*
1210 * Validate, get basics and take the semaphore.
1211 */
1212 PGMM pGMM;
1213 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
1214 PGVM pGVM;
1215 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
1216 if (RT_FAILURE(rc))
1217 return rc;
1218
1219 AssertReturn(cBasePages, VERR_INVALID_PARAMETER);
1220 AssertReturn(cShadowPages, VERR_INVALID_PARAMETER);
1221 AssertReturn(cFixedPages, VERR_INVALID_PARAMETER);
1222
1223 rc = RTSemFastMutexRequest(pGMM->Mtx);
1224 AssertRC(rc);
1225 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
1226 {
1227 if ( pGVM->gmm.s.Reserved.cBasePages
1228 && pGVM->gmm.s.Reserved.cFixedPages
1229 && pGVM->gmm.s.Reserved.cShadowPages)
1230 {
1231 /*
1232 * Check if we can accomodate this.
1233 */
1234 /* ... later ... */
1235 if (RT_SUCCESS(rc))
1236 {
1237 /*
1238 * Update the records.
1239 */
1240 pGMM->cReservedPages -= pGVM->gmm.s.Reserved.cBasePages
1241 + pGVM->gmm.s.Reserved.cFixedPages
1242 + pGVM->gmm.s.Reserved.cShadowPages;
1243 pGMM->cReservedPages += cBasePages + cFixedPages + cShadowPages;
1244
1245 pGVM->gmm.s.Reserved.cBasePages = cBasePages;
1246 pGVM->gmm.s.Reserved.cFixedPages = cFixedPages;
1247 pGVM->gmm.s.Reserved.cShadowPages = cShadowPages;
1248 }
1249 }
1250 else
1251 rc = VERR_WRONG_ORDER;
1252 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
1253 }
1254 else
1255 rc = VERR_INTERNAL_ERROR_5;
1256 RTSemFastMutexRelease(pGMM->Mtx);
1257 LogFlow(("GMMR0UpdateReservation: returns %Rrc\n", rc));
1258 return rc;
1259}
1260
1261
1262/**
1263 * VMMR0 request wrapper for GMMR0UpdateReservation.
1264 *
1265 * @returns see GMMR0UpdateReservation.
1266 * @param pVM Pointer to the shared VM structure.
1267 * @param idCpu VCPU id
1268 * @param pReq The request packet.
1269 */
1270GMMR0DECL(int) GMMR0UpdateReservationReq(PVM pVM, VMCPUID idCpu, PGMMUPDATERESERVATIONREQ pReq)
1271{
1272 /*
1273 * Validate input and pass it on.
1274 */
1275 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1276 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1277 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
1278
1279 return GMMR0UpdateReservation(pVM, idCpu, pReq->cBasePages, pReq->cShadowPages, pReq->cFixedPages);
1280}
1281
1282
1283/**
1284 * Performs sanity checks on a free set.
1285 *
1286 * @returns Error count.
1287 *
1288 * @param pGMM Pointer to the GMM instance.
1289 * @param pSet Pointer to the set.
1290 * @param pszSetName The set name.
1291 * @param pszFunction The function from which it was called.
1292 * @param uLine The line number.
1293 */
1294static uint32_t gmmR0SanityCheckSet(PGMM pGMM, PGMMCHUNKFREESET pSet, const char *pszSetName,
1295 const char *pszFunction, unsigned uLineNo)
1296{
1297 uint32_t cErrors = 0;
1298
1299 /*
1300 * Count the free pages in all the chunks and match it against pSet->cFreePages.
1301 */
1302 uint32_t cPages = 0;
1303 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists); i++)
1304 {
1305 for (PGMMCHUNK pCur = pSet->apLists[i]; pCur; pCur = pCur->pFreeNext)
1306 {
1307 /** @todo check that the chunk is hash into the right set. */
1308 cPages += pCur->cFree;
1309 }
1310 }
1311 if (RT_UNLIKELY(cPages != pSet->cFreePages))
1312 {
1313 SUPR0Printf("GMM insanity: found %#x pages in the %s set, expected %#x. (%s, line %u)\n",
1314 cPages, pszSetName, pSet->cFreePages, pszFunction, uLineNo);
1315 cErrors++;
1316 }
1317
1318 return cErrors;
1319}
1320
1321
1322/**
1323 * Performs some sanity checks on the GMM while owning lock.
1324 *
1325 * @returns Error count.
1326 *
1327 * @param pGMM Pointer to the GMM instance.
1328 * @param pszFunction The function from which it is called.
1329 * @param uLineNo The line number.
1330 */
1331static uint32_t gmmR0SanityCheck(PGMM pGMM, const char *pszFunction, unsigned uLineNo)
1332{
1333 uint32_t cErrors = 0;
1334
1335 cErrors += gmmR0SanityCheckSet(pGMM, &pGMM->Private, "private", pszFunction, uLineNo);
1336 cErrors += gmmR0SanityCheckSet(pGMM, &pGMM->Shared, "shared", pszFunction, uLineNo);
1337 /** @todo add more sanity checks. */
1338
1339 return cErrors;
1340}
1341
1342
1343/**
1344 * Looks up a chunk in the tree and fill in the TLB entry for it.
1345 *
1346 * This is not expected to fail and will bitch if it does.
1347 *
1348 * @returns Pointer to the allocation chunk, NULL if not found.
1349 * @param pGMM Pointer to the GMM instance.
1350 * @param idChunk The ID of the chunk to find.
1351 * @param pTlbe Pointer to the TLB entry.
1352 */
1353static PGMMCHUNK gmmR0GetChunkSlow(PGMM pGMM, uint32_t idChunk, PGMMCHUNKTLBE pTlbe)
1354{
1355 PGMMCHUNK pChunk = (PGMMCHUNK)RTAvlU32Get(&pGMM->pChunks, idChunk);
1356 AssertMsgReturn(pChunk, ("Chunk %#x not found!\n", idChunk), NULL);
1357 pTlbe->idChunk = idChunk;
1358 pTlbe->pChunk = pChunk;
1359 return pChunk;
1360}
1361
1362
1363/**
1364 * Finds a allocation chunk.
1365 *
1366 * This is not expected to fail and will bitch if it does.
1367 *
1368 * @returns Pointer to the allocation chunk, NULL if not found.
1369 * @param pGMM Pointer to the GMM instance.
1370 * @param idChunk The ID of the chunk to find.
1371 */
1372DECLINLINE(PGMMCHUNK) gmmR0GetChunk(PGMM pGMM, uint32_t idChunk)
1373{
1374 /*
1375 * Do a TLB lookup, branch if not in the TLB.
1376 */
1377 PGMMCHUNKTLBE pTlbe = &pGMM->ChunkTLB.aEntries[GMM_CHUNKTLB_IDX(idChunk)];
1378 if ( pTlbe->idChunk != idChunk
1379 || !pTlbe->pChunk)
1380 return gmmR0GetChunkSlow(pGMM, idChunk, pTlbe);
1381 return pTlbe->pChunk;
1382}
1383
1384
1385/**
1386 * Finds a page.
1387 *
1388 * This is not expected to fail and will bitch if it does.
1389 *
1390 * @returns Pointer to the page, NULL if not found.
1391 * @param pGMM Pointer to the GMM instance.
1392 * @param idPage The ID of the page to find.
1393 */
1394DECLINLINE(PGMMPAGE) gmmR0GetPage(PGMM pGMM, uint32_t idPage)
1395{
1396 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
1397 if (RT_LIKELY(pChunk))
1398 return &pChunk->aPages[idPage & GMM_PAGEID_IDX_MASK];
1399 return NULL;
1400}
1401
1402
1403/**
1404 * Unlinks the chunk from the free list it's currently on (if any).
1405 *
1406 * @param pChunk The allocation chunk.
1407 */
1408DECLINLINE(void) gmmR0UnlinkChunk(PGMMCHUNK pChunk)
1409{
1410 PGMMCHUNKFREESET pSet = pChunk->pSet;
1411 if (RT_LIKELY(pSet))
1412 {
1413 pSet->cFreePages -= pChunk->cFree;
1414
1415 PGMMCHUNK pPrev = pChunk->pFreePrev;
1416 PGMMCHUNK pNext = pChunk->pFreeNext;
1417 if (pPrev)
1418 pPrev->pFreeNext = pNext;
1419 else
1420 pSet->apLists[(pChunk->cFree - 1) >> GMM_CHUNK_FREE_SET_SHIFT] = pNext;
1421 if (pNext)
1422 pNext->pFreePrev = pPrev;
1423
1424 pChunk->pSet = NULL;
1425 pChunk->pFreeNext = NULL;
1426 pChunk->pFreePrev = NULL;
1427 }
1428 else
1429 {
1430 Assert(!pChunk->pFreeNext);
1431 Assert(!pChunk->pFreePrev);
1432 Assert(!pChunk->cFree);
1433 }
1434}
1435
1436
1437/**
1438 * Links the chunk onto the appropriate free list in the specified free set.
1439 *
1440 * If no free entries, it's not linked into any list.
1441 *
1442 * @param pChunk The allocation chunk.
1443 * @param pSet The free set.
1444 */
1445DECLINLINE(void) gmmR0LinkChunk(PGMMCHUNK pChunk, PGMMCHUNKFREESET pSet)
1446{
1447 Assert(!pChunk->pSet);
1448 Assert(!pChunk->pFreeNext);
1449 Assert(!pChunk->pFreePrev);
1450
1451 if (pChunk->cFree > 0)
1452 {
1453 pChunk->pSet = pSet;
1454 pChunk->pFreePrev = NULL;
1455 unsigned iList = (pChunk->cFree - 1) >> GMM_CHUNK_FREE_SET_SHIFT;
1456 pChunk->pFreeNext = pSet->apLists[iList];
1457 if (pChunk->pFreeNext)
1458 pChunk->pFreeNext->pFreePrev = pChunk;
1459 pSet->apLists[iList] = pChunk;
1460
1461 pSet->cFreePages += pChunk->cFree;
1462 }
1463}
1464
1465
1466/**
1467 * Frees a Chunk ID.
1468 *
1469 * @param pGMM Pointer to the GMM instance.
1470 * @param idChunk The Chunk ID to free.
1471 */
1472static void gmmR0FreeChunkId(PGMM pGMM, uint32_t idChunk)
1473{
1474 AssertReturnVoid(idChunk != NIL_GMM_CHUNKID);
1475 AssertMsg(ASMBitTest(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk));
1476 ASMAtomicBitClear(&pGMM->bmChunkId[0], idChunk);
1477}
1478
1479
1480/**
1481 * Allocates a new Chunk ID.
1482 *
1483 * @returns The Chunk ID.
1484 * @param pGMM Pointer to the GMM instance.
1485 */
1486static uint32_t gmmR0AllocateChunkId(PGMM pGMM)
1487{
1488 AssertCompile(!((GMM_CHUNKID_LAST + 1) & 31)); /* must be a multiple of 32 */
1489 AssertCompile(NIL_GMM_CHUNKID == 0);
1490
1491 /*
1492 * Try the next sequential one.
1493 */
1494 int32_t idChunk = ++pGMM->idChunkPrev;
1495#if 0 /* test the fallback first */
1496 if ( idChunk <= GMM_CHUNKID_LAST
1497 && idChunk > NIL_GMM_CHUNKID
1498 && !ASMAtomicBitTestAndSet(&pVMM->bmChunkId[0], idChunk))
1499 return idChunk;
1500#endif
1501
1502 /*
1503 * Scan sequentially from the last one.
1504 */
1505 if ( (uint32_t)idChunk < GMM_CHUNKID_LAST
1506 && idChunk > NIL_GMM_CHUNKID)
1507 {
1508 idChunk = ASMBitNextClear(&pGMM->bmChunkId[0], GMM_CHUNKID_LAST + 1, idChunk);
1509 if (idChunk > NIL_GMM_CHUNKID)
1510 {
1511 AssertMsgReturn(!ASMAtomicBitTestAndSet(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk), NIL_GMM_CHUNKID);
1512 return pGMM->idChunkPrev = idChunk;
1513 }
1514 }
1515
1516 /*
1517 * Ok, scan from the start.
1518 * We're not racing anyone, so there is no need to expect failures or have restart loops.
1519 */
1520 idChunk = ASMBitFirstClear(&pGMM->bmChunkId[0], GMM_CHUNKID_LAST + 1);
1521 AssertMsgReturn(idChunk > NIL_GMM_CHUNKID, ("%#x\n", idChunk), NIL_GVM_HANDLE);
1522 AssertMsgReturn(!ASMAtomicBitTestAndSet(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk), NIL_GMM_CHUNKID);
1523
1524 return pGMM->idChunkPrev = idChunk;
1525}
1526
1527
1528/**
1529 * Registers a new chunk of memory.
1530 *
1531 * This is called by both gmmR0AllocateOneChunk and GMMR0SeedChunk. The caller
1532 * must own the global lock.
1533 *
1534 * @returns VBox status code.
1535 * @param pGMM Pointer to the GMM instance.
1536 * @param pSet Pointer to the set.
1537 * @param MemObj The memory object for the chunk.
1538 * @param hGVM The affinity of the chunk. NIL_GVM_HANDLE for no
1539 * affinity.
1540 * @param enmChunkType Chunk type (continuous or non-continuous)
1541 * @param ppChunk Chunk address (out)
1542 */
1543static int gmmR0RegisterChunk(PGMM pGMM, PGMMCHUNKFREESET pSet, RTR0MEMOBJ MemObj, uint16_t hGVM, GMMCHUNKTYPE enmChunkType, PGMMCHUNK *ppChunk = NULL)
1544{
1545 Assert(hGVM != NIL_GVM_HANDLE || pGMM->fBoundMemoryMode);
1546
1547 int rc;
1548 PGMMCHUNK pChunk = (PGMMCHUNK)RTMemAllocZ(sizeof(*pChunk));
1549 if (pChunk)
1550 {
1551 /*
1552 * Initialize it.
1553 */
1554 pChunk->MemObj = MemObj;
1555 pChunk->cFree = GMM_CHUNK_NUM_PAGES;
1556 pChunk->hGVM = hGVM;
1557 pChunk->iFreeHead = 0;
1558 pChunk->enmType = enmChunkType;
1559 for (unsigned iPage = 0; iPage < RT_ELEMENTS(pChunk->aPages) - 1; iPage++)
1560 {
1561 pChunk->aPages[iPage].Free.u2State = GMM_PAGE_STATE_FREE;
1562 pChunk->aPages[iPage].Free.iNext = iPage + 1;
1563 }
1564 pChunk->aPages[RT_ELEMENTS(pChunk->aPages) - 1].Free.u2State = GMM_PAGE_STATE_FREE;
1565 pChunk->aPages[RT_ELEMENTS(pChunk->aPages) - 1].Free.iNext = UINT16_MAX;
1566
1567 /*
1568 * Allocate a Chunk ID and insert it into the tree.
1569 * This has to be done behind the mutex of course.
1570 */
1571 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
1572 {
1573 pChunk->Core.Key = gmmR0AllocateChunkId(pGMM);
1574 if ( pChunk->Core.Key != NIL_GMM_CHUNKID
1575 && pChunk->Core.Key <= GMM_CHUNKID_LAST
1576 && RTAvlU32Insert(&pGMM->pChunks, &pChunk->Core))
1577 {
1578 pGMM->cChunks++;
1579 gmmR0LinkChunk(pChunk, pSet);
1580 LogFlow(("gmmR0RegisterChunk: pChunk=%p id=%#x cChunks=%d\n", pChunk, pChunk->Core.Key, pGMM->cChunks));
1581
1582 if (ppChunk)
1583 *ppChunk = pChunk;
1584
1585 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
1586 return VINF_SUCCESS;
1587 }
1588
1589 /* bail out */
1590 rc = VERR_INTERNAL_ERROR;
1591 }
1592 else
1593 rc = VERR_INTERNAL_ERROR_5;
1594
1595 RTMemFree(pChunk);
1596 }
1597 else
1598 rc = VERR_NO_MEMORY;
1599 return rc;
1600}
1601
1602
1603/**
1604 * Allocate one new chunk and add it to the specified free set.
1605 *
1606 * @returns VBox status code.
1607 * @param pGMM Pointer to the GMM instance.
1608 * @param pSet Pointer to the set.
1609 * @param hGVM The affinity of the new chunk.
1610 * @param enmChunkType Chunk type (continuous or non-continuous)
1611 * @param ppChunk Chunk address (out)
1612 *
1613 * @remarks Called without owning the mutex.
1614 */
1615static int gmmR0AllocateOneChunk(PGMM pGMM, PGMMCHUNKFREESET pSet, uint16_t hGVM, GMMCHUNKTYPE enmChunkType, PGMMCHUNK *ppChunk = NULL)
1616{
1617 /*
1618 * Allocate the memory.
1619 */
1620 RTR0MEMOBJ MemObj;
1621 int rc;
1622
1623 AssertCompile(GMM_CHUNK_SIZE == _2M);
1624 AssertReturn(enmChunkType == GMMCHUNKTYPE_NON_CONTINUOUS || enmChunkType == GMMCHUNKTYPE_CONTINUOUS, VERR_INVALID_PARAMETER);
1625
1626 /* Leave the lock temporarily as the allocation might take long. */
1627 RTSemFastMutexRelease(pGMM->Mtx);
1628 if (enmChunkType == GMMCHUNKTYPE_NON_CONTINUOUS)
1629 rc = RTR0MemObjAllocPhysNC(&MemObj, GMM_CHUNK_SIZE, NIL_RTHCPHYS);
1630 else
1631 rc = RTR0MemObjAllocPhysEx(&MemObj, GMM_CHUNK_SIZE, NIL_RTHCPHYS, GMM_CHUNK_SIZE);
1632
1633 /* Grab the lock again. */
1634 int rc2 = RTSemFastMutexRequest(pGMM->Mtx);
1635 AssertRCReturn(rc2, rc2);
1636
1637 if (RT_SUCCESS(rc))
1638 {
1639 rc = gmmR0RegisterChunk(pGMM, pSet, MemObj, hGVM, enmChunkType, ppChunk);
1640 if (RT_FAILURE(rc))
1641 RTR0MemObjFree(MemObj, false /* fFreeMappings */);
1642 }
1643 /** @todo Check that RTR0MemObjAllocPhysNC always returns VERR_NO_MEMORY on
1644 * allocation failure. */
1645 return rc;
1646}
1647
1648
1649/**
1650 * Attempts to allocate more pages until the requested amount is met.
1651 *
1652 * @returns VBox status code.
1653 * @param pGMM Pointer to the GMM instance data.
1654 * @param pGVM The calling VM.
1655 * @param pSet Pointer to the free set to grow.
1656 * @param cPages The number of pages needed.
1657 *
1658 * @remarks Called owning the mutex, but will leave it temporarily while
1659 * allocating the memory!
1660 */
1661static int gmmR0AllocateMoreChunks(PGMM pGMM, PGVM pGVM, PGMMCHUNKFREESET pSet, uint32_t cPages)
1662{
1663 Assert(!pGMM->fLegacyAllocationMode);
1664
1665 if (!GMM_CHECK_SANITY_IN_LOOPS(pGMM))
1666 return VERR_INTERNAL_ERROR_4;
1667
1668 if (!pGMM->fBoundMemoryMode)
1669 {
1670 /*
1671 * Try steal free chunks from the other set first. (Only take 100% free chunks.)
1672 */
1673 PGMMCHUNKFREESET pOtherSet = pSet == &pGMM->Private ? &pGMM->Shared : &pGMM->Private;
1674 while ( pSet->cFreePages < cPages
1675 && pOtherSet->cFreePages >= GMM_CHUNK_NUM_PAGES)
1676 {
1677 PGMMCHUNK pChunk = pOtherSet->apLists[GMM_CHUNK_FREE_SET_LISTS - 1];
1678 while (pChunk && pChunk->cFree != GMM_CHUNK_NUM_PAGES)
1679 pChunk = pChunk->pFreeNext;
1680 if (!pChunk)
1681 break;
1682
1683 gmmR0UnlinkChunk(pChunk);
1684 gmmR0LinkChunk(pChunk, pSet);
1685 }
1686
1687 /*
1688 * If we need still more pages, allocate new chunks.
1689 * Note! We will leave the mutex while doing the allocation,
1690 */
1691 while (pSet->cFreePages < cPages)
1692 {
1693 int rc = gmmR0AllocateOneChunk(pGMM, pSet, pGVM->hSelf, GMMCHUNKTYPE_NON_CONTINUOUS);
1694 if (RT_FAILURE(rc))
1695 return rc;
1696 if (!GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
1697 return VERR_INTERNAL_ERROR_5;
1698 }
1699 }
1700 else
1701 {
1702 /*
1703 * The memory is bound to the VM allocating it, so we have to count
1704 * the free pages carefully as well as making sure we brand them with
1705 * our VM handle.
1706 *
1707 * Note! We will leave the mutex while doing the allocation,
1708 */
1709 uint16_t const hGVM = pGVM->hSelf;
1710 for (;;)
1711 {
1712 /* Count and see if we've reached the goal. */
1713 uint32_t cPagesFound = 0;
1714 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists); i++)
1715 for (PGMMCHUNK pCur = pSet->apLists[i]; pCur; pCur = pCur->pFreeNext)
1716 if (pCur->hGVM == hGVM)
1717 {
1718 cPagesFound += pCur->cFree;
1719 if (cPagesFound >= cPages)
1720 break;
1721 }
1722 if (cPagesFound >= cPages)
1723 break;
1724
1725 /* Allocate more. */
1726 int rc = gmmR0AllocateOneChunk(pGMM, pSet, hGVM, GMMCHUNKTYPE_NON_CONTINUOUS);
1727 if (RT_FAILURE(rc))
1728 return rc;
1729 if (!GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
1730 return VERR_INTERNAL_ERROR_5;
1731 }
1732 }
1733
1734 return VINF_SUCCESS;
1735}
1736
1737
1738/**
1739 * Allocates one private page.
1740 *
1741 * Worker for gmmR0AllocatePages.
1742 *
1743 * @param pGMM Pointer to the GMM instance data.
1744 * @param hGVM The GVM handle of the VM requesting memory.
1745 * @param pChunk The chunk to allocate it from.
1746 * @param pPageDesc The page descriptor.
1747 */
1748static void gmmR0AllocatePage(PGMM pGMM, uint32_t hGVM, PGMMCHUNK pChunk, PGMMPAGEDESC pPageDesc)
1749{
1750 /* update the chunk stats. */
1751 if (pChunk->hGVM == NIL_GVM_HANDLE)
1752 pChunk->hGVM = hGVM;
1753 Assert(pChunk->cFree);
1754 pChunk->cFree--;
1755 pChunk->cPrivate++;
1756
1757 /* unlink the first free page. */
1758 const uint32_t iPage = pChunk->iFreeHead;
1759 AssertReleaseMsg(iPage < RT_ELEMENTS(pChunk->aPages), ("%d\n", iPage));
1760 PGMMPAGE pPage = &pChunk->aPages[iPage];
1761 Assert(GMM_PAGE_IS_FREE(pPage));
1762 pChunk->iFreeHead = pPage->Free.iNext;
1763 Log3(("A pPage=%p iPage=%#x/%#x u2State=%d iFreeHead=%#x iNext=%#x\n",
1764 pPage, iPage, (pChunk->Core.Key << GMM_CHUNKID_SHIFT) | iPage,
1765 pPage->Common.u2State, pChunk->iFreeHead, pPage->Free.iNext));
1766
1767 /* make the page private. */
1768 pPage->u = 0;
1769 AssertCompile(GMM_PAGE_STATE_PRIVATE == 0);
1770 pPage->Private.hGVM = hGVM;
1771 AssertCompile(NIL_RTHCPHYS >= GMM_GCPHYS_LAST);
1772 AssertCompile(GMM_GCPHYS_UNSHAREABLE >= GMM_GCPHYS_LAST);
1773 if (pPageDesc->HCPhysGCPhys <= GMM_GCPHYS_LAST)
1774 pPage->Private.pfn = pPageDesc->HCPhysGCPhys >> PAGE_SHIFT;
1775 else
1776 pPage->Private.pfn = GMM_PAGE_PFN_UNSHAREABLE; /* unshareable / unassigned - same thing. */
1777
1778 /* update the page descriptor. */
1779 pPageDesc->HCPhysGCPhys = RTR0MemObjGetPagePhysAddr(pChunk->MemObj, iPage);
1780 Assert(pPageDesc->HCPhysGCPhys != NIL_RTHCPHYS);
1781 pPageDesc->idPage = (pChunk->Core.Key << GMM_CHUNKID_SHIFT) | iPage;
1782 pPageDesc->idSharedPage = NIL_GMM_PAGEID;
1783}
1784
1785
1786/**
1787 * Common worker for GMMR0AllocateHandyPages and GMMR0AllocatePages.
1788 *
1789 * @returns VBox status code:
1790 * @retval VINF_SUCCESS on success.
1791 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk or
1792 * gmmR0AllocateMoreChunks is necessary.
1793 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
1794 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
1795 * that is we're trying to allocate more than we've reserved.
1796 *
1797 * @param pGMM Pointer to the GMM instance data.
1798 * @param pGVM Pointer to the shared VM structure.
1799 * @param cPages The number of pages to allocate.
1800 * @param paPages Pointer to the page descriptors.
1801 * See GMMPAGEDESC for details on what is expected on input.
1802 * @param enmAccount The account to charge.
1803 */
1804static int gmmR0AllocatePages(PGMM pGMM, PGVM pGVM, uint32_t cPages, PGMMPAGEDESC paPages, GMMACCOUNT enmAccount)
1805{
1806 /*
1807 * Check allocation limits.
1808 */
1809 if (RT_UNLIKELY(pGMM->cAllocatedPages + cPages > pGMM->cMaxPages))
1810 return VERR_GMM_HIT_GLOBAL_LIMIT;
1811
1812 switch (enmAccount)
1813 {
1814 case GMMACCOUNT_BASE:
1815 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages + pGVM->gmm.s.cBalloonedPages + cPages > pGVM->gmm.s.Reserved.cBasePages))
1816 {
1817 Log(("gmmR0AllocatePages: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1818 pGVM->gmm.s.Reserved.cBasePages, pGVM->gmm.s.Allocated.cBasePages, cPages));
1819 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1820 }
1821 break;
1822 case GMMACCOUNT_SHADOW:
1823 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cShadowPages + cPages > pGVM->gmm.s.Reserved.cShadowPages))
1824 {
1825 Log(("gmmR0AllocatePages: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1826 pGVM->gmm.s.Reserved.cShadowPages, pGVM->gmm.s.Allocated.cShadowPages, cPages));
1827 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1828 }
1829 break;
1830 case GMMACCOUNT_FIXED:
1831 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cFixedPages + cPages > pGVM->gmm.s.Reserved.cFixedPages))
1832 {
1833 Log(("gmmR0AllocatePages: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1834 pGVM->gmm.s.Reserved.cFixedPages, pGVM->gmm.s.Allocated.cFixedPages, cPages));
1835 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1836 }
1837 break;
1838 default:
1839 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
1840 }
1841
1842 /*
1843 * Check if we need to allocate more memory or not. In bound memory mode this
1844 * is a bit extra work but it's easier to do it upfront than bailing out later.
1845 */
1846 PGMMCHUNKFREESET pSet = &pGMM->Private;
1847 if (pSet->cFreePages < cPages)
1848 return VERR_GMM_SEED_ME;
1849 if (pGMM->fBoundMemoryMode)
1850 {
1851 uint16_t hGVM = pGVM->hSelf;
1852 uint32_t cPagesFound = 0;
1853 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists); i++)
1854 for (PGMMCHUNK pCur = pSet->apLists[i]; pCur; pCur = pCur->pFreeNext)
1855 if (pCur->hGVM == hGVM)
1856 {
1857 cPagesFound += pCur->cFree;
1858 if (cPagesFound >= cPages)
1859 break;
1860 }
1861 if (cPagesFound < cPages)
1862 return VERR_GMM_SEED_ME;
1863 }
1864
1865 /*
1866 * Pick the pages.
1867 * Try make some effort keeping VMs sharing private chunks.
1868 */
1869 uint16_t hGVM = pGVM->hSelf;
1870 uint32_t iPage = 0;
1871
1872 /* first round, pick from chunks with an affinity to the VM. */
1873 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists) && iPage < cPages; i++)
1874 {
1875 PGMMCHUNK pCurFree = NULL;
1876 PGMMCHUNK pCur = pSet->apLists[i];
1877 while (pCur && iPage < cPages)
1878 {
1879 PGMMCHUNK pNext = pCur->pFreeNext;
1880
1881 if ( pCur->hGVM == hGVM
1882 && pCur->cFree < GMM_CHUNK_NUM_PAGES)
1883 {
1884 gmmR0UnlinkChunk(pCur);
1885 for (; pCur->cFree && iPage < cPages; iPage++)
1886 gmmR0AllocatePage(pGMM, hGVM, pCur, &paPages[iPage]);
1887 gmmR0LinkChunk(pCur, pSet);
1888 }
1889
1890 pCur = pNext;
1891 }
1892 }
1893
1894 if (iPage < cPages)
1895 {
1896 /* second round, pick pages from the 100% empty chunks we just skipped above. */
1897 PGMMCHUNK pCurFree = NULL;
1898 PGMMCHUNK pCur = pSet->apLists[RT_ELEMENTS(pSet->apLists) - 1];
1899 while (pCur && iPage < cPages)
1900 {
1901 PGMMCHUNK pNext = pCur->pFreeNext;
1902
1903 if ( pCur->cFree == GMM_CHUNK_NUM_PAGES
1904 && ( pCur->hGVM == hGVM
1905 || !pGMM->fBoundMemoryMode))
1906 {
1907 gmmR0UnlinkChunk(pCur);
1908 for (; pCur->cFree && iPage < cPages; iPage++)
1909 gmmR0AllocatePage(pGMM, hGVM, pCur, &paPages[iPage]);
1910 gmmR0LinkChunk(pCur, pSet);
1911 }
1912
1913 pCur = pNext;
1914 }
1915 }
1916
1917 if ( iPage < cPages
1918 && !pGMM->fBoundMemoryMode)
1919 {
1920 /* third round, disregard affinity. */
1921 unsigned i = RT_ELEMENTS(pSet->apLists);
1922 while (i-- > 0 && iPage < cPages)
1923 {
1924 PGMMCHUNK pCurFree = NULL;
1925 PGMMCHUNK pCur = pSet->apLists[i];
1926 while (pCur && iPage < cPages)
1927 {
1928 PGMMCHUNK pNext = pCur->pFreeNext;
1929
1930 if ( pCur->cFree > GMM_CHUNK_NUM_PAGES / 2
1931 && cPages >= GMM_CHUNK_NUM_PAGES / 2)
1932 pCur->hGVM = hGVM; /* change chunk affinity */
1933
1934 gmmR0UnlinkChunk(pCur);
1935 for (; pCur->cFree && iPage < cPages; iPage++)
1936 gmmR0AllocatePage(pGMM, hGVM, pCur, &paPages[iPage]);
1937 gmmR0LinkChunk(pCur, pSet);
1938
1939 pCur = pNext;
1940 }
1941 }
1942 }
1943
1944 /*
1945 * Update the account.
1946 */
1947 switch (enmAccount)
1948 {
1949 case GMMACCOUNT_BASE: pGVM->gmm.s.Allocated.cBasePages += iPage; break;
1950 case GMMACCOUNT_SHADOW: pGVM->gmm.s.Allocated.cShadowPages += iPage; break;
1951 case GMMACCOUNT_FIXED: pGVM->gmm.s.Allocated.cFixedPages += iPage; break;
1952 default:
1953 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
1954 }
1955 pGVM->gmm.s.cPrivatePages += iPage;
1956 pGMM->cAllocatedPages += iPage;
1957
1958 AssertMsgReturn(iPage == cPages, ("%u != %u\n", iPage, cPages), VERR_INTERNAL_ERROR);
1959
1960 /*
1961 * Check if we've reached some threshold and should kick one or two VMs and tell
1962 * them to inflate their balloons a bit more... later.
1963 */
1964
1965 return VINF_SUCCESS;
1966}
1967
1968
1969/**
1970 * Updates the previous allocations and allocates more pages.
1971 *
1972 * The handy pages are always taken from the 'base' memory account.
1973 * The allocated pages are not cleared and will contains random garbage.
1974 *
1975 * @returns VBox status code:
1976 * @retval VINF_SUCCESS on success.
1977 * @retval VERR_NOT_OWNER if the caller is not an EMT.
1978 * @retval VERR_GMM_PAGE_NOT_FOUND if one of the pages to update wasn't found.
1979 * @retval VERR_GMM_PAGE_NOT_PRIVATE if one of the pages to update wasn't a
1980 * private page.
1981 * @retval VERR_GMM_PAGE_NOT_SHARED if one of the pages to update wasn't a
1982 * shared page.
1983 * @retval VERR_GMM_NOT_PAGE_OWNER if one of the pages to be updated wasn't
1984 * owned by the VM.
1985 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
1986 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
1987 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
1988 * that is we're trying to allocate more than we've reserved.
1989 *
1990 * @param pVM Pointer to the shared VM structure.
1991 * @param idCpu VCPU id
1992 * @param cPagesToUpdate The number of pages to update (starting from the head).
1993 * @param cPagesToAlloc The number of pages to allocate (starting from the head).
1994 * @param paPages The array of page descriptors.
1995 * See GMMPAGEDESC for details on what is expected on input.
1996 * @thread EMT.
1997 */
1998GMMR0DECL(int) GMMR0AllocateHandyPages(PVM pVM, VMCPUID idCpu, uint32_t cPagesToUpdate, uint32_t cPagesToAlloc, PGMMPAGEDESC paPages)
1999{
2000 LogFlow(("GMMR0AllocateHandyPages: pVM=%p cPagesToUpdate=%#x cPagesToAlloc=%#x paPages=%p\n",
2001 pVM, cPagesToUpdate, cPagesToAlloc, paPages));
2002
2003 /*
2004 * Validate, get basics and take the semaphore.
2005 * (This is a relatively busy path, so make predictions where possible.)
2006 */
2007 PGMM pGMM;
2008 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2009 PGVM pGVM;
2010 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2011 if (RT_FAILURE(rc))
2012 return rc;
2013
2014 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2015 AssertMsgReturn( (cPagesToUpdate && cPagesToUpdate < 1024)
2016 || (cPagesToAlloc && cPagesToAlloc < 1024),
2017 ("cPagesToUpdate=%#x cPagesToAlloc=%#x\n", cPagesToUpdate, cPagesToAlloc),
2018 VERR_INVALID_PARAMETER);
2019
2020 unsigned iPage = 0;
2021 for (; iPage < cPagesToUpdate; iPage++)
2022 {
2023 AssertMsgReturn( ( paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST
2024 && !(paPages[iPage].HCPhysGCPhys & PAGE_OFFSET_MASK))
2025 || paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS
2026 || paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE,
2027 ("#%#x: %RHp\n", iPage, paPages[iPage].HCPhysGCPhys),
2028 VERR_INVALID_PARAMETER);
2029 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
2030 /*|| paPages[iPage].idPage == NIL_GMM_PAGEID*/,
2031 ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2032 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
2033 /*|| paPages[iPage].idSharedPage == NIL_GMM_PAGEID*/,
2034 ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
2035 }
2036
2037 for (; iPage < cPagesToAlloc; iPage++)
2038 {
2039 AssertMsgReturn(paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS, ("#%#x: %RHp\n", iPage, paPages[iPage].HCPhysGCPhys), VERR_INVALID_PARAMETER);
2040 AssertMsgReturn(paPages[iPage].idPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2041 AssertMsgReturn(paPages[iPage].idSharedPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
2042 }
2043
2044 rc = RTSemFastMutexRequest(pGMM->Mtx);
2045 AssertRC(rc);
2046 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2047 {
2048
2049 /* No allocations before the initial reservation has been made! */
2050 if (RT_LIKELY( pGVM->gmm.s.Reserved.cBasePages
2051 && pGVM->gmm.s.Reserved.cFixedPages
2052 && pGVM->gmm.s.Reserved.cShadowPages))
2053 {
2054 /*
2055 * Perform the updates.
2056 * Stop on the first error.
2057 */
2058 for (iPage = 0; iPage < cPagesToUpdate; iPage++)
2059 {
2060 if (paPages[iPage].idPage != NIL_GMM_PAGEID)
2061 {
2062 PGMMPAGE pPage = gmmR0GetPage(pGMM, paPages[iPage].idPage);
2063 if (RT_LIKELY(pPage))
2064 {
2065 if (RT_LIKELY(GMM_PAGE_IS_PRIVATE(pPage)))
2066 {
2067 if (RT_LIKELY(pPage->Private.hGVM == pGVM->hSelf))
2068 {
2069 AssertCompile(NIL_RTHCPHYS > GMM_GCPHYS_LAST && GMM_GCPHYS_UNSHAREABLE > GMM_GCPHYS_LAST);
2070 if (RT_LIKELY(paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST))
2071 pPage->Private.pfn = paPages[iPage].HCPhysGCPhys >> PAGE_SHIFT;
2072 else if (paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE)
2073 pPage->Private.pfn = GMM_PAGE_PFN_UNSHAREABLE;
2074 /* else: NIL_RTHCPHYS nothing */
2075
2076 paPages[iPage].idPage = NIL_GMM_PAGEID;
2077 paPages[iPage].HCPhysGCPhys = NIL_RTHCPHYS;
2078 }
2079 else
2080 {
2081 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not owner! hGVM=%#x hSelf=%#x\n",
2082 iPage, paPages[iPage].idPage, pPage->Private.hGVM, pGVM->hSelf));
2083 rc = VERR_GMM_NOT_PAGE_OWNER;
2084 break;
2085 }
2086 }
2087 else
2088 {
2089 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not private! %.*Rhxs\n", iPage, paPages[iPage].idPage, sizeof(*pPage), pPage));
2090 rc = VERR_GMM_PAGE_NOT_PRIVATE;
2091 break;
2092 }
2093 }
2094 else
2095 {
2096 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not found! (private)\n", iPage, paPages[iPage].idPage));
2097 rc = VERR_GMM_PAGE_NOT_FOUND;
2098 break;
2099 }
2100 }
2101
2102 if (paPages[iPage].idSharedPage != NIL_GMM_PAGEID)
2103 {
2104 PGMMPAGE pPage = gmmR0GetPage(pGMM, paPages[iPage].idSharedPage);
2105 if (RT_LIKELY(pPage))
2106 {
2107 if (RT_LIKELY(GMM_PAGE_IS_SHARED(pPage)))
2108 {
2109 AssertCompile(NIL_RTHCPHYS > GMM_GCPHYS_LAST && GMM_GCPHYS_UNSHAREABLE > GMM_GCPHYS_LAST);
2110 Assert(pPage->Shared.cRefs);
2111 Assert(pGVM->gmm.s.cSharedPages);
2112 Assert(pGVM->gmm.s.Allocated.cBasePages);
2113
2114 pGVM->gmm.s.cSharedPages--;
2115 pGVM->gmm.s.Allocated.cBasePages--;
2116 if (!--pPage->Shared.cRefs)
2117 gmmR0FreeSharedPage(pGMM, paPages[iPage].idSharedPage, pPage);
2118
2119 paPages[iPage].idSharedPage = NIL_GMM_PAGEID;
2120 }
2121 else
2122 {
2123 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not shared!\n", iPage, paPages[iPage].idSharedPage));
2124 rc = VERR_GMM_PAGE_NOT_SHARED;
2125 break;
2126 }
2127 }
2128 else
2129 {
2130 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not found! (shared)\n", iPage, paPages[iPage].idSharedPage));
2131 rc = VERR_GMM_PAGE_NOT_FOUND;
2132 break;
2133 }
2134 }
2135 }
2136
2137 /*
2138 * Join paths with GMMR0AllocatePages for the allocation.
2139 * Note! gmmR0AllocateMoreChunks may leave the protection of the mutex!
2140 */
2141 while (RT_SUCCESS(rc))
2142 {
2143 rc = gmmR0AllocatePages(pGMM, pGVM, cPagesToAlloc, paPages, GMMACCOUNT_BASE);
2144 if ( rc != VERR_GMM_SEED_ME
2145 || pGMM->fLegacyAllocationMode)
2146 break;
2147 rc = gmmR0AllocateMoreChunks(pGMM, pGVM, &pGMM->Private, cPagesToAlloc);
2148 }
2149 }
2150 else
2151 rc = VERR_WRONG_ORDER;
2152 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
2153 }
2154 else
2155 rc = VERR_INTERNAL_ERROR_5;
2156 RTSemFastMutexRelease(pGMM->Mtx);
2157 LogFlow(("GMMR0AllocateHandyPages: returns %Rrc\n", rc));
2158 return rc;
2159}
2160
2161
2162/**
2163 * Allocate one or more pages.
2164 *
2165 * This is typically used for ROMs and MMIO2 (VRAM) during VM creation.
2166 * The allocated pages are not cleared and will contains random garbage.
2167 *
2168 * @returns VBox status code:
2169 * @retval VINF_SUCCESS on success.
2170 * @retval VERR_NOT_OWNER if the caller is not an EMT.
2171 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
2172 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
2173 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
2174 * that is we're trying to allocate more than we've reserved.
2175 *
2176 * @param pVM Pointer to the shared VM structure.
2177 * @param idCpu VCPU id
2178 * @param cPages The number of pages to allocate.
2179 * @param paPages Pointer to the page descriptors.
2180 * See GMMPAGEDESC for details on what is expected on input.
2181 * @param enmAccount The account to charge.
2182 *
2183 * @thread EMT.
2184 */
2185GMMR0DECL(int) GMMR0AllocatePages(PVM pVM, VMCPUID idCpu, uint32_t cPages, PGMMPAGEDESC paPages, GMMACCOUNT enmAccount)
2186{
2187 LogFlow(("GMMR0AllocatePages: pVM=%p cPages=%#x paPages=%p enmAccount=%d\n", pVM, cPages, paPages, enmAccount));
2188
2189 /*
2190 * Validate, get basics and take the semaphore.
2191 */
2192 PGMM pGMM;
2193 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2194 PGVM pGVM;
2195 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2196 if (RT_FAILURE(rc))
2197 return rc;
2198
2199 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2200 AssertMsgReturn(enmAccount > GMMACCOUNT_INVALID && enmAccount < GMMACCOUNT_END, ("%d\n", enmAccount), VERR_INVALID_PARAMETER);
2201 AssertMsgReturn(cPages > 0 && cPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cPages), VERR_INVALID_PARAMETER);
2202
2203 for (unsigned iPage = 0; iPage < cPages; iPage++)
2204 {
2205 AssertMsgReturn( paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS
2206 || paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE
2207 || ( enmAccount == GMMACCOUNT_BASE
2208 && paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST
2209 && !(paPages[iPage].HCPhysGCPhys & PAGE_OFFSET_MASK)),
2210 ("#%#x: %RHp enmAccount=%d\n", iPage, paPages[iPage].HCPhysGCPhys, enmAccount),
2211 VERR_INVALID_PARAMETER);
2212 AssertMsgReturn(paPages[iPage].idPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2213 AssertMsgReturn(paPages[iPage].idSharedPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
2214 }
2215
2216 rc = RTSemFastMutexRequest(pGMM->Mtx);
2217 AssertRC(rc);
2218 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2219 {
2220
2221 /* No allocations before the initial reservation has been made! */
2222 if (RT_LIKELY( pGVM->gmm.s.Reserved.cBasePages
2223 && pGVM->gmm.s.Reserved.cFixedPages
2224 && pGVM->gmm.s.Reserved.cShadowPages))
2225 {
2226 /*
2227 * gmmR0AllocatePages seed loop.
2228 * Note! gmmR0AllocateMoreChunks may leave the protection of the mutex!
2229 */
2230 while (RT_SUCCESS(rc))
2231 {
2232 rc = gmmR0AllocatePages(pGMM, pGVM, cPages, paPages, enmAccount);
2233 if ( rc != VERR_GMM_SEED_ME
2234 || pGMM->fLegacyAllocationMode)
2235 break;
2236 rc = gmmR0AllocateMoreChunks(pGMM, pGVM, &pGMM->Private, cPages);
2237 }
2238 }
2239 else
2240 rc = VERR_WRONG_ORDER;
2241 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
2242 }
2243 else
2244 rc = VERR_INTERNAL_ERROR_5;
2245 RTSemFastMutexRelease(pGMM->Mtx);
2246 LogFlow(("GMMR0AllocatePages: returns %Rrc\n", rc));
2247 return rc;
2248}
2249
2250
2251/**
2252 * VMMR0 request wrapper for GMMR0AllocatePages.
2253 *
2254 * @returns see GMMR0AllocatePages.
2255 * @param pVM Pointer to the shared VM structure.
2256 * @param idCpu VCPU id
2257 * @param pReq The request packet.
2258 */
2259GMMR0DECL(int) GMMR0AllocatePagesReq(PVM pVM, VMCPUID idCpu, PGMMALLOCATEPAGESREQ pReq)
2260{
2261 /*
2262 * Validate input and pass it on.
2263 */
2264 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2265 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2266 AssertMsgReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[0]),
2267 ("%#x < %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[0])),
2268 VERR_INVALID_PARAMETER);
2269 AssertMsgReturn(pReq->Hdr.cbReq == RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[pReq->cPages]),
2270 ("%#x != %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[pReq->cPages])),
2271 VERR_INVALID_PARAMETER);
2272
2273 return GMMR0AllocatePages(pVM, idCpu, pReq->cPages, &pReq->aPages[0], pReq->enmAccount);
2274}
2275
2276/**
2277 * Allocate a large page to represent guest RAM
2278 *
2279 * The allocated pages are not cleared and will contains random garbage.
2280 *
2281 * @returns VBox status code:
2282 * @retval VINF_SUCCESS on success.
2283 * @retval VERR_NOT_OWNER if the caller is not an EMT.
2284 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
2285 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
2286 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
2287 * that is we're trying to allocate more than we've reserved.
2288 * @returns see GMMR0AllocatePages.
2289 * @param pVM Pointer to the shared VM structure.
2290 * @param idCpu VCPU id
2291 * @param cbPage Large page size
2292 */
2293GMMR0DECL(int) GMMR0AllocateLargePage(PVM pVM, VMCPUID idCpu, uint32_t cbPage, uint32_t *pIdPage, RTHCPHYS *pHCPhys)
2294{
2295 LogFlow(("GMMR0AllocateLargePage: pVM=%p cbPage=%x\n", pVM, cbPage));
2296
2297 AssertReturn(cbPage == GMM_CHUNK_SIZE, VERR_INVALID_PARAMETER);
2298 AssertPtrReturn(pIdPage, VERR_INVALID_PARAMETER);
2299 AssertPtrReturn(pHCPhys, VERR_INVALID_PARAMETER);
2300
2301 /*
2302 * Validate, get basics and take the semaphore.
2303 */
2304 PGMM pGMM;
2305 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2306 PGVM pGVM;
2307 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2308 if (RT_FAILURE(rc))
2309 return rc;
2310
2311 /* Not supported in legacy mode where we allocate the memory in ring 3 and lock it in ring 0. */
2312 if (pGMM->fLegacyAllocationMode)
2313 return VERR_NOT_SUPPORTED;
2314
2315 *pHCPhys = NIL_RTHCPHYS;
2316 *pIdPage = NIL_GMM_PAGEID;
2317
2318 rc = RTSemFastMutexRequest(pGMM->Mtx);
2319 AssertRCReturn(rc, rc);
2320 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2321 {
2322 const unsigned cPages = (GMM_CHUNK_SIZE >> PAGE_SHIFT);
2323 PGMMCHUNK pChunk;
2324 GMMPAGEDESC PageDesc;
2325
2326 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages + pGVM->gmm.s.cBalloonedPages + cPages > pGVM->gmm.s.Reserved.cBasePages))
2327 {
2328 Log(("GMMR0AllocateLargePage: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
2329 pGVM->gmm.s.Reserved.cBasePages, pGVM->gmm.s.Allocated.cBasePages, cPages));
2330 RTSemFastMutexRelease(pGMM->Mtx);
2331 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
2332 }
2333
2334 /* Allocate a new continous chunk. */
2335 rc = gmmR0AllocateOneChunk(pGMM, &pGMM->Private, pGVM->hSelf, GMMCHUNKTYPE_CONTINUOUS, &pChunk);
2336 if (RT_FAILURE(rc))
2337 {
2338 RTSemFastMutexRelease(pGMM->Mtx);
2339 return rc;
2340 }
2341
2342 /* Unlink the new chunk from the free list. */
2343 gmmR0UnlinkChunk(pChunk);
2344
2345 /* Allocate all pages. */
2346 gmmR0AllocatePage(pGMM, pGVM->hSelf, pChunk, &PageDesc);
2347 /* Return the first page as we'll use the whole chunk as one big page. */
2348 *pIdPage = PageDesc.idPage;
2349 *pHCPhys = PageDesc.HCPhysGCPhys;
2350
2351 for (unsigned i = 1; i < cPages; i++)
2352 gmmR0AllocatePage(pGMM, pGVM->hSelf, pChunk, &PageDesc);
2353
2354 /* Update accounting. */
2355 pGVM->gmm.s.Allocated.cBasePages += cPages;
2356 pGVM->gmm.s.cPrivatePages += cPages;
2357 pGMM->cAllocatedPages += cPages;
2358
2359 gmmR0LinkChunk(pChunk, &pGMM->Private);
2360 }
2361 else
2362 rc = VERR_INTERNAL_ERROR_5;
2363
2364 RTSemFastMutexRelease(pGMM->Mtx);
2365 LogFlow(("GMMR0AllocatePages: returns %Rrc\n", rc));
2366 return rc;
2367}
2368
2369
2370/**
2371 * Free a large page
2372 *
2373 * @returns VBox status code:
2374 * @param pVM Pointer to the shared VM structure.
2375 * @param idCpu VCPU id
2376 * @param idPage Large page id
2377 */
2378GMMR0DECL(int) GMMR0FreeLargePage(PVM pVM, VMCPUID idCpu, uint32_t idPage)
2379{
2380 LogFlow(("GMMR0FreeLargePage: pVM=%p idPage=%x\n", pVM, idPage));
2381
2382 /*
2383 * Validate, get basics and take the semaphore.
2384 */
2385 PGMM pGMM;
2386 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2387 PGVM pGVM;
2388 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2389 if (RT_FAILURE(rc))
2390 return rc;
2391
2392 /* Not supported in legacy mode where we allocate the memory in ring 3 and lock it in ring 0. */
2393 if (pGMM->fLegacyAllocationMode)
2394 return VERR_NOT_SUPPORTED;
2395
2396 rc = RTSemFastMutexRequest(pGMM->Mtx);
2397 AssertRC(rc);
2398 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2399 {
2400 const unsigned cPages = (GMM_CHUNK_SIZE >> PAGE_SHIFT);
2401
2402 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages < cPages))
2403 {
2404 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cBasePages, cPages));
2405 RTSemFastMutexRelease(pGMM->Mtx);
2406 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2407 }
2408
2409 PGMMPAGE pPage = gmmR0GetPage(pGMM, idPage);
2410 if ( RT_LIKELY(pPage)
2411 && RT_LIKELY(GMM_PAGE_IS_PRIVATE(pPage)))
2412 {
2413 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2414 Assert(pChunk);
2415 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2416 Assert(pChunk->cPrivate > 0);
2417
2418 /* Release the memory immediately. */
2419 gmmR0FreeChunk(pGMM, NULL, pChunk);
2420
2421 /* Update accounting. */
2422 pGVM->gmm.s.Allocated.cBasePages -= cPages;
2423 pGVM->gmm.s.cPrivatePages -= cPages;
2424 pGMM->cAllocatedPages -= cPages;
2425 }
2426 else
2427 rc = VERR_GMM_PAGE_NOT_FOUND;
2428 }
2429 else
2430 rc = VERR_INTERNAL_ERROR_5;
2431
2432 RTSemFastMutexRelease(pGMM->Mtx);
2433 LogFlow(("GMMR0FreeLargePage: returns %Rrc\n", rc));
2434 return rc;
2435}
2436
2437
2438/**
2439 * VMMR0 request wrapper for GMMR0FreeLargePage.
2440 *
2441 * @returns see GMMR0FreeLargePage.
2442 * @param pVM Pointer to the shared VM structure.
2443 * @param idCpu VCPU id
2444 * @param pReq The request packet.
2445 */
2446GMMR0DECL(int) GMMR0FreeLargePageReq(PVM pVM, VMCPUID idCpu, PGMMFREELARGEPAGEREQ pReq)
2447{
2448 /*
2449 * Validate input and pass it on.
2450 */
2451 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2452 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2453 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(GMMFREEPAGESREQ),
2454 ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(GMMFREEPAGESREQ)),
2455 VERR_INVALID_PARAMETER);
2456
2457 return GMMR0FreeLargePage(pVM, idCpu, pReq->idPage);
2458}
2459
2460/**
2461 * Frees a chunk, giving it back to the host OS.
2462 *
2463 * @param pGMM Pointer to the GMM instance.
2464 * @param pGVM This is set when called from GMMR0CleanupVM so we can
2465 * unmap and free the chunk in one go.
2466 * @param pChunk The chunk to free.
2467 */
2468static void gmmR0FreeChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk)
2469{
2470 Assert(pChunk->Core.Key != NIL_GMM_CHUNKID);
2471
2472 /*
2473 * Cleanup hack! Unmap the chunk from the callers address space.
2474 */
2475 if ( pChunk->cMappings
2476 && pGVM)
2477 gmmR0UnmapChunk(pGMM, pGVM, pChunk);
2478
2479 /*
2480 * If there are current mappings of the chunk, then request the
2481 * VMs to unmap them. Reposition the chunk in the free list so
2482 * it won't be a likely candidate for allocations.
2483 */
2484 if (pChunk->cMappings)
2485 {
2486 /** @todo R0 -> VM request */
2487 /* The chunk can be owned by more than one VM if fBoundMemoryMode is false! */
2488 }
2489 else
2490 {
2491 /*
2492 * Try free the memory object.
2493 */
2494 int rc = RTR0MemObjFree(pChunk->MemObj, false /* fFreeMappings */);
2495 if (RT_SUCCESS(rc))
2496 {
2497 pChunk->MemObj = NIL_RTR0MEMOBJ;
2498
2499 /*
2500 * Unlink it from everywhere.
2501 */
2502 gmmR0UnlinkChunk(pChunk);
2503
2504 PAVLU32NODECORE pCore = RTAvlU32Remove(&pGMM->pChunks, pChunk->Core.Key);
2505 Assert(pCore == &pChunk->Core); NOREF(pCore);
2506
2507 PGMMCHUNKTLBE pTlbe = &pGMM->ChunkTLB.aEntries[GMM_CHUNKTLB_IDX(pChunk->Core.Key)];
2508 if (pTlbe->pChunk == pChunk)
2509 {
2510 pTlbe->idChunk = NIL_GMM_CHUNKID;
2511 pTlbe->pChunk = NULL;
2512 }
2513
2514 Assert(pGMM->cChunks > 0);
2515 pGMM->cChunks--;
2516
2517 /*
2518 * Free the Chunk ID and struct.
2519 */
2520 gmmR0FreeChunkId(pGMM, pChunk->Core.Key);
2521 pChunk->Core.Key = NIL_GMM_CHUNKID;
2522
2523 RTMemFree(pChunk->paMappings);
2524 pChunk->paMappings = NULL;
2525
2526 RTMemFree(pChunk);
2527 }
2528 else
2529 AssertRC(rc);
2530 }
2531}
2532
2533
2534/**
2535 * Free page worker.
2536 *
2537 * The caller does all the statistic decrementing, we do all the incrementing.
2538 *
2539 * @param pGMM Pointer to the GMM instance data.
2540 * @param pChunk Pointer to the chunk this page belongs to.
2541 * @param idPage The Page ID.
2542 * @param pPage Pointer to the page.
2543 */
2544static void gmmR0FreePageWorker(PGMM pGMM, PGMMCHUNK pChunk, uint32_t idPage, PGMMPAGE pPage)
2545{
2546 Log3(("F pPage=%p iPage=%#x/%#x u2State=%d iFreeHead=%#x\n",
2547 pPage, pPage - &pChunk->aPages[0], idPage, pPage->Common.u2State, pChunk->iFreeHead)); NOREF(idPage);
2548
2549 /*
2550 * Put the page on the free list.
2551 */
2552 pPage->u = 0;
2553 pPage->Free.u2State = GMM_PAGE_STATE_FREE;
2554 Assert(pChunk->iFreeHead < RT_ELEMENTS(pChunk->aPages) || pChunk->iFreeHead == UINT16_MAX);
2555 pPage->Free.iNext = pChunk->iFreeHead;
2556 pChunk->iFreeHead = pPage - &pChunk->aPages[0];
2557
2558 /*
2559 * Update statistics (the cShared/cPrivate stats are up to date already),
2560 * and relink the chunk if necessary.
2561 */
2562 if ((pChunk->cFree & GMM_CHUNK_FREE_SET_MASK) == 0)
2563 {
2564 gmmR0UnlinkChunk(pChunk);
2565 pChunk->cFree++;
2566 gmmR0LinkChunk(pChunk, pChunk->cShared ? &pGMM->Shared : &pGMM->Private);
2567 }
2568 else
2569 {
2570 pChunk->cFree++;
2571 pChunk->pSet->cFreePages++;
2572
2573 /*
2574 * If the chunk becomes empty, consider giving memory back to the host OS.
2575 *
2576 * The current strategy is to try give it back if there are other chunks
2577 * in this free list, meaning if there are at least 240 free pages in this
2578 * category. Note that since there are probably mappings of the chunk,
2579 * it won't be freed up instantly, which probably screws up this logic
2580 * a bit...
2581 */
2582 if (RT_UNLIKELY( pChunk->cFree == GMM_CHUNK_NUM_PAGES
2583 && pChunk->pFreeNext
2584 && pChunk->pFreePrev
2585 && !pGMM->fLegacyAllocationMode))
2586 gmmR0FreeChunk(pGMM, NULL, pChunk);
2587 }
2588}
2589
2590
2591/**
2592 * Frees a shared page, the page is known to exist and be valid and such.
2593 *
2594 * @param pGMM Pointer to the GMM instance.
2595 * @param idPage The Page ID
2596 * @param pPage The page structure.
2597 */
2598DECLINLINE(void) gmmR0FreeSharedPage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage)
2599{
2600 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2601 Assert(pChunk);
2602 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2603 Assert(pChunk->cShared > 0);
2604 Assert(pGMM->cSharedPages > 0);
2605 Assert(pGMM->cAllocatedPages > 0);
2606 Assert(!pPage->Shared.cRefs);
2607
2608 pChunk->cShared--;
2609 pGMM->cAllocatedPages--;
2610 pGMM->cSharedPages--;
2611 gmmR0FreePageWorker(pGMM, pChunk, idPage, pPage);
2612}
2613
2614
2615/**
2616 * Frees a private page, the page is known to exist and be valid and such.
2617 *
2618 * @param pGMM Pointer to the GMM instance.
2619 * @param idPage The Page ID
2620 * @param pPage The page structure.
2621 */
2622DECLINLINE(void) gmmR0FreePrivatePage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage)
2623{
2624 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2625 Assert(pChunk);
2626 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2627 Assert(pChunk->cPrivate > 0);
2628 Assert(pGMM->cAllocatedPages > 0);
2629
2630 pChunk->cPrivate--;
2631 pGMM->cAllocatedPages--;
2632 gmmR0FreePageWorker(pGMM, pChunk, idPage, pPage);
2633}
2634
2635
2636/**
2637 * Common worker for GMMR0FreePages and GMMR0BalloonedPages.
2638 *
2639 * @returns VBox status code:
2640 * @retval xxx
2641 *
2642 * @param pGMM Pointer to the GMM instance data.
2643 * @param pGVM Pointer to the shared VM structure.
2644 * @param cPages The number of pages to free.
2645 * @param paPages Pointer to the page descriptors.
2646 * @param enmAccount The account this relates to.
2647 */
2648static int gmmR0FreePages(PGMM pGMM, PGVM pGVM, uint32_t cPages, PGMMFREEPAGEDESC paPages, GMMACCOUNT enmAccount)
2649{
2650 /*
2651 * Check that the request isn't impossible wrt to the account status.
2652 */
2653 switch (enmAccount)
2654 {
2655 case GMMACCOUNT_BASE:
2656 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages < cPages))
2657 {
2658 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cBasePages, cPages));
2659 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2660 }
2661 break;
2662 case GMMACCOUNT_SHADOW:
2663 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cShadowPages < cPages))
2664 {
2665 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cShadowPages, cPages));
2666 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2667 }
2668 break;
2669 case GMMACCOUNT_FIXED:
2670 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cFixedPages < cPages))
2671 {
2672 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cFixedPages, cPages));
2673 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2674 }
2675 break;
2676 default:
2677 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
2678 }
2679
2680 /*
2681 * Walk the descriptors and free the pages.
2682 *
2683 * Statistics (except the account) are being updated as we go along,
2684 * unlike the alloc code. Also, stop on the first error.
2685 */
2686 int rc = VINF_SUCCESS;
2687 uint32_t iPage;
2688 for (iPage = 0; iPage < cPages; iPage++)
2689 {
2690 uint32_t idPage = paPages[iPage].idPage;
2691 PGMMPAGE pPage = gmmR0GetPage(pGMM, idPage);
2692 if (RT_LIKELY(pPage))
2693 {
2694 if (RT_LIKELY(GMM_PAGE_IS_PRIVATE(pPage)))
2695 {
2696 if (RT_LIKELY(pPage->Private.hGVM == pGVM->hSelf))
2697 {
2698 Assert(pGVM->gmm.s.cPrivatePages);
2699 pGVM->gmm.s.cPrivatePages--;
2700 gmmR0FreePrivatePage(pGMM, idPage, pPage);
2701 }
2702 else
2703 {
2704 Log(("gmmR0AllocatePages: #%#x/%#x: not owner! hGVM=%#x hSelf=%#x\n", iPage, idPage,
2705 pPage->Private.hGVM, pGVM->hSelf));
2706 rc = VERR_GMM_NOT_PAGE_OWNER;
2707 break;
2708 }
2709 }
2710 else if (RT_LIKELY(GMM_PAGE_IS_SHARED(pPage)))
2711 {
2712 Assert(pGVM->gmm.s.cSharedPages);
2713 pGVM->gmm.s.cSharedPages--;
2714 Assert(pPage->Shared.cRefs);
2715 if (!--pPage->Shared.cRefs)
2716 gmmR0FreeSharedPage(pGMM, idPage, pPage);
2717 }
2718 else
2719 {
2720 Log(("gmmR0AllocatePages: #%#x/%#x: already free!\n", iPage, idPage));
2721 rc = VERR_GMM_PAGE_ALREADY_FREE;
2722 break;
2723 }
2724 }
2725 else
2726 {
2727 Log(("gmmR0AllocatePages: #%#x/%#x: not found!\n", iPage, idPage));
2728 rc = VERR_GMM_PAGE_NOT_FOUND;
2729 break;
2730 }
2731 paPages[iPage].idPage = NIL_GMM_PAGEID;
2732 }
2733
2734 /*
2735 * Update the account.
2736 */
2737 switch (enmAccount)
2738 {
2739 case GMMACCOUNT_BASE: pGVM->gmm.s.Allocated.cBasePages -= iPage; break;
2740 case GMMACCOUNT_SHADOW: pGVM->gmm.s.Allocated.cShadowPages -= iPage; break;
2741 case GMMACCOUNT_FIXED: pGVM->gmm.s.Allocated.cFixedPages -= iPage; break;
2742 default:
2743 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
2744 }
2745
2746 /*
2747 * Any threshold stuff to be done here?
2748 */
2749
2750 return rc;
2751}
2752
2753
2754/**
2755 * Free one or more pages.
2756 *
2757 * This is typically used at reset time or power off.
2758 *
2759 * @returns VBox status code:
2760 * @retval xxx
2761 *
2762 * @param pVM Pointer to the shared VM structure.
2763 * @param idCpu VCPU id
2764 * @param cPages The number of pages to allocate.
2765 * @param paPages Pointer to the page descriptors containing the Page IDs for each page.
2766 * @param enmAccount The account this relates to.
2767 * @thread EMT.
2768 */
2769GMMR0DECL(int) GMMR0FreePages(PVM pVM, VMCPUID idCpu, uint32_t cPages, PGMMFREEPAGEDESC paPages, GMMACCOUNT enmAccount)
2770{
2771 LogFlow(("GMMR0FreePages: pVM=%p cPages=%#x paPages=%p enmAccount=%d\n", pVM, cPages, paPages, enmAccount));
2772
2773 /*
2774 * Validate input and get the basics.
2775 */
2776 PGMM pGMM;
2777 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2778 PGVM pGVM;
2779 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2780 if (RT_FAILURE(rc))
2781 return rc;
2782
2783 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2784 AssertMsgReturn(enmAccount > GMMACCOUNT_INVALID && enmAccount < GMMACCOUNT_END, ("%d\n", enmAccount), VERR_INVALID_PARAMETER);
2785 AssertMsgReturn(cPages > 0 && cPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cPages), VERR_INVALID_PARAMETER);
2786
2787 for (unsigned iPage = 0; iPage < cPages; iPage++)
2788 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
2789 /*|| paPages[iPage].idPage == NIL_GMM_PAGEID*/,
2790 ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2791
2792 /*
2793 * Take the semaphore and call the worker function.
2794 */
2795 rc = RTSemFastMutexRequest(pGMM->Mtx);
2796 AssertRC(rc);
2797 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2798 {
2799 rc = gmmR0FreePages(pGMM, pGVM, cPages, paPages, enmAccount);
2800 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
2801 }
2802 else
2803 rc = VERR_INTERNAL_ERROR_5;
2804 RTSemFastMutexRelease(pGMM->Mtx);
2805 LogFlow(("GMMR0FreePages: returns %Rrc\n", rc));
2806 return rc;
2807}
2808
2809
2810/**
2811 * VMMR0 request wrapper for GMMR0FreePages.
2812 *
2813 * @returns see GMMR0FreePages.
2814 * @param pVM Pointer to the shared VM structure.
2815 * @param idCpu VCPU id
2816 * @param pReq The request packet.
2817 */
2818GMMR0DECL(int) GMMR0FreePagesReq(PVM pVM, VMCPUID idCpu, PGMMFREEPAGESREQ pReq)
2819{
2820 /*
2821 * Validate input and pass it on.
2822 */
2823 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2824 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2825 AssertMsgReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[0]),
2826 ("%#x < %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[0])),
2827 VERR_INVALID_PARAMETER);
2828 AssertMsgReturn(pReq->Hdr.cbReq == RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[pReq->cPages]),
2829 ("%#x != %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[pReq->cPages])),
2830 VERR_INVALID_PARAMETER);
2831
2832 return GMMR0FreePages(pVM, idCpu, pReq->cPages, &pReq->aPages[0], pReq->enmAccount);
2833}
2834
2835
2836/**
2837 * Report back on a memory ballooning request.
2838 *
2839 * The request may or may not have been initiated by the GMM. If it was initiated
2840 * by the GMM it is important that this function is called even if no pages was
2841 * ballooned.
2842 *
2843 * @returns VBox status code:
2844 * @retval VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH
2845 * @retval VERR_GMM_ATTEMPT_TO_DEFLATE_TOO_MUCH
2846 * @retval VERR_GMM_OVERCOMMITED_TRY_AGAIN_IN_A_BIT - reset condition
2847 * indicating that we won't neceessarily have sufficient RAM to boot
2848 * the VM again and that it should pause until this changes (we'll try
2849 * balloon some other VM). (For standard deflate we have little choice
2850 * but to hope the VM won't use the memory that was returned to it.)
2851 *
2852 * @param pVM Pointer to the shared VM structure.
2853 * @param idCpu VCPU id
2854 * @param enmAction Inflate/deflate/reset
2855 * @param cBalloonedPages The number of pages that was ballooned.
2856 *
2857 * @thread EMT.
2858 */
2859GMMR0DECL(int) GMMR0BalloonedPages(PVM pVM, VMCPUID idCpu, GMMBALLOONACTION enmAction, uint32_t cBalloonedPages)
2860{
2861 LogFlow(("GMMR0BalloonedPages: pVM=%p enmAction=%d cBalloonedPages=%#x\n",
2862 pVM, enmAction, cBalloonedPages));
2863
2864 /*
2865 * Validate input and get the basics.
2866 */
2867 PGMM pGMM;
2868 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2869 PGVM pGVM;
2870 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
2871 if (RT_FAILURE(rc))
2872 return rc;
2873
2874 AssertMsgReturn(cBalloonedPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cBalloonedPages), VERR_INVALID_PARAMETER);
2875
2876 /*
2877 * Take the sempahore and do some more validations.
2878 */
2879 rc = RTSemFastMutexRequest(pGMM->Mtx);
2880 AssertRC(rc);
2881 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
2882 {
2883 switch (enmAction)
2884 {
2885 case GMMBALLOONACTION_INFLATE:
2886 {
2887 if (pGVM->gmm.s.Allocated.cBasePages >= cBalloonedPages)
2888 {
2889 /*
2890 * Record the ballooned memory.
2891 */
2892 pGMM->cBalloonedPages += cBalloonedPages;
2893 if (pGVM->gmm.s.cReqBalloonedPages)
2894 {
2895 /* Codepath never taken. Might be interesting in the future to request ballooned memory from guests in low memory conditions.. */
2896 AssertFailed();
2897
2898 pGVM->gmm.s.cBalloonedPages += cBalloonedPages;
2899 pGVM->gmm.s.cReqActuallyBalloonedPages += cBalloonedPages;
2900 Log(("GMMR0BalloonedPages: +%#x - Global=%#llx / VM: Total=%#llx Req=%#llx Actual=%#llx (pending)\n", cBalloonedPages,
2901 pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages, pGVM->gmm.s.cReqBalloonedPages, pGVM->gmm.s.cReqActuallyBalloonedPages));
2902 }
2903 else
2904 {
2905 pGVM->gmm.s.cBalloonedPages += cBalloonedPages;
2906 Log(("GMMR0BalloonedPages: +%#x - Global=%#llx / VM: Total=%#llx (user)\n",
2907 cBalloonedPages, pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages));
2908 }
2909 }
2910 else
2911 rc = VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2912 break;
2913 }
2914
2915 case GMMBALLOONACTION_DEFLATE:
2916 {
2917 /* Deflate. */
2918 if (pGVM->gmm.s.cBalloonedPages >= cBalloonedPages)
2919 {
2920 /*
2921 * Record the ballooned memory.
2922 */
2923 Assert(pGMM->cBalloonedPages >= cBalloonedPages);
2924 pGMM->cBalloonedPages -= cBalloonedPages;
2925 pGVM->gmm.s.cBalloonedPages -= cBalloonedPages;
2926 if (pGVM->gmm.s.cReqDeflatePages)
2927 {
2928 AssertFailed(); /* This is path is for later. */
2929 Log(("GMMR0BalloonedPages: -%#x - Global=%#llx / VM: Total=%#llx Req=%#llx\n",
2930 cBalloonedPages, pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages, pGVM->gmm.s.cReqDeflatePages));
2931
2932 /*
2933 * Anything we need to do here now when the request has been completed?
2934 */
2935 pGVM->gmm.s.cReqDeflatePages = 0;
2936 }
2937 else
2938 Log(("GMMR0BalloonedPages: -%#x - Global=%#llx / VM: Total=%#llx (user)\n",
2939 cBalloonedPages, pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages));
2940 }
2941 else
2942 rc = VERR_GMM_ATTEMPT_TO_DEFLATE_TOO_MUCH;
2943 break;
2944 }
2945
2946 case GMMBALLOONACTION_RESET:
2947 {
2948 /* Reset to an empty balloon. */
2949 Assert(pGMM->cBalloonedPages >= pGVM->gmm.s.cBalloonedPages);
2950
2951 pGMM->cBalloonedPages -= pGVM->gmm.s.cBalloonedPages;
2952 pGVM->gmm.s.cBalloonedPages -= 0;
2953 break;
2954 }
2955
2956 default:
2957 rc = VERR_INVALID_PARAMETER;
2958 break;
2959 }
2960 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
2961 }
2962 else
2963 rc = VERR_INTERNAL_ERROR_5;
2964
2965 RTSemFastMutexRelease(pGMM->Mtx);
2966 LogFlow(("GMMR0BalloonedPages: returns %Rrc\n", rc));
2967 return rc;
2968}
2969
2970
2971/**
2972 * VMMR0 request wrapper for GMMR0BalloonedPages.
2973 *
2974 * @returns see GMMR0BalloonedPages.
2975 * @param pVM Pointer to the shared VM structure.
2976 * @param idCpu VCPU id
2977 * @param pReq The request packet.
2978 */
2979GMMR0DECL(int) GMMR0BalloonedPagesReq(PVM pVM, VMCPUID idCpu, PGMMBALLOONEDPAGESREQ pReq)
2980{
2981 /*
2982 * Validate input and pass it on.
2983 */
2984 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2985 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2986 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(GMMBALLOONEDPAGESREQ),
2987 ("%#x < %#x\n", pReq->Hdr.cbReq, sizeof(GMMBALLOONEDPAGESREQ)),
2988 VERR_INVALID_PARAMETER);
2989
2990 return GMMR0BalloonedPages(pVM, idCpu, pReq->enmAction, pReq->cBalloonedPages);
2991}
2992
2993
2994/**
2995 * Unmaps a chunk previously mapped into the address space of the current process.
2996 *
2997 * @returns VBox status code.
2998 * @param pGMM Pointer to the GMM instance data.
2999 * @param pGVM Pointer to the Global VM structure.
3000 * @param pChunk Pointer to the chunk to be unmapped.
3001 */
3002static int gmmR0UnmapChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk)
3003{
3004 if (!pGMM->fLegacyAllocationMode)
3005 {
3006 /*
3007 * Find the mapping and try unmapping it.
3008 */
3009 for (uint32_t i = 0; i < pChunk->cMappings; i++)
3010 {
3011 Assert(pChunk->paMappings[i].pGVM && pChunk->paMappings[i].MapObj != NIL_RTR0MEMOBJ);
3012 if (pChunk->paMappings[i].pGVM == pGVM)
3013 {
3014 /* unmap */
3015 int rc = RTR0MemObjFree(pChunk->paMappings[i].MapObj, false /* fFreeMappings (NA) */);
3016 if (RT_SUCCESS(rc))
3017 {
3018 /* update the record. */
3019 pChunk->cMappings--;
3020 if (i < pChunk->cMappings)
3021 pChunk->paMappings[i] = pChunk->paMappings[pChunk->cMappings];
3022 pChunk->paMappings[pChunk->cMappings].MapObj = NIL_RTR0MEMOBJ;
3023 pChunk->paMappings[pChunk->cMappings].pGVM = NULL;
3024 }
3025 return rc;
3026 }
3027 }
3028 }
3029 else if (pChunk->hGVM == pGVM->hSelf)
3030 return VINF_SUCCESS;
3031
3032 Log(("gmmR0MapChunk: Chunk %#x is not mapped into pGVM=%p/%#x\n", pChunk->Core.Key, pGVM, pGVM->hSelf));
3033 return VERR_GMM_CHUNK_NOT_MAPPED;
3034}
3035
3036
3037/**
3038 * Maps a chunk into the user address space of the current process.
3039 *
3040 * @returns VBox status code.
3041 * @param pGMM Pointer to the GMM instance data.
3042 * @param pGVM Pointer to the Global VM structure.
3043 * @param pChunk Pointer to the chunk to be mapped.
3044 * @param ppvR3 Where to store the ring-3 address of the mapping.
3045 * In the VERR_GMM_CHUNK_ALREADY_MAPPED case, this will be
3046 * contain the address of the existing mapping.
3047 */
3048static int gmmR0MapChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk, PRTR3PTR ppvR3)
3049{
3050 /*
3051 * If we're in legacy mode this is simple.
3052 */
3053 if (pGMM->fLegacyAllocationMode)
3054 {
3055 if (pChunk->hGVM != pGVM->hSelf)
3056 {
3057 Log(("gmmR0MapChunk: chunk %#x is already mapped at %p!\n", pChunk->Core.Key, *ppvR3));
3058 return VERR_GMM_CHUNK_NOT_FOUND;
3059 }
3060
3061 *ppvR3 = RTR0MemObjAddressR3(pChunk->MemObj);
3062 return VINF_SUCCESS;
3063 }
3064
3065 /*
3066 * Check to see if the chunk is already mapped.
3067 */
3068 for (uint32_t i = 0; i < pChunk->cMappings; i++)
3069 {
3070 Assert(pChunk->paMappings[i].pGVM && pChunk->paMappings[i].MapObj != NIL_RTR0MEMOBJ);
3071 if (pChunk->paMappings[i].pGVM == pGVM)
3072 {
3073 *ppvR3 = RTR0MemObjAddressR3(pChunk->paMappings[i].MapObj);
3074 Log(("gmmR0MapChunk: chunk %#x is already mapped at %p!\n", pChunk->Core.Key, *ppvR3));
3075 return VERR_GMM_CHUNK_ALREADY_MAPPED;
3076 }
3077 }
3078
3079 /*
3080 * Do the mapping.
3081 */
3082 RTR0MEMOBJ MapObj;
3083 int rc = RTR0MemObjMapUser(&MapObj, pChunk->MemObj, (RTR3PTR)-1, 0, RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
3084 if (RT_SUCCESS(rc))
3085 {
3086 /* reallocate the array? */
3087 if ((pChunk->cMappings & 1 /*7*/) == 0)
3088 {
3089 void *pvMappings = RTMemRealloc(pChunk->paMappings, (pChunk->cMappings + 2 /*8*/) * sizeof(pChunk->paMappings[0]));
3090 if (RT_UNLIKELY(!pvMappings))
3091 {
3092 rc = RTR0MemObjFree(MapObj, false /* fFreeMappings (NA) */);
3093 AssertRC(rc);
3094 return VERR_NO_MEMORY;
3095 }
3096 pChunk->paMappings = (PGMMCHUNKMAP)pvMappings;
3097 }
3098
3099 /* insert new entry */
3100 pChunk->paMappings[pChunk->cMappings].MapObj = MapObj;
3101 pChunk->paMappings[pChunk->cMappings].pGVM = pGVM;
3102 pChunk->cMappings++;
3103
3104 *ppvR3 = RTR0MemObjAddressR3(MapObj);
3105 }
3106
3107 return rc;
3108}
3109
3110
3111/**
3112 * Map a chunk and/or unmap another chunk.
3113 *
3114 * The mapping and unmapping applies to the current process.
3115 *
3116 * This API does two things because it saves a kernel call per mapping when
3117 * when the ring-3 mapping cache is full.
3118 *
3119 * @returns VBox status code.
3120 * @param pVM The VM.
3121 * @param idCpu VCPU id
3122 * @param idChunkMap The chunk to map. NIL_GMM_CHUNKID if nothing to map.
3123 * @param idChunkUnmap The chunk to unmap. NIL_GMM_CHUNKID if nothing to unmap.
3124 * @param ppvR3 Where to store the address of the mapped chunk. NULL is ok if nothing to map.
3125 * @thread EMT
3126 */
3127GMMR0DECL(int) GMMR0MapUnmapChunk(PVM pVM, VMCPUID idCpu, uint32_t idChunkMap, uint32_t idChunkUnmap, PRTR3PTR ppvR3)
3128{
3129 LogFlow(("GMMR0MapUnmapChunk: pVM=%p idChunkMap=%#x idChunkUnmap=%#x ppvR3=%p\n",
3130 pVM, idChunkMap, idChunkUnmap, ppvR3));
3131
3132 /*
3133 * Validate input and get the basics.
3134 */
3135 PGMM pGMM;
3136 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
3137 PGVM pGVM;
3138 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
3139 if (RT_FAILURE(rc))
3140 return rc;
3141
3142 AssertCompile(NIL_GMM_CHUNKID == 0);
3143 AssertMsgReturn(idChunkMap <= GMM_CHUNKID_LAST, ("%#x\n", idChunkMap), VERR_INVALID_PARAMETER);
3144 AssertMsgReturn(idChunkUnmap <= GMM_CHUNKID_LAST, ("%#x\n", idChunkUnmap), VERR_INVALID_PARAMETER);
3145
3146 if ( idChunkMap == NIL_GMM_CHUNKID
3147 && idChunkUnmap == NIL_GMM_CHUNKID)
3148 return VERR_INVALID_PARAMETER;
3149
3150 if (idChunkMap != NIL_GMM_CHUNKID)
3151 {
3152 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
3153 *ppvR3 = NIL_RTR3PTR;
3154 }
3155
3156 /*
3157 * Take the semaphore and do the work.
3158 *
3159 * The unmapping is done last since it's easier to undo a mapping than
3160 * undoing an unmapping. The ring-3 mapping cache cannot not be so big
3161 * that it pushes the user virtual address space to within a chunk of
3162 * it it's limits, so, no problem here.
3163 */
3164 rc = RTSemFastMutexRequest(pGMM->Mtx);
3165 AssertRC(rc);
3166 if (GMM_CHECK_SANITY_UPON_ENTERING(pGMM))
3167 {
3168 PGMMCHUNK pMap = NULL;
3169 if (idChunkMap != NIL_GVM_HANDLE)
3170 {
3171 pMap = gmmR0GetChunk(pGMM, idChunkMap);
3172 if (RT_LIKELY(pMap))
3173 rc = gmmR0MapChunk(pGMM, pGVM, pMap, ppvR3);
3174 else
3175 {
3176 Log(("GMMR0MapUnmapChunk: idChunkMap=%#x\n", idChunkMap));
3177 rc = VERR_GMM_CHUNK_NOT_FOUND;
3178 }
3179 }
3180
3181 if ( idChunkUnmap != NIL_GMM_CHUNKID
3182 && RT_SUCCESS(rc))
3183 {
3184 PGMMCHUNK pUnmap = gmmR0GetChunk(pGMM, idChunkUnmap);
3185 if (RT_LIKELY(pUnmap))
3186 rc = gmmR0UnmapChunk(pGMM, pGVM, pUnmap);
3187 else
3188 {
3189 Log(("GMMR0MapUnmapChunk: idChunkUnmap=%#x\n", idChunkUnmap));
3190 rc = VERR_GMM_CHUNK_NOT_FOUND;
3191 }
3192
3193 if (RT_FAILURE(rc) && pMap)
3194 gmmR0UnmapChunk(pGMM, pGVM, pMap);
3195 }
3196
3197 GMM_CHECK_SANITY_UPON_LEAVING(pGMM);
3198 }
3199 else
3200 rc = VERR_INTERNAL_ERROR_5;
3201 RTSemFastMutexRelease(pGMM->Mtx);
3202
3203 LogFlow(("GMMR0MapUnmapChunk: returns %Rrc\n", rc));
3204 return rc;
3205}
3206
3207
3208/**
3209 * VMMR0 request wrapper for GMMR0MapUnmapChunk.
3210 *
3211 * @returns see GMMR0MapUnmapChunk.
3212 * @param pVM Pointer to the shared VM structure.
3213 * @param idCpu VCPU id
3214 * @param pReq The request packet.
3215 */
3216GMMR0DECL(int) GMMR0MapUnmapChunkReq(PVM pVM, VMCPUID idCpu, PGMMMAPUNMAPCHUNKREQ pReq)
3217{
3218 /*
3219 * Validate input and pass it on.
3220 */
3221 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
3222 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
3223 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
3224
3225 return GMMR0MapUnmapChunk(pVM, idCpu, pReq->idChunkMap, pReq->idChunkUnmap, &pReq->pvR3);
3226}
3227
3228
3229/**
3230 * Legacy mode API for supplying pages.
3231 *
3232 * The specified user address points to a allocation chunk sized block that
3233 * will be locked down and used by the GMM when the GM asks for pages.
3234 *
3235 * @returns VBox status code.
3236 * @param pVM The VM.
3237 * @param idCpu VCPU id
3238 * @param pvR3 Pointer to the chunk size memory block to lock down.
3239 */
3240GMMR0DECL(int) GMMR0SeedChunk(PVM pVM, VMCPUID idCpu, RTR3PTR pvR3)
3241{
3242 /*
3243 * Validate input and get the basics.
3244 */
3245 PGMM pGMM;
3246 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
3247 PGVM pGVM;
3248 int rc = GVMMR0ByVMAndEMT(pVM, idCpu, &pGVM);
3249 if (RT_FAILURE(rc))
3250 return rc;
3251
3252 AssertPtrReturn(pvR3, VERR_INVALID_POINTER);
3253 AssertReturn(!(PAGE_OFFSET_MASK & pvR3), VERR_INVALID_POINTER);
3254
3255 if (!pGMM->fLegacyAllocationMode)
3256 {
3257 Log(("GMMR0SeedChunk: not in legacy allocation mode!\n"));
3258 return VERR_NOT_SUPPORTED;
3259 }
3260
3261 /*
3262 * Lock the memory before taking the semaphore.
3263 */
3264 RTR0MEMOBJ MemObj;
3265 rc = RTR0MemObjLockUser(&MemObj, pvR3, GMM_CHUNK_SIZE, RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
3266 if (RT_SUCCESS(rc))
3267 {
3268 /* Grab the lock. */
3269 rc = RTSemFastMutexRequest(pGMM->Mtx);
3270 AssertRCReturn(rc, rc);
3271
3272 /*
3273 * Add a new chunk with our hGVM.
3274 */
3275 rc = gmmR0RegisterChunk(pGMM, &pGMM->Private, MemObj, pGVM->hSelf, GMMCHUNKTYPE_NON_CONTINUOUS);
3276 RTSemFastMutexRelease(pGMM->Mtx);
3277
3278 if (RT_FAILURE(rc))
3279 RTR0MemObjFree(MemObj, false /* fFreeMappings */);
3280 }
3281
3282 LogFlow(("GMMR0SeedChunk: rc=%d (pvR3=%p)\n", rc, pvR3));
3283 return rc;
3284}
3285
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