xref: /linux/drivers/xen/balloon.c (revision cc4589ebfae6f8dbb5cf880a0a67eedab3416492)
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 program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License version 2
12  * as published by the Free Software Foundation; or, when distributed
13  * separately from the Linux kernel or incorporated into other
14  * software packages, subject to the following license:
15  *
16  * Permission is hereby granted, free of charge, to any person obtaining a copy
17  * of this source file (the "Software"), to deal in the Software without
18  * restriction, including without limitation the rights to use, copy, modify,
19  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
20  * and to permit persons to whom the Software is furnished to do so, subject to
21  * the following conditions:
22  *
23  * The above copyright notice and this permission notice shall be included in
24  * all copies or substantial portions of the Software.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
31  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
32  * IN THE SOFTWARE.
33  */
34 
35 #include <linux/kernel.h>
36 #include <linux/module.h>
37 #include <linux/sched.h>
38 #include <linux/errno.h>
39 #include <linux/mm.h>
40 #include <linux/bootmem.h>
41 #include <linux/pagemap.h>
42 #include <linux/highmem.h>
43 #include <linux/mutex.h>
44 #include <linux/list.h>
45 #include <linux/sysdev.h>
46 #include <linux/gfp.h>
47 
48 #include <asm/page.h>
49 #include <asm/pgalloc.h>
50 #include <asm/pgtable.h>
51 #include <asm/uaccess.h>
52 #include <asm/tlb.h>
53 
54 #include <asm/xen/hypervisor.h>
55 #include <asm/xen/hypercall.h>
56 
57 #include <xen/xen.h>
58 #include <xen/interface/xen.h>
59 #include <xen/interface/memory.h>
60 #include <xen/xenbus.h>
61 #include <xen/features.h>
62 #include <xen/page.h>
63 
64 #define PAGES2KB(_p) ((_p)<<(PAGE_SHIFT-10))
65 
66 #define BALLOON_CLASS_NAME "xen_memory"
67 
68 struct balloon_stats {
69 	/* We aim for 'current allocation' == 'target allocation'. */
70 	unsigned long current_pages;
71 	unsigned long target_pages;
72 	/*
73 	 * Drivers may alter the memory reservation independently, but they
74 	 * must inform the balloon driver so we avoid hitting the hard limit.
75 	 */
76 	unsigned long driver_pages;
77 	/* Number of pages in high- and low-memory balloons. */
78 	unsigned long balloon_low;
79 	unsigned long balloon_high;
80 };
81 
82 static DEFINE_MUTEX(balloon_mutex);
83 
84 static struct sys_device balloon_sysdev;
85 
86 static int register_balloon(struct sys_device *sysdev);
87 
88 /*
89  * Protects atomic reservation decrease/increase against concurrent increases.
90  * Also protects non-atomic updates of current_pages and driver_pages, and
91  * balloon lists.
92  */
93 static DEFINE_SPINLOCK(balloon_lock);
94 
95 static struct balloon_stats balloon_stats;
96 
97 /* We increase/decrease in batches which fit in a page */
98 static unsigned long frame_list[PAGE_SIZE / sizeof(unsigned long)];
99 
100 #ifdef CONFIG_HIGHMEM
101 #define inc_totalhigh_pages() (totalhigh_pages++)
102 #define dec_totalhigh_pages() (totalhigh_pages--)
103 #else
104 #define inc_totalhigh_pages() do {} while(0)
105 #define dec_totalhigh_pages() do {} while(0)
106 #endif
107 
108 /* List of ballooned pages, threaded through the mem_map array. */
109 static LIST_HEAD(ballooned_pages);
110 
111 /* Main work function, always executed in process context. */
112 static void balloon_process(struct work_struct *work);
113 static DECLARE_WORK(balloon_worker, balloon_process);
114 static struct timer_list balloon_timer;
115 
116 /* When ballooning out (allocating memory to return to Xen) we don't really
117    want the kernel to try too hard since that can trigger the oom killer. */
118 #define GFP_BALLOON \
119 	(GFP_HIGHUSER | __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC)
120 
121 static void scrub_page(struct page *page)
122 {
123 #ifdef CONFIG_XEN_SCRUB_PAGES
124 	clear_highpage(page);
125 #endif
126 }
127 
128 /* balloon_append: add the given page to the balloon. */
129 static void balloon_append(struct page *page)
130 {
131 	/* Lowmem is re-populated first, so highmem pages go at list tail. */
132 	if (PageHighMem(page)) {
133 		list_add_tail(&page->lru, &ballooned_pages);
134 		balloon_stats.balloon_high++;
135 		dec_totalhigh_pages();
136 	} else {
137 		list_add(&page->lru, &ballooned_pages);
138 		balloon_stats.balloon_low++;
139 	}
140 
141 	totalram_pages--;
142 }
143 
144 /* balloon_retrieve: rescue a page from the balloon, if it is not empty. */
145 static struct page *balloon_retrieve(void)
146 {
147 	struct page *page;
148 
149 	if (list_empty(&ballooned_pages))
150 		return NULL;
151 
152 	page = list_entry(ballooned_pages.next, struct page, lru);
153 	list_del(&page->lru);
154 
155 	if (PageHighMem(page)) {
156 		balloon_stats.balloon_high--;
157 		inc_totalhigh_pages();
158 	}
159 	else
160 		balloon_stats.balloon_low--;
161 
162 	totalram_pages++;
163 
164 	return page;
165 }
166 
167 static struct page *balloon_first_page(void)
168 {
169 	if (list_empty(&ballooned_pages))
170 		return NULL;
171 	return list_entry(ballooned_pages.next, struct page, lru);
172 }
173 
174 static struct page *balloon_next_page(struct page *page)
175 {
176 	struct list_head *next = page->lru.next;
177 	if (next == &ballooned_pages)
178 		return NULL;
179 	return list_entry(next, struct page, lru);
180 }
181 
182 static void balloon_alarm(unsigned long unused)
183 {
184 	schedule_work(&balloon_worker);
185 }
186 
187 static unsigned long current_target(void)
188 {
189 	unsigned long target = balloon_stats.target_pages;
190 
191 	target = min(target,
192 		     balloon_stats.current_pages +
193 		     balloon_stats.balloon_low +
194 		     balloon_stats.balloon_high);
195 
196 	return target;
197 }
198 
199 static int increase_reservation(unsigned long nr_pages)
200 {
201 	unsigned long  pfn, i, flags;
202 	struct page   *page;
203 	long           rc;
204 	struct xen_memory_reservation reservation = {
205 		.address_bits = 0,
206 		.extent_order = 0,
207 		.domid        = DOMID_SELF
208 	};
209 
210 	if (nr_pages > ARRAY_SIZE(frame_list))
211 		nr_pages = ARRAY_SIZE(frame_list);
212 
213 	spin_lock_irqsave(&balloon_lock, flags);
214 
215 	page = balloon_first_page();
216 	for (i = 0; i < nr_pages; i++) {
217 		BUG_ON(page == NULL);
218 		frame_list[i] = page_to_pfn(page);
219 		page = balloon_next_page(page);
220 	}
221 
222 	set_xen_guest_handle(reservation.extent_start, frame_list);
223 	reservation.nr_extents = nr_pages;
224 	rc = HYPERVISOR_memory_op(XENMEM_populate_physmap, &reservation);
225 	if (rc < 0)
226 		goto out;
227 
228 	for (i = 0; i < rc; i++) {
229 		page = balloon_retrieve();
230 		BUG_ON(page == NULL);
231 
232 		pfn = page_to_pfn(page);
233 		BUG_ON(!xen_feature(XENFEAT_auto_translated_physmap) &&
234 		       phys_to_machine_mapping_valid(pfn));
235 
236 		set_phys_to_machine(pfn, frame_list[i]);
237 
238 		/* Link back into the page tables if not highmem. */
239 		if (pfn < max_low_pfn) {
240 			int ret;
241 			ret = HYPERVISOR_update_va_mapping(
242 				(unsigned long)__va(pfn << PAGE_SHIFT),
243 				mfn_pte(frame_list[i], PAGE_KERNEL),
244 				0);
245 			BUG_ON(ret);
246 		}
247 
248 		/* Relinquish the page back to the allocator. */
249 		ClearPageReserved(page);
250 		init_page_count(page);
251 		__free_page(page);
252 	}
253 
254 	balloon_stats.current_pages += rc;
255 
256  out:
257 	spin_unlock_irqrestore(&balloon_lock, flags);
258 
259 	return rc < 0 ? rc : rc != nr_pages;
260 }
261 
262 static int decrease_reservation(unsigned long nr_pages)
263 {
264 	unsigned long  pfn, i, flags;
265 	struct page   *page;
266 	int            need_sleep = 0;
267 	int ret;
268 	struct xen_memory_reservation reservation = {
269 		.address_bits = 0,
270 		.extent_order = 0,
271 		.domid        = DOMID_SELF
272 	};
273 
274 	if (nr_pages > ARRAY_SIZE(frame_list))
275 		nr_pages = ARRAY_SIZE(frame_list);
276 
277 	for (i = 0; i < nr_pages; i++) {
278 		if ((page = alloc_page(GFP_BALLOON)) == NULL) {
279 			nr_pages = i;
280 			need_sleep = 1;
281 			break;
282 		}
283 
284 		pfn = page_to_pfn(page);
285 		frame_list[i] = pfn_to_mfn(pfn);
286 
287 		scrub_page(page);
288 
289 		if (!PageHighMem(page)) {
290 			ret = HYPERVISOR_update_va_mapping(
291 				(unsigned long)__va(pfn << PAGE_SHIFT),
292 				__pte_ma(0), 0);
293 			BUG_ON(ret);
294                 }
295 
296 	}
297 
298 	/* Ensure that ballooned highmem pages don't have kmaps. */
299 	kmap_flush_unused();
300 	flush_tlb_all();
301 
302 	spin_lock_irqsave(&balloon_lock, flags);
303 
304 	/* No more mappings: invalidate P2M and add to balloon. */
305 	for (i = 0; i < nr_pages; i++) {
306 		pfn = mfn_to_pfn(frame_list[i]);
307 		set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
308 		balloon_append(pfn_to_page(pfn));
309 	}
310 
311 	set_xen_guest_handle(reservation.extent_start, frame_list);
312 	reservation.nr_extents   = nr_pages;
313 	ret = HYPERVISOR_memory_op(XENMEM_decrease_reservation, &reservation);
314 	BUG_ON(ret != nr_pages);
315 
316 	balloon_stats.current_pages -= nr_pages;
317 
318 	spin_unlock_irqrestore(&balloon_lock, flags);
319 
320 	return need_sleep;
321 }
322 
323 /*
324  * We avoid multiple worker processes conflicting via the balloon mutex.
325  * We may of course race updates of the target counts (which are protected
326  * by the balloon lock), or with changes to the Xen hard limit, but we will
327  * recover from these in time.
328  */
329 static void balloon_process(struct work_struct *work)
330 {
331 	int need_sleep = 0;
332 	long credit;
333 
334 	mutex_lock(&balloon_mutex);
335 
336 	do {
337 		credit = current_target() - balloon_stats.current_pages;
338 		if (credit > 0)
339 			need_sleep = (increase_reservation(credit) != 0);
340 		if (credit < 0)
341 			need_sleep = (decrease_reservation(-credit) != 0);
342 
343 #ifndef CONFIG_PREEMPT
344 		if (need_resched())
345 			schedule();
346 #endif
347 	} while ((credit != 0) && !need_sleep);
348 
349 	/* Schedule more work if there is some still to be done. */
350 	if (current_target() != balloon_stats.current_pages)
351 		mod_timer(&balloon_timer, jiffies + HZ);
352 
353 	mutex_unlock(&balloon_mutex);
354 }
355 
356 /* Resets the Xen limit, sets new target, and kicks off processing. */
357 static void balloon_set_new_target(unsigned long target)
358 {
359 	/* No need for lock. Not read-modify-write updates. */
360 	balloon_stats.target_pages = target;
361 	schedule_work(&balloon_worker);
362 }
363 
364 static struct xenbus_watch target_watch =
365 {
366 	.node = "memory/target"
367 };
368 
369 /* React to a change in the target key */
370 static void watch_target(struct xenbus_watch *watch,
371 			 const char **vec, unsigned int len)
372 {
373 	unsigned long long new_target;
374 	int err;
375 
376 	err = xenbus_scanf(XBT_NIL, "memory", "target", "%llu", &new_target);
377 	if (err != 1) {
378 		/* This is ok (for domain0 at least) - so just return */
379 		return;
380 	}
381 
382 	/* The given memory/target value is in KiB, so it needs converting to
383 	 * pages. PAGE_SHIFT converts bytes to pages, hence PAGE_SHIFT - 10.
384 	 */
385 	balloon_set_new_target(new_target >> (PAGE_SHIFT - 10));
386 }
387 
388 static int balloon_init_watcher(struct notifier_block *notifier,
389 				unsigned long event,
390 				void *data)
391 {
392 	int err;
393 
394 	err = register_xenbus_watch(&target_watch);
395 	if (err)
396 		printk(KERN_ERR "Failed to set balloon watcher\n");
397 
398 	return NOTIFY_DONE;
399 }
400 
401 static struct notifier_block xenstore_notifier;
402 
403 static int __init balloon_init(void)
404 {
405 	unsigned long pfn;
406 	struct page *page;
407 
408 	if (!xen_pv_domain())
409 		return -ENODEV;
410 
411 	pr_info("xen_balloon: Initialising balloon driver.\n");
412 
413 	balloon_stats.current_pages = min(xen_start_info->nr_pages, max_pfn);
414 	balloon_stats.target_pages  = balloon_stats.current_pages;
415 	balloon_stats.balloon_low   = 0;
416 	balloon_stats.balloon_high  = 0;
417 	balloon_stats.driver_pages  = 0UL;
418 
419 	init_timer(&balloon_timer);
420 	balloon_timer.data = 0;
421 	balloon_timer.function = balloon_alarm;
422 
423 	register_balloon(&balloon_sysdev);
424 
425 	/* Initialise the balloon with excess memory space. */
426 	for (pfn = xen_start_info->nr_pages; pfn < max_pfn; pfn++) {
427 		page = pfn_to_page(pfn);
428 		if (!PageReserved(page))
429 			balloon_append(page);
430 	}
431 
432 	target_watch.callback = watch_target;
433 	xenstore_notifier.notifier_call = balloon_init_watcher;
434 
435 	register_xenstore_notifier(&xenstore_notifier);
436 
437 	return 0;
438 }
439 
440 subsys_initcall(balloon_init);
441 
442 static void balloon_exit(void)
443 {
444     /* XXX - release balloon here */
445     return;
446 }
447 
448 module_exit(balloon_exit);
449 
450 #define BALLOON_SHOW(name, format, args...)				\
451 	static ssize_t show_##name(struct sys_device *dev,		\
452 				   struct sysdev_attribute *attr,	\
453 				   char *buf)				\
454 	{								\
455 		return sprintf(buf, format, ##args);			\
456 	}								\
457 	static SYSDEV_ATTR(name, S_IRUGO, show_##name, NULL)
458 
459 BALLOON_SHOW(current_kb, "%lu\n", PAGES2KB(balloon_stats.current_pages));
460 BALLOON_SHOW(low_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_low));
461 BALLOON_SHOW(high_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_high));
462 BALLOON_SHOW(driver_kb, "%lu\n", PAGES2KB(balloon_stats.driver_pages));
463 
464 static ssize_t show_target_kb(struct sys_device *dev, struct sysdev_attribute *attr,
465 			      char *buf)
466 {
467 	return sprintf(buf, "%lu\n", PAGES2KB(balloon_stats.target_pages));
468 }
469 
470 static ssize_t store_target_kb(struct sys_device *dev,
471 			       struct sysdev_attribute *attr,
472 			       const char *buf,
473 			       size_t count)
474 {
475 	char *endchar;
476 	unsigned long long target_bytes;
477 
478 	if (!capable(CAP_SYS_ADMIN))
479 		return -EPERM;
480 
481 	target_bytes = simple_strtoull(buf, &endchar, 0) * 1024;
482 
483 	balloon_set_new_target(target_bytes >> PAGE_SHIFT);
484 
485 	return count;
486 }
487 
488 static SYSDEV_ATTR(target_kb, S_IRUGO | S_IWUSR,
489 		   show_target_kb, store_target_kb);
490 
491 
492 static ssize_t show_target(struct sys_device *dev, struct sysdev_attribute *attr,
493 			      char *buf)
494 {
495 	return sprintf(buf, "%llu\n",
496 		       (unsigned long long)balloon_stats.target_pages
497 		       << PAGE_SHIFT);
498 }
499 
500 static ssize_t store_target(struct sys_device *dev,
501 			    struct sysdev_attribute *attr,
502 			    const char *buf,
503 			    size_t count)
504 {
505 	char *endchar;
506 	unsigned long long target_bytes;
507 
508 	if (!capable(CAP_SYS_ADMIN))
509 		return -EPERM;
510 
511 	target_bytes = memparse(buf, &endchar);
512 
513 	balloon_set_new_target(target_bytes >> PAGE_SHIFT);
514 
515 	return count;
516 }
517 
518 static SYSDEV_ATTR(target, S_IRUGO | S_IWUSR,
519 		   show_target, store_target);
520 
521 
522 static struct sysdev_attribute *balloon_attrs[] = {
523 	&attr_target_kb,
524 	&attr_target,
525 };
526 
527 static struct attribute *balloon_info_attrs[] = {
528 	&attr_current_kb.attr,
529 	&attr_low_kb.attr,
530 	&attr_high_kb.attr,
531 	&attr_driver_kb.attr,
532 	NULL
533 };
534 
535 static struct attribute_group balloon_info_group = {
536 	.name = "info",
537 	.attrs = balloon_info_attrs,
538 };
539 
540 static struct sysdev_class balloon_sysdev_class = {
541 	.name = BALLOON_CLASS_NAME,
542 };
543 
544 static int register_balloon(struct sys_device *sysdev)
545 {
546 	int i, error;
547 
548 	error = sysdev_class_register(&balloon_sysdev_class);
549 	if (error)
550 		return error;
551 
552 	sysdev->id = 0;
553 	sysdev->cls = &balloon_sysdev_class;
554 
555 	error = sysdev_register(sysdev);
556 	if (error) {
557 		sysdev_class_unregister(&balloon_sysdev_class);
558 		return error;
559 	}
560 
561 	for (i = 0; i < ARRAY_SIZE(balloon_attrs); i++) {
562 		error = sysdev_create_file(sysdev, balloon_attrs[i]);
563 		if (error)
564 			goto fail;
565 	}
566 
567 	error = sysfs_create_group(&sysdev->kobj, &balloon_info_group);
568 	if (error)
569 		goto fail;
570 
571 	return 0;
572 
573  fail:
574 	while (--i >= 0)
575 		sysdev_remove_file(sysdev, balloon_attrs[i]);
576 	sysdev_unregister(sysdev);
577 	sysdev_class_unregister(&balloon_sysdev_class);
578 	return error;
579 }
580 
581 MODULE_LICENSE("GPL");
582