balloon.c 15 KB

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