blob: 8dc7109d61b760ab6162402797b24d98cff80b88 [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>
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -070044#include <linux/list.h>
45#include <linux/sysdev.h>
46
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -070047#include <asm/page.h>
48#include <asm/pgalloc.h>
49#include <asm/pgtable.h>
50#include <asm/uaccess.h>
51#include <asm/tlb.h>
52
Jeremy Fitzhardingeecbf29c2008-12-16 12:37:07 -080053#include <asm/xen/hypervisor.h>
54#include <asm/xen/hypercall.h>
55#include <xen/interface/xen.h>
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -070056#include <xen/interface/memory.h>
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -070057#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
Jeremy Fitzhardinge26a3e992008-11-17 09:35:00 -0800127 clear_highpage(page);
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700128#endif
129}
130
131/* balloon_append: add the given page to the balloon. */
132static void balloon_append(struct page *page)
133{
134 /* Lowmem is re-populated first, so highmem pages go at list tail. */
135 if (PageHighMem(page)) {
136 list_add_tail(&page->lru, &ballooned_pages);
137 balloon_stats.balloon_high++;
138 dec_totalhigh_pages();
139 } else {
140 list_add(&page->lru, &ballooned_pages);
141 balloon_stats.balloon_low++;
142 }
143}
144
145/* balloon_retrieve: rescue a page from the balloon, if it is not empty. */
146static struct page *balloon_retrieve(void)
147{
148 struct page *page;
149
150 if (list_empty(&ballooned_pages))
151 return NULL;
152
153 page = list_entry(ballooned_pages.next, struct page, lru);
154 list_del(&page->lru);
155
156 if (PageHighMem(page)) {
157 balloon_stats.balloon_high--;
158 inc_totalhigh_pages();
159 }
160 else
161 balloon_stats.balloon_low--;
162
163 return page;
164}
165
166static struct page *balloon_first_page(void)
167{
168 if (list_empty(&ballooned_pages))
169 return NULL;
170 return list_entry(ballooned_pages.next, struct page, lru);
171}
172
173static struct page *balloon_next_page(struct page *page)
174{
175 struct list_head *next = page->lru.next;
176 if (next == &ballooned_pages)
177 return NULL;
178 return list_entry(next, struct page, lru);
179}
180
181static void balloon_alarm(unsigned long unused)
182{
183 schedule_work(&balloon_worker);
184}
185
186static unsigned long current_target(void)
187{
188 unsigned long target = min(balloon_stats.target_pages, balloon_stats.hard_limit);
189
190 target = min(target,
191 balloon_stats.current_pages +
192 balloon_stats.balloon_low +
193 balloon_stats.balloon_high);
194
195 return target;
196}
197
198static int increase_reservation(unsigned long nr_pages)
199{
200 unsigned long pfn, i, flags;
201 struct page *page;
202 long rc;
203 struct xen_memory_reservation reservation = {
204 .address_bits = 0,
205 .extent_order = 0,
206 .domid = DOMID_SELF
207 };
208
209 if (nr_pages > ARRAY_SIZE(frame_list))
210 nr_pages = ARRAY_SIZE(frame_list);
211
212 spin_lock_irqsave(&balloon_lock, flags);
213
214 page = balloon_first_page();
215 for (i = 0; i < nr_pages; i++) {
216 BUG_ON(page == NULL);
217 frame_list[i] = page_to_pfn(page);;
218 page = balloon_next_page(page);
219 }
220
Isaku Yamahataa90971e2008-05-26 23:31:14 +0100221 set_xen_guest_handle(reservation.extent_start, frame_list);
Jeremy Fitzhardingefde28e82008-07-24 16:28:00 -0700222 reservation.nr_extents = nr_pages;
223 rc = HYPERVISOR_memory_op(XENMEM_populate_physmap, &reservation);
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700224 if (rc < nr_pages) {
225 if (rc > 0) {
226 int ret;
227
228 /* We hit the Xen hard limit: reprobe. */
229 reservation.nr_extents = rc;
230 ret = HYPERVISOR_memory_op(XENMEM_decrease_reservation,
Jeremy Fitzhardingefde28e82008-07-24 16:28:00 -0700231 &reservation);
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700232 BUG_ON(ret != rc);
233 }
234 if (rc >= 0)
235 balloon_stats.hard_limit = (balloon_stats.current_pages + rc -
236 balloon_stats.driver_pages);
237 goto out;
238 }
239
240 for (i = 0; i < nr_pages; i++) {
241 page = balloon_retrieve();
242 BUG_ON(page == NULL);
243
244 pfn = page_to_pfn(page);
245 BUG_ON(!xen_feature(XENFEAT_auto_translated_physmap) &&
246 phys_to_machine_mapping_valid(pfn));
247
248 set_phys_to_machine(pfn, frame_list[i]);
249
250 /* Link back into the page tables if not highmem. */
251 if (pfn < max_low_pfn) {
252 int ret;
253 ret = HYPERVISOR_update_va_mapping(
254 (unsigned long)__va(pfn << PAGE_SHIFT),
255 mfn_pte(frame_list[i], PAGE_KERNEL),
256 0);
257 BUG_ON(ret);
258 }
259
260 /* Relinquish the page back to the allocator. */
261 ClearPageReserved(page);
262 init_page_count(page);
263 __free_page(page);
264 }
265
266 balloon_stats.current_pages += nr_pages;
267 totalram_pages = balloon_stats.current_pages;
268
269 out:
270 spin_unlock_irqrestore(&balloon_lock, flags);
271
272 return 0;
273}
274
275static int decrease_reservation(unsigned long nr_pages)
276{
277 unsigned long pfn, i, flags;
278 struct page *page;
279 int need_sleep = 0;
280 int ret;
281 struct xen_memory_reservation reservation = {
282 .address_bits = 0,
283 .extent_order = 0,
284 .domid = DOMID_SELF
285 };
286
287 if (nr_pages > ARRAY_SIZE(frame_list))
288 nr_pages = ARRAY_SIZE(frame_list);
289
290 for (i = 0; i < nr_pages; i++) {
291 if ((page = alloc_page(GFP_BALLOON)) == NULL) {
292 nr_pages = i;
293 need_sleep = 1;
294 break;
295 }
296
297 pfn = page_to_pfn(page);
298 frame_list[i] = pfn_to_mfn(pfn);
299
300 scrub_page(page);
301 }
302
303 /* Ensure that ballooned highmem pages don't have kmaps. */
304 kmap_flush_unused();
305 flush_tlb_all();
306
307 spin_lock_irqsave(&balloon_lock, flags);
308
309 /* No more mappings: invalidate P2M and add to balloon. */
310 for (i = 0; i < nr_pages; i++) {
311 pfn = mfn_to_pfn(frame_list[i]);
312 set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
313 balloon_append(pfn_to_page(pfn));
314 }
315
Isaku Yamahataa90971e2008-05-26 23:31:14 +0100316 set_xen_guest_handle(reservation.extent_start, frame_list);
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700317 reservation.nr_extents = nr_pages;
318 ret = HYPERVISOR_memory_op(XENMEM_decrease_reservation, &reservation);
319 BUG_ON(ret != nr_pages);
320
321 balloon_stats.current_pages -= nr_pages;
322 totalram_pages = balloon_stats.current_pages;
323
324 spin_unlock_irqrestore(&balloon_lock, flags);
325
326 return need_sleep;
327}
328
329/*
330 * We avoid multiple worker processes conflicting via the balloon mutex.
331 * We may of course race updates of the target counts (which are protected
332 * by the balloon lock), or with changes to the Xen hard limit, but we will
333 * recover from these in time.
334 */
335static void balloon_process(struct work_struct *work)
336{
337 int need_sleep = 0;
338 long credit;
339
340 mutex_lock(&balloon_mutex);
341
342 do {
343 credit = current_target() - balloon_stats.current_pages;
344 if (credit > 0)
345 need_sleep = (increase_reservation(credit) != 0);
346 if (credit < 0)
347 need_sleep = (decrease_reservation(-credit) != 0);
348
349#ifndef CONFIG_PREEMPT
350 if (need_resched())
351 schedule();
352#endif
353 } while ((credit != 0) && !need_sleep);
354
355 /* Schedule more work if there is some still to be done. */
356 if (current_target() != balloon_stats.current_pages)
357 mod_timer(&balloon_timer, jiffies + HZ);
358
359 mutex_unlock(&balloon_mutex);
360}
361
362/* Resets the Xen limit, sets new target, and kicks off processing. */
Adrian Bunk955d6f12008-05-26 23:31:17 +0100363static void balloon_set_new_target(unsigned long target)
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700364{
365 /* No need for lock. Not read-modify-write updates. */
366 balloon_stats.hard_limit = ~0UL;
367 balloon_stats.target_pages = target;
368 schedule_work(&balloon_worker);
369}
370
371static struct xenbus_watch target_watch =
372{
373 .node = "memory/target"
374};
375
376/* React to a change in the target key */
377static void watch_target(struct xenbus_watch *watch,
378 const char **vec, unsigned int len)
379{
380 unsigned long long new_target;
381 int err;
382
383 err = xenbus_scanf(XBT_NIL, "memory", "target", "%llu", &new_target);
384 if (err != 1) {
385 /* This is ok (for domain0 at least) - so just return */
386 return;
387 }
388
389 /* The given memory/target value is in KiB, so it needs converting to
390 * pages. PAGE_SHIFT converts bytes to pages, hence PAGE_SHIFT - 10.
391 */
392 balloon_set_new_target(new_target >> (PAGE_SHIFT - 10));
393}
394
395static int balloon_init_watcher(struct notifier_block *notifier,
396 unsigned long event,
397 void *data)
398{
399 int err;
400
401 err = register_xenbus_watch(&target_watch);
402 if (err)
403 printk(KERN_ERR "Failed to set balloon watcher\n");
404
405 return NOTIFY_DONE;
406}
407
408static struct notifier_block xenstore_notifier;
409
410static int __init balloon_init(void)
411{
412 unsigned long pfn;
413 struct page *page;
414
Jeremy Fitzhardinge6e833582008-08-19 13:16:17 -0700415 if (!xen_pv_domain())
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700416 return -ENODEV;
417
418 pr_info("xen_balloon: Initialising balloon driver.\n");
419
420 balloon_stats.current_pages = min(xen_start_info->nr_pages, max_pfn);
421 totalram_pages = balloon_stats.current_pages;
422 balloon_stats.target_pages = balloon_stats.current_pages;
423 balloon_stats.balloon_low = 0;
424 balloon_stats.balloon_high = 0;
425 balloon_stats.driver_pages = 0UL;
426 balloon_stats.hard_limit = ~0UL;
427
428 init_timer(&balloon_timer);
429 balloon_timer.data = 0;
430 balloon_timer.function = balloon_alarm;
431
432 register_balloon(&balloon_sysdev);
433
434 /* Initialise the balloon with excess memory space. */
435 for (pfn = xen_start_info->nr_pages; pfn < max_pfn; pfn++) {
436 page = pfn_to_page(pfn);
437 if (!PageReserved(page))
438 balloon_append(page);
439 }
440
441 target_watch.callback = watch_target;
442 xenstore_notifier.notifier_call = balloon_init_watcher;
443
444 register_xenstore_notifier(&xenstore_notifier);
445
446 return 0;
447}
448
449subsys_initcall(balloon_init);
450
451static void balloon_exit(void)
452{
453 /* XXX - release balloon here */
454 return;
455}
456
457module_exit(balloon_exit);
458
Jeremy Fitzhardinge167e6cf2008-07-24 16:27:52 -0700459#define BALLOON_SHOW(name, format, args...) \
460 static ssize_t show_##name(struct sys_device *dev, \
461 struct sysdev_attribute *attr, \
462 char *buf) \
463 { \
464 return sprintf(buf, format, ##args); \
465 } \
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700466 static SYSDEV_ATTR(name, S_IRUGO, show_##name, NULL)
467
468BALLOON_SHOW(current_kb, "%lu\n", PAGES2KB(balloon_stats.current_pages));
469BALLOON_SHOW(low_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_low));
470BALLOON_SHOW(high_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_high));
471BALLOON_SHOW(hard_limit_kb,
472 (balloon_stats.hard_limit!=~0UL) ? "%lu\n" : "???\n",
473 (balloon_stats.hard_limit!=~0UL) ? PAGES2KB(balloon_stats.hard_limit) : 0);
474BALLOON_SHOW(driver_kb, "%lu\n", PAGES2KB(balloon_stats.driver_pages));
475
Jeremy Fitzhardinge167e6cf2008-07-24 16:27:52 -0700476static ssize_t show_target_kb(struct sys_device *dev, struct sysdev_attribute *attr,
477 char *buf)
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700478{
479 return sprintf(buf, "%lu\n", PAGES2KB(balloon_stats.target_pages));
480}
481
482static ssize_t store_target_kb(struct sys_device *dev,
Andi Kleen4a0b2b42008-07-01 18:48:41 +0200483 struct sysdev_attribute *attr,
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700484 const char *buf,
485 size_t count)
486{
Jeremy Fitzhardinge167e6cf2008-07-24 16:27:52 -0700487 char *endchar;
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700488 unsigned long long target_bytes;
489
490 if (!capable(CAP_SYS_ADMIN))
491 return -EPERM;
492
Jeremy Fitzhardinge167e6cf2008-07-24 16:27:52 -0700493 target_bytes = memparse(buf, &endchar);
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700494
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700495 balloon_set_new_target(target_bytes >> PAGE_SHIFT);
496
497 return count;
498}
499
500static SYSDEV_ATTR(target_kb, S_IRUGO | S_IWUSR,
501 show_target_kb, store_target_kb);
502
503static struct sysdev_attribute *balloon_attrs[] = {
504 &attr_target_kb,
505};
506
507static struct attribute *balloon_info_attrs[] = {
508 &attr_current_kb.attr,
509 &attr_low_kb.attr,
510 &attr_high_kb.attr,
511 &attr_hard_limit_kb.attr,
512 &attr_driver_kb.attr,
513 NULL
514};
515
516static struct attribute_group balloon_info_group = {
517 .name = "info",
518 .attrs = balloon_info_attrs,
519};
520
521static struct sysdev_class balloon_sysdev_class = {
522 .name = BALLOON_CLASS_NAME,
523};
524
525static int register_balloon(struct sys_device *sysdev)
526{
527 int i, error;
528
529 error = sysdev_class_register(&balloon_sysdev_class);
530 if (error)
531 return error;
532
533 sysdev->id = 0;
534 sysdev->cls = &balloon_sysdev_class;
535
536 error = sysdev_register(sysdev);
537 if (error) {
538 sysdev_class_unregister(&balloon_sysdev_class);
539 return error;
540 }
541
542 for (i = 0; i < ARRAY_SIZE(balloon_attrs); i++) {
543 error = sysdev_create_file(sysdev, balloon_attrs[i]);
544 if (error)
545 goto fail;
546 }
547
548 error = sysfs_create_group(&sysdev->kobj, &balloon_info_group);
549 if (error)
550 goto fail;
551
552 return 0;
553
554 fail:
555 while (--i >= 0)
556 sysdev_remove_file(sysdev, balloon_attrs[i]);
557 sysdev_unregister(sysdev);
558 sysdev_class_unregister(&balloon_sysdev_class);
559 return error;
560}
561
Jeremy Fitzhardinge17758262008-04-02 10:54:13 -0700562MODULE_LICENSE("GPL");