VirtualBox

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

Last change on this file since 60641 was 58182, checked in by vboxsync, 9 years ago

VBoxService: fixed semaphore destruction race.

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