VirtualBox

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

Last change on this file since 7692 was 6636, checked in by vboxsync, 17 years ago

Fixed invered assertions in the two reservation request wrappers.

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