VirtualBox

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

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

GMM: Fixed bugs in gmmR0AllocateChunkId and gmmR0FreePageWorker, the later causing memory leaks on reset.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 97.7 KB
Line 
1/* $Id: GMMR0.cpp 18212 2009-03-24 18:15:39Z 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 cleared.
516 * The NIL id (0) is marked allocated. */
517 uint32_t bmChunkId[(GMM_CHUNKID_LAST + 32) >> 10];
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 pSet->apLists[iList] = pChunk;
1322
1323 pSet->cPages += pChunk->cFree;
1324 }
1325}
1326
1327
1328/**
1329 * Frees a Chunk ID.
1330 *
1331 * @param pGMM Pointer to the GMM instance.
1332 * @param idChunk The Chunk ID to free.
1333 */
1334static void gmmR0FreeChunkId(PGMM pGMM, uint32_t idChunk)
1335{
1336 AssertReturnVoid(idChunk != NIL_GMM_CHUNKID);
1337 AssertMsg(ASMBitTest(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk));
1338 ASMAtomicBitClear(&pGMM->bmChunkId[0], idChunk);
1339}
1340
1341
1342/**
1343 * Allocates a new Chunk ID.
1344 *
1345 * @returns The Chunk ID.
1346 * @param pGMM Pointer to the GMM instance.
1347 */
1348static uint32_t gmmR0AllocateChunkId(PGMM pGMM)
1349{
1350 AssertCompile(!((GMM_CHUNKID_LAST + 1) & 31)); /* must be a multiple of 32 */
1351 AssertCompile(NIL_GMM_CHUNKID == 0);
1352
1353 /*
1354 * Try the next sequential one.
1355 */
1356 int32_t idChunk = ++pGMM->idChunkPrev;
1357#if 0 /* test the fallback first */
1358 if ( idChunk <= GMM_CHUNKID_LAST
1359 && idChunk > NIL_GMM_CHUNKID
1360 && !ASMAtomicBitTestAndSet(&pVMM->bmChunkId[0], idChunk))
1361 return idChunk;
1362#endif
1363
1364 /*
1365 * Scan sequentially from the last one.
1366 */
1367 if ( (uint32_t)idChunk < GMM_CHUNKID_LAST
1368 && idChunk > NIL_GMM_CHUNKID)
1369 {
1370 idChunk = ASMBitNextClear(&pGMM->bmChunkId[0], GMM_CHUNKID_LAST + 1, idChunk);
1371 if (idChunk > NIL_GMM_CHUNKID)
1372 {
1373 AssertMsgReturn(!ASMAtomicBitTestAndSet(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk), NIL_GVM_HANDLE);
1374 return pGMM->idChunkPrev = idChunk;
1375 }
1376 }
1377
1378 /*
1379 * Ok, scan from the start.
1380 * We're not racing anyone, so there is no need to expect failures or have restart loops.
1381 */
1382 idChunk = ASMBitFirstClear(&pGMM->bmChunkId[0], GMM_CHUNKID_LAST + 1);
1383 AssertMsgReturn(idChunk > NIL_GMM_CHUNKID, ("%#x\n", idChunk), NIL_GVM_HANDLE);
1384 AssertMsgReturn(!ASMAtomicBitTestAndSet(&pGMM->bmChunkId[0], idChunk), ("%#x\n", idChunk), NIL_GVM_HANDLE);
1385
1386 return pGMM->idChunkPrev = idChunk;
1387}
1388
1389
1390/**
1391 * Registers a new chunk of memory.
1392 *
1393 * This is called by both gmmR0AllocateOneChunk and GMMR0SeedChunk.
1394 *
1395 * @returns VBox status code.
1396 * @param pGMM Pointer to the GMM instance.
1397 * @param pSet Pointer to the set.
1398 * @param MemObj The memory object for the chunk.
1399 * @param hGVM The hGVM value. (Only used by GMMR0SeedChunk.)
1400 */
1401static int gmmR0RegisterChunk(PGMM pGMM, PGMMCHUNKFREESET pSet, RTR0MEMOBJ MemObj, uint16_t hGVM)
1402{
1403 int rc;
1404 PGMMCHUNK pChunk = (PGMMCHUNK)RTMemAllocZ(sizeof(*pChunk));
1405 if (pChunk)
1406 {
1407 /*
1408 * Initialize it.
1409 */
1410 pChunk->MemObj = MemObj;
1411 pChunk->cFree = GMM_CHUNK_NUM_PAGES;
1412 pChunk->hGVM = hGVM;
1413 pChunk->iFreeHead = 0;
1414 for (unsigned iPage = 0; iPage < RT_ELEMENTS(pChunk->aPages) - 1; iPage++)
1415 {
1416 pChunk->aPages[iPage].Free.u2State = GMM_PAGE_STATE_FREE;
1417 pChunk->aPages[iPage].Free.iNext = iPage + 1;
1418 }
1419 pChunk->aPages[RT_ELEMENTS(pChunk->aPages) - 1].Free.u2State = GMM_PAGE_STATE_FREE;
1420 pChunk->aPages[RT_ELEMENTS(pChunk->aPages) - 1].Free.iNext = UINT16_MAX;
1421
1422 /*
1423 * Allocate a Chunk ID and insert it into the tree.
1424 * It doesn't cost anything to be careful here.
1425 */
1426 pChunk->Core.Key = gmmR0AllocateChunkId(pGMM);
1427 if ( pChunk->Core.Key != NIL_GMM_CHUNKID
1428 && pChunk->Core.Key <= GMM_CHUNKID_LAST
1429 && RTAvlU32Insert(&pGMM->pChunks, &pChunk->Core))
1430 {
1431 pGMM->cChunks++;
1432 gmmR0LinkChunk(pChunk, pSet);
1433 LogFlow(("gmmR0RegisterChunk: pChunk=%p id=%#x cChunks=%d\n", pChunk, pChunk->Core.Key, pGMM->cChunks));
1434 return VINF_SUCCESS;
1435 }
1436
1437 rc = VERR_INTERNAL_ERROR;
1438 RTMemFree(pChunk);
1439 }
1440 else
1441 rc = VERR_NO_MEMORY;
1442 return rc;
1443}
1444
1445
1446/**
1447 * Allocate one new chunk and add it to the specified free set.
1448 *
1449 * @returns VBox status code.
1450 * @param pGMM Pointer to the GMM instance.
1451 * @param pSet Pointer to the set.
1452 */
1453static int gmmR0AllocateOneChunk(PGMM pGMM, PGMMCHUNKFREESET pSet)
1454{
1455 /*
1456 * Allocate the memory.
1457 */
1458 RTR0MEMOBJ MemObj;
1459 int rc = RTR0MemObjAllocPhysNC(&MemObj, GMM_CHUNK_SIZE, NIL_RTHCPHYS);
1460 if (RT_SUCCESS(rc))
1461 {
1462 rc = gmmR0RegisterChunk(pGMM, pSet, MemObj, NIL_GVM_HANDLE);
1463 if (RT_FAILURE(rc))
1464 RTR0MemObjFree(MemObj, false /* fFreeMappings */);
1465 }
1466 return rc;
1467}
1468
1469
1470/**
1471 * Attempts to allocate more pages until the requested amount is met.
1472 *
1473 * @returns VBox status code.
1474 * @param pGMM Pointer to the GMM instance data.
1475 * @param pSet Pointer to the free set to grow.
1476 * @param cPages The number of pages needed.
1477 */
1478static int gmmR0AllocateMoreChunks(PGMM pGMM, PGMMCHUNKFREESET pSet, uint32_t cPages)
1479{
1480 Assert(!pGMM->fLegacyMode);
1481
1482 /*
1483 * Try steal free chunks from the other set first. (Only take 100% free chunks.)
1484 */
1485 PGMMCHUNKFREESET pOtherSet = pSet == &pGMM->Private ? &pGMM->Shared : &pGMM->Private;
1486 while ( pSet->cPages < cPages
1487 && pOtherSet->cPages >= GMM_CHUNK_NUM_PAGES)
1488 {
1489 PGMMCHUNK pChunk = pOtherSet->apLists[GMM_CHUNK_FREE_SET_LISTS - 1];
1490 while (pChunk && pChunk->cFree != GMM_CHUNK_NUM_PAGES)
1491 pChunk = pChunk->pFreeNext;
1492 if (!pChunk)
1493 break;
1494
1495 gmmR0UnlinkChunk(pChunk);
1496 gmmR0LinkChunk(pChunk, pSet);
1497 }
1498
1499 /*
1500 * If we need still more pages, allocate new chunks.
1501 */
1502 while (pSet->cPages < cPages)
1503 {
1504 int rc = gmmR0AllocateOneChunk(pGMM, pSet);
1505 if (RT_FAILURE(rc))
1506 return rc;
1507 }
1508
1509 return VINF_SUCCESS;
1510}
1511
1512
1513/**
1514 * Allocates one private page.
1515 *
1516 * Worker for gmmR0AllocatePages.
1517 *
1518 * @param pGMM Pointer to the GMM instance data.
1519 * @param hGVM The GVM handle of the VM requesting memory.
1520 * @param pChunk The chunk to allocate it from.
1521 * @param pPageDesc The page descriptor.
1522 */
1523static void gmmR0AllocatePage(PGMM pGMM, uint32_t hGVM, PGMMCHUNK pChunk, PGMMPAGEDESC pPageDesc)
1524{
1525 /* update the chunk stats. */
1526 if (pChunk->hGVM == NIL_GVM_HANDLE)
1527 pChunk->hGVM = hGVM;
1528 Assert(pChunk->cFree);
1529 pChunk->cFree--;
1530 pChunk->cPrivate++;
1531
1532 /* unlink the first free page. */
1533 const uint32_t iPage = pChunk->iFreeHead;
1534 AssertReleaseMsg(iPage < RT_ELEMENTS(pChunk->aPages), ("%d\n", iPage));
1535 PGMMPAGE pPage = &pChunk->aPages[iPage];
1536 Assert(GMM_PAGE_IS_FREE(pPage));
1537 pChunk->iFreeHead = pPage->Free.iNext;
1538 Log3(("A pPage=%p iPage=%#x/%#x u2State=%d iFreeHead=%#x iNext=%#x\n",
1539 pPage, iPage, (pChunk->Core.Key << GMM_CHUNKID_SHIFT) | iPage,
1540 pPage->Common.u2State, pChunk->iFreeHead, pPage->Free.iNext));
1541
1542 /* make the page private. */
1543 pPage->u = 0;
1544 AssertCompile(GMM_PAGE_STATE_PRIVATE == 0);
1545 pPage->Private.hGVM = hGVM;
1546 AssertCompile(NIL_RTHCPHYS >= GMM_GCPHYS_LAST);
1547 AssertCompile(GMM_GCPHYS_UNSHAREABLE >= GMM_GCPHYS_LAST);
1548 if (pPageDesc->HCPhysGCPhys <= GMM_GCPHYS_LAST)
1549 pPage->Private.pfn = pPageDesc->HCPhysGCPhys >> PAGE_SHIFT;
1550 else
1551 pPage->Private.pfn = GMM_PAGE_PFN_UNSHAREABLE; /* unshareable / unassigned - same thing. */
1552
1553 /* update the page descriptor. */
1554 pPageDesc->HCPhysGCPhys = RTR0MemObjGetPagePhysAddr(pChunk->MemObj, iPage);
1555 Assert(pPageDesc->HCPhysGCPhys != NIL_RTHCPHYS);
1556 pPageDesc->idPage = (pChunk->Core.Key << GMM_CHUNKID_SHIFT) | iPage;
1557 pPageDesc->idSharedPage = NIL_GMM_PAGEID;
1558}
1559
1560
1561/**
1562 * Common worker for GMMR0AllocateHandyPages and GMMR0AllocatePages.
1563 *
1564 * @returns VBox status code:
1565 * @retval VINF_SUCCESS on success.
1566 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
1567 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
1568 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
1569 * that is we're trying to allocate more than we've reserved.
1570 *
1571 * @param pGMM Pointer to the GMM instance data.
1572 * @param pGVM Pointer to the shared VM structure.
1573 * @param cPages The number of pages to allocate.
1574 * @param paPages Pointer to the page descriptors.
1575 * See GMMPAGEDESC for details on what is expected on input.
1576 * @param enmAccount The account to charge.
1577 */
1578static int gmmR0AllocatePages(PGMM pGMM, PGVM pGVM, uint32_t cPages, PGMMPAGEDESC paPages, GMMACCOUNT enmAccount)
1579{
1580 /*
1581 * Check allocation limits.
1582 */
1583 if (RT_UNLIKELY(pGMM->cAllocatedPages + cPages > pGMM->cMaxPages))
1584 return VERR_GMM_HIT_GLOBAL_LIMIT;
1585
1586 switch (enmAccount)
1587 {
1588 case GMMACCOUNT_BASE:
1589 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages + cPages > pGVM->gmm.s.Reserved.cBasePages))
1590 {
1591 Log(("gmmR0AllocatePages: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1592 pGVM->gmm.s.Reserved.cBasePages, pGVM->gmm.s.Allocated.cBasePages, cPages));
1593 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1594 }
1595 break;
1596 case GMMACCOUNT_SHADOW:
1597 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cShadowPages + cPages > pGVM->gmm.s.Reserved.cShadowPages))
1598 {
1599 Log(("gmmR0AllocatePages: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1600 pGVM->gmm.s.Reserved.cShadowPages, pGVM->gmm.s.Allocated.cShadowPages, cPages));
1601 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1602 }
1603 break;
1604 case GMMACCOUNT_FIXED:
1605 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cFixedPages + cPages > pGVM->gmm.s.Reserved.cFixedPages))
1606 {
1607 Log(("gmmR0AllocatePages: Reserved=%#llx Allocated+Requested=%#llx+%#x!\n",
1608 pGVM->gmm.s.Reserved.cFixedPages, pGVM->gmm.s.Allocated.cFixedPages, cPages));
1609 return VERR_GMM_HIT_VM_ACCOUNT_LIMIT;
1610 }
1611 break;
1612 default:
1613 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
1614 }
1615
1616 /*
1617 * Check if we need to allocate more memory or not. In legacy mode this is
1618 * a bit extra work but it's easier to do it upfront than bailing out later.
1619 */
1620 PGMMCHUNKFREESET pSet = &pGMM->Private;
1621 if (pSet->cPages < cPages)
1622 {
1623 if (pGMM->fLegacyMode)
1624 return VERR_GMM_SEED_ME;
1625
1626 int rc = gmmR0AllocateMoreChunks(pGMM, pSet, cPages);
1627 if (RT_FAILURE(rc))
1628 return rc;
1629 Assert(pSet->cPages >= cPages);
1630 }
1631 else if (pGMM->fLegacyMode)
1632 {
1633 uint16_t hGVM = pGVM->hSelf;
1634 uint32_t cPagesFound = 0;
1635 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists); i++)
1636 for (PGMMCHUNK pCur = pSet->apLists[i]; pCur; pCur = pCur->pFreeNext)
1637 if (pCur->hGVM == hGVM)
1638 {
1639 cPagesFound += pCur->cFree;
1640 if (cPagesFound >= cPages)
1641 break;
1642 }
1643 if (cPagesFound < cPages)
1644 return VERR_GMM_SEED_ME;
1645 }
1646
1647 /*
1648 * Pick the pages.
1649 */
1650 uint16_t hGVM = pGVM->hSelf;
1651 uint32_t iPage = 0;
1652 for (unsigned i = 0; i < RT_ELEMENTS(pSet->apLists) && iPage < cPages; i++)
1653 {
1654 /* first round, pick from chunks with an affinity to the VM. */
1655 PGMMCHUNK pCur = pSet->apLists[i];
1656 while (pCur && iPage < cPages)
1657 {
1658 PGMMCHUNK pNext = pCur->pFreeNext;
1659
1660 if ( pCur->hGVM == hGVM
1661 && ( pCur->cFree <= GMM_CHUNK_NUM_PAGES
1662 || pGMM->fLegacyMode))
1663 {
1664 gmmR0UnlinkChunk(pCur);
1665 for (; pCur->cFree && iPage < cPages; iPage++)
1666 gmmR0AllocatePage(pGMM, hGVM, pCur, &paPages[iPage]);
1667 gmmR0LinkChunk(pCur, pSet);
1668 }
1669
1670 pCur = pNext;
1671 }
1672
1673 /* second round, take all free pages in this list. */
1674 if (!pGMM->fLegacyMode)
1675 {
1676 PGMMCHUNK pCur = pSet->apLists[i];
1677 while (pCur && iPage < cPages)
1678 {
1679 PGMMCHUNK pNext = pCur->pFreeNext;
1680
1681 gmmR0UnlinkChunk(pCur);
1682 for (; pCur->cFree && iPage < cPages; iPage++)
1683 gmmR0AllocatePage(pGMM, hGVM, pCur, &paPages[iPage]);
1684 gmmR0LinkChunk(pCur, pSet);
1685
1686 pCur = pNext;
1687 }
1688 }
1689 }
1690
1691 /*
1692 * Update the account.
1693 */
1694 switch (enmAccount)
1695 {
1696 case GMMACCOUNT_BASE: pGVM->gmm.s.Allocated.cBasePages += iPage; break;
1697 case GMMACCOUNT_SHADOW: pGVM->gmm.s.Allocated.cShadowPages += iPage; break;
1698 case GMMACCOUNT_FIXED: pGVM->gmm.s.Allocated.cFixedPages += iPage; break;
1699 default:
1700 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
1701 }
1702 pGVM->gmm.s.cPrivatePages += iPage;
1703 pGMM->cAllocatedPages += iPage;
1704
1705 AssertMsgReturn(iPage == cPages, ("%d != %d\n", iPage, cPages), VERR_INTERNAL_ERROR);
1706
1707 /*
1708 * Check if we've reached some threshold and should kick one or two VMs and tell
1709 * them to inflate their balloons a bit more... later.
1710 */
1711
1712 return VINF_SUCCESS;
1713}
1714
1715
1716/**
1717 * Updates the previous allocations and allocates more pages.
1718 *
1719 * The handy pages are always taken from the 'base' memory account.
1720 * The allocated pages are not cleared and will contains random garbage.
1721 *
1722 * @returns VBox status code:
1723 * @retval VINF_SUCCESS on success.
1724 * @retval VERR_NOT_OWNER if the caller is not an EMT.
1725 * @retval VERR_GMM_PAGE_NOT_FOUND if one of the pages to update wasn't found.
1726 * @retval VERR_GMM_PAGE_NOT_PRIVATE if one of the pages to update wasn't a
1727 * private page.
1728 * @retval VERR_GMM_PAGE_NOT_SHARED if one of the pages to update wasn't a
1729 * shared page.
1730 * @retval VERR_GMM_NOT_PAGE_OWNER if one of the pages to be updated wasn't
1731 * owned by the VM.
1732 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
1733 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
1734 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
1735 * that is we're trying to allocate more than we've reserved.
1736 *
1737 * @param pVM Pointer to the shared VM structure.
1738 * @param cPagesToUpdate The number of pages to update (starting from the head).
1739 * @param cPagesToAlloc The number of pages to allocate (starting from the head).
1740 * @param paPages The array of page descriptors.
1741 * See GMMPAGEDESC for details on what is expected on input.
1742 * @thread EMT.
1743 */
1744GMMR0DECL(int) GMMR0AllocateHandyPages(PVM pVM, uint32_t cPagesToUpdate, uint32_t cPagesToAlloc, PGMMPAGEDESC paPages)
1745{
1746 LogFlow(("GMMR0AllocateHandyPages: pVM=%p cPagesToUpdate=%#x cPagesToAlloc=%#x paPages=%p\n",
1747 pVM, cPagesToUpdate, cPagesToAlloc, paPages));
1748
1749 /*
1750 * Validate, get basics and take the semaphore.
1751 * (This is a relatively busy path, so make predictions where possible.)
1752 */
1753 PGMM pGMM;
1754 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
1755 PGVM pGVM = GVMMR0ByVM(pVM);
1756 if (RT_UNLIKELY(!pGVM))
1757 return VERR_INVALID_PARAMETER;
1758 if (RT_UNLIKELY(pGVM->hEMT != RTThreadNativeSelf()))
1759 return VERR_NOT_OWNER;
1760
1761 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
1762 AssertMsgReturn( (cPagesToUpdate && cPagesToUpdate < 1024)
1763 || (cPagesToAlloc && cPagesToAlloc < 1024),
1764 ("cPagesToUpdate=%#x cPagesToAlloc=%#x\n", cPagesToUpdate, cPagesToAlloc),
1765 VERR_INVALID_PARAMETER);
1766
1767 unsigned iPage = 0;
1768 for (; iPage < cPagesToUpdate; iPage++)
1769 {
1770 AssertMsgReturn( ( paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST
1771 && !(paPages[iPage].HCPhysGCPhys & PAGE_OFFSET_MASK))
1772 || paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS
1773 || paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE,
1774 ("#%#x: %RHp\n", iPage, paPages[iPage].HCPhysGCPhys),
1775 VERR_INVALID_PARAMETER);
1776 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
1777 /*|| paPages[iPage].idPage == NIL_GMM_PAGEID*/,
1778 ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
1779 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
1780 /*|| paPages[iPage].idSharedPage == NIL_GMM_PAGEID*/,
1781 ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
1782 }
1783
1784 for (; iPage < cPagesToAlloc; iPage++)
1785 {
1786 AssertMsgReturn(paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS, ("#%#x: %RHp\n", iPage, paPages[iPage].HCPhysGCPhys), VERR_INVALID_PARAMETER);
1787 AssertMsgReturn(paPages[iPage].idPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
1788 AssertMsgReturn(paPages[iPage].idSharedPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
1789 }
1790
1791 int rc = RTSemFastMutexRequest(pGMM->Mtx);
1792 AssertRC(rc);
1793
1794 /* No allocations before the initial reservation has been made! */
1795 if (RT_LIKELY( pGVM->gmm.s.Reserved.cBasePages
1796 && pGVM->gmm.s.Reserved.cFixedPages
1797 && pGVM->gmm.s.Reserved.cShadowPages))
1798 {
1799 /*
1800 * Perform the updates.
1801 * Stop on the first error.
1802 */
1803 for (iPage = 0; iPage < cPagesToUpdate; iPage++)
1804 {
1805 if (paPages[iPage].idPage != NIL_GMM_PAGEID)
1806 {
1807 PGMMPAGE pPage = gmmR0GetPage(pGMM, paPages[iPage].idPage);
1808 if (RT_LIKELY(pPage))
1809 {
1810 if (RT_LIKELY(GMM_PAGE_IS_PRIVATE(pPage)))
1811 {
1812 if (RT_LIKELY(pPage->Private.hGVM == pGVM->hSelf))
1813 {
1814 AssertCompile(NIL_RTHCPHYS > GMM_GCPHYS_LAST && GMM_GCPHYS_UNSHAREABLE > GMM_GCPHYS_LAST);
1815 if (RT_LIKELY(paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST))
1816 pPage->Private.pfn = paPages[iPage].HCPhysGCPhys >> PAGE_SHIFT;
1817 else if (paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE)
1818 pPage->Private.pfn = GMM_PAGE_PFN_UNSHAREABLE;
1819 /* else: NIL_RTHCPHYS nothing */
1820
1821 paPages[iPage].idPage = NIL_GMM_PAGEID;
1822 paPages[iPage].HCPhysGCPhys = NIL_RTHCPHYS;
1823 }
1824 else
1825 {
1826 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not owner! hGVM=%#x hSelf=%#x\n",
1827 iPage, paPages[iPage].idPage, pPage->Private.hGVM, pGVM->hSelf));
1828 rc = VERR_GMM_NOT_PAGE_OWNER;
1829 break;
1830 }
1831 }
1832 else
1833 {
1834 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not private! %.*Rhxs\n", iPage, paPages[iPage].idPage, sizeof(*pPage), pPage));
1835 rc = VERR_GMM_PAGE_NOT_PRIVATE;
1836 break;
1837 }
1838 }
1839 else
1840 {
1841 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not found! (private)\n", iPage, paPages[iPage].idPage));
1842 rc = VERR_GMM_PAGE_NOT_FOUND;
1843 break;
1844 }
1845 }
1846
1847 if (paPages[iPage].idSharedPage != NIL_GMM_PAGEID)
1848 {
1849 PGMMPAGE pPage = gmmR0GetPage(pGMM, paPages[iPage].idSharedPage);
1850 if (RT_LIKELY(pPage))
1851 {
1852 if (RT_LIKELY(GMM_PAGE_IS_SHARED(pPage)))
1853 {
1854 AssertCompile(NIL_RTHCPHYS > GMM_GCPHYS_LAST && GMM_GCPHYS_UNSHAREABLE > GMM_GCPHYS_LAST);
1855 Assert(pPage->Shared.cRefs);
1856 Assert(pGVM->gmm.s.cSharedPages);
1857 Assert(pGVM->gmm.s.Allocated.cBasePages);
1858
1859 pGVM->gmm.s.cSharedPages--;
1860 pGVM->gmm.s.Allocated.cBasePages--;
1861 if (!--pPage->Shared.cRefs)
1862 gmmR0FreeSharedPage(pGMM, paPages[iPage].idSharedPage, pPage);
1863
1864 paPages[iPage].idSharedPage = NIL_GMM_PAGEID;
1865 }
1866 else
1867 {
1868 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not shared!\n", iPage, paPages[iPage].idSharedPage));
1869 rc = VERR_GMM_PAGE_NOT_SHARED;
1870 break;
1871 }
1872 }
1873 else
1874 {
1875 Log(("GMMR0AllocateHandyPages: #%#x/%#x: Not found! (shared)\n", iPage, paPages[iPage].idSharedPage));
1876 rc = VERR_GMM_PAGE_NOT_FOUND;
1877 break;
1878 }
1879 }
1880 }
1881
1882 /*
1883 * Join paths with GMMR0AllocatePages for the allocation.
1884 */
1885 if (RT_SUCCESS(rc))
1886 rc = gmmR0AllocatePages(pGMM, pGVM, cPagesToAlloc, paPages, GMMACCOUNT_BASE);
1887 }
1888 else
1889 rc = VERR_WRONG_ORDER;
1890
1891 RTSemFastMutexRelease(pGMM->Mtx);
1892 LogFlow(("GMMR0AllocateHandyPages: returns %Rrc\n", rc));
1893 return rc;
1894}
1895
1896
1897/**
1898 * Allocate one or more pages.
1899 *
1900 * This is typically used for ROMs and MMIO2 (VRAM) during VM creation.
1901 * The allocated pages are not cleared and will contains random garbage.
1902 *
1903 * @returns VBox status code:
1904 * @retval VINF_SUCCESS on success.
1905 * @retval VERR_NOT_OWNER if the caller is not an EMT.
1906 * @retval VERR_GMM_SEED_ME if seeding via GMMR0SeedChunk is necessary.
1907 * @retval VERR_GMM_HIT_GLOBAL_LIMIT if we've exhausted the available pages.
1908 * @retval VERR_GMM_HIT_VM_ACCOUNT_LIMIT if we've hit the VM account limit,
1909 * that is we're trying to allocate more than we've reserved.
1910 *
1911 * @param pVM Pointer to the shared VM structure.
1912 * @param cPages The number of pages to allocate.
1913 * @param paPages Pointer to the page descriptors.
1914 * See GMMPAGEDESC for details on what is expected on input.
1915 * @param enmAccount The account to charge.
1916 *
1917 * @thread EMT.
1918 */
1919GMMR0DECL(int) GMMR0AllocatePages(PVM pVM, uint32_t cPages, PGMMPAGEDESC paPages, GMMACCOUNT enmAccount)
1920{
1921 LogFlow(("GMMR0AllocatePages: pVM=%p cPages=%#x paPages=%p enmAccount=%d\n", pVM, cPages, paPages, enmAccount));
1922
1923 /*
1924 * Validate, get basics and take the semaphore.
1925 */
1926 PGMM pGMM;
1927 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
1928 PGVM pGVM = GVMMR0ByVM(pVM);
1929 if (!pGVM)
1930 return VERR_INVALID_PARAMETER;
1931 if (pGVM->hEMT != RTThreadNativeSelf())
1932 return VERR_NOT_OWNER;
1933
1934 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
1935 AssertMsgReturn(enmAccount > GMMACCOUNT_INVALID && enmAccount < GMMACCOUNT_END, ("%d\n", enmAccount), VERR_INVALID_PARAMETER);
1936 AssertMsgReturn(cPages > 0 && cPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cPages), VERR_INVALID_PARAMETER);
1937
1938 for (unsigned iPage = 0; iPage < cPages; iPage++)
1939 {
1940 AssertMsgReturn( paPages[iPage].HCPhysGCPhys == NIL_RTHCPHYS
1941 || paPages[iPage].HCPhysGCPhys == GMM_GCPHYS_UNSHAREABLE
1942 || ( enmAccount == GMMACCOUNT_BASE
1943 && paPages[iPage].HCPhysGCPhys <= GMM_GCPHYS_LAST
1944 && !(paPages[iPage].HCPhysGCPhys & PAGE_OFFSET_MASK)),
1945 ("#%#x: %RHp enmAccount=%d\n", iPage, paPages[iPage].HCPhysGCPhys, enmAccount),
1946 VERR_INVALID_PARAMETER);
1947 AssertMsgReturn(paPages[iPage].idPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
1948 AssertMsgReturn(paPages[iPage].idSharedPage == NIL_GMM_PAGEID, ("#%#x: %#x\n", iPage, paPages[iPage].idSharedPage), VERR_INVALID_PARAMETER);
1949 }
1950
1951 int rc = RTSemFastMutexRequest(pGMM->Mtx);
1952 AssertRC(rc);
1953
1954 /* No allocations before the initial reservation has been made! */
1955 if ( pGVM->gmm.s.Reserved.cBasePages
1956 && pGVM->gmm.s.Reserved.cFixedPages
1957 && pGVM->gmm.s.Reserved.cShadowPages)
1958 rc = gmmR0AllocatePages(pGMM, pGVM, cPages, paPages, enmAccount);
1959 else
1960 rc = VERR_WRONG_ORDER;
1961
1962 RTSemFastMutexRelease(pGMM->Mtx);
1963 LogFlow(("GMMR0AllocatePages: returns %Rrc\n", rc));
1964 return rc;
1965}
1966
1967
1968/**
1969 * VMMR0 request wrapper for GMMR0AllocatePages.
1970 *
1971 * @returns see GMMR0AllocatePages.
1972 * @param pVM Pointer to the shared VM structure.
1973 * @param pReq The request packet.
1974 */
1975GMMR0DECL(int) GMMR0AllocatePagesReq(PVM pVM, PGMMALLOCATEPAGESREQ pReq)
1976{
1977 /*
1978 * Validate input and pass it on.
1979 */
1980 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1981 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1982 AssertMsgReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[0]),
1983 ("%#x < %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[0])),
1984 VERR_INVALID_PARAMETER);
1985 AssertMsgReturn(pReq->Hdr.cbReq == RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[pReq->cPages]),
1986 ("%#x != %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMALLOCATEPAGESREQ, aPages[pReq->cPages])),
1987 VERR_INVALID_PARAMETER);
1988
1989 return GMMR0AllocatePages(pVM, pReq->cPages, &pReq->aPages[0], pReq->enmAccount);
1990}
1991
1992
1993/**
1994 * Frees a chunk, giving it back to the host OS.
1995 *
1996 * @param pGMM Pointer to the GMM instance.
1997 * @param pChunk The chunk to free.
1998 */
1999static void gmmR0FreeChunk(PGMM pGMM, PGMMCHUNK pChunk)
2000{
2001 /*
2002 * If there are current mappings of the chunk, then request the
2003 * VMs to unmap them. Reposition the chunk in the free list so
2004 * it won't be a likely candidate for allocations.
2005 */
2006 if (pChunk->cMappings)
2007 {
2008 /** @todo R0 -> VM request */
2009
2010 }
2011 else
2012 {
2013 /*
2014 * Try free the memory object.
2015 */
2016 int rc = RTR0MemObjFree(pChunk->MemObj, false /* fFreeMappings */);
2017 if (RT_SUCCESS(rc))
2018 {
2019 pChunk->MemObj = NIL_RTR0MEMOBJ;
2020
2021 /*
2022 * Unlink it from everywhere.
2023 */
2024 gmmR0UnlinkChunk(pChunk);
2025
2026 PAVLU32NODECORE pCore = RTAvlU32Remove(&pGMM->pChunks, pChunk->Core.Key);
2027 Assert(pCore == &pChunk->Core); NOREF(pCore);
2028
2029 PGMMCHUNKTLBE pTlbe = &pGMM->ChunkTLB.aEntries[GMM_CHUNKTLB_IDX(pCore->Key)];
2030 if (pTlbe->pChunk == pChunk)
2031 {
2032 pTlbe->idChunk = NIL_GMM_CHUNKID;
2033 pTlbe->pChunk = NULL;
2034 }
2035
2036 Assert(pGMM->cChunks > 0);
2037 pGMM->cChunks--;
2038
2039 /*
2040 * Free the Chunk ID and struct.
2041 */
2042 gmmR0FreeChunkId(pGMM, pChunk->Core.Key);
2043 pChunk->Core.Key = NIL_GMM_CHUNKID;
2044
2045 RTMemFree(pChunk->paMappings);
2046 pChunk->paMappings = NULL;
2047
2048 RTMemFree(pChunk);
2049 }
2050 else
2051 AssertRC(rc);
2052 }
2053}
2054
2055
2056/**
2057 * Free page worker.
2058 *
2059 * The caller does all the statistic decrementing, we do all the incrementing.
2060 *
2061 * @param pGMM Pointer to the GMM instance data.
2062 * @param pChunk Pointer to the chunk this page belongs to.
2063 * @param idPage The Page ID.
2064 * @param pPage Pointer to the page.
2065 */
2066static void gmmR0FreePageWorker(PGMM pGMM, PGMMCHUNK pChunk, uint32_t idPage, PGMMPAGE pPage)
2067{
2068 Log3(("F pPage=%p iPage=%#x/%#x u2State=%d iFreeHead=%#x\n",
2069 pPage, pPage - &pChunk->aPages[0], idPage, pPage->Common.u2State, pChunk->iFreeHead)); NOREF(idPage);
2070
2071 /*
2072 * Put the page on the free list.
2073 */
2074 pPage->u = 0;
2075 pPage->Free.u2State = GMM_PAGE_STATE_FREE;
2076 Assert(pChunk->iFreeHead < RT_ELEMENTS(pChunk->aPages) || pChunk->iFreeHead == UINT16_MAX);
2077 pPage->Free.iNext = pChunk->iFreeHead;
2078 pChunk->iFreeHead = pPage - &pChunk->aPages[0];
2079
2080 /*
2081 * Update statistics (the cShared/cPrivate stats are up to date already),
2082 * and relink the chunk if necessary.
2083 */
2084 if ((pChunk->cFree & GMM_CHUNK_FREE_SET_MASK) == 0)
2085 {
2086 gmmR0UnlinkChunk(pChunk);
2087 pChunk->cFree++;
2088 gmmR0LinkChunk(pChunk, pChunk->cShared ? &pGMM->Shared : &pGMM->Private);
2089 }
2090 else
2091 {
2092 pChunk->cFree++;
2093 pChunk->pSet->cPages++;
2094
2095 /*
2096 * If the chunk becomes empty, consider giving memory back to the host OS.
2097 *
2098 * The current strategy is to try give it back if there are other chunks
2099 * in this free list, meaning if there are at least 240 free pages in this
2100 * category. Note that since there are probably mappings of the chunk,
2101 * it won't be freed up instantly, which probably screws up this logic
2102 * a bit...
2103 */
2104 if (RT_UNLIKELY( pChunk->cFree == GMM_CHUNK_NUM_PAGES
2105 && pChunk->pFreeNext
2106 && pChunk->pFreePrev
2107 && !pGMM->fLegacyMode))
2108 gmmR0FreeChunk(pGMM, pChunk);
2109 }
2110}
2111
2112
2113/**
2114 * Frees a shared page, the page is known to exist and be valid and such.
2115 *
2116 * @param pGMM Pointer to the GMM instance.
2117 * @param idPage The Page ID
2118 * @param pPage The page structure.
2119 */
2120DECLINLINE(void) gmmR0FreeSharedPage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage)
2121{
2122 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2123 Assert(pChunk);
2124 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2125 Assert(pChunk->cShared > 0);
2126 Assert(pGMM->cSharedPages > 0);
2127 Assert(pGMM->cAllocatedPages > 0);
2128 Assert(!pPage->Shared.cRefs);
2129
2130 pChunk->cShared--;
2131 pGMM->cAllocatedPages--;
2132 pGMM->cSharedPages--;
2133 gmmR0FreePageWorker(pGMM, pChunk, idPage, pPage);
2134}
2135
2136
2137/**
2138 * Frees a private page, the page is known to exist and be valid and such.
2139 *
2140 * @param pGMM Pointer to the GMM instance.
2141 * @param idPage The Page ID
2142 * @param pPage The page structure.
2143 */
2144DECLINLINE(void) gmmR0FreePrivatePage(PGMM pGMM, uint32_t idPage, PGMMPAGE pPage)
2145{
2146 PGMMCHUNK pChunk = gmmR0GetChunk(pGMM, idPage >> GMM_CHUNKID_SHIFT);
2147 Assert(pChunk);
2148 Assert(pChunk->cFree < GMM_CHUNK_NUM_PAGES);
2149 Assert(pChunk->cPrivate > 0);
2150 Assert(pGMM->cAllocatedPages > 0);
2151
2152 pChunk->cPrivate--;
2153 pGMM->cAllocatedPages--;
2154 gmmR0FreePageWorker(pGMM, pChunk, idPage, pPage);
2155}
2156
2157
2158/**
2159 * Common worker for GMMR0FreePages and GMMR0BalloonedPages.
2160 *
2161 * @returns VBox status code:
2162 * @retval xxx
2163 *
2164 * @param pGMM Pointer to the GMM instance data.
2165 * @param pGVM Pointer to the shared VM structure.
2166 * @param cPages The number of pages to free.
2167 * @param paPages Pointer to the page descriptors.
2168 * @param enmAccount The account this relates to.
2169 */
2170static int gmmR0FreePages(PGMM pGMM, PGVM pGVM, uint32_t cPages, PGMMFREEPAGEDESC paPages, GMMACCOUNT enmAccount)
2171{
2172 /*
2173 * Check that the request isn't impossible wrt to the account status.
2174 */
2175 switch (enmAccount)
2176 {
2177 case GMMACCOUNT_BASE:
2178 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cBasePages < cPages))
2179 {
2180 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cBasePages, cPages));
2181 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2182 }
2183 break;
2184 case GMMACCOUNT_SHADOW:
2185 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cShadowPages < cPages))
2186 {
2187 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cShadowPages, cPages));
2188 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2189 }
2190 break;
2191 case GMMACCOUNT_FIXED:
2192 if (RT_UNLIKELY(pGVM->gmm.s.Allocated.cFixedPages < cPages))
2193 {
2194 Log(("gmmR0FreePages: allocated=%#llx cPages=%#x!\n", pGVM->gmm.s.Allocated.cFixedPages, cPages));
2195 return VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2196 }
2197 break;
2198 default:
2199 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
2200 }
2201
2202 /*
2203 * Walk the descriptors and free the pages.
2204 *
2205 * Statistics (except the account) are being updated as we go along,
2206 * unlike the alloc code. Also, stop on the first error.
2207 */
2208 int rc = VINF_SUCCESS;
2209 uint32_t iPage;
2210 for (iPage = 0; iPage < cPages; iPage++)
2211 {
2212 uint32_t idPage = paPages[iPage].idPage;
2213 PGMMPAGE pPage = gmmR0GetPage(pGMM, idPage);
2214 if (RT_LIKELY(pPage))
2215 {
2216 if (RT_LIKELY(GMM_PAGE_IS_PRIVATE(pPage)))
2217 {
2218 if (RT_LIKELY(pPage->Private.hGVM == pGVM->hSelf))
2219 {
2220 Assert(pGVM->gmm.s.cPrivatePages);
2221 pGVM->gmm.s.cPrivatePages--;
2222 gmmR0FreePrivatePage(pGMM, idPage, pPage);
2223 }
2224 else
2225 {
2226 Log(("gmmR0AllocatePages: #%#x/%#x: not owner! hGVM=%#x hSelf=%#x\n", iPage, idPage,
2227 pPage->Private.hGVM, pGVM->hEMT));
2228 rc = VERR_GMM_NOT_PAGE_OWNER;
2229 break;
2230 }
2231 }
2232 else if (RT_LIKELY(GMM_PAGE_IS_SHARED(pPage)))
2233 {
2234 Assert(pGVM->gmm.s.cSharedPages);
2235 pGVM->gmm.s.cSharedPages--;
2236 Assert(pPage->Shared.cRefs);
2237 if (!--pPage->Shared.cRefs)
2238 gmmR0FreeSharedPage(pGMM, idPage, pPage);
2239 }
2240 else
2241 {
2242 Log(("gmmR0AllocatePages: #%#x/%#x: already free!\n", iPage, idPage));
2243 rc = VERR_GMM_PAGE_ALREADY_FREE;
2244 break;
2245 }
2246 }
2247 else
2248 {
2249 Log(("gmmR0AllocatePages: #%#x/%#x: not found!\n", iPage, idPage));
2250 rc = VERR_GMM_PAGE_NOT_FOUND;
2251 break;
2252 }
2253 paPages[iPage].idPage = NIL_GMM_PAGEID;
2254 }
2255
2256 /*
2257 * Update the account.
2258 */
2259 switch (enmAccount)
2260 {
2261 case GMMACCOUNT_BASE: pGVM->gmm.s.Allocated.cBasePages -= iPage; break;
2262 case GMMACCOUNT_SHADOW: pGVM->gmm.s.Allocated.cShadowPages -= iPage; break;
2263 case GMMACCOUNT_FIXED: pGVM->gmm.s.Allocated.cFixedPages -= iPage; break;
2264 default:
2265 AssertMsgFailedReturn(("enmAccount=%d\n", enmAccount), VERR_INTERNAL_ERROR);
2266 }
2267
2268 /*
2269 * Any threshold stuff to be done here?
2270 */
2271
2272 return rc;
2273}
2274
2275
2276/**
2277 * Free one or more pages.
2278 *
2279 * This is typically used at reset time or power off.
2280 *
2281 * @returns VBox status code:
2282 * @retval xxx
2283 *
2284 * @param pVM Pointer to the shared VM structure.
2285 * @param cPages The number of pages to allocate.
2286 * @param paPages Pointer to the page descriptors containing the Page IDs for each page.
2287 * @param enmAccount The account this relates to.
2288 * @thread EMT.
2289 */
2290GMMR0DECL(int) GMMR0FreePages(PVM pVM, uint32_t cPages, PGMMFREEPAGEDESC paPages, GMMACCOUNT enmAccount)
2291{
2292 LogFlow(("GMMR0FreePages: pVM=%p cPages=%#x paPages=%p enmAccount=%d\n", pVM, cPages, paPages, enmAccount));
2293
2294 /*
2295 * Validate input and get the basics.
2296 */
2297 PGMM pGMM;
2298 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2299 PGVM pGVM = GVMMR0ByVM(pVM);
2300 if (!pGVM)
2301 return VERR_INVALID_PARAMETER;
2302 if (pGVM->hEMT != RTThreadNativeSelf())
2303 return VERR_NOT_OWNER;
2304
2305 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2306 AssertMsgReturn(enmAccount > GMMACCOUNT_INVALID && enmAccount < GMMACCOUNT_END, ("%d\n", enmAccount), VERR_INVALID_PARAMETER);
2307 AssertMsgReturn(cPages > 0 && cPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cPages), VERR_INVALID_PARAMETER);
2308
2309 for (unsigned iPage = 0; iPage < cPages; iPage++)
2310 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
2311 /*|| paPages[iPage].idPage == NIL_GMM_PAGEID*/,
2312 ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2313
2314 /*
2315 * Take the semaphore and call the worker function.
2316 */
2317 int rc = RTSemFastMutexRequest(pGMM->Mtx);
2318 AssertRC(rc);
2319
2320 rc = gmmR0FreePages(pGMM, pGVM, cPages, paPages, enmAccount);
2321
2322 RTSemFastMutexRelease(pGMM->Mtx);
2323 LogFlow(("GMMR0FreePages: returns %Rrc\n", rc));
2324 return rc;
2325}
2326
2327
2328/**
2329 * VMMR0 request wrapper for GMMR0FreePages.
2330 *
2331 * @returns see GMMR0FreePages.
2332 * @param pVM Pointer to the shared VM structure.
2333 * @param pReq The request packet.
2334 */
2335GMMR0DECL(int) GMMR0FreePagesReq(PVM pVM, PGMMFREEPAGESREQ pReq)
2336{
2337 /*
2338 * Validate input and pass it on.
2339 */
2340 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2341 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2342 AssertMsgReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[0]),
2343 ("%#x < %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[0])),
2344 VERR_INVALID_PARAMETER);
2345 AssertMsgReturn(pReq->Hdr.cbReq == RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[pReq->cPages]),
2346 ("%#x != %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMFREEPAGESREQ, aPages[pReq->cPages])),
2347 VERR_INVALID_PARAMETER);
2348
2349 return GMMR0FreePages(pVM, pReq->cPages, &pReq->aPages[0], pReq->enmAccount);
2350}
2351
2352
2353/**
2354 * Report back on a memory ballooning request.
2355 *
2356 * The request may or may not have been initiated by the GMM. If it was initiated
2357 * by the GMM it is important that this function is called even if no pages was
2358 * ballooned.
2359 *
2360 * Since the whole purpose of ballooning is to free up guest RAM pages, this API
2361 * may also be given a set of related pages to be freed. These pages are assumed
2362 * to be on the base account.
2363 *
2364 * @returns VBox status code:
2365 * @retval xxx
2366 *
2367 * @param pVM Pointer to the shared VM structure.
2368 * @param cBalloonedPages The number of pages that was ballooned.
2369 * @param cPagesToFree The number of pages to be freed.
2370 * @param paPages Pointer to the page descriptors for the pages that's to be freed.
2371 * @param fCompleted Indicates whether the ballooning request was completed (true) or
2372 * if there is more pages to come (false). If the ballooning was not
2373 * not triggered by the GMM, don't set this.
2374 * @thread EMT.
2375 */
2376GMMR0DECL(int) GMMR0BalloonedPages(PVM pVM, uint32_t cBalloonedPages, uint32_t cPagesToFree, PGMMFREEPAGEDESC paPages, bool fCompleted)
2377{
2378 LogFlow(("GMMR0BalloonedPages: pVM=%p cBalloonedPages=%#x cPagestoFree=%#x paPages=%p enmAccount=%d fCompleted=%RTbool\n",
2379 pVM, cBalloonedPages, cPagesToFree, paPages, fCompleted));
2380
2381 /*
2382 * Validate input and get the basics.
2383 */
2384 PGMM pGMM;
2385 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2386 PGVM pGVM = GVMMR0ByVM(pVM);
2387 if (!pGVM)
2388 return VERR_INVALID_PARAMETER;
2389 if (pGVM->hEMT != RTThreadNativeSelf())
2390 return VERR_NOT_OWNER;
2391
2392 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2393 AssertMsgReturn(cBalloonedPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cBalloonedPages), VERR_INVALID_PARAMETER);
2394 AssertMsgReturn(cPagesToFree <= cBalloonedPages, ("%#x\n", cPagesToFree), VERR_INVALID_PARAMETER);
2395
2396 for (unsigned iPage = 0; iPage < cPagesToFree; iPage++)
2397 AssertMsgReturn( paPages[iPage].idPage <= GMM_PAGEID_LAST
2398 /*|| paPages[iPage].idPage == NIL_GMM_PAGEID*/,
2399 ("#%#x: %#x\n", iPage, paPages[iPage].idPage), VERR_INVALID_PARAMETER);
2400
2401 /*
2402 * Take the sempahore and do some more validations.
2403 */
2404 int rc = RTSemFastMutexRequest(pGMM->Mtx);
2405 AssertRC(rc);
2406 if (pGVM->gmm.s.Allocated.cBasePages >= cPagesToFree)
2407 {
2408 /*
2409 * Record the ballooned memory.
2410 */
2411 pGMM->cBalloonedPages += cBalloonedPages;
2412 if (pGVM->gmm.s.cReqBalloonedPages)
2413 {
2414 pGVM->gmm.s.cBalloonedPages += cBalloonedPages;
2415 pGVM->gmm.s.cReqActuallyBalloonedPages += cBalloonedPages;
2416 if (fCompleted)
2417 {
2418 Log(("GMMR0BalloonedPages: +%#x - Global=%#llx; / VM: Total=%#llx Req=%#llx Actual=%#llx (completed)\n", cBalloonedPages,
2419 pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages, pGVM->gmm.s.cReqBalloonedPages, pGVM->gmm.s.cReqActuallyBalloonedPages));
2420
2421 /*
2422 * Anything we need to do here now when the request has been completed?
2423 */
2424 pGVM->gmm.s.cReqBalloonedPages = 0;
2425 }
2426 else
2427 Log(("GMMR0BalloonedPages: +%#x - Global=%#llx / VM: Total=%#llx Req=%#llx Actual=%#llx (pending)\n", cBalloonedPages,
2428 pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages, pGVM->gmm.s.cReqBalloonedPages, pGVM->gmm.s.cReqActuallyBalloonedPages));
2429 }
2430 else
2431 {
2432 pGVM->gmm.s.cBalloonedPages += cBalloonedPages;
2433 Log(("GMMR0BalloonedPages: +%#x - Global=%#llx / VM: Total=%#llx (user)\n",
2434 cBalloonedPages, pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages));
2435 }
2436
2437 /*
2438 * Any pages to free?
2439 */
2440 if (cPagesToFree)
2441 rc = gmmR0FreePages(pGMM, pGVM, cPagesToFree, paPages, GMMACCOUNT_BASE);
2442 }
2443 else
2444 {
2445 rc = VERR_GMM_ATTEMPT_TO_FREE_TOO_MUCH;
2446 }
2447
2448 RTSemFastMutexRelease(pGMM->Mtx);
2449 LogFlow(("GMMR0BalloonedPages: returns %Rrc\n", rc));
2450 return rc;
2451}
2452
2453
2454/**
2455 * VMMR0 request wrapper for GMMR0BalloonedPages.
2456 *
2457 * @returns see GMMR0BalloonedPages.
2458 * @param pVM Pointer to the shared VM structure.
2459 * @param pReq The request packet.
2460 */
2461GMMR0DECL(int) GMMR0BalloonedPagesReq(PVM pVM, PGMMBALLOONEDPAGESREQ pReq)
2462{
2463 /*
2464 * Validate input and pass it on.
2465 */
2466 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2467 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2468 AssertMsgReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF(GMMBALLOONEDPAGESREQ, aPages[0]),
2469 ("%#x < %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMBALLOONEDPAGESREQ, aPages[0])),
2470 VERR_INVALID_PARAMETER);
2471 AssertMsgReturn(pReq->Hdr.cbReq == RT_UOFFSETOF(GMMBALLOONEDPAGESREQ, aPages[pReq->cPagesToFree]),
2472 ("%#x != %#x\n", pReq->Hdr.cbReq, RT_UOFFSETOF(GMMBALLOONEDPAGESREQ, aPages[pReq->cPagesToFree])),
2473 VERR_INVALID_PARAMETER);
2474
2475 return GMMR0BalloonedPages(pVM, pReq->cBalloonedPages, pReq->cPagesToFree, &pReq->aPages[0], pReq->fCompleted);
2476}
2477
2478
2479/**
2480 * Report balloon deflating.
2481 *
2482 * @returns VBox status code:
2483 * @retval xxx
2484 *
2485 * @param pVM Pointer to the shared VM structure.
2486 * @param cPages The number of pages that was let out of the balloon.
2487 * @thread EMT.
2488 */
2489GMMR0DECL(int) GMMR0DeflatedBalloon(PVM pVM, uint32_t cPages)
2490{
2491 LogFlow(("GMMR0DeflatedBalloon: pVM=%p cPages=%#x\n", pVM, cPages));
2492
2493 /*
2494 * Validate input and get the basics.
2495 */
2496 PGMM pGMM;
2497 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2498 PGVM pGVM = GVMMR0ByVM(pVM);
2499 if (!pGVM)
2500 return VERR_INVALID_PARAMETER;
2501 if (pGVM->hEMT != RTThreadNativeSelf())
2502 return VERR_NOT_OWNER;
2503
2504 AssertMsgReturn(cPages < RT_BIT(32 - PAGE_SHIFT), ("%#x\n", cPages), VERR_INVALID_PARAMETER);
2505
2506 /*
2507 * Take the sempahore and do some more validations.
2508 */
2509 int rc = RTSemFastMutexRequest(pGMM->Mtx);
2510 AssertRC(rc);
2511
2512 if (pGVM->gmm.s.cBalloonedPages < cPages)
2513 {
2514 Assert(pGMM->cBalloonedPages >= pGVM->gmm.s.cBalloonedPages);
2515
2516 /*
2517 * Record it.
2518 */
2519 pGMM->cBalloonedPages -= cPages;
2520 pGVM->gmm.s.cBalloonedPages -= cPages;
2521 if (pGVM->gmm.s.cReqDeflatePages)
2522 {
2523 Log(("GMMR0BalloonedPages: -%#x - Global=%#llx / VM: Total=%#llx Req=%#llx\n", cPages,
2524 pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages, pGVM->gmm.s.cReqDeflatePages));
2525
2526 /*
2527 * Anything we need to do here now when the request has been completed?
2528 */
2529 pGVM->gmm.s.cReqDeflatePages = 0;
2530 }
2531 else
2532 Log(("GMMR0BalloonedPages: -%#x - Global=%#llx / VM: Total=%#llx\n", cPages,
2533 pGMM->cBalloonedPages, pGVM->gmm.s.cBalloonedPages));
2534 }
2535 else
2536 {
2537 Log(("GMMR0DeflatedBalloon: cBalloonedPages=%#llx cPages=%#x\n", pGVM->gmm.s.cBalloonedPages, cPages));
2538 rc = VERR_GMM_ATTEMPT_TO_DEFLATE_TOO_MUCH;
2539 }
2540
2541 RTSemFastMutexRelease(pGMM->Mtx);
2542 LogFlow(("GMMR0BalloonedPages: returns %Rrc\n", rc));
2543 return rc;
2544}
2545
2546
2547/**
2548 * Unmaps a chunk previously mapped into the address space of the current process.
2549 *
2550 * @returns VBox status code.
2551 * @param pGMM Pointer to the GMM instance data.
2552 * @param pGVM Pointer to the Global VM structure.
2553 * @param pChunk Pointer to the chunk to be unmapped.
2554 */
2555static int gmmR0UnmapChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk)
2556{
2557 if (!pGMM->fLegacyMode)
2558 {
2559 /*
2560 * Find the mapping and try unmapping it.
2561 */
2562 for (uint32_t i = 0; i < pChunk->cMappings; i++)
2563 {
2564 Assert(pChunk->paMappings[i].pGVM && pChunk->paMappings[i].MapObj != NIL_RTR0MEMOBJ);
2565 if (pChunk->paMappings[i].pGVM == pGVM)
2566 {
2567 /* unmap */
2568 int rc = RTR0MemObjFree(pChunk->paMappings[i].MapObj, false /* fFreeMappings (NA) */);
2569 if (RT_SUCCESS(rc))
2570 {
2571 /* update the record. */
2572 pChunk->cMappings--;
2573 if (i < pChunk->cMappings)
2574 pChunk->paMappings[i] = pChunk->paMappings[pChunk->cMappings];
2575 pChunk->paMappings[pChunk->cMappings].MapObj = NIL_RTR0MEMOBJ;
2576 pChunk->paMappings[pChunk->cMappings].pGVM = NULL;
2577 }
2578 return rc;
2579 }
2580 }
2581 }
2582 else if (pChunk->hGVM == pGVM->hSelf)
2583 return VINF_SUCCESS;
2584
2585 Log(("gmmR0MapChunk: Chunk %#x is not mapped into pGVM=%p/%#x\n", pChunk->Core.Key, pGVM, pGVM->hSelf));
2586 return VERR_GMM_CHUNK_NOT_MAPPED;
2587}
2588
2589
2590/**
2591 * Maps a chunk into the user address space of the current process.
2592 *
2593 * @returns VBox status code.
2594 * @param pGMM Pointer to the GMM instance data.
2595 * @param pGVM Pointer to the Global VM structure.
2596 * @param pChunk Pointer to the chunk to be mapped.
2597 * @param ppvR3 Where to store the ring-3 address of the mapping.
2598 * In the VERR_GMM_CHUNK_ALREADY_MAPPED case, this will be
2599 * contain the address of the existing mapping.
2600 */
2601static int gmmR0MapChunk(PGMM pGMM, PGVM pGVM, PGMMCHUNK pChunk, PRTR3PTR ppvR3)
2602{
2603 /*
2604 * If we're in legacy mode this is simple.
2605 */
2606 if (pGMM->fLegacyMode)
2607 {
2608 if (pChunk->hGVM != pGVM->hSelf)
2609 {
2610 Log(("gmmR0MapChunk: chunk %#x is already mapped at %p!\n", pChunk->Core.Key, *ppvR3));
2611 return VERR_GMM_CHUNK_NOT_FOUND;
2612 }
2613
2614 *ppvR3 = RTR0MemObjAddressR3(pChunk->MemObj);
2615 return VINF_SUCCESS;
2616 }
2617
2618 /*
2619 * Check to see if the chunk is already mapped.
2620 */
2621 for (uint32_t i = 0; i < pChunk->cMappings; i++)
2622 {
2623 Assert(pChunk->paMappings[i].pGVM && pChunk->paMappings[i].MapObj != NIL_RTR0MEMOBJ);
2624 if (pChunk->paMappings[i].pGVM == pGVM)
2625 {
2626 *ppvR3 = RTR0MemObjAddressR3(pChunk->paMappings[i].MapObj);
2627 Log(("gmmR0MapChunk: chunk %#x is already mapped at %p!\n", pChunk->Core.Key, *ppvR3));
2628 return VERR_GMM_CHUNK_ALREADY_MAPPED;
2629 }
2630 }
2631
2632 /*
2633 * Do the mapping.
2634 */
2635 RTR0MEMOBJ MapObj;
2636 int rc = RTR0MemObjMapUser(&MapObj, pChunk->MemObj, (RTR3PTR)-1, 0, RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
2637 if (RT_SUCCESS(rc))
2638 {
2639 /* reallocate the array? */
2640 if ((pChunk->cMappings & 1 /*7*/) == 0)
2641 {
2642 void *pvMappings = RTMemRealloc(pChunk->paMappings, (pChunk->cMappings + 2 /*8*/) * sizeof(pChunk->paMappings[0]));
2643 if (RT_UNLIKELY(pvMappings))
2644 {
2645 rc = RTR0MemObjFree(MapObj, false /* fFreeMappings (NA) */);
2646 AssertRC(rc);
2647 return VERR_NO_MEMORY;
2648 }
2649 pChunk->paMappings = (PGMMCHUNKMAP)pvMappings;
2650 }
2651
2652 /* insert new entry */
2653 pChunk->paMappings[pChunk->cMappings].MapObj = MapObj;
2654 pChunk->paMappings[pChunk->cMappings].pGVM = pGVM;
2655 pChunk->cMappings++;
2656
2657 *ppvR3 = RTR0MemObjAddressR3(MapObj);
2658 }
2659
2660 return rc;
2661}
2662
2663
2664/**
2665 * Map a chunk and/or unmap another chunk.
2666 *
2667 * The mapping and unmapping applies to the current process.
2668 *
2669 * This API does two things because it saves a kernel call per mapping when
2670 * when the ring-3 mapping cache is full.
2671 *
2672 * @returns VBox status code.
2673 * @param pVM The VM.
2674 * @param idChunkMap The chunk to map. NIL_GMM_CHUNKID if nothing to map.
2675 * @param idChunkUnmap The chunk to unmap. NIL_GMM_CHUNKID if nothing to unmap.
2676 * @param ppvR3 Where to store the address of the mapped chunk. NULL is ok if nothing to map.
2677 * @thread EMT
2678 */
2679GMMR0DECL(int) GMMR0MapUnmapChunk(PVM pVM, uint32_t idChunkMap, uint32_t idChunkUnmap, PRTR3PTR ppvR3)
2680{
2681 LogFlow(("GMMR0MapUnmapChunk: pVM=%p idChunkMap=%#x idChunkUnmap=%#x ppvR3=%p\n",
2682 pVM, idChunkMap, idChunkUnmap, ppvR3));
2683
2684 /*
2685 * Validate input and get the basics.
2686 */
2687 PGMM pGMM;
2688 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2689 PGVM pGVM = GVMMR0ByVM(pVM);
2690 if (!pGVM)
2691 return VERR_INVALID_PARAMETER;
2692 if (pGVM->hEMT != RTThreadNativeSelf())
2693 return VERR_NOT_OWNER;
2694
2695 AssertCompile(NIL_GMM_CHUNKID == 0);
2696 AssertMsgReturn(idChunkMap <= GMM_CHUNKID_LAST, ("%#x\n", idChunkMap), VERR_INVALID_PARAMETER);
2697 AssertMsgReturn(idChunkUnmap <= GMM_CHUNKID_LAST, ("%#x\n", idChunkUnmap), VERR_INVALID_PARAMETER);
2698
2699 if ( idChunkMap == NIL_GMM_CHUNKID
2700 && idChunkUnmap == NIL_GMM_CHUNKID)
2701 return VERR_INVALID_PARAMETER;
2702
2703 if (idChunkMap != NIL_GMM_CHUNKID)
2704 {
2705 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
2706 *ppvR3 = NIL_RTR3PTR;
2707 }
2708
2709 /*
2710 * Take the semaphore and do the work.
2711 *
2712 * The unmapping is done last since it's easier to undo a mapping than
2713 * undoing an unmapping. The ring-3 mapping cache cannot not be so big
2714 * that it pushes the user virtual address space to within a chunk of
2715 * it it's limits, so, no problem here.
2716 */
2717 int rc = RTSemFastMutexRequest(pGMM->Mtx);
2718 AssertRC(rc);
2719
2720 PGMMCHUNK pMap = NULL;
2721 if (idChunkMap != NIL_GVM_HANDLE)
2722 {
2723 pMap = gmmR0GetChunk(pGMM, idChunkMap);
2724 if (RT_LIKELY(pMap))
2725 rc = gmmR0MapChunk(pGMM, pGVM, pMap, ppvR3);
2726 else
2727 {
2728 Log(("GMMR0MapUnmapChunk: idChunkMap=%#x\n", idChunkMap));
2729 rc = VERR_GMM_CHUNK_NOT_FOUND;
2730 }
2731 }
2732
2733 if ( idChunkUnmap != NIL_GMM_CHUNKID
2734 && RT_SUCCESS(rc))
2735 {
2736 PGMMCHUNK pUnmap = gmmR0GetChunk(pGMM, idChunkUnmap);
2737 if (RT_LIKELY(pUnmap))
2738 rc = gmmR0UnmapChunk(pGMM, pGVM, pUnmap);
2739 else
2740 {
2741 Log(("GMMR0MapUnmapChunk: idChunkUnmap=%#x\n", idChunkUnmap));
2742 rc = VERR_GMM_CHUNK_NOT_FOUND;
2743 }
2744
2745 if (RT_FAILURE(rc) && pMap)
2746 gmmR0UnmapChunk(pGMM, pGVM, pMap);
2747 }
2748
2749 RTSemFastMutexRelease(pGMM->Mtx);
2750
2751 LogFlow(("GMMR0MapUnmapChunk: returns %Rrc\n", rc));
2752 return rc;
2753}
2754
2755
2756/**
2757 * VMMR0 request wrapper for GMMR0MapUnmapChunk.
2758 *
2759 * @returns see GMMR0MapUnmapChunk.
2760 * @param pVM Pointer to the shared VM structure.
2761 * @param pReq The request packet.
2762 */
2763GMMR0DECL(int) GMMR0MapUnmapChunkReq(PVM pVM, PGMMMAPUNMAPCHUNKREQ pReq)
2764{
2765 /*
2766 * Validate input and pass it on.
2767 */
2768 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
2769 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
2770 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
2771
2772 return GMMR0MapUnmapChunk(pVM, pReq->idChunkMap, pReq->idChunkUnmap, &pReq->pvR3);
2773}
2774
2775
2776/**
2777 * Legacy mode API for supplying pages.
2778 *
2779 * The specified user address points to a allocation chunk sized block that
2780 * will be locked down and used by the GMM when the GM asks for pages.
2781 *
2782 * @returns VBox status code.
2783 * @param pVM The VM.
2784 * @param pvR3 Pointer to the chunk size memory block to lock down.
2785 */
2786GMMR0DECL(int) GMMR0SeedChunk(PVM pVM, RTR3PTR pvR3)
2787{
2788 /*
2789 * Validate input and get the basics.
2790 */
2791 PGMM pGMM;
2792 GMM_GET_VALID_INSTANCE(pGMM, VERR_INTERNAL_ERROR);
2793 PGVM pGVM = GVMMR0ByVM(pVM);
2794 if (!pGVM)
2795 return VERR_INVALID_PARAMETER;
2796 if (pGVM->hEMT != RTThreadNativeSelf())
2797 return VERR_NOT_OWNER;
2798
2799 AssertPtrReturn(pvR3, VERR_INVALID_POINTER);
2800 AssertReturn(!(PAGE_OFFSET_MASK & pvR3), VERR_INVALID_POINTER);
2801
2802 if (!pGMM->fLegacyMode)
2803 {
2804 Log(("GMMR0SeedChunk: not in legacy mode!\n"));
2805 return VERR_NOT_SUPPORTED;
2806 }
2807
2808 /*
2809 * Lock the memory before taking the semaphore.
2810 */
2811 RTR0MEMOBJ MemObj;
2812 int rc = RTR0MemObjLockUser(&MemObj, pvR3, GMM_CHUNK_SIZE, NIL_RTR0PROCESS);
2813 if (RT_SUCCESS(rc))
2814 {
2815 /*
2816 * Take the semaphore and add a new chunk with our hGVM.
2817 */
2818 int rc = RTSemFastMutexRequest(pGMM->Mtx);
2819 AssertRC(rc);
2820
2821 rc = gmmR0RegisterChunk(pGMM, &pGMM->Private, MemObj, pGVM->hSelf);
2822
2823 RTSemFastMutexRelease(pGMM->Mtx);
2824
2825 if (RT_FAILURE(rc))
2826 RTR0MemObjFree(MemObj, false /* fFreeMappings */);
2827 }
2828
2829 LogFlow(("GMMR0SeedChunk: rc=%d (pvR3=%p)\n", rc, pvR3));
2830 return rc;
2831}
2832
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