PageRenderTime 28ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/drivers/hv/hv_balloon.c

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