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