balloon.c 15 KB

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