VirtualBox

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

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

PGM,VMM,GMM: handy page allocation and some other fixes.

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