Xen balloon: fix totalram_pages counting.
[linux-2.6.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/list.h>
45 #include <linux/sysdev.h>
46
47 #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
53 #include <asm/xen/hypervisor.h>
54 #include <asm/xen/hypercall.h>
55 #include <xen/interface/xen.h>
56 #include <xen/interface/memory.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 #ifdef CONFIG_HIGHMEM
100 #define inc_totalhigh_pages() (totalhigh_pages++)
101 #define dec_totalhigh_pages() (totalhigh_pages--)
102 #else
103 #define inc_totalhigh_pages() do {} while(0)
104 #define dec_totalhigh_pages() do {} while(0)
105 #endif
106
107 /* List of ballooned pages, threaded through the mem_map array. */
108 static LIST_HEAD(ballooned_pages);
109
110 /* Main work function, always executed in process context. */
111 static void balloon_process(struct work_struct *work);
112 static DECLARE_WORK(balloon_worker, balloon_process);
113 static struct timer_list balloon_timer;
114
115 /* When ballooning out (allocating memory to return to Xen) we don't really
116    want the kernel to try too hard since that can trigger the oom killer. */
117 #define GFP_BALLOON \
118         (GFP_HIGHUSER | __GFP_NOWARN | __GFP_NORETRY | __GFP_NOMEMALLOC)
119
120 static void scrub_page(struct page *page)
121 {
122 #ifdef CONFIG_XEN_SCRUB_PAGES
123         clear_highpage(page);
124 #endif
125 }
126
127 /* balloon_append: add the given page to the balloon. */
128 static void balloon_append(struct page *page)
129 {
130         /* Lowmem is re-populated first, so highmem pages go at list tail. */
131         if (PageHighMem(page)) {
132                 list_add_tail(&page->lru, &ballooned_pages);
133                 balloon_stats.balloon_high++;
134                 dec_totalhigh_pages();
135         } else {
136                 list_add(&page->lru, &ballooned_pages);
137                 balloon_stats.balloon_low++;
138         }
139
140         totalram_pages--;
141 }
142
143 /* balloon_retrieve: rescue a page from the balloon, if it is not empty. */
144 static struct page *balloon_retrieve(void)
145 {
146         struct page *page;
147
148         if (list_empty(&ballooned_pages))
149                 return NULL;
150
151         page = list_entry(ballooned_pages.next, struct page, lru);
152         list_del(&page->lru);
153
154         if (PageHighMem(page)) {
155                 balloon_stats.balloon_high--;
156                 inc_totalhigh_pages();
157         }
158         else
159                 balloon_stats.balloon_low--;
160
161         totalram_pages++;
162
163         return page;
164 }
165
166 static 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
173 static 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
181 static void balloon_alarm(unsigned long unused)
182 {
183         schedule_work(&balloon_worker);
184 }
185
186 static 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
198 static 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
221         set_xen_guest_handle(reservation.extent_start, frame_list);
222         reservation.nr_extents = nr_pages;
223         rc = HYPERVISOR_memory_op(XENMEM_populate_physmap, &reservation);
224         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,
231                                                    &reservation);
232                         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
268  out:
269         spin_unlock_irqrestore(&balloon_lock, flags);
270
271         return 0;
272 }
273
274 static int decrease_reservation(unsigned long nr_pages)
275 {
276         unsigned long  pfn, i, flags;
277         struct page   *page;
278         int            need_sleep = 0;
279         int ret;
280         struct xen_memory_reservation reservation = {
281                 .address_bits = 0,
282                 .extent_order = 0,
283                 .domid        = DOMID_SELF
284         };
285
286         if (nr_pages > ARRAY_SIZE(frame_list))
287                 nr_pages = ARRAY_SIZE(frame_list);
288
289         for (i = 0; i < nr_pages; i++) {
290                 if ((page = alloc_page(GFP_BALLOON)) == NULL) {
291                         nr_pages = i;
292                         need_sleep = 1;
293                         break;
294                 }
295
296                 pfn = page_to_pfn(page);
297                 frame_list[i] = pfn_to_mfn(pfn);
298
299                 scrub_page(page);
300
301                 if (!PageHighMem(page)) {
302                         ret = HYPERVISOR_update_va_mapping(
303                                 (unsigned long)__va(pfn << PAGE_SHIFT),
304                                 __pte_ma(0), 0);
305                         BUG_ON(ret);
306                 }
307
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
330         spin_unlock_irqrestore(&balloon_lock, flags);
331
332         return need_sleep;
333 }
334
335 /*
336  * We avoid multiple worker processes conflicting via the balloon mutex.
337  * We may of course race updates of the target counts (which are protected
338  * by the balloon lock), or with changes to the Xen hard limit, but we will
339  * recover from these in time.
340  */
341 static void balloon_process(struct work_struct *work)
342 {
343         int need_sleep = 0;
344         long credit;
345
346         mutex_lock(&balloon_mutex);
347
348         do {
349                 credit = current_target() - balloon_stats.current_pages;
350                 if (credit > 0)
351                         need_sleep = (increase_reservation(credit) != 0);
352                 if (credit < 0)
353                         need_sleep = (decrease_reservation(-credit) != 0);
354
355 #ifndef CONFIG_PREEMPT
356                 if (need_resched())
357                         schedule();
358 #endif
359         } while ((credit != 0) && !need_sleep);
360
361         /* Schedule more work if there is some still to be done. */
362         if (current_target() != balloon_stats.current_pages)
363                 mod_timer(&balloon_timer, jiffies + HZ);
364
365         mutex_unlock(&balloon_mutex);
366 }
367
368 /* Resets the Xen limit, sets new target, and kicks off processing. */
369 static void balloon_set_new_target(unsigned long target)
370 {
371         /* No need for lock. Not read-modify-write updates. */
372         balloon_stats.hard_limit   = ~0UL;
373         balloon_stats.target_pages = target;
374         schedule_work(&balloon_worker);
375 }
376
377 static struct xenbus_watch target_watch =
378 {
379         .node = "memory/target"
380 };
381
382 /* React to a change in the target key */
383 static void watch_target(struct xenbus_watch *watch,
384                          const char **vec, unsigned int len)
385 {
386         unsigned long long new_target;
387         int err;
388
389         err = xenbus_scanf(XBT_NIL, "memory", "target", "%llu", &new_target);
390         if (err != 1) {
391                 /* This is ok (for domain0 at least) - so just return */
392                 return;
393         }
394
395         /* The given memory/target value is in KiB, so it needs converting to
396          * pages. PAGE_SHIFT converts bytes to pages, hence PAGE_SHIFT - 10.
397          */
398         balloon_set_new_target(new_target >> (PAGE_SHIFT - 10));
399 }
400
401 static int balloon_init_watcher(struct notifier_block *notifier,
402                                 unsigned long event,
403                                 void *data)
404 {
405         int err;
406
407         err = register_xenbus_watch(&target_watch);
408         if (err)
409                 printk(KERN_ERR "Failed to set balloon watcher\n");
410
411         return NOTIFY_DONE;
412 }
413
414 static struct notifier_block xenstore_notifier;
415
416 static int __init balloon_init(void)
417 {
418         unsigned long pfn;
419         struct page *page;
420
421         if (!xen_pv_domain())
422                 return -ENODEV;
423
424         pr_info("xen_balloon: Initialising balloon driver.\n");
425
426         balloon_stats.current_pages = min(xen_start_info->nr_pages, max_pfn);
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
454 subsys_initcall(balloon_init);
455
456 static void balloon_exit(void)
457 {
458     /* XXX - release balloon here */
459     return;
460 }
461
462 module_exit(balloon_exit);
463
464 #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         }                                                               \
471         static SYSDEV_ATTR(name, S_IRUGO, show_##name, NULL)
472
473 BALLOON_SHOW(current_kb, "%lu\n", PAGES2KB(balloon_stats.current_pages));
474 BALLOON_SHOW(low_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_low));
475 BALLOON_SHOW(high_kb, "%lu\n", PAGES2KB(balloon_stats.balloon_high));
476 BALLOON_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);
479 BALLOON_SHOW(driver_kb, "%lu\n", PAGES2KB(balloon_stats.driver_pages));
480
481 static ssize_t show_target_kb(struct sys_device *dev, struct sysdev_attribute *attr,
482                               char *buf)
483 {
484         return sprintf(buf, "%lu\n", PAGES2KB(balloon_stats.target_pages));
485 }
486
487 static ssize_t store_target_kb(struct sys_device *dev,
488                                struct sysdev_attribute *attr,
489                                const char *buf,
490                                size_t count)
491 {
492         char *endchar;
493         unsigned long long target_bytes;
494
495         if (!capable(CAP_SYS_ADMIN))
496                 return -EPERM;
497
498         target_bytes = simple_strtoull(buf, &endchar, 0) * 1024;
499
500         balloon_set_new_target(target_bytes >> PAGE_SHIFT);
501
502         return count;
503 }
504
505 static SYSDEV_ATTR(target_kb, S_IRUGO | S_IWUSR,
506                    show_target_kb, store_target_kb);
507
508
509 static ssize_t show_target(struct sys_device *dev, struct sysdev_attribute *attr,
510                               char *buf)
511 {
512         return sprintf(buf, "%llu\n",
513                        (unsigned long long)balloon_stats.target_pages
514                        << PAGE_SHIFT);
515 }
516
517 static ssize_t store_target(struct sys_device *dev,
518                             struct sysdev_attribute *attr,
519                             const char *buf,
520                             size_t count)
521 {
522         char *endchar;
523         unsigned long long target_bytes;
524
525         if (!capable(CAP_SYS_ADMIN))
526                 return -EPERM;
527
528         target_bytes = memparse(buf, &endchar);
529
530         balloon_set_new_target(target_bytes >> PAGE_SHIFT);
531
532         return count;
533 }
534
535 static SYSDEV_ATTR(target, S_IRUGO | S_IWUSR,
536                    show_target, store_target);
537
538
539 static struct sysdev_attribute *balloon_attrs[] = {
540         &attr_target_kb,
541         &attr_target,
542 };
543
544 static struct attribute *balloon_info_attrs[] = {
545         &attr_current_kb.attr,
546         &attr_low_kb.attr,
547         &attr_high_kb.attr,
548         &attr_hard_limit_kb.attr,
549         &attr_driver_kb.attr,
550         NULL
551 };
552
553 static struct attribute_group balloon_info_group = {
554         .name = "info",
555         .attrs = balloon_info_attrs,
556 };
557
558 static struct sysdev_class balloon_sysdev_class = {
559         .name = BALLOON_CLASS_NAME,
560 };
561
562 static int register_balloon(struct sys_device *sysdev)
563 {
564         int i, error;
565
566         error = sysdev_class_register(&balloon_sysdev_class);
567         if (error)
568                 return error;
569
570         sysdev->id = 0;
571         sysdev->cls = &balloon_sysdev_class;
572
573         error = sysdev_register(sysdev);
574         if (error) {
575                 sysdev_class_unregister(&balloon_sysdev_class);
576                 return error;
577         }
578
579         for (i = 0; i < ARRAY_SIZE(balloon_attrs); i++) {
580                 error = sysdev_create_file(sysdev, balloon_attrs[i]);
581                 if (error)
582                         goto fail;
583         }
584
585         error = sysfs_create_group(&sysdev->kobj, &balloon_info_group);
586         if (error)
587                 goto fail;
588
589         return 0;
590
591  fail:
592         while (--i >= 0)
593                 sysdev_remove_file(sysdev, balloon_attrs[i]);
594         sysdev_unregister(sysdev);
595         sysdev_class_unregister(&balloon_sysdev_class);
596         return error;
597 }
598
599 MODULE_LICENSE("GPL");