1 /******************************************************************************
4 * Xen balloon driver - enables returning/claiming memory to/from Xen.
6 * Copyright (c) 2003, B Dragovic
7 * Copyright (c) 2003-2004, M Williamson, K Fraser
8 * Copyright (c) 2005 Dan M. Smith, IBM Corporation
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:
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:
23 * The above copyright notice and this permission notice shall be included in
24 * all copies or substantial portions of the Software.
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
35 #include <linux/kernel.h>
36 #include <linux/module.h>
37 #include <linux/sched.h>
38 #include <linux/errno.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>
48 #include <asm/pgalloc.h>
49 #include <asm/pgtable.h>
50 #include <asm/uaccess.h>
53 #include <asm/xen/hypervisor.h>
54 #include <asm/xen/hypercall.h>
57 #include <xen/interface/xen.h>
58 #include <xen/interface/memory.h>
59 #include <xen/xenbus.h>
60 #include <xen/features.h>
63 #define PAGES2KB(_p) ((_p)<<(PAGE_SHIFT-10))
65 #define BALLOON_CLASS_NAME "xen_memory"
67 struct balloon_stats {
68 /* We aim for 'current allocation' == 'target allocation'. */
69 unsigned long current_pages;
70 unsigned long target_pages;
71 /* We may hit the hard limit in Xen. If we do then we remember it. */
72 unsigned long hard_limit;
74 * Drivers may alter the memory reservation independently, but they
75 * must inform the balloon driver so we avoid hitting the hard limit.
77 unsigned long driver_pages;
78 /* Number of pages in high- and low-memory balloons. */
79 unsigned long balloon_low;
80 unsigned long balloon_high;
83 static DEFINE_MUTEX(balloon_mutex);
85 static struct sys_device balloon_sysdev;
87 static int register_balloon(struct sys_device *sysdev);
90 * Protects atomic reservation decrease/increase against concurrent increases.
91 * Also protects non-atomic updates of current_pages and driver_pages, and
94 static DEFINE_SPINLOCK(balloon_lock);
96 static struct balloon_stats balloon_stats;
98 /* We increase/decrease in batches which fit in a page */
99 static unsigned long frame_list[PAGE_SIZE / sizeof(unsigned long)];
101 #ifdef CONFIG_HIGHMEM
102 #define inc_totalhigh_pages() (totalhigh_pages++)
103 #define dec_totalhigh_pages() (totalhigh_pages--)
105 #define inc_totalhigh_pages() do {} while(0)
106 #define dec_totalhigh_pages() do {} while(0)
109 /* List of ballooned pages, threaded through the mem_map array. */
110 static LIST_HEAD(ballooned_pages);
112 /* Main work function, always executed in process context. */
113 static void balloon_process(struct work_struct *work);
114 static DECLARE_WORK(balloon_worker, balloon_process);
115 static struct timer_list balloon_timer;
117 /* When ballooning out (allocating memory to return to Xen) we don't really
118 want the kernel to try too hard since that can trigger the oom killer. */
119 #define GFP_BALLOON \
120 (GFP_HIGHUSER | __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC)
122 static void scrub_page(struct page *page)
124 #ifdef CONFIG_XEN_SCRUB_PAGES
125 clear_highpage(page);
129 /* balloon_append: add the given page to the balloon. */
130 static void balloon_append(struct page *page)
132 /* Lowmem is re-populated first, so highmem pages go at list tail. */
133 if (PageHighMem(page)) {
134 list_add_tail(&page->lru, &ballooned_pages);
135 balloon_stats.balloon_high++;
136 dec_totalhigh_pages();
138 list_add(&page->lru, &ballooned_pages);
139 balloon_stats.balloon_low++;
143 /* balloon_retrieve: rescue a page from the balloon, if it is not empty. */
144 static struct page *balloon_retrieve(void)
148 if (list_empty(&ballooned_pages))
151 page = list_entry(ballooned_pages.next, struct page, lru);
152 list_del(&page->lru);
154 if (PageHighMem(page)) {
155 balloon_stats.balloon_high--;
156 inc_totalhigh_pages();
159 balloon_stats.balloon_low--;
164 static struct page *balloon_first_page(void)
166 if (list_empty(&ballooned_pages))
168 return list_entry(ballooned_pages.next, struct page, lru);
171 static struct page *balloon_next_page(struct page *page)
173 struct list_head *next = page->lru.next;
174 if (next == &ballooned_pages)
176 return list_entry(next, struct page, lru);
179 static void balloon_alarm(unsigned long unused)
181 schedule_work(&balloon_worker);
184 static unsigned long current_target(void)
186 unsigned long target = min(balloon_stats.target_pages, balloon_stats.hard_limit);
189 balloon_stats.current_pages +
190 balloon_stats.balloon_low +
191 balloon_stats.balloon_high);
196 static int increase_reservation(unsigned long nr_pages)
198 unsigned long pfn, i, flags;
201 struct xen_memory_reservation reservation = {
207 if (nr_pages > ARRAY_SIZE(frame_list))
208 nr_pages = ARRAY_SIZE(frame_list);
210 spin_lock_irqsave(&balloon_lock, flags);
212 page = balloon_first_page();
213 for (i = 0; i < nr_pages; i++) {
214 BUG_ON(page == NULL);
215 frame_list[i] = page_to_pfn(page);
216 page = balloon_next_page(page);
219 set_xen_guest_handle(reservation.extent_start, frame_list);
220 reservation.nr_extents = nr_pages;
221 rc = HYPERVISOR_memory_op(XENMEM_populate_physmap, &reservation);
226 /* We hit the Xen hard limit: reprobe. */
227 reservation.nr_extents = rc;
228 ret = HYPERVISOR_memory_op(XENMEM_decrease_reservation,
233 balloon_stats.hard_limit = (balloon_stats.current_pages + rc -
234 balloon_stats.driver_pages);
238 for (i = 0; i < nr_pages; i++) {
239 page = balloon_retrieve();
240 BUG_ON(page == NULL);
242 pfn = page_to_pfn(page);
243 BUG_ON(!xen_feature(XENFEAT_auto_translated_physmap) &&
244 phys_to_machine_mapping_valid(pfn));
246 set_phys_to_machine(pfn, frame_list[i]);
248 /* Link back into the page tables if not highmem. */
249 if (pfn < max_low_pfn) {
251 ret = HYPERVISOR_update_va_mapping(
252 (unsigned long)__va(pfn << PAGE_SHIFT),
253 mfn_pte(frame_list[i], PAGE_KERNEL),
258 /* Relinquish the page back to the allocator. */
259 ClearPageReserved(page);
260 init_page_count(page);
264 balloon_stats.current_pages += nr_pages;
265 totalram_pages = balloon_stats.current_pages;
268 spin_unlock_irqrestore(&balloon_lock, flags);
273 static int decrease_reservation(unsigned long nr_pages)
275 unsigned long pfn, i, flags;
279 struct xen_memory_reservation reservation = {
285 if (nr_pages > ARRAY_SIZE(frame_list))
286 nr_pages = ARRAY_SIZE(frame_list);
288 for (i = 0; i < nr_pages; i++) {
289 if ((page = alloc_page(GFP_BALLOON)) == NULL) {
295 pfn = page_to_pfn(page);
296 frame_list[i] = pfn_to_mfn(pfn);
300 if (!PageHighMem(page)) {
301 ret = HYPERVISOR_update_va_mapping(
302 (unsigned long)__va(pfn << PAGE_SHIFT),
309 /* Ensure that ballooned highmem pages don't have kmaps. */
313 spin_lock_irqsave(&balloon_lock, flags);
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));
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);
327 balloon_stats.current_pages -= nr_pages;
328 totalram_pages = balloon_stats.current_pages;
330 spin_unlock_irqrestore(&balloon_lock, flags);
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.
341 static void balloon_process(struct work_struct *work)
346 mutex_lock(&balloon_mutex);
349 credit = current_target() - balloon_stats.current_pages;
351 need_sleep = (increase_reservation(credit) != 0);
353 need_sleep = (decrease_reservation(-credit) != 0);
355 #ifndef CONFIG_PREEMPT
359 } while ((credit != 0) && !need_sleep);
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);
365 mutex_unlock(&balloon_mutex);
368 /* Resets the Xen limit, sets new target, and kicks off processing. */
369 static void balloon_set_new_target(unsigned long target)
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);
377 static struct xenbus_watch target_watch =
379 .node = "memory/target"
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)
386 unsigned long long new_target;
389 err = xenbus_scanf(XBT_NIL, "memory", "target", "%llu", &new_target);
391 /* This is ok (for domain0 at least) - so just return */
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.
398 balloon_set_new_target(new_target >> (PAGE_SHIFT - 10));
401 static int balloon_init_watcher(struct notifier_block *notifier,
407 err = register_xenbus_watch(&target_watch);
409 printk(KERN_ERR "Failed to set balloon watcher\n");
414 static struct notifier_block xenstore_notifier;
416 static int __init balloon_init(void)
421 if (!xen_pv_domain())
424 pr_info("xen_balloon: Initialising balloon driver.\n");
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;
434 init_timer(&balloon_timer);
435 balloon_timer.data = 0;
436 balloon_timer.function = balloon_alarm;
438 register_balloon(&balloon_sysdev);
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);
447 target_watch.callback = watch_target;
448 xenstore_notifier.notifier_call = balloon_init_watcher;
450 register_xenstore_notifier(&xenstore_notifier);
455 subsys_initcall(balloon_init);
457 static void balloon_exit(void)
459 /* XXX - release balloon here */
463 module_exit(balloon_exit);
465 #define BALLOON_SHOW(name, format, args...) \
466 static ssize_t show_##name(struct sys_device *dev, \
467 struct sysdev_attribute *attr, \
470 return sprintf(buf, format, ##args); \
472 static SYSDEV_ATTR(name, S_IRUGO, show_##name, NULL)
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));
482 static ssize_t show_target_kb(struct sys_device *dev, struct sysdev_attribute *attr,
485 return sprintf(buf, "%lu\n", PAGES2KB(balloon_stats.target_pages));
488 static ssize_t store_target_kb(struct sys_device *dev,
489 struct sysdev_attribute *attr,
494 unsigned long long target_bytes;
496 if (!capable(CAP_SYS_ADMIN))
499 target_bytes = simple_strtoull(buf, &endchar, 0) * 1024;
501 balloon_set_new_target(target_bytes >> PAGE_SHIFT);
506 static SYSDEV_ATTR(target_kb, S_IRUGO | S_IWUSR,
507 show_target_kb, store_target_kb);
510 static ssize_t show_target(struct sys_device *dev, struct sysdev_attribute *attr,
513 return sprintf(buf, "%llu\n",
514 (unsigned long long)balloon_stats.target_pages
518 static ssize_t store_target(struct sys_device *dev,
519 struct sysdev_attribute *attr,
524 unsigned long long target_bytes;
526 if (!capable(CAP_SYS_ADMIN))
529 target_bytes = memparse(buf, &endchar);
531 balloon_set_new_target(target_bytes >> PAGE_SHIFT);
536 static SYSDEV_ATTR(target, S_IRUGO | S_IWUSR,
537 show_target, store_target);
540 static struct sysdev_attribute *balloon_attrs[] = {
545 static struct attribute *balloon_info_attrs[] = {
546 &attr_current_kb.attr,
549 &attr_hard_limit_kb.attr,
550 &attr_driver_kb.attr,
554 static struct attribute_group balloon_info_group = {
556 .attrs = balloon_info_attrs,
559 static struct sysdev_class balloon_sysdev_class = {
560 .name = BALLOON_CLASS_NAME,
563 static int register_balloon(struct sys_device *sysdev)
567 error = sysdev_class_register(&balloon_sysdev_class);
572 sysdev->cls = &balloon_sysdev_class;
574 error = sysdev_register(sysdev);
576 sysdev_class_unregister(&balloon_sysdev_class);
580 for (i = 0; i < ARRAY_SIZE(balloon_attrs); i++) {
581 error = sysdev_create_file(sysdev, balloon_attrs[i]);
586 error = sysfs_create_group(&sysdev->kobj, &balloon_info_group);
594 sysdev_remove_file(sysdev, balloon_attrs[i]);
595 sysdev_unregister(sysdev);
596 sysdev_class_unregister(&balloon_sysdev_class);
600 MODULE_LICENSE("GPL");