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