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