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>
46 #include <linux/gfp.h>
49 #include <asm/pgalloc.h>
50 #include <asm/pgtable.h>
51 #include <asm/uaccess.h>
55 #include <asm/xen/hypervisor.h>
56 #include <asm/xen/hypercall.h>
59 #include <xen/interface/xen.h>
60 #include <xen/interface/memory.h>
61 #include <xen/xenbus.h>
62 #include <xen/features.h>
65 #define PAGES2KB(_p) ((_p)<<(PAGE_SHIFT-10))
67 #define BALLOON_CLASS_NAME "xen_memory"
69 struct balloon_stats {
70 /* We aim for 'current allocation' == 'target allocation'. */
71 unsigned long current_pages;
72 unsigned long target_pages;
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);
89 static struct balloon_stats balloon_stats;
91 /* We increase/decrease in batches which fit in a page */
92 static unsigned long frame_list[PAGE_SIZE / sizeof(unsigned long)];
95 #define inc_totalhigh_pages() (totalhigh_pages++)
96 #define dec_totalhigh_pages() (totalhigh_pages--)
98 #define inc_totalhigh_pages() do {} while(0)
99 #define dec_totalhigh_pages() do {} while(0)
102 /* List of ballooned pages, threaded through the mem_map array. */
103 static LIST_HEAD(ballooned_pages);
105 /* Main work function, always executed in process context. */
106 static void balloon_process(struct work_struct *work);
107 static DECLARE_WORK(balloon_worker, balloon_process);
108 static struct timer_list balloon_timer;
110 /* When ballooning out (allocating memory to return to Xen) we don't really
111 want the kernel to try too hard since that can trigger the oom killer. */
112 #define GFP_BALLOON \
113 (GFP_HIGHUSER | __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC)
115 static void scrub_page(struct page *page)
117 #ifdef CONFIG_XEN_SCRUB_PAGES
118 clear_highpage(page);
122 /* balloon_append: add the given page to the balloon. */
123 static void __balloon_append(struct page *page)
125 /* Lowmem is re-populated first, so highmem pages go at list tail. */
126 if (PageHighMem(page)) {
127 list_add_tail(&page->lru, &ballooned_pages);
128 balloon_stats.balloon_high++;
129 dec_totalhigh_pages();
131 list_add(&page->lru, &ballooned_pages);
132 balloon_stats.balloon_low++;
136 static void balloon_append(struct page *page)
138 __balloon_append(page);
142 /* balloon_retrieve: rescue a page from the balloon, if it is not empty. */
143 static struct page *balloon_retrieve(void)
147 if (list_empty(&ballooned_pages))
150 page = list_entry(ballooned_pages.next, struct page, lru);
151 list_del(&page->lru);
153 if (PageHighMem(page)) {
154 balloon_stats.balloon_high--;
155 inc_totalhigh_pages();
158 balloon_stats.balloon_low--;
165 static struct page *balloon_first_page(void)
167 if (list_empty(&ballooned_pages))
169 return list_entry(ballooned_pages.next, struct page, lru);
172 static struct page *balloon_next_page(struct page *page)
174 struct list_head *next = page->lru.next;
175 if (next == &ballooned_pages)
177 return list_entry(next, struct page, lru);
180 static void balloon_alarm(unsigned long unused)
182 schedule_work(&balloon_worker);
185 static unsigned long current_target(void)
187 unsigned long target = balloon_stats.target_pages;
190 balloon_stats.current_pages +
191 balloon_stats.balloon_low +
192 balloon_stats.balloon_high);
197 static int increase_reservation(unsigned long nr_pages)
199 unsigned long pfn, i;
202 struct xen_memory_reservation reservation = {
208 if (nr_pages > ARRAY_SIZE(frame_list))
209 nr_pages = ARRAY_SIZE(frame_list);
211 page = balloon_first_page();
212 for (i = 0; i < nr_pages; i++) {
213 BUG_ON(page == NULL);
214 frame_list[i] = page_to_pfn(page);
215 page = balloon_next_page(page);
218 set_xen_guest_handle(reservation.extent_start, frame_list);
219 reservation.nr_extents = nr_pages;
220 rc = HYPERVISOR_memory_op(XENMEM_populate_physmap, &reservation);
224 for (i = 0; i < rc; i++) {
225 page = balloon_retrieve();
226 BUG_ON(page == NULL);
228 pfn = page_to_pfn(page);
229 BUG_ON(!xen_feature(XENFEAT_auto_translated_physmap) &&
230 phys_to_machine_mapping_valid(pfn));
232 set_phys_to_machine(pfn, frame_list[i]);
234 /* Link back into the page tables if not highmem. */
235 if (!xen_hvm_domain() && pfn < max_low_pfn) {
237 ret = HYPERVISOR_update_va_mapping(
238 (unsigned long)__va(pfn << PAGE_SHIFT),
239 mfn_pte(frame_list[i], PAGE_KERNEL),
244 /* Relinquish the page back to the allocator. */
245 ClearPageReserved(page);
246 init_page_count(page);
250 balloon_stats.current_pages += rc;
253 return rc < 0 ? rc : rc != nr_pages;
256 static int decrease_reservation(unsigned long nr_pages)
258 unsigned long pfn, i;
262 struct xen_memory_reservation reservation = {
268 if (nr_pages > ARRAY_SIZE(frame_list))
269 nr_pages = ARRAY_SIZE(frame_list);
271 for (i = 0; i < nr_pages; i++) {
272 if ((page = alloc_page(GFP_BALLOON)) == NULL) {
278 pfn = page_to_pfn(page);
279 frame_list[i] = pfn_to_mfn(pfn);
283 if (!xen_hvm_domain() && !PageHighMem(page)) {
284 ret = HYPERVISOR_update_va_mapping(
285 (unsigned long)__va(pfn << PAGE_SHIFT),
292 /* Ensure that ballooned highmem pages don't have kmaps. */
296 /* No more mappings: invalidate P2M and add to balloon. */
297 for (i = 0; i < nr_pages; i++) {
298 pfn = mfn_to_pfn(frame_list[i]);
299 __set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
300 balloon_append(pfn_to_page(pfn));
303 set_xen_guest_handle(reservation.extent_start, frame_list);
304 reservation.nr_extents = nr_pages;
305 ret = HYPERVISOR_memory_op(XENMEM_decrease_reservation, &reservation);
306 BUG_ON(ret != nr_pages);
308 balloon_stats.current_pages -= nr_pages;
314 * We avoid multiple worker processes conflicting via the balloon mutex.
315 * We may of course race updates of the target counts (which are protected
316 * by the balloon lock), or with changes to the Xen hard limit, but we will
317 * recover from these in time.
319 static void balloon_process(struct work_struct *work)
324 mutex_lock(&balloon_mutex);
327 credit = current_target() - balloon_stats.current_pages;
329 need_sleep = (increase_reservation(credit) != 0);
331 need_sleep = (decrease_reservation(-credit) != 0);
333 #ifndef CONFIG_PREEMPT
337 } while ((credit != 0) && !need_sleep);
339 /* Schedule more work if there is some still to be done. */
340 if (current_target() != balloon_stats.current_pages)
341 mod_timer(&balloon_timer, jiffies + HZ);
343 mutex_unlock(&balloon_mutex);
346 /* Resets the Xen limit, sets new target, and kicks off processing. */
347 static void balloon_set_new_target(unsigned long target)
349 /* No need for lock. Not read-modify-write updates. */
350 balloon_stats.target_pages = target;
351 schedule_work(&balloon_worker);
354 static struct xenbus_watch target_watch =
356 .node = "memory/target"
359 /* React to a change in the target key */
360 static void watch_target(struct xenbus_watch *watch,
361 const char **vec, unsigned int len)
363 unsigned long long new_target;
366 err = xenbus_scanf(XBT_NIL, "memory", "target", "%llu", &new_target);
368 /* This is ok (for domain0 at least) - so just return */
372 /* The given memory/target value is in KiB, so it needs converting to
373 * pages. PAGE_SHIFT converts bytes to pages, hence PAGE_SHIFT - 10.
375 balloon_set_new_target(new_target >> (PAGE_SHIFT - 10));
378 static int balloon_init_watcher(struct notifier_block *notifier,
384 err = register_xenbus_watch(&target_watch);
386 printk(KERN_ERR "Failed to set balloon watcher\n");
391 static struct notifier_block xenstore_notifier;
393 static int __init balloon_init(void)
395 unsigned long pfn, nr_pages, extra_pfn_end;
401 pr_info("xen_balloon: Initialising balloon driver.\n");
404 nr_pages = xen_start_info->nr_pages;
407 balloon_stats.current_pages = min(nr_pages, max_pfn);
408 balloon_stats.target_pages = balloon_stats.current_pages;
409 balloon_stats.balloon_low = 0;
410 balloon_stats.balloon_high = 0;
411 balloon_stats.driver_pages = 0UL;
413 init_timer(&balloon_timer);
414 balloon_timer.data = 0;
415 balloon_timer.function = balloon_alarm;
417 register_balloon(&balloon_sysdev);
420 * Initialise the balloon with excess memory space. We need
421 * to make sure we don't add memory which doesn't exist or
422 * logically exist. The E820 map can be trimmed to be smaller
423 * than the amount of physical memory due to the mem= command
424 * line parameter. And if this is a 32-bit non-HIGHMEM kernel
425 * on a system with memory which requires highmem to access,
426 * don't try to use it.
428 extra_pfn_end = min(min(max_pfn, e820_end_of_ram_pfn()),
429 (unsigned long)PFN_DOWN(xen_extra_mem_start + xen_extra_mem_size));
430 for (pfn = PFN_UP(xen_extra_mem_start);
433 page = pfn_to_page(pfn);
434 /* totalram_pages doesn't include the boot-time
435 balloon extension, so don't subtract from it. */
436 __balloon_append(page);
439 target_watch.callback = watch_target;
440 xenstore_notifier.notifier_call = balloon_init_watcher;
442 register_xenstore_notifier(&xenstore_notifier);
447 subsys_initcall(balloon_init);
449 static void balloon_exit(void)
451 /* XXX - release balloon here */
455 module_exit(balloon_exit);
457 #define BALLOON_SHOW(name, format, args...) \
458 static ssize_t show_##name(struct sys_device *dev, \
459 struct sysdev_attribute *attr, \
462 return sprintf(buf, format, ##args); \
464 static SYSDEV_ATTR(name, S_IRUGO, show_##name, NULL)
466 BALLOON_SHOW(current_kb, "%lu\n", PAGES2KB(balloon_stats.current_pages));
467 BALLOON_SHOW(low_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_low));
468 BALLOON_SHOW(high_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_high));
469 BALLOON_SHOW(driver_kb, "%lu\n", PAGES2KB(balloon_stats.driver_pages));
471 static ssize_t show_target_kb(struct sys_device *dev, struct sysdev_attribute *attr,
474 return sprintf(buf, "%lu\n", PAGES2KB(balloon_stats.target_pages));
477 static ssize_t store_target_kb(struct sys_device *dev,
478 struct sysdev_attribute *attr,
483 unsigned long long target_bytes;
485 if (!capable(CAP_SYS_ADMIN))
488 target_bytes = simple_strtoull(buf, &endchar, 0) * 1024;
490 balloon_set_new_target(target_bytes >> PAGE_SHIFT);
495 static SYSDEV_ATTR(target_kb, S_IRUGO | S_IWUSR,
496 show_target_kb, store_target_kb);
499 static ssize_t show_target(struct sys_device *dev, struct sysdev_attribute *attr,
502 return sprintf(buf, "%llu\n",
503 (unsigned long long)balloon_stats.target_pages
507 static ssize_t store_target(struct sys_device *dev,
508 struct sysdev_attribute *attr,
513 unsigned long long target_bytes;
515 if (!capable(CAP_SYS_ADMIN))
518 target_bytes = memparse(buf, &endchar);
520 balloon_set_new_target(target_bytes >> PAGE_SHIFT);
525 static SYSDEV_ATTR(target, S_IRUGO | S_IWUSR,
526 show_target, store_target);
529 static struct sysdev_attribute *balloon_attrs[] = {
534 static struct attribute *balloon_info_attrs[] = {
535 &attr_current_kb.attr,
538 &attr_driver_kb.attr,
542 static struct attribute_group balloon_info_group = {
544 .attrs = balloon_info_attrs,
547 static struct sysdev_class balloon_sysdev_class = {
548 .name = BALLOON_CLASS_NAME,
551 static int register_balloon(struct sys_device *sysdev)
555 error = sysdev_class_register(&balloon_sysdev_class);
560 sysdev->cls = &balloon_sysdev_class;
562 error = sysdev_register(sysdev);
564 sysdev_class_unregister(&balloon_sysdev_class);
568 for (i = 0; i < ARRAY_SIZE(balloon_attrs); i++) {
569 error = sysdev_create_file(sysdev, balloon_attrs[i]);
574 error = sysfs_create_group(&sysdev->kobj, &balloon_info_group);
582 sysdev_remove_file(sysdev, balloon_attrs[i]);
583 sysdev_unregister(sysdev);
584 sysdev_class_unregister(&balloon_sysdev_class);
588 MODULE_LICENSE("GPL");