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