VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxServiceBalloon.cpp

Last change on this file was 100316, checked in by vboxsync, 10 months ago

Additions/VBoxService/VBoxServiceBalloon.cpp: Replace PAGE_SIZE with RTSystemGetPageSize(), bugref:10476

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 14.0 KB
Line 
1/* $Id: VBoxServiceBalloon.cpp 100316 2023-06-28 10:34:00Z vboxsync $ */
2/** @file
3 * VBoxService - Memory Ballooning.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/** @page pg_vgsvc_memballoon VBoxService - Memory Ballooning
30 *
31 * The Memory Ballooning subservice works with VBoxGuest, PGM and GMM to
32 * dynamically reallocate memory between VMs.
33 *
34 * Memory ballooning is typically used to deal with overcomitting memory on the
35 * host. It allowes you to borrow memory from one or more VMs and make it
36 * available to others. In theory it could also be used to make memory
37 * available to the host system, however memory fragmentation typically makes
38 * that difficult.
39 *
40 * The memory ballooning subservices talks to PGM, GMM and Main via the VMMDev.
41 * It polls for change requests at an interval and executes them when they
42 * arrive. There are two ways we implement the actual ballooning, either
43 * VBoxGuest allocates kernel memory and donates it to the host, or this service
44 * allocates process memory which VBoxGuest then locks down and donates to the
45 * host. While we prefer the former method it is not practicable on all OS and
46 * we have to use the latter.
47 *
48 */
49
50
51/*********************************************************************************************************************************
52* Header Files *
53*********************************************************************************************************************************/
54#include <iprt/assert.h>
55#include <iprt/mem.h>
56#include <iprt/stream.h>
57#include <iprt/string.h>
58#include <iprt/semaphore.h>
59#include <iprt/system.h>
60#include <iprt/thread.h>
61#include <iprt/time.h>
62#include <VBox/err.h>
63#include <VBox/VBoxGuestLib.h>
64#include "VBoxServiceInternal.h"
65#include "VBoxServiceUtils.h"
66
67#ifdef RT_OS_LINUX
68# include <iprt/param.h>
69# include <sys/mman.h>
70# ifndef MADV_DONTFORK
71# define MADV_DONTFORK 10
72# endif
73#endif
74
75
76
77/*********************************************************************************************************************************
78* Global Variables *
79*********************************************************************************************************************************/
80/** The balloon size. */
81static uint32_t g_cMemBalloonChunks = 0;
82
83/** The semaphore we're blocking on. */
84static RTSEMEVENTMULTI g_MemBalloonEvent = NIL_RTSEMEVENTMULTI;
85
86/** The array holding the R3 pointers of the balloon. */
87static void **g_pavBalloon = NULL;
88
89#ifdef RT_OS_LINUX
90/** True = madvise(MADV_DONTFORK) works, false otherwise. */
91static bool g_fSysMadviseWorks;
92#endif
93
94
95/**
96 * Check whether madvise() works.
97 */
98static void vgsvcBalloonInitMadvise(void)
99{
100#ifdef RT_OS_LINUX
101 size_t const cbPage = RTSystemGetPageSize();
102 void *pv = (void*)mmap(NULL, cbPage, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
103 if (pv != MAP_FAILED)
104 {
105 g_fSysMadviseWorks = madvise(pv, cbPage, MADV_DONTFORK) == 0;
106 munmap(pv, cbPage);
107 }
108#endif
109}
110
111
112/**
113 * Allocate a chunk of the balloon. Fulfil the prerequisite that we can lock this memory
114 * and protect it against fork() in R0. See also suplibOsPageAlloc().
115 */
116static void *VGSvcBalloonAllocChunk(void)
117{
118 size_t cb = VMMDEV_MEMORY_BALLOON_CHUNK_SIZE;
119 char *pu8;
120
121#ifdef RT_OS_LINUX
122 size_t const cbPage = RTSystemGetPageSize();
123 if (!g_fSysMadviseWorks)
124 cb += 2 * cbPage;
125
126 pu8 = (char*)mmap(NULL, cb, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
127 if (pu8 == MAP_FAILED)
128 return NULL;
129
130 if (g_fSysMadviseWorks)
131 {
132 /*
133 * It is not fatal if we fail here but a forked child (e.g. the ALSA sound server)
134 * could crash. Linux < 2.6.16 does not implement madvise(MADV_DONTFORK) but the
135 * kernel seems to split bigger VMAs and that is all that we want -- later we set the
136 * VM_DONTCOPY attribute in supdrvOSLockMemOne().
137 */
138 madvise(pu8, cb, MADV_DONTFORK);
139 }
140 else
141 {
142 /*
143 * madvise(MADV_DONTFORK) is not available (most probably Linux 2.4). Enclose any
144 * mmapped region by two unmapped pages to guarantee that there is exactly one VM
145 * area struct of the very same size as the mmap area.
146 */
147 RTMemProtect(pu8, cbPage, RTMEM_PROT_NONE);
148 RTMemProtect(pu8 + cb - cbPage, cbPage, RTMEM_PROT_NONE);
149 pu8 += cbPage;
150 }
151
152#else
153
154 pu8 = (char*)RTMemPageAlloc(cb);
155 if (!pu8)
156 return pu8;
157
158#endif
159
160 memset(pu8, 0, VMMDEV_MEMORY_BALLOON_CHUNK_SIZE);
161 return pu8;
162}
163
164
165/**
166 * Free an allocated chunk undoing VGSvcBalloonAllocChunk().
167 */
168static void vgsvcBalloonFreeChunk(void *pv)
169{
170 char *pu8 = (char*)pv;
171 size_t cb = VMMDEV_MEMORY_BALLOON_CHUNK_SIZE;
172
173#ifdef RT_OS_LINUX
174 if (!g_fSysMadviseWorks)
175 {
176 size_t const cbPage = RTSystemGetPageSize();
177
178 cb += 2 * cbPage;
179 pu8 -= cbPage;
180 /* This is not really necessary */
181 RTMemProtect(pu8, cbPage, RTMEM_PROT_READ | RTMEM_PROT_WRITE);
182 RTMemProtect(pu8 + cb - cbPage, cbPage, RTMEM_PROT_READ | RTMEM_PROT_WRITE);
183 }
184 munmap(pu8, cb);
185
186#else
187
188 RTMemPageFree(pu8, cb);
189
190#endif
191}
192
193
194/**
195 * Adapt the R0 memory balloon by granting/reclaiming 1MB chunks to/from R0.
196 *
197 * returns IPRT status code.
198 * @param cNewChunks The new number of 1MB chunks in the balloon.
199 */
200static int vgsvcBalloonSetUser(uint32_t cNewChunks)
201{
202 if (cNewChunks == g_cMemBalloonChunks)
203 return VINF_SUCCESS;
204
205 VGSvcVerbose(3, "vgsvcBalloonSetUser: cNewChunks=%u g_cMemBalloonChunks=%u\n", cNewChunks, g_cMemBalloonChunks);
206 int rc = VINF_SUCCESS;
207 if (cNewChunks > g_cMemBalloonChunks)
208 {
209 /* inflate */
210 g_pavBalloon = (void**)RTMemRealloc(g_pavBalloon, cNewChunks * sizeof(void*));
211 uint32_t i;
212 for (i = g_cMemBalloonChunks; i < cNewChunks; i++)
213 {
214 void *pv = VGSvcBalloonAllocChunk();
215 if (!pv)
216 break;
217 rc = VbglR3MemBalloonChange(pv, /* inflate=*/ true);
218 if (RT_SUCCESS(rc))
219 {
220 g_pavBalloon[i] = pv;
221#ifndef RT_OS_SOLARIS
222 /*
223 * Protect against access by dangling pointers (ignore errors as it may fail).
224 * On Solaris it corrupts the address space leaving the process unkillable. This
225 * could perhaps be related to what the underlying segment driver does; currently
226 * just disable it.
227 */
228 RTMemProtect(pv, VMMDEV_MEMORY_BALLOON_CHUNK_SIZE, RTMEM_PROT_NONE);
229#endif
230 g_cMemBalloonChunks++;
231 }
232 else
233 {
234 vgsvcBalloonFreeChunk(pv);
235 break;
236 }
237 }
238 VGSvcVerbose(3, "vgsvcBalloonSetUser: inflation complete. chunks=%u rc=%d\n", i, rc);
239 }
240 else
241 {
242 /* deflate */
243 uint32_t i;
244 for (i = g_cMemBalloonChunks; i-- > cNewChunks;)
245 {
246 void *pv = g_pavBalloon[i];
247 rc = VbglR3MemBalloonChange(pv, /* inflate=*/ false);
248 if (RT_SUCCESS(rc))
249 {
250#ifndef RT_OS_SOLARIS
251 /* unprotect */
252 RTMemProtect(pv, VMMDEV_MEMORY_BALLOON_CHUNK_SIZE, RTMEM_PROT_READ | RTMEM_PROT_WRITE);
253#endif
254 vgsvcBalloonFreeChunk(pv);
255 g_pavBalloon[i] = NULL;
256 g_cMemBalloonChunks--;
257 }
258 else
259 break;
260 VGSvcVerbose(3, "vgsvcBalloonSetUser: deflation complete. chunks=%u rc=%d\n", i, rc);
261 }
262 }
263
264 return VINF_SUCCESS;
265}
266
267
268/**
269 * @interface_method_impl{VBOXSERVICE,pfnInit}
270 */
271static DECLCALLBACK(int) vgsvcBalloonInit(void)
272{
273 VGSvcVerbose(3, "vgsvcBalloonInit\n");
274
275 int rc = RTSemEventMultiCreate(&g_MemBalloonEvent);
276 AssertRCReturn(rc, rc);
277
278 vgsvcBalloonInitMadvise();
279
280 g_cMemBalloonChunks = 0;
281 uint32_t cNewChunks = 0;
282 bool fHandleInR3;
283
284 /* Check balloon size */
285 rc = VbglR3MemBalloonRefresh(&cNewChunks, &fHandleInR3);
286 if (RT_SUCCESS(rc))
287 {
288 VGSvcVerbose(3, "MemBalloon: New balloon size %d MB (%s memory)\n", cNewChunks, fHandleInR3 ? "R3" : "R0");
289 if (fHandleInR3)
290 rc = vgsvcBalloonSetUser(cNewChunks);
291 else
292 g_cMemBalloonChunks = cNewChunks;
293 }
294 if (RT_FAILURE(rc))
295 {
296 /* If the service was not found, we disable this service without
297 causing VBoxService to fail. */
298 if ( rc == VERR_NOT_IMPLEMENTED
299#ifdef RT_OS_WINDOWS /** @todo r=bird: Windows kernel driver should return VERR_NOT_IMPLEMENTED,
300 * VERR_INVALID_PARAMETER has too many other uses. */
301 || rc == VERR_INVALID_PARAMETER
302#endif
303 )
304 {
305 VGSvcVerbose(0, "MemBalloon: Memory ballooning support is not available\n");
306 rc = VERR_SERVICE_DISABLED;
307 }
308 else
309 {
310 VGSvcVerbose(3, "MemBalloon: VbglR3MemBalloonRefresh failed with %Rrc\n", rc);
311 rc = VERR_SERVICE_DISABLED; /** @todo Playing safe for now, figure out the exact status codes here. */
312 }
313 RTSemEventMultiDestroy(g_MemBalloonEvent);
314 g_MemBalloonEvent = NIL_RTSEMEVENTMULTI;
315 }
316
317 return rc;
318}
319
320
321/**
322 * Query the size of the memory balloon, given as a page count.
323 *
324 * @returns Number of pages.
325 * @param cbPage The page size.
326 */
327uint32_t VGSvcBalloonQueryPages(uint32_t cbPage)
328{
329 Assert(cbPage > 0);
330 return g_cMemBalloonChunks * (VMMDEV_MEMORY_BALLOON_CHUNK_SIZE / cbPage);
331}
332
333
334/**
335 * @interface_method_impl{VBOXSERVICE,pfnWorker}
336 */
337static DECLCALLBACK(int) vgsvcBalloonWorker(bool volatile *pfShutdown)
338{
339 /* Start monitoring of the stat event change event. */
340 int rc = VbglR3CtlFilterMask(VMMDEV_EVENT_BALLOON_CHANGE_REQUEST, 0);
341 if (RT_FAILURE(rc))
342 {
343 VGSvcVerbose(3, "vgsvcBalloonInit: VbglR3CtlFilterMask failed with %Rrc\n", rc);
344 return rc;
345 }
346
347 /*
348 * Tell the control thread that it can continue
349 * spawning services.
350 */
351 RTThreadUserSignal(RTThreadSelf());
352
353 /*
354 * Now enter the loop retrieving runtime data continuously.
355 */
356 for (;;)
357 {
358 uint32_t fEvents = 0;
359
360 /* Check if an update interval change is pending. */
361 rc = VbglR3WaitEvent(VMMDEV_EVENT_BALLOON_CHANGE_REQUEST, 0 /* no wait */, &fEvents);
362 if ( RT_SUCCESS(rc)
363 && (fEvents & VMMDEV_EVENT_BALLOON_CHANGE_REQUEST))
364 {
365 uint32_t cNewChunks;
366 bool fHandleInR3;
367 rc = VbglR3MemBalloonRefresh(&cNewChunks, &fHandleInR3);
368 if (RT_SUCCESS(rc))
369 {
370 VGSvcVerbose(3, "vgsvcBalloonInit: new balloon size %d MB (%s memory)\n", cNewChunks, fHandleInR3 ? "R3" : "R0");
371 if (fHandleInR3)
372 {
373 rc = vgsvcBalloonSetUser(cNewChunks);
374 if (RT_FAILURE(rc))
375 {
376 VGSvcVerbose(3, "vgsvcBalloonInit: failed to set balloon size %d MB (%s memory)\n",
377 cNewChunks, fHandleInR3 ? "R3" : "R0");
378 }
379 else
380 VGSvcVerbose(3, "vgsvcBalloonInit: successfully set requested balloon size %d.\n", cNewChunks);
381 }
382 else
383 g_cMemBalloonChunks = cNewChunks;
384 }
385 else
386 VGSvcVerbose(3, "vgsvcBalloonInit: VbglR3MemBalloonRefresh failed with %Rrc\n", rc);
387 }
388
389 /*
390 * Block for a while.
391 *
392 * The event semaphore takes care of ignoring interruptions and it
393 * allows us to implement service wakeup later.
394 */
395 if (*pfShutdown)
396 break;
397 int rc2 = RTSemEventMultiWait(g_MemBalloonEvent, 5000);
398 if (*pfShutdown)
399 break;
400 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
401 {
402 VGSvcError("vgsvcBalloonInit: RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
403 rc = rc2;
404 break;
405 }
406 }
407
408 /* Cancel monitoring of the memory balloon change event. */
409 rc = VbglR3CtlFilterMask(0, VMMDEV_EVENT_BALLOON_CHANGE_REQUEST);
410 if (RT_FAILURE(rc))
411 VGSvcVerbose(3, "vgsvcBalloonInit: VbglR3CtlFilterMask failed with %Rrc\n", rc);
412
413 VGSvcVerbose(3, "vgsvcBalloonInit: finished mem balloon change request thread\n");
414 return VINF_SUCCESS;
415}
416
417
418/**
419 * @interface_method_impl{VBOXSERVICE,pfnStop}
420 */
421static DECLCALLBACK(void) vgsvcBalloonStop(void)
422{
423 RTSemEventMultiSignal(g_MemBalloonEvent);
424}
425
426
427/**
428 * @interface_method_impl{VBOXSERVICE,pfnTerm}
429 */
430static DECLCALLBACK(void) vgsvcBalloonTerm(void)
431{
432 if (g_MemBalloonEvent != NIL_RTSEMEVENTMULTI)
433 {
434 RTSemEventMultiDestroy(g_MemBalloonEvent);
435 g_MemBalloonEvent = NIL_RTSEMEVENTMULTI;
436 }
437}
438
439
440/**
441 * The 'memballoon' service description.
442 */
443VBOXSERVICE g_MemBalloon =
444{
445 /* pszName. */
446 "memballoon",
447 /* pszDescription. */
448 "Memory Ballooning",
449 /* pszUsage. */
450 NULL,
451 /* pszOptions. */
452 NULL,
453 /* methods */
454 VGSvcDefaultPreInit,
455 VGSvcDefaultOption,
456 vgsvcBalloonInit,
457 vgsvcBalloonWorker,
458 vgsvcBalloonStop,
459 vgsvcBalloonTerm
460};
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use