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