PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/drivers/hv/hv_balloon.c

https://github.com/kvaneesh/linux
C | 1942 lines | 1146 code | 305 blank | 491 comment | 149 complexity | 77168d59daa7cec266a086b3c93ea56c MD5 | raw file
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (c) 2012, Microsoft Corporation.
  4. *
  5. * Author:
  6. * K. Y. Srinivasan <kys@microsoft.com>
  7. */
  8. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  9. #include <linux/kernel.h>
  10. #include <linux/jiffies.h>
  11. #include <linux/mman.h>
  12. #include <linux/delay.h>
  13. #include <linux/init.h>
  14. #include <linux/module.h>
  15. #include <linux/slab.h>
  16. #include <linux/kthread.h>
  17. #include <linux/completion.h>
  18. #include <linux/memory_hotplug.h>
  19. #include <linux/memory.h>
  20. #include <linux/notifier.h>
  21. #include <linux/percpu_counter.h>
  22. #include <linux/page_reporting.h>
  23. #include <linux/hyperv.h>
  24. #include <asm/hyperv-tlfs.h>
  25. #include <asm/mshyperv.h>
  26. #define CREATE_TRACE_POINTS
  27. #include "hv_trace_balloon.h"
  28. /*
  29. * We begin with definitions supporting the Dynamic Memory protocol
  30. * with the host.
  31. *
  32. * Begin protocol definitions.
  33. */
  34. /*
  35. * Protocol versions. The low word is the minor version, the high word the major
  36. * version.
  37. *
  38. * History:
  39. * Initial version 1.0
  40. * Changed to 0.1 on 2009/03/25
  41. * Changes to 0.2 on 2009/05/14
  42. * Changes to 0.3 on 2009/12/03
  43. * Changed to 1.0 on 2011/04/05
  44. */
  45. #define DYNMEM_MAKE_VERSION(Major, Minor) ((__u32)(((Major) << 16) | (Minor)))
  46. #define DYNMEM_MAJOR_VERSION(Version) ((__u32)(Version) >> 16)
  47. #define DYNMEM_MINOR_VERSION(Version) ((__u32)(Version) & 0xff)
  48. enum {
  49. DYNMEM_PROTOCOL_VERSION_1 = DYNMEM_MAKE_VERSION(0, 3),
  50. DYNMEM_PROTOCOL_VERSION_2 = DYNMEM_MAKE_VERSION(1, 0),
  51. DYNMEM_PROTOCOL_VERSION_3 = DYNMEM_MAKE_VERSION(2, 0),
  52. DYNMEM_PROTOCOL_VERSION_WIN7 = DYNMEM_PROTOCOL_VERSION_1,
  53. DYNMEM_PROTOCOL_VERSION_WIN8 = DYNMEM_PROTOCOL_VERSION_2,
  54. DYNMEM_PROTOCOL_VERSION_WIN10 = DYNMEM_PROTOCOL_VERSION_3,
  55. DYNMEM_PROTOCOL_VERSION_CURRENT = DYNMEM_PROTOCOL_VERSION_WIN10
  56. };
  57. /*
  58. * Message Types
  59. */
  60. enum dm_message_type {
  61. /*
  62. * Version 0.3
  63. */
  64. DM_ERROR = 0,
  65. DM_VERSION_REQUEST = 1,
  66. DM_VERSION_RESPONSE = 2,
  67. DM_CAPABILITIES_REPORT = 3,
  68. DM_CAPABILITIES_RESPONSE = 4,
  69. DM_STATUS_REPORT = 5,
  70. DM_BALLOON_REQUEST = 6,
  71. DM_BALLOON_RESPONSE = 7,
  72. DM_UNBALLOON_REQUEST = 8,
  73. DM_UNBALLOON_RESPONSE = 9,
  74. DM_MEM_HOT_ADD_REQUEST = 10,
  75. DM_MEM_HOT_ADD_RESPONSE = 11,
  76. DM_VERSION_03_MAX = 11,
  77. /*
  78. * Version 1.0.
  79. */
  80. DM_INFO_MESSAGE = 12,
  81. DM_VERSION_1_MAX = 12
  82. };
  83. /*
  84. * Structures defining the dynamic memory management
  85. * protocol.
  86. */
  87. union dm_version {
  88. struct {
  89. __u16 minor_version;
  90. __u16 major_version;
  91. };
  92. __u32 version;
  93. } __packed;
  94. union dm_caps {
  95. struct {
  96. __u64 balloon:1;
  97. __u64 hot_add:1;
  98. /*
  99. * To support guests that may have alignment
  100. * limitations on hot-add, the guest can specify
  101. * its alignment requirements; a value of n
  102. * represents an alignment of 2^n in mega bytes.
  103. */
  104. __u64 hot_add_alignment:4;
  105. __u64 reservedz:58;
  106. } cap_bits;
  107. __u64 caps;
  108. } __packed;
  109. union dm_mem_page_range {
  110. struct {
  111. /*
  112. * The PFN number of the first page in the range.
  113. * 40 bits is the architectural limit of a PFN
  114. * number for AMD64.
  115. */
  116. __u64 start_page:40;
  117. /*
  118. * The number of pages in the range.
  119. */
  120. __u64 page_cnt:24;
  121. } finfo;
  122. __u64 page_range;
  123. } __packed;
  124. /*
  125. * The header for all dynamic memory messages:
  126. *
  127. * type: Type of the message.
  128. * size: Size of the message in bytes; including the header.
  129. * trans_id: The guest is responsible for manufacturing this ID.
  130. */
  131. struct dm_header {
  132. __u16 type;
  133. __u16 size;
  134. __u32 trans_id;
  135. } __packed;
  136. /*
  137. * A generic message format for dynamic memory.
  138. * Specific message formats are defined later in the file.
  139. */
  140. struct dm_message {
  141. struct dm_header hdr;
  142. __u8 data[]; /* enclosed message */
  143. } __packed;
  144. /*
  145. * Specific message types supporting the dynamic memory protocol.
  146. */
  147. /*
  148. * Version negotiation message. Sent from the guest to the host.
  149. * The guest is free to try different versions until the host
  150. * accepts the version.
  151. *
  152. * dm_version: The protocol version requested.
  153. * is_last_attempt: If TRUE, this is the last version guest will request.
  154. * reservedz: Reserved field, set to zero.
  155. */
  156. struct dm_version_request {
  157. struct dm_header hdr;
  158. union dm_version version;
  159. __u32 is_last_attempt:1;
  160. __u32 reservedz:31;
  161. } __packed;
  162. /*
  163. * Version response message; Host to Guest and indicates
  164. * if the host has accepted the version sent by the guest.
  165. *
  166. * is_accepted: If TRUE, host has accepted the version and the guest
  167. * should proceed to the next stage of the protocol. FALSE indicates that
  168. * guest should re-try with a different version.
  169. *
  170. * reservedz: Reserved field, set to zero.
  171. */
  172. struct dm_version_response {
  173. struct dm_header hdr;
  174. __u64 is_accepted:1;
  175. __u64 reservedz:63;
  176. } __packed;
  177. /*
  178. * Message reporting capabilities. This is sent from the guest to the
  179. * host.
  180. */
  181. struct dm_capabilities {
  182. struct dm_header hdr;
  183. union dm_caps caps;
  184. __u64 min_page_cnt;
  185. __u64 max_page_number;
  186. } __packed;
  187. /*
  188. * Response to the capabilities message. This is sent from the host to the
  189. * guest. This message notifies if the host has accepted the guest's
  190. * capabilities. If the host has not accepted, the guest must shutdown
  191. * the service.
  192. *
  193. * is_accepted: Indicates if the host has accepted guest's capabilities.
  194. * reservedz: Must be 0.
  195. */
  196. struct dm_capabilities_resp_msg {
  197. struct dm_header hdr;
  198. __u64 is_accepted:1;
  199. __u64 reservedz:63;
  200. } __packed;
  201. /*
  202. * This message is used to report memory pressure from the guest.
  203. * This message is not part of any transaction and there is no
  204. * response to this message.
  205. *
  206. * num_avail: Available memory in pages.
  207. * num_committed: Committed memory in pages.
  208. * page_file_size: The accumulated size of all page files
  209. * in the system in pages.
  210. * zero_free: The nunber of zero and free pages.
  211. * page_file_writes: The writes to the page file in pages.
  212. * io_diff: An indicator of file cache efficiency or page file activity,
  213. * calculated as File Cache Page Fault Count - Page Read Count.
  214. * This value is in pages.
  215. *
  216. * Some of these metrics are Windows specific and fortunately
  217. * the algorithm on the host side that computes the guest memory
  218. * pressure only uses num_committed value.
  219. */
  220. struct dm_status {
  221. struct dm_header hdr;
  222. __u64 num_avail;
  223. __u64 num_committed;
  224. __u64 page_file_size;
  225. __u64 zero_free;
  226. __u32 page_file_writes;
  227. __u32 io_diff;
  228. } __packed;
  229. /*
  230. * Message to ask the guest to allocate memory - balloon up message.
  231. * This message is sent from the host to the guest. The guest may not be
  232. * able to allocate as much memory as requested.
  233. *
  234. * num_pages: number of pages to allocate.
  235. */
  236. struct dm_balloon {
  237. struct dm_header hdr;
  238. __u32 num_pages;
  239. __u32 reservedz;
  240. } __packed;
  241. /*
  242. * Balloon response message; this message is sent from the guest
  243. * to the host in response to the balloon message.
  244. *
  245. * reservedz: Reserved; must be set to zero.
  246. * more_pages: If FALSE, this is the last message of the transaction.
  247. * if TRUE there will atleast one more message from the guest.
  248. *
  249. * range_count: The number of ranges in the range array.
  250. *
  251. * range_array: An array of page ranges returned to the host.
  252. *
  253. */
  254. struct dm_balloon_response {
  255. struct dm_header hdr;
  256. __u32 reservedz;
  257. __u32 more_pages:1;
  258. __u32 range_count:31;
  259. union dm_mem_page_range range_array[];
  260. } __packed;
  261. /*
  262. * Un-balloon message; this message is sent from the host
  263. * to the guest to give guest more memory.
  264. *
  265. * more_pages: If FALSE, this is the last message of the transaction.
  266. * if TRUE there will atleast one more message from the guest.
  267. *
  268. * reservedz: Reserved; must be set to zero.
  269. *
  270. * range_count: The number of ranges in the range array.
  271. *
  272. * range_array: An array of page ranges returned to the host.
  273. *
  274. */
  275. struct dm_unballoon_request {
  276. struct dm_header hdr;
  277. __u32 more_pages:1;
  278. __u32 reservedz:31;
  279. __u32 range_count;
  280. union dm_mem_page_range range_array[];
  281. } __packed;
  282. /*
  283. * Un-balloon response message; this message is sent from the guest
  284. * to the host in response to an unballoon request.
  285. *
  286. */
  287. struct dm_unballoon_response {
  288. struct dm_header hdr;
  289. } __packed;
  290. /*
  291. * Hot add request message. Message sent from the host to the guest.
  292. *
  293. * mem_range: Memory range to hot add.
  294. *
  295. */
  296. struct dm_hot_add {
  297. struct dm_header hdr;
  298. union dm_mem_page_range range;
  299. } __packed;
  300. /*
  301. * Hot add response message.
  302. * This message is sent by the guest to report the status of a hot add request.
  303. * If page_count is less than the requested page count, then the host should
  304. * assume all further hot add requests will fail, since this indicates that
  305. * the guest has hit an upper physical memory barrier.
  306. *
  307. * Hot adds may also fail due to low resources; in this case, the guest must
  308. * not complete this message until the hot add can succeed, and the host must
  309. * not send a new hot add request until the response is sent.
  310. * If VSC fails to hot add memory DYNMEM_NUMBER_OF_UNSUCCESSFUL_HOTADD_ATTEMPTS
  311. * times it fails the request.
  312. *
  313. *
  314. * page_count: number of pages that were successfully hot added.
  315. *
  316. * result: result of the operation 1: success, 0: failure.
  317. *
  318. */
  319. struct dm_hot_add_response {
  320. struct dm_header hdr;
  321. __u32 page_count;
  322. __u32 result;
  323. } __packed;
  324. /*
  325. * Types of information sent from host to the guest.
  326. */
  327. enum dm_info_type {
  328. INFO_TYPE_MAX_PAGE_CNT = 0,
  329. MAX_INFO_TYPE
  330. };
  331. /*
  332. * Header for the information message.
  333. */
  334. struct dm_info_header {
  335. enum dm_info_type type;
  336. __u32 data_size;
  337. } __packed;
  338. /*
  339. * This message is sent from the host to the guest to pass
  340. * some relevant information (win8 addition).
  341. *
  342. * reserved: no used.
  343. * info_size: size of the information blob.
  344. * info: information blob.
  345. */
  346. struct dm_info_msg {
  347. struct dm_header hdr;
  348. __u32 reserved;
  349. __u32 info_size;
  350. __u8 info[];
  351. };
  352. /*
  353. * End protocol definitions.
  354. */
  355. /*
  356. * State to manage hot adding memory into the guest.
  357. * The range start_pfn : end_pfn specifies the range
  358. * that the host has asked us to hot add. The range
  359. * start_pfn : ha_end_pfn specifies the range that we have
  360. * currently hot added. We hot add in multiples of 128M
  361. * chunks; it is possible that we may not be able to bring
  362. * online all the pages in the region. The range
  363. * covered_start_pfn:covered_end_pfn defines the pages that can
  364. * be brough online.
  365. */
  366. struct hv_hotadd_state {
  367. struct list_head list;
  368. unsigned long start_pfn;
  369. unsigned long covered_start_pfn;
  370. unsigned long covered_end_pfn;
  371. unsigned long ha_end_pfn;
  372. unsigned long end_pfn;
  373. /*
  374. * A list of gaps.
  375. */
  376. struct list_head gap_list;
  377. };
  378. struct hv_hotadd_gap {
  379. struct list_head list;
  380. unsigned long start_pfn;
  381. unsigned long end_pfn;
  382. };
  383. struct balloon_state {
  384. __u32 num_pages;
  385. struct work_struct wrk;
  386. };
  387. struct hot_add_wrk {
  388. union dm_mem_page_range ha_page_range;
  389. union dm_mem_page_range ha_region_range;
  390. struct work_struct wrk;
  391. };
  392. static bool allow_hibernation;
  393. static bool hot_add = true;
  394. static bool do_hot_add;
  395. /*
  396. * Delay reporting memory pressure by
  397. * the specified number of seconds.
  398. */
  399. static uint pressure_report_delay = 45;
  400. /*
  401. * The last time we posted a pressure report to host.
  402. */
  403. static unsigned long last_post_time;
  404. module_param(hot_add, bool, (S_IRUGO | S_IWUSR));
  405. MODULE_PARM_DESC(hot_add, "If set attempt memory hot_add");
  406. module_param(pressure_report_delay, uint, (S_IRUGO | S_IWUSR));
  407. MODULE_PARM_DESC(pressure_report_delay, "Delay in secs in reporting pressure");
  408. static atomic_t trans_id = ATOMIC_INIT(0);
  409. static int dm_ring_size = 20 * 1024;
  410. /*
  411. * Driver specific state.
  412. */
  413. enum hv_dm_state {
  414. DM_INITIALIZING = 0,
  415. DM_INITIALIZED,
  416. DM_BALLOON_UP,
  417. DM_BALLOON_DOWN,
  418. DM_HOT_ADD,
  419. DM_INIT_ERROR
  420. };
  421. static __u8 recv_buffer[HV_HYP_PAGE_SIZE];
  422. static __u8 balloon_up_send_buffer[HV_HYP_PAGE_SIZE];
  423. #define PAGES_IN_2M (2 * 1024 * 1024 / PAGE_SIZE)
  424. #define HA_CHUNK (128 * 1024 * 1024 / PAGE_SIZE)
  425. struct hv_dynmem_device {
  426. struct hv_device *dev;
  427. enum hv_dm_state state;
  428. struct completion host_event;
  429. struct completion config_event;
  430. /*
  431. * Number of pages we have currently ballooned out.
  432. */
  433. unsigned int num_pages_ballooned;
  434. unsigned int num_pages_onlined;
  435. unsigned int num_pages_added;
  436. /*
  437. * State to manage the ballooning (up) operation.
  438. */
  439. struct balloon_state balloon_wrk;
  440. /*
  441. * State to execute the "hot-add" operation.
  442. */
  443. struct hot_add_wrk ha_wrk;
  444. /*
  445. * This state tracks if the host has specified a hot-add
  446. * region.
  447. */
  448. bool host_specified_ha_region;
  449. /*
  450. * State to synchronize hot-add.
  451. */
  452. struct completion ol_waitevent;
  453. /*
  454. * This thread handles hot-add
  455. * requests from the host as well as notifying
  456. * the host with regards to memory pressure in
  457. * the guest.
  458. */
  459. struct task_struct *thread;
  460. /*
  461. * Protects ha_region_list, num_pages_onlined counter and individual
  462. * regions from ha_region_list.
  463. */
  464. spinlock_t ha_lock;
  465. /*
  466. * A list of hot-add regions.
  467. */
  468. struct list_head ha_region_list;
  469. /*
  470. * We start with the highest version we can support
  471. * and downgrade based on the host; we save here the
  472. * next version to try.
  473. */
  474. __u32 next_version;
  475. /*
  476. * The negotiated version agreed by host.
  477. */
  478. __u32 version;
  479. struct page_reporting_dev_info pr_dev_info;
  480. };
  481. static struct hv_dynmem_device dm_device;
  482. static void post_status(struct hv_dynmem_device *dm);
  483. #ifdef CONFIG_MEMORY_HOTPLUG
  484. static inline bool has_pfn_is_backed(struct hv_hotadd_state *has,
  485. unsigned long pfn)
  486. {
  487. struct hv_hotadd_gap *gap;
  488. /* The page is not backed. */
  489. if ((pfn < has->covered_start_pfn) || (pfn >= has->covered_end_pfn))
  490. return false;
  491. /* Check for gaps. */
  492. list_for_each_entry(gap, &has->gap_list, list) {
  493. if ((pfn >= gap->start_pfn) && (pfn < gap->end_pfn))
  494. return false;
  495. }
  496. return true;
  497. }
  498. static unsigned long hv_page_offline_check(unsigned long start_pfn,
  499. unsigned long nr_pages)
  500. {
  501. unsigned long pfn = start_pfn, count = 0;
  502. struct hv_hotadd_state *has;
  503. bool found;
  504. while (pfn < start_pfn + nr_pages) {
  505. /*
  506. * Search for HAS which covers the pfn and when we find one
  507. * count how many consequitive PFNs are covered.
  508. */
  509. found = false;
  510. list_for_each_entry(has, &dm_device.ha_region_list, list) {
  511. while ((pfn >= has->start_pfn) &&
  512. (pfn < has->end_pfn) &&
  513. (pfn < start_pfn + nr_pages)) {
  514. found = true;
  515. if (has_pfn_is_backed(has, pfn))
  516. count++;
  517. pfn++;
  518. }
  519. }
  520. /*
  521. * This PFN is not in any HAS (e.g. we're offlining a region
  522. * which was present at boot), no need to account for it. Go
  523. * to the next one.
  524. */
  525. if (!found)
  526. pfn++;
  527. }
  528. return count;
  529. }
  530. static int hv_memory_notifier(struct notifier_block *nb, unsigned long val,
  531. void *v)
  532. {
  533. struct memory_notify *mem = (struct memory_notify *)v;
  534. unsigned long flags, pfn_count;
  535. switch (val) {
  536. case MEM_ONLINE:
  537. case MEM_CANCEL_ONLINE:
  538. complete(&dm_device.ol_waitevent);
  539. break;
  540. case MEM_OFFLINE:
  541. spin_lock_irqsave(&dm_device.ha_lock, flags);
  542. pfn_count = hv_page_offline_check(mem->start_pfn,
  543. mem->nr_pages);
  544. if (pfn_count <= dm_device.num_pages_onlined) {
  545. dm_device.num_pages_onlined -= pfn_count;
  546. } else {
  547. /*
  548. * We're offlining more pages than we managed to online.
  549. * This is unexpected. In any case don't let
  550. * num_pages_onlined wrap around zero.
  551. */
  552. WARN_ON_ONCE(1);
  553. dm_device.num_pages_onlined = 0;
  554. }
  555. spin_unlock_irqrestore(&dm_device.ha_lock, flags);
  556. break;
  557. case MEM_GOING_ONLINE:
  558. case MEM_GOING_OFFLINE:
  559. case MEM_CANCEL_OFFLINE:
  560. break;
  561. }
  562. return NOTIFY_OK;
  563. }
  564. static struct notifier_block hv_memory_nb = {
  565. .notifier_call = hv_memory_notifier,
  566. .priority = 0
  567. };
  568. /* Check if the particular page is backed and can be onlined and online it. */
  569. static void hv_page_online_one(struct hv_hotadd_state *has, struct page *pg)
  570. {
  571. if (!has_pfn_is_backed(has, page_to_pfn(pg))) {
  572. if (!PageOffline(pg))
  573. __SetPageOffline(pg);
  574. return;
  575. }
  576. if (PageOffline(pg))
  577. __ClearPageOffline(pg);
  578. /* This frame is currently backed; online the page. */
  579. generic_online_page(pg, 0);
  580. lockdep_assert_held(&dm_device.ha_lock);
  581. dm_device.num_pages_onlined++;
  582. }
  583. static void hv_bring_pgs_online(struct hv_hotadd_state *has,
  584. unsigned long start_pfn, unsigned long size)
  585. {
  586. int i;
  587. pr_debug("Online %lu pages starting at pfn 0x%lx\n", size, start_pfn);
  588. for (i = 0; i < size; i++)
  589. hv_page_online_one(has, pfn_to_page(start_pfn + i));
  590. }
  591. static void hv_mem_hot_add(unsigned long start, unsigned long size,
  592. unsigned long pfn_count,
  593. struct hv_hotadd_state *has)
  594. {
  595. int ret = 0;
  596. int i, nid;
  597. unsigned long start_pfn;
  598. unsigned long processed_pfn;
  599. unsigned long total_pfn = pfn_count;
  600. unsigned long flags;
  601. for (i = 0; i < (size/HA_CHUNK); i++) {
  602. start_pfn = start + (i * HA_CHUNK);
  603. spin_lock_irqsave(&dm_device.ha_lock, flags);
  604. has->ha_end_pfn += HA_CHUNK;
  605. if (total_pfn > HA_CHUNK) {
  606. processed_pfn = HA_CHUNK;
  607. total_pfn -= HA_CHUNK;
  608. } else {
  609. processed_pfn = total_pfn;
  610. total_pfn = 0;
  611. }
  612. has->covered_end_pfn += processed_pfn;
  613. spin_unlock_irqrestore(&dm_device.ha_lock, flags);
  614. reinit_completion(&dm_device.ol_waitevent);
  615. nid = memory_add_physaddr_to_nid(PFN_PHYS(start_pfn));
  616. ret = add_memory(nid, PFN_PHYS((start_pfn)),
  617. (HA_CHUNK << PAGE_SHIFT), MHP_MERGE_RESOURCE);
  618. if (ret) {
  619. pr_err("hot_add memory failed error is %d\n", ret);
  620. if (ret == -EEXIST) {
  621. /*
  622. * This error indicates that the error
  623. * is not a transient failure. This is the
  624. * case where the guest's physical address map
  625. * precludes hot adding memory. Stop all further
  626. * memory hot-add.
  627. */
  628. do_hot_add = false;
  629. }
  630. spin_lock_irqsave(&dm_device.ha_lock, flags);
  631. has->ha_end_pfn -= HA_CHUNK;
  632. has->covered_end_pfn -= processed_pfn;
  633. spin_unlock_irqrestore(&dm_device.ha_lock, flags);
  634. break;
  635. }
  636. /*
  637. * Wait for memory to get onlined. If the kernel onlined the
  638. * memory when adding it, this will return directly. Otherwise,
  639. * it will wait for user space to online the memory. This helps
  640. * to avoid adding memory faster than it is getting onlined. As
  641. * adding succeeded, it is ok to proceed even if the memory was
  642. * not onlined in time.
  643. */
  644. wait_for_completion_timeout(&dm_device.ol_waitevent, 5 * HZ);
  645. post_status(&dm_device);
  646. }
  647. }
  648. static void hv_online_page(struct page *pg, unsigned int order)
  649. {
  650. struct hv_hotadd_state *has;
  651. unsigned long flags;
  652. unsigned long pfn = page_to_pfn(pg);
  653. spin_lock_irqsave(&dm_device.ha_lock, flags);
  654. list_for_each_entry(has, &dm_device.ha_region_list, list) {
  655. /* The page belongs to a different HAS. */
  656. if ((pfn < has->start_pfn) ||
  657. (pfn + (1UL << order) > has->end_pfn))
  658. continue;
  659. hv_bring_pgs_online(has, pfn, 1UL << order);
  660. break;
  661. }
  662. spin_unlock_irqrestore(&dm_device.ha_lock, flags);
  663. }
  664. static int pfn_covered(unsigned long start_pfn, unsigned long pfn_cnt)
  665. {
  666. struct hv_hotadd_state *has;
  667. struct hv_hotadd_gap *gap;
  668. unsigned long residual, new_inc;
  669. int ret = 0;
  670. unsigned long flags;
  671. spin_lock_irqsave(&dm_device.ha_lock, flags);
  672. list_for_each_entry(has, &dm_device.ha_region_list, list) {
  673. /*
  674. * If the pfn range we are dealing with is not in the current
  675. * "hot add block", move on.
  676. */
  677. if (start_pfn < has->start_pfn || start_pfn >= has->end_pfn)
  678. continue;
  679. /*
  680. * If the current start pfn is not where the covered_end
  681. * is, create a gap and update covered_end_pfn.
  682. */
  683. if (has->covered_end_pfn != start_pfn) {
  684. gap = kzalloc(sizeof(struct hv_hotadd_gap), GFP_ATOMIC);
  685. if (!gap) {
  686. ret = -ENOMEM;
  687. break;
  688. }
  689. INIT_LIST_HEAD(&gap->list);
  690. gap->start_pfn = has->covered_end_pfn;
  691. gap->end_pfn = start_pfn;
  692. list_add_tail(&gap->list, &has->gap_list);
  693. has->covered_end_pfn = start_pfn;
  694. }
  695. /*
  696. * If the current hot add-request extends beyond
  697. * our current limit; extend it.
  698. */
  699. if ((start_pfn + pfn_cnt) > has->end_pfn) {
  700. residual = (start_pfn + pfn_cnt - has->end_pfn);
  701. /*
  702. * Extend the region by multiples of HA_CHUNK.
  703. */
  704. new_inc = (residual / HA_CHUNK) * HA_CHUNK;
  705. if (residual % HA_CHUNK)
  706. new_inc += HA_CHUNK;
  707. has->end_pfn += new_inc;
  708. }
  709. ret = 1;
  710. break;
  711. }
  712. spin_unlock_irqrestore(&dm_device.ha_lock, flags);
  713. return ret;
  714. }
  715. static unsigned long handle_pg_range(unsigned long pg_start,
  716. unsigned long pg_count)
  717. {
  718. unsigned long start_pfn = pg_start;
  719. unsigned long pfn_cnt = pg_count;
  720. unsigned long size;
  721. struct hv_hotadd_state *has;
  722. unsigned long pgs_ol = 0;
  723. unsigned long old_covered_state;
  724. unsigned long res = 0, flags;
  725. pr_debug("Hot adding %lu pages starting at pfn 0x%lx.\n", pg_count,
  726. pg_start);
  727. spin_lock_irqsave(&dm_device.ha_lock, flags);
  728. list_for_each_entry(has, &dm_device.ha_region_list, list) {
  729. /*
  730. * If the pfn range we are dealing with is not in the current
  731. * "hot add block", move on.
  732. */
  733. if (start_pfn < has->start_pfn || start_pfn >= has->end_pfn)
  734. continue;
  735. old_covered_state = has->covered_end_pfn;
  736. if (start_pfn < has->ha_end_pfn) {
  737. /*
  738. * This is the case where we are backing pages
  739. * in an already hot added region. Bring
  740. * these pages online first.
  741. */
  742. pgs_ol = has->ha_end_pfn - start_pfn;
  743. if (pgs_ol > pfn_cnt)
  744. pgs_ol = pfn_cnt;
  745. has->covered_end_pfn += pgs_ol;
  746. pfn_cnt -= pgs_ol;
  747. /*
  748. * Check if the corresponding memory block is already
  749. * online. It is possible to observe struct pages still
  750. * being uninitialized here so check section instead.
  751. * In case the section is online we need to bring the
  752. * rest of pfns (which were not backed previously)
  753. * online too.
  754. */
  755. if (start_pfn > has->start_pfn &&
  756. online_section_nr(pfn_to_section_nr(start_pfn)))
  757. hv_bring_pgs_online(has, start_pfn, pgs_ol);
  758. }
  759. if ((has->ha_end_pfn < has->end_pfn) && (pfn_cnt > 0)) {
  760. /*
  761. * We have some residual hot add range
  762. * that needs to be hot added; hot add
  763. * it now. Hot add a multiple of
  764. * of HA_CHUNK that fully covers the pages
  765. * we have.
  766. */
  767. size = (has->end_pfn - has->ha_end_pfn);
  768. if (pfn_cnt <= size) {
  769. size = ((pfn_cnt / HA_CHUNK) * HA_CHUNK);
  770. if (pfn_cnt % HA_CHUNK)
  771. size += HA_CHUNK;
  772. } else {
  773. pfn_cnt = size;
  774. }
  775. spin_unlock_irqrestore(&dm_device.ha_lock, flags);
  776. hv_mem_hot_add(has->ha_end_pfn, size, pfn_cnt, has);
  777. spin_lock_irqsave(&dm_device.ha_lock, flags);
  778. }
  779. /*
  780. * If we managed to online any pages that were given to us,
  781. * we declare success.
  782. */
  783. res = has->covered_end_pfn - old_covered_state;
  784. break;
  785. }
  786. spin_unlock_irqrestore(&dm_device.ha_lock, flags);
  787. return res;
  788. }
  789. static unsigned long process_hot_add(unsigned long pg_start,
  790. unsigned long pfn_cnt,
  791. unsigned long rg_start,
  792. unsigned long rg_size)
  793. {
  794. struct hv_hotadd_state *ha_region = NULL;
  795. int covered;
  796. unsigned long flags;
  797. if (pfn_cnt == 0)
  798. return 0;
  799. if (!dm_device.host_specified_ha_region) {
  800. covered = pfn_covered(pg_start, pfn_cnt);
  801. if (covered < 0)
  802. return 0;
  803. if (covered)
  804. goto do_pg_range;
  805. }
  806. /*
  807. * If the host has specified a hot-add range; deal with it first.
  808. */
  809. if (rg_size != 0) {
  810. ha_region = kzalloc(sizeof(struct hv_hotadd_state), GFP_KERNEL);
  811. if (!ha_region)
  812. return 0;
  813. INIT_LIST_HEAD(&ha_region->list);
  814. INIT_LIST_HEAD(&ha_region->gap_list);
  815. ha_region->start_pfn = rg_start;
  816. ha_region->ha_end_pfn = rg_start;
  817. ha_region->covered_start_pfn = pg_start;
  818. ha_region->covered_end_pfn = pg_start;
  819. ha_region->end_pfn = rg_start + rg_size;
  820. spin_lock_irqsave(&dm_device.ha_lock, flags);
  821. list_add_tail(&ha_region->list, &dm_device.ha_region_list);
  822. spin_unlock_irqrestore(&dm_device.ha_lock, flags);
  823. }
  824. do_pg_range:
  825. /*
  826. * Process the page range specified; bringing them
  827. * online if possible.
  828. */
  829. return handle_pg_range(pg_start, pfn_cnt);
  830. }
  831. #endif
  832. static void hot_add_req(struct work_struct *dummy)
  833. {
  834. struct dm_hot_add_response resp;
  835. #ifdef CONFIG_MEMORY_HOTPLUG
  836. unsigned long pg_start, pfn_cnt;
  837. unsigned long rg_start, rg_sz;
  838. #endif
  839. struct hv_dynmem_device *dm = &dm_device;
  840. memset(&resp, 0, sizeof(struct dm_hot_add_response));
  841. resp.hdr.type = DM_MEM_HOT_ADD_RESPONSE;
  842. resp.hdr.size = sizeof(struct dm_hot_add_response);
  843. #ifdef CONFIG_MEMORY_HOTPLUG
  844. pg_start = dm->ha_wrk.ha_page_range.finfo.start_page;
  845. pfn_cnt = dm->ha_wrk.ha_page_range.finfo.page_cnt;
  846. rg_start = dm->ha_wrk.ha_region_range.finfo.start_page;
  847. rg_sz = dm->ha_wrk.ha_region_range.finfo.page_cnt;
  848. if ((rg_start == 0) && (!dm->host_specified_ha_region)) {
  849. unsigned long region_size;
  850. unsigned long region_start;
  851. /*
  852. * The host has not specified the hot-add region.
  853. * Based on the hot-add page range being specified,
  854. * compute a hot-add region that can cover the pages
  855. * that need to be hot-added while ensuring the alignment
  856. * and size requirements of Linux as it relates to hot-add.
  857. */
  858. region_size = (pfn_cnt / HA_CHUNK) * HA_CHUNK;
  859. if (pfn_cnt % HA_CHUNK)
  860. region_size += HA_CHUNK;
  861. region_start = (pg_start / HA_CHUNK) * HA_CHUNK;
  862. rg_start = region_start;
  863. rg_sz = region_size;
  864. }
  865. if (do_hot_add)
  866. resp.page_count = process_hot_add(pg_start, pfn_cnt,
  867. rg_start, rg_sz);
  868. dm->num_pages_added += resp.page_count;
  869. #endif
  870. /*
  871. * The result field of the response structure has the
  872. * following semantics:
  873. *
  874. * 1. If all or some pages hot-added: Guest should return success.
  875. *
  876. * 2. If no pages could be hot-added:
  877. *
  878. * If the guest returns success, then the host
  879. * will not attempt any further hot-add operations. This
  880. * signifies a permanent failure.
  881. *
  882. * If the guest returns failure, then this failure will be
  883. * treated as a transient failure and the host may retry the
  884. * hot-add operation after some delay.
  885. */
  886. if (resp.page_count > 0)
  887. resp.result = 1;
  888. else if (!do_hot_add)
  889. resp.result = 1;
  890. else
  891. resp.result = 0;
  892. if (!do_hot_add || resp.page_count == 0) {
  893. if (!allow_hibernation)
  894. pr_err("Memory hot add failed\n");
  895. else
  896. pr_info("Ignore hot-add request!\n");
  897. }
  898. dm->state = DM_INITIALIZED;
  899. resp.hdr.trans_id = atomic_inc_return(&trans_id);
  900. vmbus_sendpacket(dm->dev->channel, &resp,
  901. sizeof(struct dm_hot_add_response),
  902. (unsigned long)NULL,
  903. VM_PKT_DATA_INBAND, 0);
  904. }
  905. static void process_info(struct hv_dynmem_device *dm, struct dm_info_msg *msg)
  906. {
  907. struct dm_info_header *info_hdr;
  908. info_hdr = (struct dm_info_header *)msg->info;
  909. switch (info_hdr->type) {
  910. case INFO_TYPE_MAX_PAGE_CNT:
  911. if (info_hdr->data_size == sizeof(__u64)) {
  912. __u64 *max_page_count = (__u64 *)&info_hdr[1];
  913. pr_info("Max. dynamic memory size: %llu MB\n",
  914. (*max_page_count) >> (20 - HV_HYP_PAGE_SHIFT));
  915. }
  916. break;
  917. default:
  918. pr_warn("Received Unknown type: %d\n", info_hdr->type);
  919. }
  920. }
  921. static unsigned long compute_balloon_floor(void)
  922. {
  923. unsigned long min_pages;
  924. unsigned long nr_pages = totalram_pages();
  925. #define MB2PAGES(mb) ((mb) << (20 - PAGE_SHIFT))
  926. /* Simple continuous piecewiese linear function:
  927. * max MiB -> min MiB gradient
  928. * 0 0
  929. * 16 16
  930. * 32 24
  931. * 128 72 (1/2)
  932. * 512 168 (1/4)
  933. * 2048 360 (1/8)
  934. * 8192 744 (1/16)
  935. * 32768 1512 (1/32)
  936. */
  937. if (nr_pages < MB2PAGES(128))
  938. min_pages = MB2PAGES(8) + (nr_pages >> 1);
  939. else if (nr_pages < MB2PAGES(512))
  940. min_pages = MB2PAGES(40) + (nr_pages >> 2);
  941. else if (nr_pages < MB2PAGES(2048))
  942. min_pages = MB2PAGES(104) + (nr_pages >> 3);
  943. else if (nr_pages < MB2PAGES(8192))
  944. min_pages = MB2PAGES(232) + (nr_pages >> 4);
  945. else
  946. min_pages = MB2PAGES(488) + (nr_pages >> 5);
  947. #undef MB2PAGES
  948. return min_pages;
  949. }
  950. /*
  951. * Post our status as it relates memory pressure to the
  952. * host. Host expects the guests to post this status
  953. * periodically at 1 second intervals.
  954. *
  955. * The metrics specified in this protocol are very Windows
  956. * specific and so we cook up numbers here to convey our memory
  957. * pressure.
  958. */
  959. static void post_status(struct hv_dynmem_device *dm)
  960. {
  961. struct dm_status status;
  962. unsigned long now = jiffies;
  963. unsigned long last_post = last_post_time;
  964. if (pressure_report_delay > 0) {
  965. --pressure_report_delay;
  966. return;
  967. }
  968. if (!time_after(now, (last_post_time + HZ)))
  969. return;
  970. memset(&status, 0, sizeof(struct dm_status));
  971. status.hdr.type = DM_STATUS_REPORT;
  972. status.hdr.size = sizeof(struct dm_status);
  973. status.hdr.trans_id = atomic_inc_return(&trans_id);
  974. /*
  975. * The host expects the guest to report free and committed memory.
  976. * Furthermore, the host expects the pressure information to include
  977. * the ballooned out pages. For a given amount of memory that we are
  978. * managing we need to compute a floor below which we should not
  979. * balloon. Compute this and add it to the pressure report.
  980. * We also need to report all offline pages (num_pages_added -
  981. * num_pages_onlined) as committed to the host, otherwise it can try
  982. * asking us to balloon them out.
  983. */
  984. status.num_avail = si_mem_available();
  985. status.num_committed = vm_memory_committed() +
  986. dm->num_pages_ballooned +
  987. (dm->num_pages_added > dm->num_pages_onlined ?
  988. dm->num_pages_added - dm->num_pages_onlined : 0) +
  989. compute_balloon_floor();
  990. trace_balloon_status(status.num_avail, status.num_committed,
  991. vm_memory_committed(), dm->num_pages_ballooned,
  992. dm->num_pages_added, dm->num_pages_onlined);
  993. /*
  994. * If our transaction ID is no longer current, just don't
  995. * send the status. This can happen if we were interrupted
  996. * after we picked our transaction ID.
  997. */
  998. if (status.hdr.trans_id != atomic_read(&trans_id))
  999. return;
  1000. /*
  1001. * If the last post time that we sampled has changed,
  1002. * we have raced, don't post the status.
  1003. */
  1004. if (last_post != last_post_time)
  1005. return;
  1006. last_post_time = jiffies;
  1007. vmbus_sendpacket(dm->dev->channel, &status,
  1008. sizeof(struct dm_status),
  1009. (unsigned long)NULL,
  1010. VM_PKT_DATA_INBAND, 0);
  1011. }
  1012. static void free_balloon_pages(struct hv_dynmem_device *dm,
  1013. union dm_mem_page_range *range_array)
  1014. {
  1015. int num_pages = range_array->finfo.page_cnt;
  1016. __u64 start_frame = range_array->finfo.start_page;
  1017. struct page *pg;
  1018. int i;
  1019. for (i = 0; i < num_pages; i++) {
  1020. pg = pfn_to_page(i + start_frame);
  1021. __ClearPageOffline(pg);
  1022. __free_page(pg);
  1023. dm->num_pages_ballooned--;
  1024. adjust_managed_page_count(pg, 1);
  1025. }
  1026. }
  1027. static unsigned int alloc_balloon_pages(struct hv_dynmem_device *dm,
  1028. unsigned int num_pages,
  1029. struct dm_balloon_response *bl_resp,
  1030. int alloc_unit)
  1031. {
  1032. unsigned int i, j;
  1033. struct page *pg;
  1034. for (i = 0; i < num_pages / alloc_unit; i++) {
  1035. if (bl_resp->hdr.size + sizeof(union dm_mem_page_range) >
  1036. HV_HYP_PAGE_SIZE)
  1037. return i * alloc_unit;
  1038. /*
  1039. * We execute this code in a thread context. Furthermore,
  1040. * we don't want the kernel to try too hard.
  1041. */
  1042. pg = alloc_pages(GFP_HIGHUSER | __GFP_NORETRY |
  1043. __GFP_NOMEMALLOC | __GFP_NOWARN,
  1044. get_order(alloc_unit << PAGE_SHIFT));
  1045. if (!pg)
  1046. return i * alloc_unit;
  1047. dm->num_pages_ballooned += alloc_unit;
  1048. /*
  1049. * If we allocatted 2M pages; split them so we
  1050. * can free them in any order we get.
  1051. */
  1052. if (alloc_unit != 1)
  1053. split_page(pg, get_order(alloc_unit << PAGE_SHIFT));
  1054. /* mark all pages offline */
  1055. for (j = 0; j < alloc_unit; j++) {
  1056. __SetPageOffline(pg + j);
  1057. adjust_managed_page_count(pg + j, -1);
  1058. }
  1059. bl_resp->range_count++;
  1060. bl_resp->range_array[i].finfo.start_page =
  1061. page_to_pfn(pg);
  1062. bl_resp->range_array[i].finfo.page_cnt = alloc_unit;
  1063. bl_resp->hdr.size += sizeof(union dm_mem_page_range);
  1064. }
  1065. return i * alloc_unit;
  1066. }
  1067. static void balloon_up(struct work_struct *dummy)
  1068. {
  1069. unsigned int num_pages = dm_device.balloon_wrk.num_pages;
  1070. unsigned int num_ballooned = 0;
  1071. struct dm_balloon_response *bl_resp;
  1072. int alloc_unit;
  1073. int ret;
  1074. bool done = false;
  1075. int i;
  1076. long avail_pages;
  1077. unsigned long floor;
  1078. /*
  1079. * We will attempt 2M allocations. However, if we fail to
  1080. * allocate 2M chunks, we will go back to PAGE_SIZE allocations.
  1081. */
  1082. alloc_unit = PAGES_IN_2M;
  1083. avail_pages = si_mem_available();
  1084. floor = compute_balloon_floor();
  1085. /* Refuse to balloon below the floor. */
  1086. if (avail_pages < num_pages || avail_pages - num_pages < floor) {
  1087. pr_info("Balloon request will be partially fulfilled. %s\n",
  1088. avail_pages < num_pages ? "Not enough memory." :
  1089. "Balloon floor reached.");
  1090. num_pages = avail_pages > floor ? (avail_pages - floor) : 0;
  1091. }
  1092. while (!done) {
  1093. memset(balloon_up_send_buffer, 0, HV_HYP_PAGE_SIZE);
  1094. bl_resp = (struct dm_balloon_response *)balloon_up_send_buffer;
  1095. bl_resp->hdr.type = DM_BALLOON_RESPONSE;
  1096. bl_resp->hdr.size = sizeof(struct dm_balloon_response);
  1097. bl_resp->more_pages = 1;
  1098. num_pages -= num_ballooned;
  1099. num_ballooned = alloc_balloon_pages(&dm_device, num_pages,
  1100. bl_resp, alloc_unit);
  1101. if (alloc_unit != 1 && num_ballooned == 0) {
  1102. alloc_unit = 1;
  1103. continue;
  1104. }
  1105. if (num_ballooned == 0 || num_ballooned == num_pages) {
  1106. pr_debug("Ballooned %u out of %u requested pages.\n",
  1107. num_pages, dm_device.balloon_wrk.num_pages);
  1108. bl_resp->more_pages = 0;
  1109. done = true;
  1110. dm_device.state = DM_INITIALIZED;
  1111. }
  1112. /*
  1113. * We are pushing a lot of data through the channel;
  1114. * deal with transient failures caused because of the
  1115. * lack of space in the ring buffer.
  1116. */
  1117. do {
  1118. bl_resp->hdr.trans_id = atomic_inc_return(&trans_id);
  1119. ret = vmbus_sendpacket(dm_device.dev->channel,
  1120. bl_resp,
  1121. bl_resp->hdr.size,
  1122. (unsigned long)NULL,
  1123. VM_PKT_DATA_INBAND, 0);
  1124. if (ret == -EAGAIN)
  1125. msleep(20);
  1126. post_status(&dm_device);
  1127. } while (ret == -EAGAIN);
  1128. if (ret) {
  1129. /*
  1130. * Free up the memory we allocatted.
  1131. */
  1132. pr_err("Balloon response failed\n");
  1133. for (i = 0; i < bl_resp->range_count; i++)
  1134. free_balloon_pages(&dm_device,
  1135. &bl_resp->range_array[i]);
  1136. done = true;
  1137. }
  1138. }
  1139. }
  1140. static void balloon_down(struct hv_dynmem_device *dm,
  1141. struct dm_unballoon_request *req)
  1142. {
  1143. union dm_mem_page_range *range_array = req->range_array;
  1144. int range_count = req->range_count;
  1145. struct dm_unballoon_response resp;
  1146. int i;
  1147. unsigned int prev_pages_ballooned = dm->num_pages_ballooned;
  1148. for (i = 0; i < range_count; i++) {
  1149. free_balloon_pages(dm, &range_array[i]);
  1150. complete(&dm_device.config_event);
  1151. }
  1152. pr_debug("Freed %u ballooned pages.\n",
  1153. prev_pages_ballooned - dm->num_pages_ballooned);
  1154. if (req->more_pages == 1)
  1155. return;
  1156. memset(&resp, 0, sizeof(struct dm_unballoon_response));
  1157. resp.hdr.type = DM_UNBALLOON_RESPONSE;
  1158. resp.hdr.trans_id = atomic_inc_return(&trans_id);
  1159. resp.hdr.size = sizeof(struct dm_unballoon_response);
  1160. vmbus_sendpacket(dm_device.dev->channel, &resp,
  1161. sizeof(struct dm_unballoon_response),
  1162. (unsigned long)NULL,
  1163. VM_PKT_DATA_INBAND, 0);
  1164. dm->state = DM_INITIALIZED;
  1165. }
  1166. static void balloon_onchannelcallback(void *context);
  1167. static int dm_thread_func(void *dm_dev)
  1168. {
  1169. struct hv_dynmem_device *dm = dm_dev;
  1170. while (!kthread_should_stop()) {
  1171. wait_for_completion_interruptible_timeout(
  1172. &dm_device.config_event, 1*HZ);
  1173. /*
  1174. * The host expects us to post information on the memory
  1175. * pressure every second.
  1176. */
  1177. reinit_completion(&dm_device.config_event);
  1178. post_status(dm);
  1179. }
  1180. return 0;
  1181. }
  1182. static void version_resp(struct hv_dynmem_device *dm,
  1183. struct dm_version_response *vresp)
  1184. {
  1185. struct dm_version_request version_req;
  1186. int ret;
  1187. if (vresp->is_accepted) {
  1188. /*
  1189. * We are done; wakeup the
  1190. * context waiting for version
  1191. * negotiation.
  1192. */
  1193. complete(&dm->host_event);
  1194. return;
  1195. }
  1196. /*
  1197. * If there are more versions to try, continue
  1198. * with negotiations; if not
  1199. * shutdown the service since we are not able
  1200. * to negotiate a suitable version number
  1201. * with the host.
  1202. */
  1203. if (dm->next_version == 0)
  1204. goto version_error;
  1205. memset(&version_req, 0, sizeof(struct dm_version_request));
  1206. version_req.hdr.type = DM_VERSION_REQUEST;
  1207. version_req.hdr.size = sizeof(struct dm_version_request);
  1208. version_req.hdr.trans_id = atomic_inc_return(&trans_id);
  1209. version_req.version.version = dm->next_version;
  1210. dm->version = version_req.version.version;
  1211. /*
  1212. * Set the next version to try in case current version fails.
  1213. * Win7 protocol ought to be the last one to try.
  1214. */
  1215. switch (version_req.version.version) {
  1216. case DYNMEM_PROTOCOL_VERSION_WIN8:
  1217. dm->next_version = DYNMEM_PROTOCOL_VERSION_WIN7;
  1218. version_req.is_last_attempt = 0;
  1219. break;
  1220. default:
  1221. dm->next_version = 0;
  1222. version_req.is_last_attempt = 1;
  1223. }
  1224. ret = vmbus_sendpacket(dm->dev->channel, &version_req,
  1225. sizeof(struct dm_version_request),
  1226. (unsigned long)NULL,
  1227. VM_PKT_DATA_INBAND, 0);
  1228. if (ret)
  1229. goto version_error;
  1230. return;
  1231. version_error:
  1232. dm->state = DM_INIT_ERROR;
  1233. complete(&dm->host_event);
  1234. }
  1235. static void cap_resp(struct hv_dynmem_device *dm,
  1236. struct dm_capabilities_resp_msg *cap_resp)
  1237. {
  1238. if (!cap_resp->is_accepted) {
  1239. pr_err("Capabilities not accepted by host\n");
  1240. dm->state = DM_INIT_ERROR;
  1241. }
  1242. complete(&dm->host_event);
  1243. }
  1244. static void balloon_onchannelcallback(void *context)
  1245. {
  1246. struct hv_device *dev = context;
  1247. u32 recvlen;
  1248. u64 requestid;
  1249. struct dm_message *dm_msg;
  1250. struct dm_header *dm_hdr;
  1251. struct hv_dynmem_device *dm = hv_get_drvdata(dev);
  1252. struct dm_balloon *bal_msg;
  1253. struct dm_hot_add *ha_msg;
  1254. union dm_mem_page_range *ha_pg_range;
  1255. union dm_mem_page_range *ha_region;
  1256. memset(recv_buffer, 0, sizeof(recv_buffer));
  1257. vmbus_recvpacket(dev->channel, recv_buffer,
  1258. HV_HYP_PAGE_SIZE, &recvlen, &requestid);
  1259. if (recvlen > 0) {
  1260. dm_msg = (struct dm_message *)recv_buffer;
  1261. dm_hdr = &dm_msg->hdr;
  1262. switch (dm_hdr->type) {
  1263. case DM_VERSION_RESPONSE:
  1264. version_resp(dm,
  1265. (struct dm_version_response *)dm_msg);
  1266. break;
  1267. case DM_CAPABILITIES_RESPONSE:
  1268. cap_resp(dm,
  1269. (struct dm_capabilities_resp_msg *)dm_msg);
  1270. break;
  1271. case DM_BALLOON_REQUEST:
  1272. if (allow_hibernation) {
  1273. pr_info("Ignore balloon-up request!\n");
  1274. break;
  1275. }
  1276. if (dm->state == DM_BALLOON_UP)
  1277. pr_warn("Currently ballooning\n");
  1278. bal_msg = (struct dm_balloon *)recv_buffer;
  1279. dm->state = DM_BALLOON_UP;
  1280. dm_device.balloon_wrk.num_pages = bal_msg->num_pages;
  1281. schedule_work(&dm_device.balloon_wrk.wrk);
  1282. break;
  1283. case DM_UNBALLOON_REQUEST:
  1284. if (allow_hibernation) {
  1285. pr_info("Ignore balloon-down request!\n");
  1286. break;
  1287. }
  1288. dm->state = DM_BALLOON_DOWN;
  1289. balloon_down(dm,
  1290. (struct dm_unballoon_request *)recv_buffer);
  1291. break;
  1292. case DM_MEM_HOT_ADD_REQUEST:
  1293. if (dm->state == DM_HOT_ADD)
  1294. pr_warn("Currently hot-adding\n");
  1295. dm->state = DM_HOT_ADD;
  1296. ha_msg = (struct dm_hot_add *)recv_buffer;
  1297. if (ha_msg->hdr.size == sizeof(struct dm_hot_add)) {
  1298. /*
  1299. * This is a normal hot-add request specifying
  1300. * hot-add memory.
  1301. */
  1302. dm->host_specified_ha_region = false;
  1303. ha_pg_range = &ha_msg->range;
  1304. dm->ha_wrk.ha_page_range = *ha_pg_range;
  1305. dm->ha_wrk.ha_region_range.page_range = 0;
  1306. } else {
  1307. /*
  1308. * Host is specifying that we first hot-add
  1309. * a region and then partially populate this
  1310. * region.
  1311. */
  1312. dm->host_specified_ha_region = true;
  1313. ha_pg_range = &ha_msg->range;
  1314. ha_region = &ha_pg_range[1];
  1315. dm->ha_wrk.ha_page_range = *ha_pg_range;
  1316. dm->ha_wrk.ha_region_range = *ha_region;
  1317. }
  1318. schedule_work(&dm_device.ha_wrk.wrk);
  1319. break;
  1320. case DM_INFO_MESSAGE:
  1321. process_info(dm, (struct dm_info_msg *)dm_msg);
  1322. break;
  1323. default:
  1324. pr_warn("Unhandled message: type: %d\n", dm_hdr->type);
  1325. }
  1326. }
  1327. }
  1328. /* Hyper-V only supports reporting 2MB pages or higher */
  1329. #define HV_MIN_PAGE_REPORTING_ORDER 9
  1330. #define HV_MIN_PAGE_REPORTING_LEN (HV_HYP_PAGE_SIZE << HV_MIN_PAGE_REPORTING_ORDER)
  1331. static int hv_free_page_report(struct page_reporting_dev_info *pr_dev_info,
  1332. struct scatterlist *sgl, unsigned int nents)
  1333. {
  1334. unsigned long flags;
  1335. struct hv_memory_hint *hint;
  1336. int i;
  1337. u64 status;
  1338. struct scatterlist *sg;
  1339. WARN_ON_ONCE(nents > HV_MEMORY_HINT_MAX_GPA_PAGE_RANGES);
  1340. WARN_ON_ONCE(sgl->length < HV_MIN_PAGE_REPORTING_LEN);
  1341. local_irq_save(flags);
  1342. hint = *(struct hv_memory_hint **)this_cpu_ptr(hyperv_pcpu_input_arg);
  1343. if (!hint) {
  1344. local_irq_restore(flags);
  1345. return -ENOSPC;
  1346. }
  1347. hint->type = HV_EXT_MEMORY_HEAT_HINT_TYPE_COLD_DISCARD;
  1348. hint->reserved = 0;
  1349. for_each_sg(sgl, sg, nents, i) {
  1350. union hv_gpa_page_range *range;
  1351. range = &hint->ranges[i];
  1352. range->address_space = 0;
  1353. /* page reporting only reports 2MB pages or higher */
  1354. range->page.largepage = 1;
  1355. range->page.additional_pages =
  1356. (sg->length / HV_MIN_PAGE_REPORTING_LEN) - 1;
  1357. range->page_size = HV_GPA_PAGE_RANGE_PAGE_SIZE_2MB;
  1358. range->base_large_pfn =
  1359. page_to_hvpfn(sg_page(sg)) >> HV_MIN_PAGE_REPORTING_ORDER;
  1360. }
  1361. status = hv_do_rep_hypercall(HV_EXT_CALL_MEMORY_HEAT_HINT, nents, 0,
  1362. hint, NULL);
  1363. local_irq_restore(flags);
  1364. if ((status & HV_HYPERCALL_RESULT_MASK) != HV_STATUS_SUCCESS) {
  1365. pr_err("Cold memory discard hypercall failed with status %llx\n",
  1366. status);
  1367. return -EINVAL;
  1368. }
  1369. return 0;
  1370. }
  1371. static void enable_page_reporting(void)
  1372. {
  1373. int ret;
  1374. /* Essentially, validating 'PAGE_REPORTING_MIN_ORDER' is big enough. */
  1375. if (pageblock_order < HV_MIN_PAGE_REPORTING_ORDER) {
  1376. pr_debug("Cold memory discard is only supported on 2MB pages and above\n");
  1377. return;
  1378. }
  1379. if (!hv_query_ext_cap(HV_EXT_CAPABILITY_MEMORY_COLD_DISCARD_HINT)) {
  1380. pr_debug("Cold memory discard hint not supported by Hyper-V\n");
  1381. return;
  1382. }
  1383. BUILD_BUG_ON(PAGE_REPORTING_CAPACITY > HV_MEMORY_HINT_MAX_GPA_PAGE_RANGES);
  1384. dm_device.pr_dev_info.report = hv_free_page_report;
  1385. ret = page_reporting_register(&dm_device.pr_dev_info);
  1386. if (ret < 0) {
  1387. dm_device.pr_dev_info.report = NULL;
  1388. pr_err("Failed to enable cold memory discard: %d\n", ret);
  1389. } else {
  1390. pr_info("Cold memory discard hint enabled\n");
  1391. }
  1392. }
  1393. static void disable_page_reporting(void)
  1394. {
  1395. if (dm_device.pr_dev_info.report) {
  1396. page_reporting_unregister(&dm_device.pr_dev_info);
  1397. dm_device.pr_dev_info.report = NULL;
  1398. }
  1399. }
  1400. static int balloon_connect_vsp(struct hv_device *dev)
  1401. {
  1402. struct dm_version_request version_req;
  1403. struct dm_capabilities cap_msg;
  1404. unsigned long t;
  1405. int ret;
  1406. ret = vmbus_open(dev->channel, dm_ring_size, dm_ring_size, NULL, 0,
  1407. balloon_onchannelcallback, dev);
  1408. if (ret)
  1409. return ret;
  1410. /*
  1411. * Initiate the hand shake with the host and negotiate
  1412. * a version that the host can support. We start with the
  1413. * highest version number and go down if the host cannot
  1414. * support it.
  1415. */
  1416. memset(&version_req, 0, sizeof(struct dm_version_request));
  1417. version_req.hdr.type = DM_VERSION_REQUEST;
  1418. version_req.hdr.size = sizeof(struct dm_version_request);
  1419. version_req.hdr.trans_id = atomic_inc_return(&trans_id);
  1420. version_req.version.version = DYNMEM_PROTOCOL_VERSION_WIN10;
  1421. version_req.is_last_attempt = 0;
  1422. dm_device.version = version_req.version.version;
  1423. ret = vmbus_sendpacket(dev->channel, &version_req,
  1424. sizeof(struct dm_version_request),
  1425. (unsigned long)NULL, VM_PKT_DATA_INBAND, 0);
  1426. if (ret)
  1427. goto out;
  1428. t = wait_for_completion_timeout(&dm_device.host_event, 5*HZ);
  1429. if (t == 0) {
  1430. ret = -ETIMEDOUT;
  1431. goto out;
  1432. }
  1433. /*
  1434. * If we could not negotiate a compatible version with the host
  1435. * fail the probe function.
  1436. */
  1437. if (dm_device.state == DM_INIT_ERROR) {
  1438. ret = -EPROTO;
  1439. goto out;
  1440. }
  1441. pr_info("Using Dynamic Memory protocol version %u.%u\n",
  1442. DYNMEM_MAJOR_VERSION(dm_device.version),
  1443. DYNMEM_MINOR_VERSION(dm_device.version));
  1444. /*
  1445. * Now submit our capabilities to the host.
  1446. */
  1447. memset(&cap_msg, 0, sizeof(struct dm_capabilities));
  1448. cap_msg.hdr.type = DM_CAPABILITIES_REPORT;
  1449. cap_msg.hdr.size = sizeof(struct dm_capabilities);
  1450. cap_msg.hdr.trans_id = atomic_inc_return(&trans_id);
  1451. /*
  1452. * When hibernation (i.e. virtual ACPI S4 state) is enabled, the host
  1453. * currently still requires the bits to be set, so we have to add code
  1454. * to fail the host's hot-add and balloon up/down requests, if any.
  1455. */
  1456. cap_msg.caps.cap_bits.balloon = 1;
  1457. cap_msg.caps.cap_bits.hot_add = 1;
  1458. /*
  1459. * Specify our alignment requirements as it relates
  1460. * memory hot-add. Specify 128MB alignment.
  1461. */
  1462. cap_msg.caps.cap_bits.hot_add_alignment = 7;
  1463. /*
  1464. * Currently the host does not use these
  1465. * values and we set them to what is done in the
  1466. * Windows driver.
  1467. */
  1468. cap_msg.min_page_cnt = 0;
  1469. cap_msg.max_page_number = -1;
  1470. ret = vmbus_sendpacket(dev->channel, &cap_msg,
  1471. sizeof(struct dm_capabilities),
  1472. (unsigned long)NULL, VM_PKT_DATA_INBAND, 0);
  1473. if (ret)
  1474. goto out;
  1475. t = wait_for_completion_timeout(&dm_device.host_event, 5*HZ);
  1476. if (t == 0) {
  1477. ret = -ETIMEDOUT;
  1478. goto out;
  1479. }
  1480. /*
  1481. * If the host does not like our capabilities,
  1482. * fail the probe function.
  1483. */
  1484. if (dm_device.state == DM_INIT_ERROR) {
  1485. ret = -EPROTO;
  1486. goto out;
  1487. }
  1488. return 0;
  1489. out:
  1490. vmbus_close(dev->channel);
  1491. return ret;
  1492. }
  1493. static int balloon_probe(struct hv_device *dev,
  1494. const struct hv_vmbus_device_id *dev_id)
  1495. {
  1496. int ret;
  1497. allow_hibernation = hv_is_hibernation_supported();
  1498. if (allow_hibernation)
  1499. hot_add = false;
  1500. #ifdef CONFIG_MEMORY_HOTPLUG
  1501. do_hot_add = hot_add;
  1502. #else
  1503. do_hot_add = false;
  1504. #endif
  1505. dm_device.dev = dev;
  1506. dm_device.state = DM_INITIALIZING;
  1507. dm_device.next_version = DYNMEM_PROTOCOL_VERSION_WIN8;
  1508. init_completion(&dm_device.host_event);
  1509. init_completion(&dm_device.config_event);
  1510. INIT_LIST_HEAD(&dm_device.ha_region_list);
  1511. spin_lock_init(&dm_device.ha_lock);
  1512. INIT_WORK(&dm_device.balloon_wrk.wrk, balloon_up);
  1513. INIT_WORK(&dm_device.ha_wrk.wrk, hot_add_req);
  1514. dm_device.host_specified_ha_region = false;
  1515. #ifdef CONFIG_MEMORY_HOTPLUG
  1516. set_online_page_callback(&hv_online_page);
  1517. init_completion(&dm_device.ol_waitevent);
  1518. register_memory_notifier(&hv_memory_nb);
  1519. #endif
  1520. hv_set_drvdata(dev, &dm_device);
  1521. ret = balloon_connect_vsp(dev);
  1522. if (ret != 0)
  1523. return ret;
  1524. enable_page_reporting();
  1525. dm_device.state = DM_INITIALIZED;
  1526. dm_device.thread =
  1527. kthread_run(dm_thread_func, &dm_device, "hv_balloon");
  1528. if (IS_ERR(dm_device.thread)) {
  1529. ret = PTR_ERR(dm_device.thread);
  1530. goto probe_error;
  1531. }
  1532. return 0;
  1533. probe_error:
  1534. dm_device.state = DM_INIT_ERROR;
  1535. dm_device.thread = NULL;
  1536. disable_page_reporting();
  1537. vmbus_close(dev->channel);
  1538. #ifdef CONFIG_MEMORY_HOTPLUG
  1539. unregister_memory_notifier(&hv_memory_nb);
  1540. restore_online_page_callback(&hv_online_page);
  1541. #endif
  1542. return ret;
  1543. }
  1544. static int balloon_remove(struct hv_device *dev)
  1545. {
  1546. struct hv_dynmem_device *dm = hv_get_drvdata(dev);
  1547. struct hv_hotadd_state *has, *tmp;
  1548. struct hv_hotadd_gap *gap, *tmp_gap;
  1549. unsigned long flags;
  1550. if (dm->num_pages_ballooned != 0)
  1551. pr_warn("Ballooned pages: %d\n", dm->num_pages_ballooned);
  1552. cancel_work_sync(&dm->balloon_wrk.wrk);
  1553. cancel_work_sync(&dm->ha_wrk.wrk);
  1554. kthread_stop(dm->thread);
  1555. disable_page_reporting();
  1556. vmbus_close(dev->channel);
  1557. #ifdef CONFIG_MEMORY_HOTPLUG
  1558. unregister_memory_notifier(&hv_memory_nb);
  1559. restore_online_page_callback(&hv_online_page);
  1560. #endif
  1561. spin_lock_irqsave(&dm_device.ha_lock, flags);
  1562. list_for_each_entry_safe(has, tmp, &dm->ha_region_list, list) {
  1563. list_for_each_entry_safe(gap, tmp_gap, &has->gap_list, list) {
  1564. list_del(&gap->list);
  1565. kfree(gap);
  1566. }
  1567. list_del(&has->list);
  1568. kfree(has);
  1569. }
  1570. spin_unlock_irqrestore(&dm_device.ha_lock, flags);
  1571. return 0;
  1572. }
  1573. static int balloon_suspend(struct hv_device *hv_dev)
  1574. {
  1575. struct hv_dynmem_device *dm = hv_get_drvdata(hv_dev);
  1576. tasklet_disable(&hv_dev->channel->callback_event);
  1577. cancel_work_sync(&dm->balloon_wrk.wrk);
  1578. cancel_work_sync(&dm->ha_wrk.wrk);
  1579. if (dm->thread) {
  1580. kthread_stop(dm->thread);
  1581. dm->thread = NULL;
  1582. vmbus_close(hv_dev->channel);
  1583. }
  1584. tasklet_enable(&hv_dev->channel->callback_event);
  1585. return 0;
  1586. }
  1587. static int balloon_resume(struct hv_device *dev)
  1588. {
  1589. int ret;
  1590. dm_device.state = DM_INITIALIZING;
  1591. ret = balloon_connect_vsp(dev);
  1592. if (ret != 0)
  1593. goto out;
  1594. dm_device.thread =
  1595. kthread_run(dm_thread_func, &dm_device, "hv_balloon");
  1596. if (IS_ERR(dm_device.thread)) {
  1597. ret = PTR_ERR(dm_device.thread);
  1598. dm_device.thread = NULL;
  1599. goto close_channel;
  1600. }
  1601. dm_device.state = DM_INITIALIZED;
  1602. return 0;
  1603. close_channel:
  1604. vmbus_close(dev->channel);
  1605. out:
  1606. dm_device.state = DM_INIT_ERROR;
  1607. #ifdef CONFIG_MEMORY_HOTPLUG
  1608. unregister_memory_notifier(&hv_memory_nb);
  1609. restore_online_page_callback(&hv_online_page);
  1610. #endif
  1611. return ret;
  1612. }
  1613. static const struct hv_vmbus_device_id id_table[] = {
  1614. /* Dynamic Memory Class ID */
  1615. /* 525074DC-8985-46e2-8057-A307DC18A502 */
  1616. { HV_DM_GUID, },
  1617. { },
  1618. };
  1619. MODULE_DEVICE_TABLE(vmbus, id_table);
  1620. static struct hv_driver balloon_drv = {
  1621. .name = "hv_balloon",
  1622. .id_table = id_table,
  1623. .probe = balloon_probe,
  1624. .remove = balloon_remove,
  1625. .suspend = balloon_suspend,
  1626. .resume = balloon_resume,
  1627. .driver = {
  1628. .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  1629. },
  1630. };
  1631. static int __init init_balloon_drv(void)
  1632. {
  1633. return vmbus_driver_register(&balloon_drv);
  1634. }
  1635. module_init(init_balloon_drv);
  1636. MODULE_DESCRIPTION("Hyper-V Balloon");
  1637. MODULE_LICENSE("GPL");