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