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