VirtualBox

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

Last change on this file since 78393 was 76553, checked in by vboxsync, 6 years ago

scm --update-copyright-year

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