balloon.c 15 KB

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