balloon.c 14 KB

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