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