VirtualBox

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

Last change on this file since 18369 was 18369, checked in by vboxsync, 16 years ago

GMMR0: Baka tori! Bitmap was a wee bit too small.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 97.8 KB
Line 
1/* $Id: GMMR0.cpp 18369 2009-03-27 03:24:07Z 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
369
370/**
371 * A GMM allocation chunk.
372 */
373typedef struct GMMCHUNK
374{
375 /** The AVL node core.
376 * The Key is the chunk ID. */
377 AVLU32NODECORE Core;
378 /** The memory object.
379 * Either from RTR0MemObjAllocPhysNC or RTR0MemObjLockUser depending on
380 * what the host can dish up with. */
381 RTR0MEMOBJ MemObj;
382 /** Pointer to the next chunk in the free list. */
383 PGMMCHUNK pFreeNext;
384 /** Pointer to the previous chunk in the free list. */
385 PGMMCHUNK pFreePrev;
386 /** Pointer to the free set this chunk belongs to. NULL for
387 * chunks with no free pages. */
388 PGMMCHUNKFREESET pSet;
389 /** Pointer to an array of mappings. */
390 PGMMCHUNKMAP paMappings;
391 /** The number of mappings. */
392 uint16_t cMappings;
393 /** The head of the list of free pages. UINT16_MAX is the NIL value. */
394 uint16_t iFreeHead;
395 /** The number of free pages. */
396 uint16_t cFree;
397 /** The GVM handle of the VM that first allocated pages from this chunk, this
398 * is used as a preference when there are several chunks to choose from.
399 * When in legacy mode this isn't a preference any longer. */
400 uint16_t hGVM;
401 /** The number of private pages. */
402 uint16_t cPrivate;
403 /** The number of shared pages. */
404 uint16_t cShared;
405#if HC_ARCH_BITS == 64
406 /** Reserved for later. */
407 uint16_t au16Reserved[2];
408#endif
409 /** The pages. */
410 GMMPAGE aPages[GMM_CHUNK_SIZE >> PAGE_SHIFT];
411} GMMCHUNK;
412
413
414/**
415 * An allocation chunk TLB entry.
416 */
417typedef struct GMMCHUNKTLBE
418{
419 /** The chunk id. */
420 uint32_t idChunk;
421 /** Pointer to the chunk. */
422 PGMMCHUNK pChunk;
423} GMMCHUNKTLBE;
424/** Pointer to an allocation chunk TLB entry. */
425typedef GMMCHUNKTLBE *PGMMCHUNKTLBE;
426
427
428/** The number of entries tin the allocation chunk TLB. */
429#define GMM_CHUNKTLB_ENTRIES 32
430/** Gets the TLB entry index for the given Chunk ID. */
431#define GMM_CHUNKTLB_IDX(idChunk) ( (idChunk) & (GMM_CHUNKTLB_ENTRIES - 1) )
432
433/**
434 * An allocation chunk TLB.
435 */
436typedef struct GMMCHUNKTLB
437{
438 /** The TLB entries. */
439 GMMCHUNKTLBE aEntries[GMM_CHUNKTLB_ENTRIES];
440} GMMCHUNKTLB;
441/** Pointer to an allocation chunk TLB. */
442typedef GMMCHUNKTLB *PGMMCHUNKTLB;
443
444
445/** The number of lists in set. */
446#define GMM_CHUNK_FREE_SET_LISTS 16
447/** The GMMCHUNK::cFree shift count. */
448#define GMM_CHUNK_FREE_SET_SHIFT 4
449/** The GMMCHUNK::cFree mask for use when considering relinking a chunk. */
450#define GMM_CHUNK_FREE_SET_MASK 15
451
452/**
453 * A set of free chunks.
454 */
455typedef struct GMMCHUNKFREESET
456{
457 /** The number of free pages in the set. */
458 uint64_t cPages;
459 /** */
460 PGMMCHUNK apLists[GMM_CHUNK_FREE_SET_LISTS];
461} GMMCHUNKFREESET;
462
463
464/**
465 * The GMM instance data.
466 */
467typedef struct GMM
468{
469 /** Magic / eye catcher. GMM_MAGIC */
470 uint32_t u32Magic;
471 /** The fast mutex protecting the GMM.
472 * More fine grained locking can be implemented later if necessary. */
473 RTSEMFASTMUTEX Mtx;
474 /** The chunk tree. */
475 PAVLU32NODECORE pChunks;
476 /** The chunk TLB. */
477 GMMCHUNKTLB ChunkTLB;
478 /** The private free set. */
479 GMMCHUNKFREESET Private;
480 /** The shared free set. */
481 GMMCHUNKFREESET Shared;
482
483 /** The maximum number of pages we're allowed to allocate.
484 * @gcfgm 64-bit GMM/MaxPages Direct.
485 * @gcfgm 32-bit GMM/PctPages Relative to the number of host pages. */
486 uint64_t cMaxPages;
487 /** The number of pages that has been reserved.
488 * The deal is that cReservedPages - cOverCommittedPages <= cMaxPages. */
489 uint64_t cReservedPages;
490 /** The number of pages that we have over-committed in reservations. */
491 uint64_t cOverCommittedPages;
492 /** The number of actually allocated (committed if you like) pages. */
493 uint64_t cAllocatedPages;
494 /** The number of pages that are shared. A subset of cAllocatedPages. */
495 uint64_t cSharedPages;
496 /** The number of pages that are shared that has been left behind by
497 * VMs not doing proper cleanups. */
498 uint64_t cLeftBehindSharedPages;
499 /** The number of allocation chunks.
500 * (The number of pages we've allocated from the host can be derived from this.) */
501 uint32_t cChunks;
502 /** The number of current ballooned pages. */
503 uint64_t cBalloonedPages;
504
505 /** The legacy mode indicator.
506 * This is determined at initialization time. */
507 bool fLegacyMode;
508 /** The number of registered VMs. */
509 uint16_t cRegisteredVMs;
510
511 /** The previous allocated Chunk ID.
512 * Used as a hint to avoid scanning the whole bitmap. */
513 uint32_t idChunkPrev;
514 /** Chunk ID allocation bitmap.
515 * Bits of allocated IDs are set, free ones are clear.
516 * The NIL id (0) is marked allocated. */
517 uint32_t bmChunkId[(GMM_CHUNKID_LAST + 1 + 31) / 32];
518} GMM;
519/** Pointer to the GMM instance. */
520typedef GMM *PGMM;
521
522/** The value of GMM::u32Magic (Katsuhiro Otomo). */
523#define GMM_MAGIC 0x19540414
524
525
526/*******************************************************************************
527* Global Variables *
528*******************************************************************************/
529/** Pointer to the GMM instance data. */
530static PGMM g_pGMM = NULL;
531
532/** Macro for obtaining and validating the g_pGMM pointer.
533 * On failure it will return from the invoking function with the specified return value.
534 *
535 * @param pGMM The name of the pGMM variable.
536 * @param rc The return value on failure. Use VERR_INTERNAL_ERROR for
537 * VBox status codes.
538 */
539#define GMM_GET_VALID_INSTANCE(pGMM, rc) \
540 do { \
541 (pGMM) = g_pGMM; \
542 AssertPtrReturn((pGMM), (rc)); \
543 AssertMsgReturn((pGMM)->u32Magic == GMM_MAGIC, ("%p - %#x\n", (pGMM), (pGMM)->u32Magic), (rc)); \
544 } while (0)
545
546/** Macro for obtaining and validating the g_pGMM pointer, void function variant.
547 * On failure it will return from the invoking function.
548 *
549 * @param pGMM The name of the pGMM variable.
550 */
551#define GMM_GET_VALID_INSTANCE_VOID(pGMM) \
552 do { \
553 (pGMM) = g_pGMM; \
554 AssertPtrReturnVoid((pGMM)); \
555 AssertMsgReturnVoid((pGMM)->u32Magic == GMM_MAGIC, ("%p - %#x\n", (pGMM), (pGMM)->u32Magic)); \
556 } while (0)
557
558
559/*******************************************************************************
560* Internal Functions *
561*******************************************************************************/
562static DECLCALLBACK(int) gmmR0TermDestroyChunk(PAVLU32NODECORE pNode, void *pvGMM);
563static DECLCALLBACK(int) gmmR0CleanupVMScanChunk(PAVLU32NODECORE pNode, void *pvGMM);
564/*static*/ DECLCALLBACK(int) gmmR0CleanupVMDestroyChunk(PAVLU32NODECORE pNode, void *pvGVM);
565DECLINLINE(void) gmmR0LinkChunk(PGMMCHUNK pChunk, PGMMCHUNKFREESET pSet);
566DECLINLINE(void) gmmR0UnlinkChunk(PGMMCHUNK pChunk);
567static void gmmR0FreeChunk(PGMM pGMM, PGMMCHUNK pChunk);
568static void gmmR0FreeSharedPage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage);
569
570
571
572/**
573 * Initializes the GMM component.
574 *
575 * This is called when the VMMR0.r0 module is loaded and protected by the
576 * loader semaphore.
577 *
578 * @returns VBox status code.
579 */
580GMMR0DECL(int) GMMR0Init(void)
581{
582 LogFlow(("GMMInit:\n"));
583
584 /*
585 * Allocate the instance data and the lock(s).
586 */
587 PGMM pGMM = (PGMM)RTMemAllocZ(sizeof(*pGMM));
588 if (!pGMM)
589 return VERR_NO_MEMORY;
590 pGMM->u32Magic = GMM_MAGIC;
591 for (unsigned i = 0; i < RT_ELEMENTS(pGMM->ChunkTLB.aEntries); i++)
592 pGMM->ChunkTLB.aEntries[i].idChunk = NIL_GMM_CHUNKID;
593 ASMBitSet(&pGMM->bmChunkId[0], NIL_GMM_CHUNKID);
594
595 int rc = RTSemFastMutexCreate(&pGMM->Mtx);
596 if (RT_SUCCESS(rc))
597 {
598 /*
599 * Check and see if RTR0MemObjAllocPhysNC works.
600 */
601#if 0 /* later, see #3170. */
602 RTR0MEMOBJ MemObj;
603 rc = RTR0MemObjAllocPhysNC(&MemObj, _64K, NIL_RTHCPHYS);
604 if (RT_SUCCESS(rc))
605 {
606 rc = RTR0MemObjFree(MemObj, true);
607 AssertRC(rc);
608 }
609 else if (rc == VERR_NOT_SUPPORTED)
610 pGMM->fLegacyMode = true;
611 else
612 SUPR0Printf("GMMR0Init: RTR0MemObjAllocPhysNC(,64K,Any) -> %d!\n", rc);
613#else
614 pGMM->fLegacyMode = true;
615#endif
616
617 /*
618 * Query system page count and guess a reasonable cMaxPages value.
619 */
620 pGMM->cMaxPages = UINT32_MAX; /** @todo IPRT function for query ram size and such. */
621
622 g_pGMM = pGMM;
623 LogFlow(("GMMInit: pGMM=%p fLegacy=%RTbool\n", pGMM, pGMM->fLegacyMode));
624 return VINF_SUCCESS;
625 }
626
627 RTMemFree(pGMM);
628 SUPR0Printf("GMMR0Init: failed! rc=%d\n", rc);
629 return rc;
630}
631
632
633/**
634 * Terminates the GMM component.
635 */
636GMMR0DECL(void) GMMR0Term(void)
637{
638 LogFlow(("GMMTerm:\n"));
639
640 /*
641 * Take care / be paranoid...
642 */
643 PGMM pGMM = g_pGMM;
644 if (!VALID_PTR(pGMM))
645 return;
646 if (pGMM->u32Magic != GMM_MAGIC)
647 {
648 SUPR0Printf("GMMR0Term: u32Magic=%#x\n", pGMM->u32Magic);
649 return;
650 }
651
652 /*
653 * Undo what init did and free all the resources we've acquired.
654 */
655 /* Destroy the fundamentals. */
656 g_pGMM = NULL;
657 pGMM->u32Magic++;
658 RTSemFastMutexDestroy(pGMM->Mtx);
659 pGMM->Mtx = NIL_RTSEMFASTMUTEX;
660
661 /* free any chunks still hanging around. */
662 RTAvlU32Destroy(&pGMM->pChunks, gmmR0TermDestroyChunk, pGMM);
663
664 /* finally the instance data itself. */
665 RTMemFree(pGMM);
666 LogFlow(("GMMTerm: done\n"));
667}
668
669
670/**
671 * RTAvlU32Destroy callback.
672 *
673 * @returns 0
674 * @param pNode The node to destroy.
675 * @param pvGMM The GMM handle.
676 */
677static DECLCALLBACK(int) gmmR0TermDestroyChunk(PAVLU32NODECORE pNode, void *pvGMM)
678{
679 PGMMCHUNK pChunk = (PGMMCHUNK)pNode;
680
681 if (pChunk->cFree != (GMM_CHUNK_SIZE >> PAGE_SHIFT))
682 SUPR0Printf("GMMR0Term: %p/%#x: cFree=%d cPrivate=%d cShared=%d cMappings=%d\n", pChunk,
683 pChunk->Core.Key, pChunk->cFree, pChunk->cPrivate, pChunk->cShared, pChunk->cMappings);
684
685 int rc = RTR0MemObjFree(pChunk->MemObj, true /* fFreeMappings */);
686 if (RT_FAILURE(rc))
687 {
688 SUPR0Printf("GMMR0Term: %p/%#x: RTRMemObjFree(%p,true) -> %d (cMappings=%d)\n", pChunk,
689 pChunk->Core.Key, pChunk->MemObj, rc, pChunk->cMappings);
690 AssertRC(rc);
691 }
692 pChunk->MemObj = NIL_RTR0MEMOBJ;
693
694 RTMemFree(pChunk->paMappings);
695 pChunk->paMappings = NULL;
696
697 RTMemFree(pChunk);
698 NOREF(pvGMM);
699 return 0;
700}
701
702
703/**
704 * Initializes the per-VM data for the GMM.
705 *
706 * This is called from within the GVMM lock (from GVMMR0CreateVM)
707 * and should only initialize the data members so GMMR0CleanupVM
708 * can deal with them. We reserve no memory or anything here,
709 * that's done later in GMMR0InitVM.
710 *
711 * @param pGVM Pointer to the Global VM structure.
712 */
713GMMR0DECL(void) GMMR0InitPerVMData(PGVM pGVM)
714{
715 AssertCompile(RT_SIZEOFMEMB(GVM,gmm.s) <= RT_SIZEOFMEMB(GVM,gmm.padding));
716 AssertRelease(RT_SIZEOFMEMB(GVM,gmm.s) <= RT_SIZEOFMEMB(GVM,gmm.padding));
717
718 pGVM->gmm.s.enmPolicy = GMMOCPOLICY_INVALID;
719 pGVM->gmm.s.enmPriority = GMMPRIORITY_INVALID;
720 pGVM->gmm.s.fMayAllocate = false;
721}
722
723
724/**
725 * Cleans up when a VM is terminating.
726 *
727 * @param pGVM Pointer to the Global VM structure.
728 */
729GMMR0DECL(void) GMMR0CleanupVM(PGVM pGVM)
730{
731 LogFlow(("GMMR0CleanupVM: pGVM=%p:{.pVM=%p, .hSelf=%#x}\n", pGVM, pGVM->pVM, pGVM->hSelf));
732
733 PGMM pGMM;
734 GMM_GET_VALID_INSTANCE_VOID(pGMM);
735
736 int rc = RTSemFastMutexRequest(pGMM->Mtx);
737 AssertRC(rc);
738
739 /*
740 * The policy is 'INVALID' until the initial reservation
741 * request has been serviced.
742 */
743 if ( pGVM->gmm.s.enmPolicy > GMMOCPOLICY_INVALID
744 || pGVM->gmm.s.enmPolicy < GMMOCPOLICY_END)
745 {
746 /*
747 * If it's the last VM around, we can skip walking all the chunk looking
748 * for the pages owned by this VM and instead flush the whole shebang.
749 *
750 * This takes care of the eventuality that a VM has left shared page
751 * references behind (shouldn't happen of course, but you never know).
752 */
753 Assert(pGMM->cRegisteredVMs);
754 pGMM->cRegisteredVMs--;
755#if 0 /* disabled so it won't hide bugs. */
756 if (!pGMM->cRegisteredVMs)
757 {
758 RTAvlU32Destroy(&pGMM->pChunks, gmmR0CleanupVMDestroyChunk, pGMM);
759
760 for (unsigned i = 0; i < RT_ELEMENTS(pGMM->ChunkTLB.aEntries); i++)
761 {
762 pGMM->ChunkTLB.aEntries[i].idChunk = NIL_GMM_CHUNKID;
763 pGMM->ChunkTLB.aEntries[i].pChunk = NULL;
764 }
765
766 memset(&pGMM->Private, 0, sizeof(pGMM->Private));
767 memset(&pGMM->Shared, 0, sizeof(pGMM->Shared));
768
769 memset(&pGMM->bmChunkId[0], 0, sizeof(pGMM->bmChunkId));
770 ASMBitSet(&pGMM->bmChunkId[0], NIL_GMM_CHUNKID);
771
772 pGMM->cReservedPages = 0;
773 pGMM->cOverCommittedPages = 0;
774 pGMM->cAllocatedPages = 0;
775 pGMM->cSharedPages = 0;
776 pGMM->cLeftBehindSharedPages = 0;
777 pGMM->cChunks = 0;
778 pGMM->cBalloonedPages = 0;
779 }
780 else
781#endif
782 {
783 /*
784 * Walk the entire pool looking for pages that belongs to this VM
785 * and left over mappings. (This'll only catch private pages, shared
786 * pages will be 'left behind'.)
787 */
788 uint64_t cPrivatePages = pGVM->gmm.s.cPrivatePages; /* save */
789 RTAvlU32DoWithAll(&pGMM->pChunks, true /* fFromLeft */, gmmR0CleanupVMScanChunk, pGVM);
790 if (pGVM->gmm.s.cPrivatePages)
791 SUPR0Printf("GMMR0CleanupVM: hGVM=%#x has %#x private pages that cannot be found!\n", pGVM->hSelf, pGVM->gmm.s.cPrivatePages);
792 pGMM->cAllocatedPages -= cPrivatePages;
793
794 /* free empty chunks. */
795 if (cPrivatePages)
796 {
797 PGMMCHUNK pCur = pGMM->Private.apLists[RT_ELEMENTS(pGMM->Private.apLists) - 1];
798 while (pCur)
799 {
800 PGMMCHUNK pNext = pCur->pFreeNext;
801 if ( pCur->cFree == GMM_CHUNK_NUM_PAGES
802 && (!pGMM->fLegacyMode || pCur->hGVM == pGVM->hSelf))
803 gmmR0FreeChunk(pGMM, pCur);
804 pCur = pNext;
805 }
806 }
807
808 /* account for shared pages that weren't freed. */
809 if (pGVM->gmm.s.cSharedPages)
810 {
811 Assert(pGMM->cSharedPages >= pGVM->gmm.s.cSharedPages);
812 SUPR0Printf("GMMR0CleanupVM: hGVM=%#x left %#x shared pages behind!\n", pGVM->hSelf, pGVM->gmm.s.cSharedPages);
813 pGMM->cLeftBehindSharedPages += pGVM->gmm.s.cSharedPages;
814 }
815
816 /*
817 * Update the over-commitment management statistics.
818 */
819 pGMM->cReservedPages -= pGVM->gmm.s.Reserved.cBasePages
820 + pGVM->gmm.s.Reserved.cFixedPages
821 + pGVM->gmm.s.Reserved.cShadowPages;
822 switch (pGVM->gmm.s.enmPolicy)
823 {
824 case GMMOCPOLICY_NO_OC:
825 break;
826 default:
827 /** @todo Update GMM->cOverCommittedPages */
828 break;
829 }
830 }
831 }
832
833 /* zap the GVM data. */
834 pGVM->gmm.s.enmPolicy = GMMOCPOLICY_INVALID;
835 pGVM->gmm.s.enmPriority = GMMPRIORITY_INVALID;
836 pGVM->gmm.s.fMayAllocate = false;
837
838 RTSemFastMutexRelease(pGMM->Mtx);
839
840 LogFlow(("GMMR0CleanupVM: returns\n"));
841}
842
843
844/**
845 * RTAvlU32DoWithAll callback.
846 *
847 * @returns 0
848 * @param pNode The node to search.
849 * @param pvGVM Pointer to the shared VM structure.
850 */
851static DECLCALLBACK(int) gmmR0CleanupVMScanChunk(PAVLU32NODECORE pNode, void *pvGVM)
852{
853 PGMMCHUNK pChunk = (PGMMCHUNK)pNode;
854 PGVM pGVM = (PGVM)pvGVM;
855
856 /*
857 * Look for pages belonging to the VM.
858 * (Perform some internal checks while we're scanning.)
859 */
860#ifndef VBOX_STRICT
861 if (pChunk->cFree != (GMM_CHUNK_SIZE >> PAGE_SHIFT))
862#endif
863 {
864 unsigned cPrivate = 0;
865 unsigned cShared = 0;
866 unsigned cFree = 0;
867
868 uint16_t hGVM = pGVM->hSelf;
869 unsigned iPage = (GMM_CHUNK_SIZE >> PAGE_SHIFT);
870 while (iPage-- > 0)
871 if (GMM_PAGE_IS_PRIVATE(&pChunk->aPages[iPage]))
872 {
873 if (pChunk->aPages[iPage].Private.hGVM == hGVM)
874 {
875 /*
876 * Free the page.
877 *
878 * The reason for not using gmmR0FreePrivatePage here is that we
879 * must *not* cause the chunk to be freed from under us - we're in
880 * a AVL tree walk here.
881 */
882 pChunk->aPages[iPage].u = 0;
883 pChunk->aPages[iPage].Free.iNext = pChunk->iFreeHead;
884 pChunk->aPages[iPage].Free.u2State = GMM_PAGE_STATE_FREE;
885 pChunk->iFreeHead = iPage;
886 pChunk->cPrivate--;
887 if ((pChunk->cFree & GMM_CHUNK_FREE_SET_MASK) == 0)
888 {
889 gmmR0UnlinkChunk(pChunk);
890 pChunk->cFree++;
891 gmmR0LinkChunk(pChunk, pChunk->cShared ? &g_pGMM->Shared : &g_pGMM->Private);
892 }
893 else
894 pChunk->cFree++;
895 pGVM->gmm.s.cPrivatePages--;
896 cFree++;
897 }
898 else
899 cPrivate++;
900 }
901 else if (GMM_PAGE_IS_FREE(&pChunk->aPages[iPage]))
902 cFree++;
903 else
904 cShared++;
905
906 /*
907 * Did it add up?
908 */
909 if (RT_UNLIKELY( pChunk->cFree != cFree
910 || pChunk->cPrivate != cPrivate
911 || pChunk->cShared != cShared))
912 {
913 SUPR0Printf("gmmR0CleanupVMScanChunk: Chunk %p/%#x has bogus stats - free=%d/%d private=%d/%d shared=%d/%d\n",
914 pChunk->cFree, cFree, pChunk->cPrivate, cPrivate, pChunk->cShared, cShared);
915 pChunk->cFree = cFree;
916 pChunk->cPrivate = cPrivate;
917 pChunk->cShared = cShared;
918 }
919 }
920
921 /*
922 * Look for the mapping belonging to the terminating VM.
923 */
924 for (unsigned i = 0; i < pChunk->cMappings; i++)
925 if (pChunk->paMappings[i].pGVM == pGVM)
926 {
927 RTR0MEMOBJ MemObj = pChunk->paMappings[i].MapObj;
928
929 pChunk->cMappings--;
930 if (i < pChunk->cMappings)
931 pChunk->paMappings[i] = pChunk->paMappings[pChunk->cMappings];
932 pChunk->paMappings[pChunk->cMappings].pGVM = NULL;
933 pChunk->paMappings[pChunk->cMappings].MapObj = NIL_RTR0MEMOBJ;
934
935 int rc = RTR0MemObjFree(MemObj, false /* fFreeMappings (NA) */);
936 if (RT_FAILURE(rc))
937 {
938 SUPR0Printf("gmmR0CleanupVMScanChunk: %p/%#x: mapping #%x: RTRMemObjFree(%p,false) -> %d \n",
939 pChunk, pChunk->Core.Key, i, MemObj, rc);
940 AssertRC(rc);
941 }
942 break;
943 }
944
945 /*
946 * If not in legacy mode, we should reset the hGVM field
947 * if it has our handle in it.
948 */
949 if (pChunk->hGVM == pGVM->hSelf)
950 {
951 if (!g_pGMM->fLegacyMode)
952 pChunk->hGVM = NIL_GVM_HANDLE;
953 else if (pChunk->cFree != GMM_CHUNK_NUM_PAGES)
954 {
955 SUPR0Printf("gmmR0CleanupVMScanChunk: %p/%#x: cFree=%#x - it should be 0 in legacy mode!\n",
956 pChunk, pChunk->Core.Key, pChunk->cFree);
957 AssertMsgFailed(("%p/%#x: cFree=%#x - it should be 0 in legacy mode!\n", pChunk, pChunk->Core.Key, pChunk->cFree));
958
959 gmmR0UnlinkChunk(pChunk);
960 pChunk->cFree = GMM_CHUNK_NUM_PAGES;
961 gmmR0LinkChunk(pChunk, pChunk->cShared ? &g_pGMM->Shared : &g_pGMM->Private);
962 }
963 }
964
965 return 0;
966}
967
968
969/**
970 * RTAvlU32Destroy callback for GMMR0CleanupVM.
971 *
972 * @returns 0
973 * @param pNode The node (allocation chunk) to destroy.
974 * @param pvGVM Pointer to the shared VM structure.
975 */
976/*static*/ DECLCALLBACK(int) gmmR0CleanupVMDestroyChunk(PAVLU32NODECORE pNode, void *pvGVM)
977{
978 PGMMCHUNK pChunk = (PGMMCHUNK)pNode;
979 PGVM pGVM = (PGVM)pvGVM;
980
981 for (unsigned i = 0; i < pChunk->cMappings; i++)
982 {
983 if (pChunk->paMappings[i].pGVM != pGVM)
984 SUPR0Printf("gmmR0CleanupVMDestroyChunk: %p/%#x: mapping #%x: pGVM=%p exepcted %p\n", pChunk,
985 pChunk->Core.Key, i, pChunk->paMappings[i].pGVM, pGVM);
986 int rc = RTR0MemObjFree(pChunk->paMappings[i].MapObj, false /* fFreeMappings (NA) */);
987 if (RT_FAILURE(rc))
988 {
989 SUPR0Printf("gmmR0CleanupVMDestroyChunk: %p/%#x: mapping #%x: RTRMemObjFree(%p,false) -> %d \n", pChunk,
990 pChunk->Core.Key, i, pChunk->paMappings[i].MapObj, rc);
991 AssertRC(rc);
992 }
993 }
994
995 int rc = RTR0MemObjFree(pChunk->MemObj, true /* fFreeMappings */);
996 if (RT_FAILURE(rc))
997 {
998 SUPR0Printf("gmmR0CleanupVMDestroyChunk: %p/%#x: RTRMemObjFree(%p,true) -> %d (cMappings=%d)\n", pChunk,
999 pChunk->Core.Key, pChunk->MemObj, rc, pChunk->cMappings);
1000 AssertRC(rc);
1001 }
1002 pChunk->MemObj = NIL_RTR0MEMOBJ;
1003
1004 RTMemFree(pChunk->paMappings);
1005 pChunk->paMappings = NULL;
1006
1007 RTMemFree(pChunk);
1008 return 0;
1009}
1010
1011
1012/**
1013 * The initial resource reservations.
1014 *
1015 * This will make memory reservations according to policy and priority. If there isn't
1016 * sufficient resources available to sustain the VM this function will fail and all
1017 * future allocations requests will fail as well.
1018 *
1019 * These are just the initial reservations made very very early during the VM creation
1020 * process and will be adjusted later in the GMMR0UpdateReservation call after the
1021 * ring-3 init has completed.
1022 *
1023 * @returns VBox status code.
1024 * @retval VERR_GMM_MEMORY_RESERVATION_DECLINED
1025 * @retval VERR_GMM_
1026 *
1027 * @param pVM Pointer to the shared VM structure.
1028 * @param cBasePages The number of pages that may be allocated for the base RAM and ROMs.
1029 * This does not include MMIO2 and similar.
1030 * @param cShadowPages The number of pages that may be allocated for shadow pageing structures.
1031 * @param cFixedPages The number of pages that may be allocated for fixed objects like the
1032 * hyper heap, MMIO2 and similar.
1033 * @param enmPolicy The OC policy to use on this VM.
1034 * @param enmPriority The priority in an out-of-memory situation.
1035 *
1036 * @thread The creator thread / EMT.
1037 */
1038GMMR0DECL(int) GMMR0InitialReservation(PVM pVM, uint64_t cBasePages, uint32_t cShadowPages, uint32_t cFixedPages,
1039 GMMOCPOLICY enmPolicy, GMMPRIORITY enmPriority)
1040{
1041 LogFlow(("GMMR0InitialReservation: pVM=%p cBasePages=%#llx cShadowPages=%#x cFixedPages=%#x enmPolicy=%d enmPriority=%d\n",
1042 pVM, cBasePages, cShadowPages, cFixedPages, enmPolicy, enmPriority));
1043
1044 /*
1045 * Validate, get basics and take the semaphore.
1046 */
1047 PGMM pGMM;
1048 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
1049 PGVM pGVM = GVMMR0ByVM(pVM);
1050 if (!pGVM)
1051 return VERR_INVALID_PARAMETER;
1052 if (pGVM->hEMT != RTThreadNativeSelf())
1053 return VERR_NOT_OWNER;
1054
1055 AssertReturn(cBasePages, VERR_INVALID_PARAMETER);
1056 AssertReturn(cShadowPages, VERR_INVALID_PARAMETER);
1057 AssertReturn(cFixedPages, VERR_INVALID_PARAMETER);
1058 AssertReturn(enmPolicy > GMMOCPOLICY_INVALID && enmPolicy < GMMOCPOLICY_END, VERR_INVALID_PARAMETER);
1059 AssertReturn(enmPriority > GMMPRIORITY_INVALID && enmPriority < GMMPRIORITY_END, VERR_INVALID_PARAMETER);
1060
1061 int rc = RTSemFastMutexRequest(pGMM->Mtx);
1062 AssertRC(rc);
1063
1064 if ( !pGVM->gmm.s.Reserved.cBasePages
1065 && !pGVM->gmm.s.Reserved.cFixedPages
1066 && !pGVM->gmm.s.Reserved.cShadowPages)
1067 {
1068 /*
1069 * Check if we can accomodate this.
1070 */
1071 /* ... later ... */
1072 if (RT_SUCCESS(rc))
1073 {
1074 /*
1075 * Update the records.
1076 */
1077 pGVM->gmm.s.Reserved.cBasePages = cBasePages;
1078 pGVM->gmm.s.Reserved.cFixedPages = cFixedPages;
1079 pGVM->gmm.s.Reserved.cShadowPages = cShadowPages;
1080 pGVM->gmm.s.enmPolicy = enmPolicy;
1081 pGVM->gmm.s.enmPriority = enmPriority;
1082 pGVM->gmm.s.fMayAllocate = true;
1083
1084 pGMM->cReservedPages += cBasePages + cFixedPages + cShadowPages;
1085 pGMM->cRegisteredVMs++;
1086 }
1087 }
1088 else
1089 rc = VERR_WRONG_ORDER;
1090
1091 RTSemFastMutexRelease(pGMM->Mtx);
1092 LogFlow(("GMMR0InitialReservation: returns %Rrc\n", rc));
1093 return rc;
1094}
1095
1096
1097/**
1098 * VMMR0 request wrapper for GMMR0InitialReservation.
1099 *
1100 * @returns see GMMR0InitialReservation.
1101 * @param pVM Pointer to the shared VM structure.
1102 * @param pReq The request packet.
1103 */
1104GMMR0DECL(int) GMMR0InitialReservationReq(PVM pVM, PGMMINITIALRESERVATIONREQ pReq)
1105{
1106 /*
1107 * Validate input and pass it on.
1108 */
1109 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1110 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1111 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
1112
1113 return GMMR0InitialReservation(pVM, pReq->cBasePages, pReq->cShadowPages, pReq->cFixedPages, pReq->enmPolicy, pReq->enmPriority);
1114}
1115
1116
1117/**
1118 * This updates the memory reservation with the additional MMIO2 and ROM pages.
1119 *
1120 * @returns VBox status code.
1121 * @retval VERR_GMM_MEMORY_RESERVATION_DECLINED
1122 *
1123 * @param pVM Pointer to the shared VM structure.
1124 * @param cBasePages The number of pages that may be allocated for the base RAM and ROMs.
1125 * This does not include MMIO2 and similar.
1126 * @param cShadowPages The number of pages that may be allocated for shadow pageing structures.
1127 * @param cFixedPages The number of pages that may be allocated for fixed objects like the
1128 * hyper heap, MMIO2 and similar.
1129 *
1130 * @thread EMT.
1131 */
1132GMMR0DECL(int) GMMR0UpdateReservation(PVM pVM, uint64_t cBasePages, uint32_t cShadowPages, uint32_t cFixedPages)
1133{
1134 LogFlow(("GMMR0UpdateReservation: pVM=%p cBasePages=%#llx cShadowPages=%#x cFixedPages=%#x\n",
1135 pVM, cBasePages, cShadowPages, cFixedPages));
1136
1137 /*
1138 * Validate, get basics and take the semaphore.
1139 */
1140 PGMM pGMM;
1141 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
1142 PGVM pGVM = GVMMR0ByVM(pVM);
1143 if (!pGVM)
1144 return VERR_INVALID_PARAMETER;
1145 if (pGVM->hEMT != RTThreadNativeSelf())
1146 return VERR_NOT_OWNER;
1147
1148 AssertReturn(cBasePages, VERR_INVALID_PARAMETER);
1149 AssertReturn(cShadowPages, VERR_INVALID_PARAMETER);
1150 AssertReturn(cFixedPages, VERR_INVALID_PARAMETER);
1151
1152 int rc = RTSemFastMutexRequest(pGMM->Mtx);
1153 AssertRC(rc);
1154
1155 if ( pGVM->gmm.s.Reserved.cBasePages
1156 && pGVM->gmm.s.Reserved.cFixedPages
1157 && pGVM->gmm.s.Reserved.cShadowPages)
1158 {
1159 /*
1160 * Check if we can accomodate this.
1161 */
1162 /* ... later ... */
1163 if (RT_SUCCESS(rc))
1164 {
1165 /*
1166 * Update the records.
1167 */
1168 pGMM->cReservedPages -= pGVM->gmm.s.Reserved.cBasePages
1169 + pGVM->gmm.s.Reserved.cFixedPages
1170 + pGVM->gmm.s.Reserved.cShadowPages;
1171 pGMM->cReservedPages += cBasePages + cFixedPages + cShadowPages;
1172
1173 pGVM->gmm.s.Reserved.cBasePages = cBasePages;
1174 pGVM->gmm.s.Reserved.cFixedPages = cFixedPages;
1175 pGVM->gmm.s.Reserved.cShadowPages = cShadowPages;
1176 }
1177 }
1178 else
1179 rc = VERR_WRONG_ORDER;
1180
1181 RTSemFastMutexRelease(pGMM->Mtx);
1182 LogFlow(("GMMR0UpdateReservation: returns %Rrc\n", rc));
1183 return rc;
1184}
1185
1186
1187/**
1188 * VMMR0 request wrapper for GMMR0UpdateReservation.
1189 *
1190 * @returns see GMMR0UpdateReservation.
1191 * @param pVM Pointer to the shared VM structure.
1192 * @param pReq The request packet.
1193 */
1194GMMR0DECL(int) GMMR0UpdateReservationReq(PVM pVM, PGMMUPDATERESERVATIONREQ pReq)
1195{
1196 /*
1197 * Validate input and pass it on.
1198 */
1199 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1200 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1201 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
1202
1203 return GMMR0UpdateReservation(pVM, pReq->cBasePages, pReq->cShadowPages, pReq->cFixedPages);
1204}
1205
1206
1207/**
1208 * Looks up a chunk in the tree and fill in the TLB entry for it.
1209 *
1210 * This is not expected to fail and will bitch if it does.
1211 *
1212 * @returns Pointer to the allocation chunk, NULL if not found.
1213 * @param pGMM Pointer to the GMM instance.
1214 * @param idChunk The ID of the chunk to find.
1215 * @param pTlbe Pointer to the TLB entry.
1216 */
1217static PGMMCHUNK gmmR0GetChunkSlow(PGMM pGMM, uint32_t idChunk, PGMMCHUNKTLBE pTlbe)
1218{
1219 PGMMCHUNK pChunk = (PGMMCHUNK)RTAvlU32Get(&pGMM->pChunks, idChunk);
1220 AssertMsgReturn(pChunk, ("Chunk %#x not found!\n", idChunk), NULL);
1221 pTlbe->idChunk = idChunk;
1222 pTlbe->pChunk = pChunk;
1223 return pChunk;
1224}
1225
1226
1227/**
1228 * Finds a allocation chunk.
1229 *
1230 * This is not expected to fail and will bitch if it does.
1231 *
1232 * @returns Pointer to the allocation chunk, NULL if not found.
1233 * @param pGMM Pointer to the GMM instance.
1234 * @param idChunk The ID of the chunk to find.
1235 */
1236DECLINLINE(PGMMCHUNK) gmmR0GetChunk(PGMM pGMM, uint32_t idChunk)
1237{
1238 /*
1239 * Do a TLB lookup, branch if not in the TLB.
1240 */
1241 PGMMCHUNKTLBE pTlbe = &pGMM->ChunkTLB.aEntries[GMM_CHUNKTLB_IDX(idChunk)];
1242 if ( pTlbe->idChunk != idChunk
1243 || !pTlbe->pChunk)
1244 return gmmR0GetChunkSlow(pGMM, idChunk, pTlbe);
1245 return pTlbe->pChunk;
1246}
1247
1248
1249/**
1250 * Finds a page.
1251 *
1252 * This is not expected to fail and will bitch if it does.
1253 *
1254 * @returns Pointer to the page, NULL if not found.
1255 * @param pGMM Pointer to the GMM instance.
1256 * @param idPage The ID of the page to find.
1257 */
1258DECLINLINE(PGMMPAGE) gmmR0GetPage(PGMM pGMM, uint32_t idPage)
1259{
1260 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
1261 if (RT_LIKELY(pChunk))
1262 return &pChunk->aPages[idPage & GMM_PAGEID_IDX_MASK];
1263 return NULL;
1264}
1265
1266
1267/**
1268 * Unlinks the chunk from the free list it's currently on (if any).
1269 *
1270 * @param pChunk The allocation chunk.
1271 */
1272DECLINLINE(void) gmmR0UnlinkChunk(PGMMCHUNK pChunk)
1273{
1274 PGMMCHUNKFREESET pSet = pChunk->pSet;
1275 if (RT_LIKELY(pSet))
1276 {
1277 pSet->cPages -= pChunk->cFree;
1278
1279 PGMMCHUNK pPrev = pChunk->pFreePrev;
1280 PGMMCHUNK pNext = pChunk->pFreeNext;
1281 if (pPrev)
1282 pPrev->pFreeNext = pNext;
1283 else
1284 pSet->apLists[(pChunk->cFree - 1) >> GMM_CHUNK_FREE_SET_SHIFT] = pNext;
1285 if (pNext)
1286 pNext->pFreePrev = pPrev;
1287
1288 pChunk->pSet = NULL;
1289 pChunk->pFreeNext = NULL;
1290 pChunk->pFreePrev = NULL;
1291 }
1292 else
1293 {
1294 Assert(!pChunk->pFreeNext);
1295 Assert(!pChunk->pFreePrev);
1296 Assert(!pChunk->cFree);
1297 }
1298}
1299
1300
1301/**
1302 * Links the chunk onto the appropriate free list in the specified free set.
1303 *
1304 * If no free entries, it's not linked into any list.
1305 *
1306 * @param pChunk The allocation chunk.
1307 * @param pSet The free set.
1308 */
1309DECLINLINE(void) gmmR0LinkChunk(PGMMCHUNK pChunk, PGMMCHUNKFREESET pSet)
1310{
1311 Assert(!pChunk->pSet);
1312 Assert(!pChunk->pFreeNext);
1313 Assert(!pChunk->pFreePrev);
1314
1315 if (pChunk->cFree > 0)
1316 {
1317 pChunk->pSet = pSet;
1318 pChunk->pFreePrev = NULL;
1319 unsigned iList = (pChunk->cFree - 1) >> GMM_CHUNK_FREE_SET_SHIFT;
1320 pChunk->pFreeNext = pSet->apLists[iList];
1321 if (pChunk->pFreeNext)
1322 pChunk->pFreeNext->pFreePrev = pChunk;
1323 pSet->apLists[iList] = pChunk;
1324
1325 pSet->cPages += pChunk->cFree;
1326 }
1327}
1328
1329
1330/**
1331 * Frees a Chunk ID.
1332 *
1333 * @param pGMM Pointer to the GMM instance.
1334 * @param idChunk The Chunk ID to free.
1335 */
1336static void gmmR0FreeChunkId(PGMM pGMM, uint32_t idChunk)
1337{
1338 AssertReturnVoid(idChunk != NIL_GMM_CHUNKID);
1339 AssertMsg(ASMBitTest(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk));
1340 ASMAtomicBitClear(&pGMM->bmChunkId[0], idChunk);
1341}
1342
1343
1344/**
1345 * Allocates a new Chunk ID.
1346 *
1347 * @returns The Chunk ID.
1348 * @param pGMM Pointer to the GMM instance.
1349 */
1350static uint32_t gmmR0AllocateChunkId(PGMM pGMM)
1351{
1352 AssertCompile(!((GMM_CHUNKID_LAST + 1) & 31)); /* must be a multiple of 32 */
1353 AssertCompile(NIL_GMM_CHUNKID == 0);
1354
1355 /*
1356 * Try the next sequential one.
1357 */
1358 int32_t idChunk = ++pGMM->idChunkPrev;
1359#if 0 /* test the fallback first */
1360 if ( idChunk <= GMM_CHUNKID_LAST
1361 && idChunk > NIL_GMM_CHUNKID
1362 && !ASMAtomicBitTestAndSet(&pVMM->bmChunkId[0], idChunk))
1363 return idChunk;
1364#endif
1365
1366 /*
1367 * Scan sequentially from the last one.
1368 */
1369 if ( (uint32_t)idChunk < GMM_CHUNKID_LAST
1370 && idChunk > NIL_GMM_CHUNKID)
1371 {
1372 idChunk = ASMBitNextClear(&pGMM->bmChunkId[0], GMM_CHUNKID_LAST + 1, idChunk);
1373 if (idChunk > NIL_GMM_CHUNKID)
1374 {
1375 AssertMsgReturn(!ASMAtomicBitTestAndSet(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk), NIL_GMM_CHUNKID);
1376 return pGMM->idChunkPrev = idChunk;
1377 }
1378 }
1379
1380 /*
1381 * Ok, scan from the start.
1382 * We're not racing anyone, so there is no need to expect failures or have restart loops.
1383 */
1384 idChunk = ASMBitFirstClear(&pGMM->bmChunkId[0], GMM_CHUNKID_LAST + 1);
1385 AssertMsgReturn(idChunk > NIL_GMM_CHUNKID, ("%#x\n", idChunk), NIL_GVM_HANDLE);
1386 AssertMsgReturn(!ASMAtomicBitTestAndSet(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk), NIL_GMM_CHUNKID);
1387
1388 return pGMM->idChunkPrev = idChunk;
1389}
1390
1391
1392/**
1393 * Registers a new chunk of memory.
1394 *
1395 * This is called by both gmmR0AllocateOneChunk and GMMR0SeedChunk.
1396 *
1397 * @returns VBox status code.
1398 * @param pGMM Pointer to the GMM instance.
1399 * @param pSet Pointer to the set.
1400 * @param MemObj The memory object for the chunk.
1401 * @param hGVM The hGVM value. (Only used by GMMR0SeedChunk.)
1402 */
1403static int gmmR0RegisterChunk(PGMM pGMM, PGMMCHUNKFREESET pSet, RTR0MEMOBJ MemObj, uint16_t hGVM)
1404{
1405 int rc;
1406 PGMMCHUNK pChunk = (PGMMCHUNK)RTMemAllocZ(sizeof(*pChunk));
1407 if (pChunk)
1408 {
1409 /*
1410 * Initialize it.
1411 */
1412 pChunk->MemObj = MemObj;
1413 pChunk->cFree = GMM_CHUNK_NUM_PAGES;
1414 pChunk->hGVM = hGVM;
1415 pChunk->iFreeHead = 0;
1416 for (unsigned iPage = 0; iPage < RT_ELEMENTS(pChunk->aPages) - 1; iPage++)
1417 {
1418 pChunk->aPages[iPage].Free.u2State = GMM_PAGE_STATE_FREE;
1419 pChunk->aPages[iPage].Free.iNext = iPage + 1;
1420 }
1421 pChunk->aPages[RT_ELEMENTS(pChunk->aPages) - 1].Free.u2State = GMM_PAGE_STATE_FREE;
1422 pChunk->aPages[RT_ELEMENTS(pChunk->aPages) - 1].Free.iNext = UINT16_MAX;
1423
1424 /*
1425 * Allocate a Chunk ID and insert it into the tree.
1426 * It doesn't cost anything to be careful here.
1427 */
1428 pChunk->Core.Key = gmmR0AllocateChunkId(pGMM);
1429 if ( pChunk->Core.Key != NIL_GMM_CHUNKID
1430 && pChunk->Core.Key <= GMM_CHUNKID_LAST
1431 && RTAvlU32Insert(&pGMM->pChunks, &pChunk->Core))
1432 {
1433 pGMM->cChunks++;
1434 gmmR0LinkChunk(pChunk, pSet);
1435 LogFlow(("gmmR0RegisterChunk: pChunk=%p id=%#x cChunks=%d\n", pChunk, pChunk->Core.Key, pGMM->cChunks));
1436 return VINF_SUCCESS;
1437 }
1438
1439 rc = VERR_INTERNAL_ERROR;
1440 RTMemFree(pChunk);
1441 }
1442 else
1443 rc = VERR_NO_MEMORY;
1444 return rc;
1445}
1446
1447
1448/**
1449 * Allocate one new chunk and add it to the specified free set.
1450 *
1451 * @returns VBox status code.
1452 * @param pGMM Pointer to the GMM instance.
1453 * @param pSet Pointer to the set.
1454 */
1455static int gmmR0AllocateOneChunk(PGMM pGMM, PGMMCHUNKFREESET pSet)
1456{
1457 /*
1458 * Allocate the memory.
1459 */
1460 RTR0MEMOBJ MemObj;
1461 int rc = RTR0MemObjAllocPhysNC(&MemObj, GMM_CHUNK_SIZE, NIL_RTHCPHYS);
1462 if (RT_SUCCESS(rc))
1463 {
1464 rc = gmmR0RegisterChunk(pGMM, pSet, MemObj, NIL_GVM_HANDLE);
1465 if (RT_FAILURE(rc))
1466 RTR0MemObjFree(MemObj, false /* fFreeMappings */);
1467 }
1468 return rc;
1469}
1470
1471
1472/**
1473 * Attempts to allocate more pages until the requested amount is met.
1474 *
1475 * @returns VBox status code.
1476 * @param pGMM Pointer to the GMM instance data.
1477 * @param pSet Pointer to the free set to grow.
1478 * @param cPages The number of pages needed.
1479 */
1480static int gmmR0AllocateMoreChunks(PGMM pGMM, PGMMCHUNKFREESET pSet, uint32_t cPages)
1481{
1482 Assert(!pGMM->fLegacyMode);
1483
1484 /*
1485 * Try steal free chunks from the other set first. (Only take 100% free chunks.)
1486 */
1487 PGMMCHUNKFREESET pOtherSet = pSet == &pGMM->Private ? &pGMM->Shared : &pGMM->Private;
1488 while ( pSet->cPages < cPages
1489 && pOtherSet->cPages >= GMM_CHUNK_NUM_PAGES)
1490 {
1491 PGMMCHUNK pChunk = pOtherSet->apLists[GMM_CHUNK_FREE_SET_LISTS - 1];
1492 while (pChunk && pChunk->cFree != GMM_CHUNK_NUM_PAGES)
1493 pChunk = pChunk->pFreeNext;
1494 if (!pChunk)
1495 break;
1496
1497 gmmR0UnlinkChunk(pChunk);
1498 gmmR0LinkChunk(pChunk, pSet);
1499 }
1500
1501 /*
1502 * If we need still more pages, allocate new chunks.
1503 */
1504 while (pSet->cPages < cPages)
1505 {
1506 int rc = gmmR0AllocateOneChunk(pGMM, pSet);
1507 if (RT_FAILURE(rc))
1508 return rc;
1509 }
1510
1511 return VINF_SUCCESS;
1512}
1513
1514
1515/**
1516 * Allocates one private page.
1517 *
1518 * Worker for gmmR0AllocatePages.
1519 *
1520 * @param pGMM Pointer to the GMM instance data.
1521 * @param hGVM The GVM handle of the VM requesting memory.
1522 * @param pChunk The chunk to allocate it from.
1523 * @param pPageDesc The page descriptor.
1524 */
1525static void gmmR0AllocatePage(PGMM pGMM, uint32_t hGVM, PGMMCHUNK pChunk, PGMMPAGEDESC pPageDesc)
1526{
1527 /* update the chunk stats. */
1528 if (pChunk->hGVM == NIL_GVM_HANDLE)
1529 pChunk->hGVM = hGVM;
1530 Assert(pChunk->cFree);
1531 pChunk->cFree--;
1532 pChunk->cPrivate++;
1533
1534 /* unlink the first free page. */
1535 const uint32_t iPage = pChunk->iFreeHead;
1536 AssertReleaseMsg(iPage < RT_ELEMENTS(pChunk->aPages), ("%d\n", iPage));
1537 PGMMPAGE pPage = &pChunk->aPages[iPage];
1538 Assert(GMM_PAGE_IS_FREE(pPage));
1539 pChunk->iFreeHead = pPage->Free.iNext;
1540 Log3(("A pPage=%p iPage=%#x/%#x u2State=%d iFreeHead=%#x iNext=%#x\n",
1541 pPage, iPage, (pChunk->Core.Key << GMM_CHUNKID_SHIFT) | iPage,
1542 pPage->Common.u2State, pChunk->iFreeHead, pPage->Free.iNext));
1543
1544 /* make the page private. */
1545 pPage->u = 0;
1546 AssertCompile(GMM_PAGE_STATE_PRIVATE == 0);
1547 pPage->Private.hGVM = hGVM;
1548 AssertCompile(NIL_RTHCPHYS >= GMM_GCPHYS_LAST);
1549 AssertCompile(GMM_GCPHYS_UNSHAREABLE >= GMM_GCPHYS_LAST);
1550 if (pPageDesc->HCPhysGCPhys <= GMM_GCPHYS_LAST)
1551 pPage->Private.pfn = pPageDesc->HCPhysGCPhys >> PAGE_SHIFT;
1552 else
1553 pPage->Private.pfn = GMM_PAGE_PFN_UNSHAREABLE; /* unshareable / unassigned - same thing. */
1554
1555 /* update the page descriptor. */
1556 pPageDesc->HCPhysGCPhys = RTR0MemObjGetPagePhysAddr(pChunk->MemObj, iPage);
1557 Assert(pPageDesc->HCPhysGCPhys != NIL_RTHCPHYS);
1558 pPageDesc->idPage = (pChunk->Core.Key << GMM_CHUNKID_SHIFT) | iPage;
1559 pPageDesc->idSharedPage = NIL_GMM_PAGEID;
1560}
1561
1562
1563/**
1564 * Common worker for GMMR0AllocateHandyPages and GMMR0AllocatePages.
1565 *
1566 * @returns VBox status code:
1567 * @retval VINF_SUCCESS on success.
1568 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
1569 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
1570 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
1571 * that is we're trying to allocate more than we've reserved.
1572 *
1573 * @param pGMM Pointer to the GMM instance data.
1574 * @param pGVM Pointer to the shared VM structure.
1575 * @param cPages The number of pages to allocate.
1576 * @param paPages Pointer to the page descriptors.
1577 * See GMMPAGEDESC for details on what is expected on input.
1578 * @param enmAccount The account to charge.
1579 */
1580static int gmmR0AllocatePages(PGMM pGMM, PGVM pGVM, uint32_t cPages, PGMMPAGEDESC paPages, GMMACCOUNT enmAccount)
1581{
1582 /*
1583 * Check allocation limits.
1584 */
1585 if (RT_UNLIKELY(pGMM->cAllocatedPages + cPages > pGMM->cMaxPages))
1586 return VERR_GMM_HIT_GLOBAL_LIMIT;
1587
1588 switch (enmAccount)
1589 {
1590 case GMMACCOUNT_BASE:
1591 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages + cPages > pGVM->gmm.s.Reserved.cBasePages))
1592 {
1593 Log(("gmmR0AllocatePages: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1594 pGVM->gmm.s.Reserved.cBasePages, pGVM->gmm.s.Allocated.cBasePages, cPages));
1595 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1596 }
1597 break;
1598 case GMMACCOUNT_SHADOW:
1599 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cShadowPages + cPages > pGVM->gmm.s.Reserved.cShadowPages))
1600 {
1601 Log(("gmmR0AllocatePages: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1602 pGVM->gmm.s.Reserved.cShadowPages, pGVM->gmm.s.Allocated.cShadowPages, cPages));
1603 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1604 }
1605 break;
1606 case GMMACCOUNT_FIXED:
1607 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cFixedPages + cPages > pGVM->gmm.s.Reserved.cFixedPages))
1608 {
1609 Log(("gmmR0AllocatePages: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1610 pGVM->gmm.s.Reserved.cFixedPages, pGVM->gmm.s.Allocated.cFixedPages, cPages));
1611 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1612 }
1613 break;
1614 default:
1615 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
1616 }
1617
1618 /*
1619 * Check if we need to allocate more memory or not. In legacy mode this is
1620 * a bit extra work but it's easier to do it upfront than bailing out later.
1621 */
1622 PGMMCHUNKFREESET pSet = &pGMM->Private;
1623 if (pSet->cPages < cPages)
1624 {
1625 if (pGMM->fLegacyMode)
1626 return VERR_GMM_SEED_ME;
1627
1628 int rc = gmmR0AllocateMoreChunks(pGMM, pSet, cPages);
1629 if (RT_FAILURE(rc))
1630 return rc;
1631 Assert(pSet->cPages >= cPages);
1632 }
1633 else if (pGMM->fLegacyMode)
1634 {
1635 uint16_t hGVM = pGVM->hSelf;
1636 uint32_t cPagesFound = 0;
1637 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists); i++)
1638 for (PGMMCHUNK pCur = pSet->apLists[i]; pCur; pCur = pCur->pFreeNext)
1639 if (pCur->hGVM == hGVM)
1640 {
1641 cPagesFound += pCur->cFree;
1642 if (cPagesFound >= cPages)
1643 break;
1644 }
1645 if (cPagesFound < cPages)
1646 return VERR_GMM_SEED_ME;
1647 }
1648
1649 /*
1650 * Pick the pages.
1651 */
1652 uint16_t hGVM = pGVM->hSelf;
1653 uint32_t iPage = 0;
1654 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists) && iPage < cPages; i++)
1655 {
1656 /* first round, pick from chunks with an affinity to the VM. */
1657 PGMMCHUNK pCur = pSet->apLists[i];
1658 while (pCur && iPage < cPages)
1659 {
1660 PGMMCHUNK pNext = pCur->pFreeNext;
1661
1662 if ( pCur->hGVM == hGVM
1663 && ( pCur->cFree <= GMM_CHUNK_NUM_PAGES
1664 || pGMM->fLegacyMode))
1665 {
1666 gmmR0UnlinkChunk(pCur);
1667 for (; pCur->cFree && iPage < cPages; iPage++)
1668 gmmR0AllocatePage(pGMM, hGVM, pCur, &paPages[iPage]);
1669 gmmR0LinkChunk(pCur, pSet);
1670 }
1671
1672 pCur = pNext;
1673 }
1674
1675 /* second round, take all free pages in this list. */
1676 if (!pGMM->fLegacyMode)
1677 {
1678 PGMMCHUNK pCur = pSet->apLists[i];
1679 while (pCur && iPage < cPages)
1680 {
1681 PGMMCHUNK pNext = pCur->pFreeNext;
1682
1683 gmmR0UnlinkChunk(pCur);
1684 for (; pCur->cFree && iPage < cPages; iPage++)
1685 gmmR0AllocatePage(pGMM, hGVM, pCur, &paPages[iPage]);
1686 gmmR0LinkChunk(pCur, pSet);
1687
1688 pCur = pNext;
1689 }
1690 }
1691 }
1692
1693 /*
1694 * Update the account.
1695 */
1696 switch (enmAccount)
1697 {
1698 case GMMACCOUNT_BASE: pGVM->gmm.s.Allocated.cBasePages += iPage; break;
1699 case GMMACCOUNT_SHADOW: pGVM->gmm.s.Allocated.cShadowPages += iPage; break;
1700 case GMMACCOUNT_FIXED: pGVM->gmm.s.Allocated.cFixedPages += iPage; break;
1701 default:
1702 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
1703 }
1704 pGVM->gmm.s.cPrivatePages += iPage;
1705 pGMM->cAllocatedPages += iPage;
1706
1707 AssertMsgReturn(iPage == cPages, ("%d != %d\n", iPage, cPages), VERR_INTERNAL_ERROR);
1708
1709 /*
1710 * Check if we've reached some threshold and should kick one or two VMs and tell
1711 * them to inflate their balloons a bit more... later.
1712 */
1713
1714 return VINF_SUCCESS;
1715}
1716
1717
1718/**
1719 * Updates the previous allocations and allocates more pages.
1720 *
1721 * The handy pages are always taken from the 'base' memory account.
1722 * The allocated pages are not cleared and will contains random garbage.
1723 *
1724 * @returns VBox status code:
1725 * @retval VINF_SUCCESS on success.
1726 * @retval VERR_NOT_OWNER if the caller is not an EMT.
1727 * @retval VERR_GMM_PAGE_NOT_FOUND if one of the pages to update wasn't found.
1728 * @retval VERR_GMM_PAGE_NOT_PRIVATE if one of the pages to update wasn't a
1729 * private page.
1730 * @retval VERR_GMM_PAGE_NOT_SHARED if one of the pages to update wasn't a
1731 * shared page.
1732 * @retval VERR_GMM_NOT_PAGE_OWNER if one of the pages to be updated wasn't
1733 * owned by the VM.
1734 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
1735 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
1736 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
1737 * that is we're trying to allocate more than we've reserved.
1738 *
1739 * @param pVM Pointer to the shared VM structure.
1740 * @param cPagesToUpdate The number of pages to update (starting from the head).
1741 * @param cPagesToAlloc The number of pages to allocate (starting from the head).
1742 * @param paPages The array of page descriptors.
1743 * See GMMPAGEDESC for details on what is expected on input.
1744 * @thread EMT.
1745 */
1746GMMR0DECL(int) GMMR0AllocateHandyPages(PVM pVM, uint32_t cPagesToUpdate, uint32_t cPagesToAlloc, PGMMPAGEDESC paPages)
1747{
1748 LogFlow(("GMMR0AllocateHandyPages: pVM=%p cPagesToUpdate=%#x cPagesToAlloc=%#x paPages=%p\n",
1749 pVM, cPagesToUpdate, cPagesToAlloc, paPages));
1750
1751 /*
1752 * Validate, get basics and take the semaphore.
1753 * (This is a relatively busy path, so make predictions where possible.)
1754 */
1755 PGMM pGMM;
1756 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
1757 PGVM pGVM = GVMMR0ByVM(pVM);
1758 if (RT_UNLIKELY(!pGVM))
1759 return VERR_INVALID_PARAMETER;
1760 if (RT_UNLIKELY(pGVM->hEMT != RTThreadNativeSelf()))
1761 return VERR_NOT_OWNER;
1762
1763 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
1764 AssertMsgReturn( (cPagesToUpdate && cPagesToUpdate < 1024)
1765 || (cPagesToAlloc && cPagesToAlloc < 1024),
1766 ("cPagesToUpdate=%#x cPagesToAlloc=%#x\n", cPagesToUpdate, cPagesToAlloc),
1767 VERR_INVALID_PARAMETER);
1768
1769 unsigned iPage = 0;
1770 for (; iPage < cPagesToUpdate; iPage++)
1771 {
1772 AssertMsgReturn( ( paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST
1773 && !(paPages[iPage].HCPhysGCPhys & PAGE_OFFSET_MASK))
1774 || paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS
1775 || paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE,
1776 ("#%#x: %RHp\n", iPage, paPages[iPage].HCPhysGCPhys),
1777 VERR_INVALID_PARAMETER);
1778 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
1779 /*|| paPages[iPage].idPage == NIL_GMM_PAGEID*/,
1780 ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
1781 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
1782 /*|| paPages[iPage].idSharedPage == NIL_GMM_PAGEID*/,
1783 ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
1784 }
1785
1786 for (; iPage < cPagesToAlloc; iPage++)
1787 {
1788 AssertMsgReturn(paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS, ("#%#x: %RHp\n", iPage, paPages[iPage].HCPhysGCPhys), VERR_INVALID_PARAMETER);
1789 AssertMsgReturn(paPages[iPage].idPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
1790 AssertMsgReturn(paPages[iPage].idSharedPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
1791 }
1792
1793 int rc = RTSemFastMutexRequest(pGMM->Mtx);
1794 AssertRC(rc);
1795
1796 /* No allocations before the initial reservation has been made! */
1797 if (RT_LIKELY( pGVM->gmm.s.Reserved.cBasePages
1798 && pGVM->gmm.s.Reserved.cFixedPages
1799 && pGVM->gmm.s.Reserved.cShadowPages))
1800 {
1801 /*
1802 * Perform the updates.
1803 * Stop on the first error.
1804 */
1805 for (iPage = 0; iPage < cPagesToUpdate; iPage++)
1806 {
1807 if (paPages[iPage].idPage != NIL_GMM_PAGEID)
1808 {
1809 PGMMPAGE pPage = gmmR0GetPage(pGMM, paPages[iPage].idPage);
1810 if (RT_LIKELY(pPage))
1811 {
1812 if (RT_LIKELY(GMM_PAGE_IS_PRIVATE(pPage)))
1813 {
1814 if (RT_LIKELY(pPage->Private.hGVM == pGVM->hSelf))
1815 {
1816 AssertCompile(NIL_RTHCPHYS > GMM_GCPHYS_LAST && GMM_GCPHYS_UNSHAREABLE > GMM_GCPHYS_LAST);
1817 if (RT_LIKELY(paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST))
1818 pPage->Private.pfn = paPages[iPage].HCPhysGCPhys >> PAGE_SHIFT;
1819 else if (paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE)
1820 pPage->Private.pfn = GMM_PAGE_PFN_UNSHAREABLE;
1821 /* else: NIL_RTHCPHYS nothing */
1822
1823 paPages[iPage].idPage = NIL_GMM_PAGEID;
1824 paPages[iPage].HCPhysGCPhys = NIL_RTHCPHYS;
1825 }
1826 else
1827 {
1828 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not owner! hGVM=%#x hSelf=%#x\n",
1829 iPage, paPages[iPage].idPage, pPage->Private.hGVM, pGVM->hSelf));
1830 rc = VERR_GMM_NOT_PAGE_OWNER;
1831 break;
1832 }
1833 }
1834 else
1835 {
1836 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not private! %.*Rhxs\n", iPage, paPages[iPage].idPage, sizeof(*pPage), pPage));
1837 rc = VERR_GMM_PAGE_NOT_PRIVATE;
1838 break;
1839 }
1840 }
1841 else
1842 {
1843 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not found! (private)\n", iPage, paPages[iPage].idPage));
1844 rc = VERR_GMM_PAGE_NOT_FOUND;
1845 break;
1846 }
1847 }
1848
1849 if (paPages[iPage].idSharedPage != NIL_GMM_PAGEID)
1850 {
1851 PGMMPAGE pPage = gmmR0GetPage(pGMM, paPages[iPage].idSharedPage);
1852 if (RT_LIKELY(pPage))
1853 {
1854 if (RT_LIKELY(GMM_PAGE_IS_SHARED(pPage)))
1855 {
1856 AssertCompile(NIL_RTHCPHYS > GMM_GCPHYS_LAST && GMM_GCPHYS_UNSHAREABLE > GMM_GCPHYS_LAST);
1857 Assert(pPage->Shared.cRefs);
1858 Assert(pGVM->gmm.s.cSharedPages);
1859 Assert(pGVM->gmm.s.Allocated.cBasePages);
1860
1861 pGVM->gmm.s.cSharedPages--;
1862 pGVM->gmm.s.Allocated.cBasePages--;
1863 if (!--pPage->Shared.cRefs)
1864 gmmR0FreeSharedPage(pGMM, paPages[iPage].idSharedPage, pPage);
1865
1866 paPages[iPage].idSharedPage = NIL_GMM_PAGEID;
1867 }
1868 else
1869 {
1870 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not shared!\n", iPage, paPages[iPage].idSharedPage));
1871 rc = VERR_GMM_PAGE_NOT_SHARED;
1872 break;
1873 }
1874 }
1875 else
1876 {
1877 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not found! (shared)\n", iPage, paPages[iPage].idSharedPage));
1878 rc = VERR_GMM_PAGE_NOT_FOUND;
1879 break;
1880 }
1881 }
1882 }
1883
1884 /*
1885 * Join paths with GMMR0AllocatePages for the allocation.
1886 */
1887 if (RT_SUCCESS(rc))
1888 rc = gmmR0AllocatePages(pGMM, pGVM, cPagesToAlloc, paPages, GMMACCOUNT_BASE);
1889 }
1890 else
1891 rc = VERR_WRONG_ORDER;
1892
1893 RTSemFastMutexRelease(pGMM->Mtx);
1894 LogFlow(("GMMR0AllocateHandyPages: returns %Rrc\n", rc));
1895 return rc;
1896}
1897
1898
1899/**
1900 * Allocate one or more pages.
1901 *
1902 * This is typically used for ROMs and MMIO2 (VRAM) during VM creation.
1903 * The allocated pages are not cleared and will contains random garbage.
1904 *
1905 * @returns VBox status code:
1906 * @retval VINF_SUCCESS on success.
1907 * @retval VERR_NOT_OWNER if the caller is not an EMT.
1908 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
1909 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
1910 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
1911 * that is we're trying to allocate more than we've reserved.
1912 *
1913 * @param pVM Pointer to the shared VM structure.
1914 * @param cPages The number of pages to allocate.
1915 * @param paPages Pointer to the page descriptors.
1916 * See GMMPAGEDESC for details on what is expected on input.
1917 * @param enmAccount The account to charge.
1918 *
1919 * @thread EMT.
1920 */
1921GMMR0DECL(int) GMMR0AllocatePages(PVM pVM, uint32_t cPages, PGMMPAGEDESC paPages, GMMACCOUNT enmAccount)
1922{
1923 LogFlow(("GMMR0AllocatePages: pVM=%p cPages=%#x paPages=%p enmAccount=%d\n", pVM, cPages, paPages, enmAccount));
1924
1925 /*
1926 * Validate, get basics and take the semaphore.
1927 */
1928 PGMM pGMM;
1929 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
1930 PGVM pGVM = GVMMR0ByVM(pVM);
1931 if (!pGVM)
1932 return VERR_INVALID_PARAMETER;
1933 if (pGVM->hEMT != RTThreadNativeSelf())
1934 return VERR_NOT_OWNER;
1935
1936 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
1937 AssertMsgReturn(enmAccount > GMMACCOUNT_INVALID && enmAccount < GMMACCOUNT_END, ("%d\n", enmAccount), VERR_INVALID_PARAMETER);
1938 AssertMsgReturn(cPages > 0 && cPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cPages), VERR_INVALID_PARAMETER);
1939
1940 for (unsigned iPage = 0; iPage < cPages; iPage++)
1941 {
1942 AssertMsgReturn( paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS
1943 || paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE
1944 || ( enmAccount == GMMACCOUNT_BASE
1945 && paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST
1946 && !(paPages[iPage].HCPhysGCPhys & PAGE_OFFSET_MASK)),
1947 ("#%#x: %RHp enmAccount=%d\n", iPage, paPages[iPage].HCPhysGCPhys, enmAccount),
1948 VERR_INVALID_PARAMETER);
1949 AssertMsgReturn(paPages[iPage].idPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
1950 AssertMsgReturn(paPages[iPage].idSharedPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
1951 }
1952
1953 int rc = RTSemFastMutexRequest(pGMM->Mtx);
1954 AssertRC(rc);
1955
1956 /* No allocations before the initial reservation has been made! */
1957 if ( pGVM->gmm.s.Reserved.cBasePages
1958 && pGVM->gmm.s.Reserved.cFixedPages
1959 && pGVM->gmm.s.Reserved.cShadowPages)
1960 rc = gmmR0AllocatePages(pGMM, pGVM, cPages, paPages, enmAccount);
1961 else
1962 rc = VERR_WRONG_ORDER;
1963
1964 RTSemFastMutexRelease(pGMM->Mtx);
1965 LogFlow(("GMMR0AllocatePages: returns %Rrc\n", rc));
1966 return rc;
1967}
1968
1969
1970/**
1971 * VMMR0 request wrapper for GMMR0AllocatePages.
1972 *
1973 * @returns see GMMR0AllocatePages.
1974 * @param pVM Pointer to the shared VM structure.
1975 * @param pReq The request packet.
1976 */
1977GMMR0DECL(int) GMMR0AllocatePagesReq(PVM pVM, PGMMALLOCATEPAGESREQ pReq)
1978{
1979 /*
1980 * Validate input and pass it on.
1981 */
1982 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1983 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1984 AssertMsgReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[0]),
1985 ("%#x < %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[0])),
1986 VERR_INVALID_PARAMETER);
1987 AssertMsgReturn(pReq->Hdr.cbReq == RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[pReq->cPages]),
1988 ("%#x != %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[pReq->cPages])),
1989 VERR_INVALID_PARAMETER);
1990
1991 return GMMR0AllocatePages(pVM, pReq->cPages, &pReq->aPages[0], pReq->enmAccount);
1992}
1993
1994
1995/**
1996 * Frees a chunk, giving it back to the host OS.
1997 *
1998 * @param pGMM Pointer to the GMM instance.
1999 * @param pChunk The chunk to free.
2000 */
2001static void gmmR0FreeChunk(PGMM pGMM, PGMMCHUNK pChunk)
2002{
2003 Assert(pChunk->Core.Key != NIL_GMM_CHUNKID);
2004
2005 /*
2006 * If there are current mappings of the chunk, then request the
2007 * VMs to unmap them. Reposition the chunk in the free list so
2008 * it won't be a likely candidate for allocations.
2009 */
2010 if (pChunk->cMappings)
2011 {
2012 /** @todo R0 -> VM request */
2013
2014 }
2015 else
2016 {
2017 /*
2018 * Try free the memory object.
2019 */
2020 int rc = RTR0MemObjFree(pChunk->MemObj, false /* fFreeMappings */);
2021 if (RT_SUCCESS(rc))
2022 {
2023 pChunk->MemObj = NIL_RTR0MEMOBJ;
2024
2025 /*
2026 * Unlink it from everywhere.
2027 */
2028 gmmR0UnlinkChunk(pChunk);
2029
2030 PAVLU32NODECORE pCore = RTAvlU32Remove(&pGMM->pChunks, pChunk->Core.Key);
2031 Assert(pCore == &pChunk->Core); NOREF(pCore);
2032
2033 PGMMCHUNKTLBE pTlbe = &pGMM->ChunkTLB.aEntries[GMM_CHUNKTLB_IDX(pChunk->Core.Key)];
2034 if (pTlbe->pChunk == pChunk)
2035 {
2036 pTlbe->idChunk = NIL_GMM_CHUNKID;
2037 pTlbe->pChunk = NULL;
2038 }
2039
2040 Assert(pGMM->cChunks > 0);
2041 pGMM->cChunks--;
2042
2043 /*
2044 * Free the Chunk ID and struct.
2045 */
2046 gmmR0FreeChunkId(pGMM, pChunk->Core.Key);
2047 pChunk->Core.Key = NIL_GMM_CHUNKID;
2048
2049 RTMemFree(pChunk->paMappings);
2050 pChunk->paMappings = NULL;
2051
2052 RTMemFree(pChunk);
2053 }
2054 else
2055 AssertRC(rc);
2056 }
2057}
2058
2059
2060/**
2061 * Free page worker.
2062 *
2063 * The caller does all the statistic decrementing, we do all the incrementing.
2064 *
2065 * @param pGMM Pointer to the GMM instance data.
2066 * @param pChunk Pointer to the chunk this page belongs to.
2067 * @param idPage The Page ID.
2068 * @param pPage Pointer to the page.
2069 */
2070static void gmmR0FreePageWorker(PGMM pGMM, PGMMCHUNK pChunk, uint32_t idPage, PGMMPAGE pPage)
2071{
2072 Log3(("F pPage=%p iPage=%#x/%#x u2State=%d iFreeHead=%#x\n",
2073 pPage, pPage - &pChunk->aPages[0], idPage, pPage->Common.u2State, pChunk->iFreeHead)); NOREF(idPage);
2074
2075 /*
2076 * Put the page on the free list.
2077 */
2078 pPage->u = 0;
2079 pPage->Free.u2State = GMM_PAGE_STATE_FREE;
2080 Assert(pChunk->iFreeHead < RT_ELEMENTS(pChunk->aPages) || pChunk->iFreeHead == UINT16_MAX);
2081 pPage->Free.iNext = pChunk->iFreeHead;
2082 pChunk->iFreeHead = pPage - &pChunk->aPages[0];
2083
2084 /*
2085 * Update statistics (the cShared/cPrivate stats are up to date already),
2086 * and relink the chunk if necessary.
2087 */
2088 if ((pChunk->cFree & GMM_CHUNK_FREE_SET_MASK) == 0)
2089 {
2090 gmmR0UnlinkChunk(pChunk);
2091 pChunk->cFree++;
2092 gmmR0LinkChunk(pChunk, pChunk->cShared ? &pGMM->Shared : &pGMM->Private);
2093 }
2094 else
2095 {
2096 pChunk->cFree++;
2097 pChunk->pSet->cPages++;
2098
2099 /*
2100 * If the chunk becomes empty, consider giving memory back to the host OS.
2101 *
2102 * The current strategy is to try give it back if there are other chunks
2103 * in this free list, meaning if there are at least 240 free pages in this
2104 * category. Note that since there are probably mappings of the chunk,
2105 * it won't be freed up instantly, which probably screws up this logic
2106 * a bit...
2107 */
2108 if (RT_UNLIKELY( pChunk->cFree == GMM_CHUNK_NUM_PAGES
2109 && pChunk->pFreeNext
2110 && pChunk->pFreePrev
2111 && !pGMM->fLegacyMode))
2112 gmmR0FreeChunk(pGMM, pChunk);
2113 }
2114}
2115
2116
2117/**
2118 * Frees a shared page, the page is known to exist and be valid and such.
2119 *
2120 * @param pGMM Pointer to the GMM instance.
2121 * @param idPage The Page ID
2122 * @param pPage The page structure.
2123 */
2124DECLINLINE(void) gmmR0FreeSharedPage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage)
2125{
2126 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2127 Assert(pChunk);
2128 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2129 Assert(pChunk->cShared > 0);
2130 Assert(pGMM->cSharedPages > 0);
2131 Assert(pGMM->cAllocatedPages > 0);
2132 Assert(!pPage->Shared.cRefs);
2133
2134 pChunk->cShared--;
2135 pGMM->cAllocatedPages--;
2136 pGMM->cSharedPages--;
2137 gmmR0FreePageWorker(pGMM, pChunk, idPage, pPage);
2138}
2139
2140
2141/**
2142 * Frees a private page, the page is known to exist and be valid and such.
2143 *
2144 * @param pGMM Pointer to the GMM instance.
2145 * @param idPage The Page ID
2146 * @param pPage The page structure.
2147 */
2148DECLINLINE(void) gmmR0FreePrivatePage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage)
2149{
2150 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2151 Assert(pChunk);
2152 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2153 Assert(pChunk->cPrivate > 0);
2154 Assert(pGMM->cAllocatedPages > 0);
2155
2156 pChunk->cPrivate--;
2157 pGMM->cAllocatedPages--;
2158 gmmR0FreePageWorker(pGMM, pChunk, idPage, pPage);
2159}
2160
2161
2162/**
2163 * Common worker for GMMR0FreePages and GMMR0BalloonedPages.
2164 *
2165 * @returns VBox status code:
2166 * @retval xxx
2167 *
2168 * @param pGMM Pointer to the GMM instance data.
2169 * @param pGVM Pointer to the shared VM structure.
2170 * @param cPages The number of pages to free.
2171 * @param paPages Pointer to the page descriptors.
2172 * @param enmAccount The account this relates to.
2173 */
2174static int gmmR0FreePages(PGMM pGMM, PGVM pGVM, uint32_t cPages, PGMMFREEPAGEDESC paPages, GMMACCOUNT enmAccount)
2175{
2176 /*
2177 * Check that the request isn't impossible wrt to the account status.
2178 */
2179 switch (enmAccount)
2180 {
2181 case GMMACCOUNT_BASE:
2182 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages < cPages))
2183 {
2184 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cBasePages, cPages));
2185 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2186 }
2187 break;
2188 case GMMACCOUNT_SHADOW:
2189 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cShadowPages < cPages))
2190 {
2191 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cShadowPages, cPages));
2192 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2193 }
2194 break;
2195 case GMMACCOUNT_FIXED:
2196 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cFixedPages < cPages))
2197 {
2198 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cFixedPages, cPages));
2199 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2200 }
2201 break;
2202 default:
2203 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
2204 }
2205
2206 /*
2207 * Walk the descriptors and free the pages.
2208 *
2209 * Statistics (except the account) are being updated as we go along,
2210 * unlike the alloc code. Also, stop on the first error.
2211 */
2212 int rc = VINF_SUCCESS;
2213 uint32_t iPage;
2214 for (iPage = 0; iPage < cPages; iPage++)
2215 {
2216 uint32_t idPage = paPages[iPage].idPage;
2217 PGMMPAGE pPage = gmmR0GetPage(pGMM, idPage);
2218 if (RT_LIKELY(pPage))
2219 {
2220 if (RT_LIKELY(GMM_PAGE_IS_PRIVATE(pPage)))
2221 {
2222 if (RT_LIKELY(pPage->Private.hGVM == pGVM->hSelf))
2223 {
2224 Assert(pGVM->gmm.s.cPrivatePages);
2225 pGVM->gmm.s.cPrivatePages--;
2226 gmmR0FreePrivatePage(pGMM, idPage, pPage);
2227 }
2228 else
2229 {
2230 Log(("gmmR0AllocatePages: #%#x/%#x: not owner! hGVM=%#x hSelf=%#x\n", iPage, idPage,
2231 pPage->Private.hGVM, pGVM->hEMT));
2232 rc = VERR_GMM_NOT_PAGE_OWNER;
2233 break;
2234 }
2235 }
2236 else if (RT_LIKELY(GMM_PAGE_IS_SHARED(pPage)))
2237 {
2238 Assert(pGVM->gmm.s.cSharedPages);
2239 pGVM->gmm.s.cSharedPages--;
2240 Assert(pPage->Shared.cRefs);
2241 if (!--pPage->Shared.cRefs)
2242 gmmR0FreeSharedPage(pGMM, idPage, pPage);
2243 }
2244 else
2245 {
2246 Log(("gmmR0AllocatePages: #%#x/%#x: already free!\n", iPage, idPage));
2247 rc = VERR_GMM_PAGE_ALREADY_FREE;
2248 break;
2249 }
2250 }
2251 else
2252 {
2253 Log(("gmmR0AllocatePages: #%#x/%#x: not found!\n", iPage, idPage));
2254 rc = VERR_GMM_PAGE_NOT_FOUND;
2255 break;
2256 }
2257 paPages[iPage].idPage = NIL_GMM_PAGEID;
2258 }
2259
2260 /*
2261 * Update the account.
2262 */
2263 switch (enmAccount)
2264 {
2265 case GMMACCOUNT_BASE: pGVM->gmm.s.Allocated.cBasePages -= iPage; break;
2266 case GMMACCOUNT_SHADOW: pGVM->gmm.s.Allocated.cShadowPages -= iPage; break;
2267 case GMMACCOUNT_FIXED: pGVM->gmm.s.Allocated.cFixedPages -= iPage; break;
2268 default:
2269 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
2270 }
2271
2272 /*
2273 * Any threshold stuff to be done here?
2274 */
2275
2276 return rc;
2277}
2278
2279
2280/**
2281 * Free one or more pages.
2282 *
2283 * This is typically used at reset time or power off.
2284 *
2285 * @returns VBox status code:
2286 * @retval xxx
2287 *
2288 * @param pVM Pointer to the shared VM structure.
2289 * @param cPages The number of pages to allocate.
2290 * @param paPages Pointer to the page descriptors containing the Page IDs for each page.
2291 * @param enmAccount The account this relates to.
2292 * @thread EMT.
2293 */
2294GMMR0DECL(int) GMMR0FreePages(PVM pVM, uint32_t cPages, PGMMFREEPAGEDESC paPages, GMMACCOUNT enmAccount)
2295{
2296 LogFlow(("GMMR0FreePages: pVM=%p cPages=%#x paPages=%p enmAccount=%d\n", pVM, cPages, paPages, enmAccount));
2297
2298 /*
2299 * Validate input and get the basics.
2300 */
2301 PGMM pGMM;
2302 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2303 PGVM pGVM = GVMMR0ByVM(pVM);
2304 if (!pGVM)
2305 return VERR_INVALID_PARAMETER;
2306 if (pGVM->hEMT != RTThreadNativeSelf())
2307 return VERR_NOT_OWNER;
2308
2309 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2310 AssertMsgReturn(enmAccount > GMMACCOUNT_INVALID && enmAccount < GMMACCOUNT_END, ("%d\n", enmAccount), VERR_INVALID_PARAMETER);
2311 AssertMsgReturn(cPages > 0 && cPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cPages), VERR_INVALID_PARAMETER);
2312
2313 for (unsigned iPage = 0; iPage < cPages; iPage++)
2314 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
2315 /*|| paPages[iPage].idPage == NIL_GMM_PAGEID*/,
2316 ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2317
2318 /*
2319 * Take the semaphore and call the worker function.
2320 */
2321 int rc = RTSemFastMutexRequest(pGMM->Mtx);
2322 AssertRC(rc);
2323
2324 rc = gmmR0FreePages(pGMM, pGVM, cPages, paPages, enmAccount);
2325
2326 RTSemFastMutexRelease(pGMM->Mtx);
2327 LogFlow(("GMMR0FreePages: returns %Rrc\n", rc));
2328 return rc;
2329}
2330
2331
2332/**
2333 * VMMR0 request wrapper for GMMR0FreePages.
2334 *
2335 * @returns see GMMR0FreePages.
2336 * @param pVM Pointer to the shared VM structure.
2337 * @param pReq The request packet.
2338 */
2339GMMR0DECL(int) GMMR0FreePagesReq(PVM pVM, PGMMFREEPAGESREQ pReq)
2340{
2341 /*
2342 * Validate input and pass it on.
2343 */
2344 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2345 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2346 AssertMsgReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[0]),
2347 ("%#x < %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[0])),
2348 VERR_INVALID_PARAMETER);
2349 AssertMsgReturn(pReq->Hdr.cbReq == RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[pReq->cPages]),
2350 ("%#x != %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[pReq->cPages])),
2351 VERR_INVALID_PARAMETER);
2352
2353 return GMMR0FreePages(pVM, pReq->cPages, &pReq->aPages[0], pReq->enmAccount);
2354}
2355
2356
2357/**
2358 * Report back on a memory ballooning request.
2359 *
2360 * The request may or may not have been initiated by the GMM. If it was initiated
2361 * by the GMM it is important that this function is called even if no pages was
2362 * ballooned.
2363 *
2364 * Since the whole purpose of ballooning is to free up guest RAM pages, this API
2365 * may also be given a set of related pages to be freed. These pages are assumed
2366 * to be on the base account.
2367 *
2368 * @returns VBox status code:
2369 * @retval xxx
2370 *
2371 * @param pVM Pointer to the shared VM structure.
2372 * @param cBalloonedPages The number of pages that was ballooned.
2373 * @param cPagesToFree The number of pages to be freed.
2374 * @param paPages Pointer to the page descriptors for the pages that's to be freed.
2375 * @param fCompleted Indicates whether the ballooning request was completed (true) or
2376 * if there is more pages to come (false). If the ballooning was not
2377 * not triggered by the GMM, don't set this.
2378 * @thread EMT.
2379 */
2380GMMR0DECL(int) GMMR0BalloonedPages(PVM pVM, uint32_t cBalloonedPages, uint32_t cPagesToFree, PGMMFREEPAGEDESC paPages, bool fCompleted)
2381{
2382 LogFlow(("GMMR0BalloonedPages: pVM=%p cBalloonedPages=%#x cPagestoFree=%#x paPages=%p enmAccount=%d fCompleted=%RTbool\n",
2383 pVM, cBalloonedPages, cPagesToFree, paPages, fCompleted));
2384
2385 /*
2386 * Validate input and get the basics.
2387 */
2388 PGMM pGMM;
2389 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2390 PGVM pGVM = GVMMR0ByVM(pVM);
2391 if (!pGVM)
2392 return VERR_INVALID_PARAMETER;
2393 if (pGVM->hEMT != RTThreadNativeSelf())
2394 return VERR_NOT_OWNER;
2395
2396 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2397 AssertMsgReturn(cBalloonedPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cBalloonedPages), VERR_INVALID_PARAMETER);
2398 AssertMsgReturn(cPagesToFree <= cBalloonedPages, ("%#x\n", cPagesToFree), VERR_INVALID_PARAMETER);
2399
2400 for (unsigned iPage = 0; iPage < cPagesToFree; iPage++)
2401 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
2402 /*|| paPages[iPage].idPage == NIL_GMM_PAGEID*/,
2403 ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2404
2405 /*
2406 * Take the sempahore and do some more validations.
2407 */
2408 int rc = RTSemFastMutexRequest(pGMM->Mtx);
2409 AssertRC(rc);
2410 if (pGVM->gmm.s.Allocated.cBasePages >= cPagesToFree)
2411 {
2412 /*
2413 * Record the ballooned memory.
2414 */
2415 pGMM->cBalloonedPages += cBalloonedPages;
2416 if (pGVM->gmm.s.cReqBalloonedPages)
2417 {
2418 pGVM->gmm.s.cBalloonedPages += cBalloonedPages;
2419 pGVM->gmm.s.cReqActuallyBalloonedPages += cBalloonedPages;
2420 if (fCompleted)
2421 {
2422 Log(("GMMR0BalloonedPages: +%#x - Global=%#llx; / VM: Total=%#llx Req=%#llx Actual=%#llx (completed)\n", cBalloonedPages,
2423 pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages, pGVM->gmm.s.cReqBalloonedPages, pGVM->gmm.s.cReqActuallyBalloonedPages));
2424
2425 /*
2426 * Anything we need to do here now when the request has been completed?
2427 */
2428 pGVM->gmm.s.cReqBalloonedPages = 0;
2429 }
2430 else
2431 Log(("GMMR0BalloonedPages: +%#x - Global=%#llx / VM: Total=%#llx Req=%#llx Actual=%#llx (pending)\n", cBalloonedPages,
2432 pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages, pGVM->gmm.s.cReqBalloonedPages, pGVM->gmm.s.cReqActuallyBalloonedPages));
2433 }
2434 else
2435 {
2436 pGVM->gmm.s.cBalloonedPages += cBalloonedPages;
2437 Log(("GMMR0BalloonedPages: +%#x - Global=%#llx / VM: Total=%#llx (user)\n",
2438 cBalloonedPages, pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages));
2439 }
2440
2441 /*
2442 * Any pages to free?
2443 */
2444 if (cPagesToFree)
2445 rc = gmmR0FreePages(pGMM, pGVM, cPagesToFree, paPages, GMMACCOUNT_BASE);
2446 }
2447 else
2448 {
2449 rc = VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2450 }
2451
2452 RTSemFastMutexRelease(pGMM->Mtx);
2453 LogFlow(("GMMR0BalloonedPages: returns %Rrc\n", rc));
2454 return rc;
2455}
2456
2457
2458/**
2459 * VMMR0 request wrapper for GMMR0BalloonedPages.
2460 *
2461 * @returns see GMMR0BalloonedPages.
2462 * @param pVM Pointer to the shared VM structure.
2463 * @param pReq The request packet.
2464 */
2465GMMR0DECL(int) GMMR0BalloonedPagesReq(PVM pVM, PGMMBALLOONEDPAGESREQ pReq)
2466{
2467 /*
2468 * Validate input and pass it on.
2469 */
2470 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2471 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2472 AssertMsgReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF(GMMBALLOONEDPAGESREQ, aPages[0]),
2473 ("%#x < %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMBALLOONEDPAGESREQ, aPages[0])),
2474 VERR_INVALID_PARAMETER);
2475 AssertMsgReturn(pReq->Hdr.cbReq == RT_UOFFSETOF(GMMBALLOONEDPAGESREQ, aPages[pReq->cPagesToFree]),
2476 ("%#x != %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMBALLOONEDPAGESREQ, aPages[pReq->cPagesToFree])),
2477 VERR_INVALID_PARAMETER);
2478
2479 return GMMR0BalloonedPages(pVM, pReq->cBalloonedPages, pReq->cPagesToFree, &pReq->aPages[0], pReq->fCompleted);
2480}
2481
2482
2483/**
2484 * Report balloon deflating.
2485 *
2486 * @returns VBox status code:
2487 * @retval xxx
2488 *
2489 * @param pVM Pointer to the shared VM structure.
2490 * @param cPages The number of pages that was let out of the balloon.
2491 * @thread EMT.
2492 */
2493GMMR0DECL(int) GMMR0DeflatedBalloon(PVM pVM, uint32_t cPages)
2494{
2495 LogFlow(("GMMR0DeflatedBalloon: pVM=%p cPages=%#x\n", pVM, cPages));
2496
2497 /*
2498 * Validate input and get the basics.
2499 */
2500 PGMM pGMM;
2501 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2502 PGVM pGVM = GVMMR0ByVM(pVM);
2503 if (!pGVM)
2504 return VERR_INVALID_PARAMETER;
2505 if (pGVM->hEMT != RTThreadNativeSelf())
2506 return VERR_NOT_OWNER;
2507
2508 AssertMsgReturn(cPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cPages), VERR_INVALID_PARAMETER);
2509
2510 /*
2511 * Take the sempahore and do some more validations.
2512 */
2513 int rc = RTSemFastMutexRequest(pGMM->Mtx);
2514 AssertRC(rc);
2515
2516 if (pGVM->gmm.s.cBalloonedPages < cPages)
2517 {
2518 Assert(pGMM->cBalloonedPages >= pGVM->gmm.s.cBalloonedPages);
2519
2520 /*
2521 * Record it.
2522 */
2523 pGMM->cBalloonedPages -= cPages;
2524 pGVM->gmm.s.cBalloonedPages -= cPages;
2525 if (pGVM->gmm.s.cReqDeflatePages)
2526 {
2527 Log(("GMMR0BalloonedPages: -%#x - Global=%#llx / VM: Total=%#llx Req=%#llx\n", cPages,
2528 pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages, pGVM->gmm.s.cReqDeflatePages));
2529
2530 /*
2531 * Anything we need to do here now when the request has been completed?
2532 */
2533 pGVM->gmm.s.cReqDeflatePages = 0;
2534 }
2535 else
2536 Log(("GMMR0BalloonedPages: -%#x - Global=%#llx / VM: Total=%#llx\n", cPages,
2537 pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages));
2538 }
2539 else
2540 {
2541 Log(("GMMR0DeflatedBalloon: cBalloonedPages=%#llx cPages=%#x\n", pGVM->gmm.s.cBalloonedPages, cPages));
2542 rc = VERR_GMM_ATTEMPT_TO_DEFLATE_TOO_MUCH;
2543 }
2544
2545 RTSemFastMutexRelease(pGMM->Mtx);
2546 LogFlow(("GMMR0BalloonedPages: returns %Rrc\n", rc));
2547 return rc;
2548}
2549
2550
2551/**
2552 * Unmaps a chunk previously mapped into the address space of the current process.
2553 *
2554 * @returns VBox status code.
2555 * @param pGMM Pointer to the GMM instance data.
2556 * @param pGVM Pointer to the Global VM structure.
2557 * @param pChunk Pointer to the chunk to be unmapped.
2558 */
2559static int gmmR0UnmapChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk)
2560{
2561 if (!pGMM->fLegacyMode)
2562 {
2563 /*
2564 * Find the mapping and try unmapping it.
2565 */
2566 for (uint32_t i = 0; i < pChunk->cMappings; i++)
2567 {
2568 Assert(pChunk->paMappings[i].pGVM && pChunk->paMappings[i].MapObj != NIL_RTR0MEMOBJ);
2569 if (pChunk->paMappings[i].pGVM == pGVM)
2570 {
2571 /* unmap */
2572 int rc = RTR0MemObjFree(pChunk->paMappings[i].MapObj, false /* fFreeMappings (NA) */);
2573 if (RT_SUCCESS(rc))
2574 {
2575 /* update the record. */
2576 pChunk->cMappings--;
2577 if (i < pChunk->cMappings)
2578 pChunk->paMappings[i] = pChunk->paMappings[pChunk->cMappings];
2579 pChunk->paMappings[pChunk->cMappings].MapObj = NIL_RTR0MEMOBJ;
2580 pChunk->paMappings[pChunk->cMappings].pGVM = NULL;
2581 }
2582 return rc;
2583 }
2584 }
2585 }
2586 else if (pChunk->hGVM == pGVM->hSelf)
2587 return VINF_SUCCESS;
2588
2589 Log(("gmmR0MapChunk: Chunk %#x is not mapped into pGVM=%p/%#x\n", pChunk->Core.Key, pGVM, pGVM->hSelf));
2590 return VERR_GMM_CHUNK_NOT_MAPPED;
2591}
2592
2593
2594/**
2595 * Maps a chunk into the user address space of the current process.
2596 *
2597 * @returns VBox status code.
2598 * @param pGMM Pointer to the GMM instance data.
2599 * @param pGVM Pointer to the Global VM structure.
2600 * @param pChunk Pointer to the chunk to be mapped.
2601 * @param ppvR3 Where to store the ring-3 address of the mapping.
2602 * In the VERR_GMM_CHUNK_ALREADY_MAPPED case, this will be
2603 * contain the address of the existing mapping.
2604 */
2605static int gmmR0MapChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk, PRTR3PTR ppvR3)
2606{
2607 /*
2608 * If we're in legacy mode this is simple.
2609 */
2610 if (pGMM->fLegacyMode)
2611 {
2612 if (pChunk->hGVM != pGVM->hSelf)
2613 {
2614 Log(("gmmR0MapChunk: chunk %#x is already mapped at %p!\n", pChunk->Core.Key, *ppvR3));
2615 return VERR_GMM_CHUNK_NOT_FOUND;
2616 }
2617
2618 *ppvR3 = RTR0MemObjAddressR3(pChunk->MemObj);
2619 return VINF_SUCCESS;
2620 }
2621
2622 /*
2623 * Check to see if the chunk is already mapped.
2624 */
2625 for (uint32_t i = 0; i < pChunk->cMappings; i++)
2626 {
2627 Assert(pChunk->paMappings[i].pGVM && pChunk->paMappings[i].MapObj != NIL_RTR0MEMOBJ);
2628 if (pChunk->paMappings[i].pGVM == pGVM)
2629 {
2630 *ppvR3 = RTR0MemObjAddressR3(pChunk->paMappings[i].MapObj);
2631 Log(("gmmR0MapChunk: chunk %#x is already mapped at %p!\n", pChunk->Core.Key, *ppvR3));
2632 return VERR_GMM_CHUNK_ALREADY_MAPPED;
2633 }
2634 }
2635
2636 /*
2637 * Do the mapping.
2638 */
2639 RTR0MEMOBJ MapObj;
2640 int rc = RTR0MemObjMapUser(&MapObj, pChunk->MemObj, (RTR3PTR)-1, 0, RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
2641 if (RT_SUCCESS(rc))
2642 {
2643 /* reallocate the array? */
2644 if ((pChunk->cMappings & 1 /*7*/) == 0)
2645 {
2646 void *pvMappings = RTMemRealloc(pChunk->paMappings, (pChunk->cMappings + 2 /*8*/) * sizeof(pChunk->paMappings[0]));
2647 if (RT_UNLIKELY(pvMappings))
2648 {
2649 rc = RTR0MemObjFree(MapObj, false /* fFreeMappings (NA) */);
2650 AssertRC(rc);
2651 return VERR_NO_MEMORY;
2652 }
2653 pChunk->paMappings = (PGMMCHUNKMAP)pvMappings;
2654 }
2655
2656 /* insert new entry */
2657 pChunk->paMappings[pChunk->cMappings].MapObj = MapObj;
2658 pChunk->paMappings[pChunk->cMappings].pGVM = pGVM;
2659 pChunk->cMappings++;
2660
2661 *ppvR3 = RTR0MemObjAddressR3(MapObj);
2662 }
2663
2664 return rc;
2665}
2666
2667
2668/**
2669 * Map a chunk and/or unmap another chunk.
2670 *
2671 * The mapping and unmapping applies to the current process.
2672 *
2673 * This API does two things because it saves a kernel call per mapping when
2674 * when the ring-3 mapping cache is full.
2675 *
2676 * @returns VBox status code.
2677 * @param pVM The VM.
2678 * @param idChunkMap The chunk to map. NIL_GMM_CHUNKID if nothing to map.
2679 * @param idChunkUnmap The chunk to unmap. NIL_GMM_CHUNKID if nothing to unmap.
2680 * @param ppvR3 Where to store the address of the mapped chunk. NULL is ok if nothing to map.
2681 * @thread EMT
2682 */
2683GMMR0DECL(int) GMMR0MapUnmapChunk(PVM pVM, uint32_t idChunkMap, uint32_t idChunkUnmap, PRTR3PTR ppvR3)
2684{
2685 LogFlow(("GMMR0MapUnmapChunk: pVM=%p idChunkMap=%#x idChunkUnmap=%#x ppvR3=%p\n",
2686 pVM, idChunkMap, idChunkUnmap, ppvR3));
2687
2688 /*
2689 * Validate input and get the basics.
2690 */
2691 PGMM pGMM;
2692 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2693 PGVM pGVM = GVMMR0ByVM(pVM);
2694 if (!pGVM)
2695 return VERR_INVALID_PARAMETER;
2696 if (pGVM->hEMT != RTThreadNativeSelf())
2697 return VERR_NOT_OWNER;
2698
2699 AssertCompile(NIL_GMM_CHUNKID == 0);
2700 AssertMsgReturn(idChunkMap <= GMM_CHUNKID_LAST, ("%#x\n", idChunkMap), VERR_INVALID_PARAMETER);
2701 AssertMsgReturn(idChunkUnmap <= GMM_CHUNKID_LAST, ("%#x\n", idChunkUnmap), VERR_INVALID_PARAMETER);
2702
2703 if ( idChunkMap == NIL_GMM_CHUNKID
2704 && idChunkUnmap == NIL_GMM_CHUNKID)
2705 return VERR_INVALID_PARAMETER;
2706
2707 if (idChunkMap != NIL_GMM_CHUNKID)
2708 {
2709 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
2710 *ppvR3 = NIL_RTR3PTR;
2711 }
2712
2713 /*
2714 * Take the semaphore and do the work.
2715 *
2716 * The unmapping is done last since it's easier to undo a mapping than
2717 * undoing an unmapping. The ring-3 mapping cache cannot not be so big
2718 * that it pushes the user virtual address space to within a chunk of
2719 * it it's limits, so, no problem here.
2720 */
2721 int rc = RTSemFastMutexRequest(pGMM->Mtx);
2722 AssertRC(rc);
2723
2724 PGMMCHUNK pMap = NULL;
2725 if (idChunkMap != NIL_GVM_HANDLE)
2726 {
2727 pMap = gmmR0GetChunk(pGMM, idChunkMap);
2728 if (RT_LIKELY(pMap))
2729 rc = gmmR0MapChunk(pGMM, pGVM, pMap, ppvR3);
2730 else
2731 {
2732 Log(("GMMR0MapUnmapChunk: idChunkMap=%#x\n", idChunkMap));
2733 rc = VERR_GMM_CHUNK_NOT_FOUND;
2734 }
2735 }
2736
2737 if ( idChunkUnmap != NIL_GMM_CHUNKID
2738 && RT_SUCCESS(rc))
2739 {
2740 PGMMCHUNK pUnmap = gmmR0GetChunk(pGMM, idChunkUnmap);
2741 if (RT_LIKELY(pUnmap))
2742 rc = gmmR0UnmapChunk(pGMM, pGVM, pUnmap);
2743 else
2744 {
2745 Log(("GMMR0MapUnmapChunk: idChunkUnmap=%#x\n", idChunkUnmap));
2746 rc = VERR_GMM_CHUNK_NOT_FOUND;
2747 }
2748
2749 if (RT_FAILURE(rc) && pMap)
2750 gmmR0UnmapChunk(pGMM, pGVM, pMap);
2751 }
2752
2753 RTSemFastMutexRelease(pGMM->Mtx);
2754
2755 LogFlow(("GMMR0MapUnmapChunk: returns %Rrc\n", rc));
2756 return rc;
2757}
2758
2759
2760/**
2761 * VMMR0 request wrapper for GMMR0MapUnmapChunk.
2762 *
2763 * @returns see GMMR0MapUnmapChunk.
2764 * @param pVM Pointer to the shared VM structure.
2765 * @param pReq The request packet.
2766 */
2767GMMR0DECL(int) GMMR0MapUnmapChunkReq(PVM pVM, PGMMMAPUNMAPCHUNKREQ pReq)
2768{
2769 /*
2770 * Validate input and pass it on.
2771 */
2772 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2773 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2774 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
2775
2776 return GMMR0MapUnmapChunk(pVM, pReq->idChunkMap, pReq->idChunkUnmap, &pReq->pvR3);
2777}
2778
2779
2780/**
2781 * Legacy mode API for supplying pages.
2782 *
2783 * The specified user address points to a allocation chunk sized block that
2784 * will be locked down and used by the GMM when the GM asks for pages.
2785 *
2786 * @returns VBox status code.
2787 * @param pVM The VM.
2788 * @param pvR3 Pointer to the chunk size memory block to lock down.
2789 */
2790GMMR0DECL(int) GMMR0SeedChunk(PVM pVM, RTR3PTR pvR3)
2791{
2792 /*
2793 * Validate input and get the basics.
2794 */
2795 PGMM pGMM;
2796 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2797 PGVM pGVM = GVMMR0ByVM(pVM);
2798 if (!pGVM)
2799 return VERR_INVALID_PARAMETER;
2800 if (pGVM->hEMT != RTThreadNativeSelf())
2801 return VERR_NOT_OWNER;
2802
2803 AssertPtrReturn(pvR3, VERR_INVALID_POINTER);
2804 AssertReturn(!(PAGE_OFFSET_MASK & pvR3), VERR_INVALID_POINTER);
2805
2806 if (!pGMM->fLegacyMode)
2807 {
2808 Log(("GMMR0SeedChunk: not in legacy mode!\n"));
2809 return VERR_NOT_SUPPORTED;
2810 }
2811
2812 /*
2813 * Lock the memory before taking the semaphore.
2814 */
2815 RTR0MEMOBJ MemObj;
2816 int rc = RTR0MemObjLockUser(&MemObj, pvR3, GMM_CHUNK_SIZE, NIL_RTR0PROCESS);
2817 if (RT_SUCCESS(rc))
2818 {
2819 /*
2820 * Take the semaphore and add a new chunk with our hGVM.
2821 */
2822 int rc = RTSemFastMutexRequest(pGMM->Mtx);
2823 AssertRC(rc);
2824
2825 rc = gmmR0RegisterChunk(pGMM, &pGMM->Private, MemObj, pGVM->hSelf);
2826
2827 RTSemFastMutexRelease(pGMM->Mtx);
2828
2829 if (RT_FAILURE(rc))
2830 RTR0MemObjFree(MemObj, false /* fFreeMappings */);
2831 }
2832
2833 LogFlow(("GMMR0SeedChunk: rc=%d (pvR3=%p)\n", rc, pvR3));
2834 return rc;
2835}
2836
Note: See TracBrowser for help on using the repository browser.

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