VirtualBox

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

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

Free.iNext should be 16 bit and use UINT16_MAX instead of UINT32_MAX.

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