balloon.c 15 KB

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