VirtualBox

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

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

GMMR0CleanupVM: fixed state validation.

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

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