]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/xen/balloon.c
a51f3e17a5fd724b8a4d282b3d2518e40172f26f
[linux-2.6-omap-h63xx.git] / drivers / xen / balloon.c
1 /******************************************************************************
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
63 #define BALLOON_CLASS_NAME "xen_memory"
64
65 struct 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
81 static DEFINE_MUTEX(balloon_mutex);
82
83 static struct sys_device balloon_sysdev;
84
85 static 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  */
92 static DEFINE_SPINLOCK(balloon_lock);
93
94 static struct balloon_stats balloon_stats;
95
96 /* We increase/decrease in batches which fit in a page */
97 static unsigned long frame_list[PAGE_SIZE / sizeof(unsigned long)];
98
99 /* VM /proc information for memory */
100 extern unsigned long totalram_pages;
101
102 #ifdef CONFIG_HIGHMEM
103 extern 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. */
112 static LIST_HEAD(ballooned_pages);
113
114 /* Main work function, always executed in process context. */
115 static void balloon_process(struct work_struct *work);
116 static DECLARE_WORK(balloon_worker, balloon_process);
117 static 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
124 static 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. */
139 static 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. */
153 static 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
173 static 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
180 static 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
188 static void balloon_alarm(unsigned long unused)
189 {
190         schedule_work(&balloon_worker);
191 }
192
193 static 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
205 static 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
228         set_xen_guest_handle(reservation.extent_start, frame_list);
229         reservation.nr_extents = nr_pages;
230         rc = HYPERVISOR_memory_op(XENMEM_populate_physmap, &reservation);
231         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,
238                                                    &reservation);
239                         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
282 static 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
323         set_xen_guest_handle(reservation.extent_start, frame_list);
324         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  */
342 static 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. */
370 static void balloon_set_new_target(unsigned long target)
371 {
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
378 static struct xenbus_watch target_watch =
379 {
380         .node = "memory/target"
381 };
382
383 /* React to a change in the target key */
384 static 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
402 static 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
415 static struct notifier_block xenstore_notifier;
416
417 static int __init balloon_init(void)
418 {
419         unsigned long pfn;
420         struct page *page;
421
422         if (!xen_pv_domain())
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
456 subsys_initcall(balloon_init);
457
458 static void balloon_exit(void)
459 {
460     /* XXX - release balloon here */
461     return;
462 }
463
464 module_exit(balloon_exit);
465
466 #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         }                                                               \
473         static SYSDEV_ATTR(name, S_IRUGO, show_##name, NULL)
474
475 BALLOON_SHOW(current_kb, "%lu\n", PAGES2KB(balloon_stats.current_pages));
476 BALLOON_SHOW(low_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_low));
477 BALLOON_SHOW(high_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_high));
478 BALLOON_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);
481 BALLOON_SHOW(driver_kb, "%lu\n", PAGES2KB(balloon_stats.driver_pages));
482
483 static ssize_t show_target_kb(struct sys_device *dev, struct sysdev_attribute *attr,
484                               char *buf)
485 {
486         return sprintf(buf, "%lu\n", PAGES2KB(balloon_stats.target_pages));
487 }
488
489 static ssize_t store_target_kb(struct sys_device *dev,
490                                struct sysdev_attribute *attr,
491                                const char *buf,
492                                size_t count)
493 {
494         char *endchar;
495         unsigned long long target_bytes;
496
497         if (!capable(CAP_SYS_ADMIN))
498                 return -EPERM;
499
500         target_bytes = memparse(buf, &endchar);
501
502         balloon_set_new_target(target_bytes >> PAGE_SHIFT);
503
504         return count;
505 }
506
507 static SYSDEV_ATTR(target_kb, S_IRUGO | S_IWUSR,
508                    show_target_kb, store_target_kb);
509
510 static struct sysdev_attribute *balloon_attrs[] = {
511         &attr_target_kb,
512 };
513
514 static 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
523 static struct attribute_group balloon_info_group = {
524         .name = "info",
525         .attrs = balloon_info_attrs,
526 };
527
528 static struct sysdev_class balloon_sysdev_class = {
529         .name = BALLOON_CLASS_NAME,
530 };
531
532 static 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
569 MODULE_LICENSE("GPL");