xref: /freebsd/sys/dev/xen/balloon/balloon.c (revision 7757a1b4dc60696d9a95137ee0a2accd4ee680f4)
1 /******************************************************************************
2  * balloon.c
3  *
4  * Xen balloon driver - enables returning/claiming memory to/from Xen.
5  *
6  * Copyright (c) 2003, B Dragovic
7  * Copyright (c) 2003-2004, M Williamson, K Fraser
8  * Copyright (c) 2005 Dan M. Smith, IBM Corporation
9  *
10  * This file may be distributed separately from the Linux kernel, or
11  * incorporated into other software packages, subject to the following license:
12  *
13  * Permission is hereby granted, free of charge, to any person obtaining a copy
14  * of this source file (the "Software"), to deal in the Software without
15  * restriction, including without limitation the rights to use, copy, modify,
16  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
17  * and to permit persons to whom the Software is furnished to do so, subject to
18  * the following conditions:
19  *
20  * The above copyright notice and this permission notice shall be included in
21  * all copies or substantial portions of the Software.
22  *
23  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
29  * IN THE SOFTWARE.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/param.h>
36 #include <sys/lock.h>
37 #include <sys/kernel.h>
38 #include <sys/kthread.h>
39 #include <sys/malloc.h>
40 #include <sys/mutex.h>
41 #include <sys/sysctl.h>
42 #include <sys/module.h>
43 
44 #include <vm/vm.h>
45 #include <vm/vm_page.h>
46 
47 #include <xen/xen-os.h>
48 #include <xen/hypervisor.h>
49 #include <xen/features.h>
50 #include <xen/xenstore/xenstorevar.h>
51 
52 #include <machine/xen/xenvar.h>
53 
54 static MALLOC_DEFINE(M_BALLOON, "Balloon", "Xen Balloon Driver");
55 
56 /* Convert from KB (as fetched from xenstore) to number of PAGES */
57 #define KB_TO_PAGE_SHIFT	(PAGE_SHIFT - 10)
58 
59 struct mtx balloon_mutex;
60 
61 /* We increase/decrease in batches which fit in a page */
62 static unsigned long frame_list[PAGE_SIZE / sizeof(unsigned long)];
63 
64 struct balloon_stats {
65 	/* We aim for 'current allocation' == 'target allocation'. */
66 	unsigned long current_pages;
67 	unsigned long target_pages;
68 	/* We may hit the hard limit in Xen. If we do then we remember it. */
69 	unsigned long hard_limit;
70 	/*
71 	 * Drivers may alter the memory reservation independently, but they
72 	 * must inform the balloon driver so we avoid hitting the hard limit.
73 	 */
74 	unsigned long driver_pages;
75 	/* Number of pages in high- and low-memory balloons. */
76 	unsigned long balloon_low;
77 	unsigned long balloon_high;
78 };
79 
80 static struct balloon_stats balloon_stats;
81 #define bs balloon_stats
82 
83 SYSCTL_DECL(_dev_xen);
84 static SYSCTL_NODE(_dev_xen, OID_AUTO, balloon, CTLFLAG_RD, NULL, "Balloon");
85 SYSCTL_ULONG(_dev_xen_balloon, OID_AUTO, current, CTLFLAG_RD,
86     &bs.current_pages, 0, "Current allocation");
87 SYSCTL_ULONG(_dev_xen_balloon, OID_AUTO, target, CTLFLAG_RD,
88     &bs.target_pages, 0, "Target allocation");
89 SYSCTL_ULONG(_dev_xen_balloon, OID_AUTO, driver_pages, CTLFLAG_RD,
90     &bs.driver_pages, 0, "Driver pages");
91 SYSCTL_ULONG(_dev_xen_balloon, OID_AUTO, hard_limit, CTLFLAG_RD,
92     &bs.hard_limit, 0, "Xen hard limit");
93 SYSCTL_ULONG(_dev_xen_balloon, OID_AUTO, low_mem, CTLFLAG_RD,
94     &bs.balloon_low, 0, "Low-mem balloon");
95 SYSCTL_ULONG(_dev_xen_balloon, OID_AUTO, high_mem, CTLFLAG_RD,
96     &bs.balloon_high, 0, "High-mem balloon");
97 
98 /* List of ballooned pages, threaded through the mem_map array. */
99 static TAILQ_HEAD(,vm_page) ballooned_pages;
100 
101 /* Main work function, always executed in process context. */
102 static void balloon_process(void *unused);
103 
104 #define IPRINTK(fmt, args...) \
105 	printk(KERN_INFO "xen_mem: " fmt, ##args)
106 #define WPRINTK(fmt, args...) \
107 	printk(KERN_WARNING "xen_mem: " fmt, ##args)
108 
109 static unsigned long
110 current_target(void)
111 {
112 	unsigned long target = min(bs.target_pages, bs.hard_limit);
113 	if (target > (bs.current_pages + bs.balloon_low + bs.balloon_high))
114 		target = bs.current_pages + bs.balloon_low + bs.balloon_high;
115 	return (target);
116 }
117 
118 static unsigned long
119 minimum_target(void)
120 {
121 	unsigned long min_pages, curr_pages = current_target();
122 
123 #define MB2PAGES(mb) ((mb) << (20 - PAGE_SHIFT))
124 	/*
125 	 * Simple continuous piecewiese linear function:
126 	 *  max MiB -> min MiB	gradient
127 	 *       0	   0
128 	 *      16	  16
129 	 *      32	  24
130 	 *     128	  72	(1/2)
131 	 *     512 	 168	(1/4)
132 	 *    2048	 360	(1/8)
133 	 *    8192	 552	(1/32)
134 	 *   32768	1320
135 	 *  131072	4392
136 	 */
137 	if (realmem < MB2PAGES(128))
138 		min_pages = MB2PAGES(8) + (realmem >> 1);
139 	else if (realmem < MB2PAGES(512))
140 		min_pages = MB2PAGES(40) + (realmem >> 2);
141 	else if (realmem < MB2PAGES(2048))
142 		min_pages = MB2PAGES(104) + (realmem >> 3);
143 	else
144 		min_pages = MB2PAGES(296) + (realmem >> 5);
145 #undef MB2PAGES
146 
147 	/* Don't enforce growth */
148 	return (min(min_pages, curr_pages));
149 }
150 
151 static int
152 increase_reservation(unsigned long nr_pages)
153 {
154 	unsigned long  pfn, i;
155 	vm_page_t      page;
156 	long           rc;
157 	struct xen_memory_reservation reservation = {
158 		.address_bits = 0,
159 		.extent_order = 0,
160 		.domid        = DOMID_SELF
161 	};
162 
163 	mtx_assert(&balloon_mutex, MA_OWNED);
164 
165 	if (nr_pages > nitems(frame_list))
166 		nr_pages = nitems(frame_list);
167 
168 	for (page = TAILQ_FIRST(&ballooned_pages), i = 0;
169 	    i < nr_pages; i++, page = TAILQ_NEXT(page, plinks.q)) {
170 		KASSERT(page != NULL, ("ballooned_pages list corrupt"));
171 		frame_list[i] = (VM_PAGE_TO_PHYS(page) >> PAGE_SHIFT);
172 	}
173 
174 	set_xen_guest_handle(reservation.extent_start, frame_list);
175 	reservation.nr_extents   = nr_pages;
176 	rc = HYPERVISOR_memory_op(
177 		XENMEM_populate_physmap, &reservation);
178 	if (rc < nr_pages) {
179 		if (rc > 0) {
180 			int ret;
181 
182 			/* We hit the Xen hard limit: reprobe. */
183 			reservation.nr_extents = rc;
184 			ret = HYPERVISOR_memory_op(XENMEM_decrease_reservation,
185 					&reservation);
186 			KASSERT(ret == rc, ("HYPERVISOR_memory_op failed"));
187 		}
188 		if (rc >= 0)
189 			bs.hard_limit = (bs.current_pages + rc -
190 					 bs.driver_pages);
191 		goto out;
192 	}
193 
194 	for (i = 0; i < nr_pages; i++) {
195 		page = TAILQ_FIRST(&ballooned_pages);
196 		KASSERT(page != NULL, ("Unable to get ballooned page"));
197 		TAILQ_REMOVE(&ballooned_pages, page, plinks.q);
198 		bs.balloon_low--;
199 
200 		pfn = (VM_PAGE_TO_PHYS(page) >> PAGE_SHIFT);
201 		KASSERT(xen_feature(XENFEAT_auto_translated_physmap),
202 		    ("auto translated physmap but mapping is valid"));
203 
204 		vm_page_free(page);
205 	}
206 
207 	bs.current_pages += nr_pages;
208 
209  out:
210 	return (0);
211 }
212 
213 static int
214 decrease_reservation(unsigned long nr_pages)
215 {
216 	unsigned long  pfn, i;
217 	vm_page_t      page;
218 	int            need_sleep = 0;
219 	int ret;
220 	struct xen_memory_reservation reservation = {
221 		.address_bits = 0,
222 		.extent_order = 0,
223 		.domid        = DOMID_SELF
224 	};
225 
226 	mtx_assert(&balloon_mutex, MA_OWNED);
227 
228 	if (nr_pages > nitems(frame_list))
229 		nr_pages = nitems(frame_list);
230 
231 	for (i = 0; i < nr_pages; i++) {
232 		if ((page = vm_page_alloc(NULL, 0,
233 			    VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
234 			    VM_ALLOC_ZERO)) == NULL) {
235 			nr_pages = i;
236 			need_sleep = 1;
237 			break;
238 		}
239 
240 		if ((page->flags & PG_ZERO) == 0) {
241 			/*
242 			 * Zero the page, or else we might be leaking
243 			 * important data to other domains on the same
244 			 * host. Xen doesn't scrub ballooned out memory
245 			 * pages, the guest is in charge of making
246 			 * sure that no information is leaked.
247 			 */
248 			pmap_zero_page(page);
249 		}
250 
251 		pfn = (VM_PAGE_TO_PHYS(page) >> PAGE_SHIFT);
252 		frame_list[i] = pfn;
253 
254 		TAILQ_INSERT_HEAD(&ballooned_pages, page, plinks.q);
255 		bs.balloon_low++;
256 	}
257 
258 	set_xen_guest_handle(reservation.extent_start, frame_list);
259 	reservation.nr_extents   = nr_pages;
260 	ret = HYPERVISOR_memory_op(XENMEM_decrease_reservation, &reservation);
261 	KASSERT(ret == nr_pages, ("HYPERVISOR_memory_op failed"));
262 
263 	bs.current_pages -= nr_pages;
264 
265 	return (need_sleep);
266 }
267 
268 /*
269  * We avoid multiple worker processes conflicting via the balloon mutex.
270  * We may of course race updates of the target counts (which are protected
271  * by the balloon lock), or with changes to the Xen hard limit, but we will
272  * recover from these in time.
273  */
274 static void
275 balloon_process(void *unused)
276 {
277 	int need_sleep = 0;
278 	long credit;
279 
280 	mtx_lock(&balloon_mutex);
281 	for (;;) {
282 		int sleep_time;
283 
284 		do {
285 			credit = current_target() - bs.current_pages;
286 			if (credit > 0)
287 				need_sleep = (increase_reservation(credit) != 0);
288 			if (credit < 0)
289 				need_sleep = (decrease_reservation(-credit) != 0);
290 
291 		} while ((credit != 0) && !need_sleep);
292 
293 		/* Schedule more work if there is some still to be done. */
294 		if (current_target() != bs.current_pages)
295 			sleep_time = hz;
296 		else
297 			sleep_time = 0;
298 
299 		msleep(balloon_process, &balloon_mutex, 0, "balloon",
300 		       sleep_time);
301 	}
302 	mtx_unlock(&balloon_mutex);
303 }
304 
305 /* Resets the Xen limit, sets new target, and kicks off processing. */
306 static void
307 set_new_target(unsigned long target)
308 {
309 	/* No need for lock. Not read-modify-write updates. */
310 	bs.hard_limit   = ~0UL;
311 	bs.target_pages = max(target, minimum_target());
312 	wakeup(balloon_process);
313 }
314 
315 static struct xs_watch target_watch =
316 {
317 	.node = "memory/target"
318 };
319 
320 /* React to a change in the target key */
321 static void
322 watch_target(struct xs_watch *watch,
323 	     const char **vec, unsigned int len)
324 {
325 	unsigned long long new_target;
326 	int err;
327 
328 	err = xs_scanf(XST_NIL, "memory", "target", NULL,
329 	    "%llu", &new_target);
330 	if (err) {
331 		/* This is ok (for domain0 at least) - so just return */
332 		return;
333 	}
334 
335 	/*
336 	 * The given memory/target value is in KiB, so it needs converting to
337 	 * pages.  PAGE_SHIFT converts bytes to pages, hence PAGE_SHIFT - 10.
338 	 */
339 	set_new_target(new_target >> KB_TO_PAGE_SHIFT);
340 }
341 
342 /*------------------ Private Device Attachment Functions  --------------------*/
343 /**
344  * \brief Identify instances of this device type in the system.
345  *
346  * \param driver  The driver performing this identify action.
347  * \param parent  The NewBus parent device for any devices this method adds.
348  */
349 static void
350 xenballoon_identify(driver_t *driver __unused, device_t parent)
351 {
352 	/*
353 	 * A single device instance for our driver is always present
354 	 * in a system operating under Xen.
355 	 */
356 	BUS_ADD_CHILD(parent, 0, driver->name, 0);
357 }
358 
359 /**
360  * \brief Probe for the existance of the Xen Balloon device
361  *
362  * \param dev  NewBus device_t for this Xen control instance.
363  *
364  * \return  Always returns 0 indicating success.
365  */
366 static int
367 xenballoon_probe(device_t dev)
368 {
369 
370 	device_set_desc(dev, "Xen Balloon Device");
371 	return (0);
372 }
373 
374 /**
375  * \brief Attach the Xen Balloon device.
376  *
377  * \param dev  NewBus device_t for this Xen control instance.
378  *
379  * \return  On success, 0. Otherwise an errno value indicating the
380  *          type of failure.
381  */
382 static int
383 xenballoon_attach(device_t dev)
384 {
385 	int err;
386 
387 	mtx_init(&balloon_mutex, "balloon_mutex", NULL, MTX_DEF);
388 
389 	bs.current_pages = xen_pv_domain() ?
390 	    HYPERVISOR_start_info->nr_pages : realmem;
391 	bs.target_pages  = bs.current_pages;
392 	bs.balloon_low   = 0;
393 	bs.balloon_high  = 0;
394 	bs.driver_pages  = 0UL;
395 	bs.hard_limit    = ~0UL;
396 
397 	kproc_create(balloon_process, NULL, NULL, 0, 0, "balloon");
398 
399 	target_watch.callback = watch_target;
400 
401 	err = xs_register_watch(&target_watch);
402 	if (err)
403 		device_printf(dev,
404 		    "xenballon: failed to set balloon watcher\n");
405 
406 	return (err);
407 }
408 
409 /*-------------------- Private Device Attachment Data  -----------------------*/
410 static device_method_t xenballoon_methods[] = {
411 	/* Device interface */
412 	DEVMETHOD(device_identify,	xenballoon_identify),
413 	DEVMETHOD(device_probe,         xenballoon_probe),
414 	DEVMETHOD(device_attach,        xenballoon_attach),
415 
416 	DEVMETHOD_END
417 };
418 
419 DEFINE_CLASS_0(xenballoon, xenballoon_driver, xenballoon_methods, 0);
420 devclass_t xenballoon_devclass;
421 
422 DRIVER_MODULE(xenballoon, xenstore, xenballoon_driver, xenballoon_devclass,
423     NULL, NULL);
424