2 * Copyright (c) 2012, Microsoft Corporation.
5 * K. Y. Srinivasan <kys@microsoft.com>
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License version 2 as published
9 * by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
14 * NON INFRINGEMENT. See the GNU General Public License for more
19 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
21 #include <linux/kernel.h>
22 #include <linux/mman.h>
23 #include <linux/delay.h>
24 #include <linux/init.h>
25 #include <linux/module.h>
26 #include <linux/slab.h>
27 #include <linux/kthread.h>
28 #include <linux/completion.h>
29 #include <linux/memory_hotplug.h>
30 #include <linux/memory.h>
31 #include <linux/notifier.h>
32 #include <linux/mman.h>
33 #include <linux/percpu_counter.h>
35 #include <linux/hyperv.h>
38 * We begin with definitions supporting the Dynamic Memory protocol
41 * Begin protocol definitions.
47 * Protocol versions. The low word is the minor version, the high word the major
52 * Changed to 0.1 on 2009/03/25
53 * Changes to 0.2 on 2009/05/14
54 * Changes to 0.3 on 2009/12/03
55 * Changed to 1.0 on 2011/04/05
58 #define DYNMEM_MAKE_VERSION(Major, Minor) ((__u32)(((Major) << 16) | (Minor)))
59 #define DYNMEM_MAJOR_VERSION(Version) ((__u32)(Version) >> 16)
60 #define DYNMEM_MINOR_VERSION(Version) ((__u32)(Version) & 0xff)
63 DYNMEM_PROTOCOL_VERSION_1 = DYNMEM_MAKE_VERSION(0, 3),
64 DYNMEM_PROTOCOL_VERSION_2 = DYNMEM_MAKE_VERSION(1, 0),
66 DYNMEM_PROTOCOL_VERSION_WIN7 = DYNMEM_PROTOCOL_VERSION_1,
67 DYNMEM_PROTOCOL_VERSION_WIN8 = DYNMEM_PROTOCOL_VERSION_2,
69 DYNMEM_PROTOCOL_VERSION_CURRENT = DYNMEM_PROTOCOL_VERSION_WIN8
78 enum dm_message_type {
83 DM_VERSION_REQUEST = 1,
84 DM_VERSION_RESPONSE = 2,
85 DM_CAPABILITIES_REPORT = 3,
86 DM_CAPABILITIES_RESPONSE = 4,
88 DM_BALLOON_REQUEST = 6,
89 DM_BALLOON_RESPONSE = 7,
90 DM_UNBALLOON_REQUEST = 8,
91 DM_UNBALLOON_RESPONSE = 9,
92 DM_MEM_HOT_ADD_REQUEST = 10,
93 DM_MEM_HOT_ADD_RESPONSE = 11,
94 DM_VERSION_03_MAX = 11,
104 * Structures defining the dynamic memory management
126 union dm_mem_page_range {
129 * The PFN number of the first page in the range.
130 * 40 bits is the architectural limit of a PFN
135 * The number of pages in the range.
145 * The header for all dynamic memory messages:
147 * type: Type of the message.
148 * size: Size of the message in bytes; including the header.
149 * trans_id: The guest is responsible for manufacturing this ID.
159 * A generic message format for dynamic memory.
160 * Specific message formats are defined later in the file.
164 struct dm_header hdr;
165 __u8 data[]; /* enclosed message */
170 * Specific message types supporting the dynamic memory protocol.
174 * Version negotiation message. Sent from the guest to the host.
175 * The guest is free to try different versions until the host
176 * accepts the version.
178 * dm_version: The protocol version requested.
179 * is_last_attempt: If TRUE, this is the last version guest will request.
180 * reservedz: Reserved field, set to zero.
183 struct dm_version_request {
184 struct dm_header hdr;
185 union dm_version version;
186 __u32 is_last_attempt:1;
191 * Version response message; Host to Guest and indicates
192 * if the host has accepted the version sent by the guest.
194 * is_accepted: If TRUE, host has accepted the version and the guest
195 * should proceed to the next stage of the protocol. FALSE indicates that
196 * guest should re-try with a different version.
198 * reservedz: Reserved field, set to zero.
201 struct dm_version_response {
202 struct dm_header hdr;
208 * Message reporting capabilities. This is sent from the guest to the
212 struct dm_capabilities {
213 struct dm_header hdr;
216 __u64 max_page_number;
220 * Response to the capabilities message. This is sent from the host to the
221 * guest. This message notifies if the host has accepted the guest's
222 * capabilities. If the host has not accepted, the guest must shutdown
225 * is_accepted: Indicates if the host has accepted guest's capabilities.
226 * reservedz: Must be 0.
229 struct dm_capabilities_resp_msg {
230 struct dm_header hdr;
236 * This message is used to report memory pressure from the guest.
237 * This message is not part of any transaction and there is no
238 * response to this message.
240 * num_avail: Available memory in pages.
241 * num_committed: Committed memory in pages.
242 * page_file_size: The accumulated size of all page files
243 * in the system in pages.
244 * zero_free: The nunber of zero and free pages.
245 * page_file_writes: The writes to the page file in pages.
246 * io_diff: An indicator of file cache efficiency or page file activity,
247 * calculated as File Cache Page Fault Count - Page Read Count.
248 * This value is in pages.
250 * Some of these metrics are Windows specific and fortunately
251 * the algorithm on the host side that computes the guest memory
252 * pressure only uses num_committed value.
256 struct dm_header hdr;
259 __u64 page_file_size;
261 __u32 page_file_writes;
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.
271 * num_pages: number of pages to allocate.
275 struct dm_header hdr;
282 * Balloon response message; this message is sent from the guest
283 * to the host in response to the balloon message.
285 * reservedz: Reserved; must be set to zero.
286 * more_pages: If FALSE, this is the last message of the transaction.
287 * if TRUE there will atleast one more message from the guest.
289 * range_count: The number of ranges in the range array.
291 * range_array: An array of page ranges returned to the host.
295 struct dm_balloon_response {
296 struct dm_header hdr;
299 __u32 range_count:31;
300 union dm_mem_page_range range_array[];
304 * Un-balloon message; this message is sent from the host
305 * to the guest to give guest more memory.
307 * more_pages: If FALSE, this is the last message of the transaction.
308 * if TRUE there will atleast one more message from the guest.
310 * reservedz: Reserved; must be set to zero.
312 * range_count: The number of ranges in the range array.
314 * range_array: An array of page ranges returned to the host.
318 struct dm_unballoon_request {
319 struct dm_header hdr;
323 union dm_mem_page_range range_array[];
327 * Un-balloon response message; this message is sent from the guest
328 * to the host in response to an unballoon request.
332 struct dm_unballoon_response {
333 struct dm_header hdr;
338 * Hot add request message. Message sent from the host to the guest.
340 * mem_range: Memory range to hot add.
342 * On Linux we currently don't support this since we cannot hot add
343 * arbitrary granularity of memory.
347 struct dm_header hdr;
348 union dm_mem_page_range range;
352 * Hot add response message.
353 * This message is sent by the guest to report the status of a hot add request.
354 * If page_count is less than the requested page count, then the host should
355 * assume all further hot add requests will fail, since this indicates that
356 * the guest has hit an upper physical memory barrier.
358 * Hot adds may also fail due to low resources; in this case, the guest must
359 * not complete this message until the hot add can succeed, and the host must
360 * not send a new hot add request until the response is sent.
361 * If VSC fails to hot add memory DYNMEM_NUMBER_OF_UNSUCCESSFUL_HOTADD_ATTEMPTS
362 * times it fails the request.
365 * page_count: number of pages that were successfully hot added.
367 * result: result of the operation 1: success, 0: failure.
371 struct dm_hot_add_response {
372 struct dm_header hdr;
378 * Types of information sent from host to the guest.
382 INFO_TYPE_MAX_PAGE_CNT = 0,
388 * Header for the information message.
391 struct dm_info_header {
392 enum dm_info_type type;
397 * This message is sent from the host to the guest to pass
398 * some relevant information (win8 addition).
401 * info_size: size of the information blob.
402 * info: information blob.
406 struct dm_header hdr;
413 * End protocol definitions.
417 static bool do_hot_add;
419 module_param(hot_add, bool, (S_IRUGO | S_IWUSR));
420 MODULE_PARM_DESC(hot_add, "If set attempt memory hot_add");
422 static atomic_t trans_id = ATOMIC_INIT(0);
424 static int dm_ring_size = (5 * PAGE_SIZE);
427 * Driver specific state.
440 static __u8 recv_buffer[PAGE_SIZE];
441 static __u8 *send_buffer;
442 #define PAGES_IN_2M 512
444 struct hv_dynmem_device {
445 struct hv_device *dev;
446 enum hv_dm_state state;
447 struct completion host_event;
448 struct completion config_event;
451 * Number of pages we have currently ballooned out.
453 unsigned int num_pages_ballooned;
456 * This thread handles both balloon/hot-add
457 * requests from the host as well as notifying
458 * the host with regards to memory pressure in
461 struct task_struct *thread;
464 * We start with the highest version we can support
465 * and downgrade based on the host; we save here the
466 * next version to try.
471 static struct hv_dynmem_device dm_device;
473 static void hot_add_req(struct hv_dynmem_device *dm, struct dm_hot_add *msg)
476 struct dm_hot_add_response resp;
480 pr_info("Memory hot add not supported\n");
483 * Currently we do not support hot add.
484 * Just fail the request.
488 memset(&resp, 0, sizeof(struct dm_hot_add_response));
489 resp.hdr.type = DM_MEM_HOT_ADD_RESPONSE;
490 resp.hdr.size = sizeof(struct dm_hot_add_response);
491 resp.hdr.trans_id = atomic_inc_return(&trans_id);
496 dm->state = DM_INITIALIZED;
497 vmbus_sendpacket(dm->dev->channel, &resp,
498 sizeof(struct dm_hot_add_response),
500 VM_PKT_DATA_INBAND, 0);
504 static void process_info(struct hv_dynmem_device *dm, struct dm_info_msg *msg)
506 struct dm_info_header *info_hdr;
508 info_hdr = (struct dm_info_header *)msg->info;
510 switch (info_hdr->type) {
511 case INFO_TYPE_MAX_PAGE_CNT:
512 pr_info("Received INFO_TYPE_MAX_PAGE_CNT\n");
513 pr_info("Data Size is %d\n", info_hdr->data_size);
516 pr_info("Received Unknown type: %d\n", info_hdr->type);
521 * Post our status as it relates memory pressure to the
522 * host. Host expects the guests to post this status
523 * periodically at 1 second intervals.
525 * The metrics specified in this protocol are very Windows
526 * specific and so we cook up numbers here to convey our memory
530 static void post_status(struct hv_dynmem_device *dm)
532 struct dm_status status;
535 memset(&status, 0, sizeof(struct dm_status));
536 status.hdr.type = DM_STATUS_REPORT;
537 status.hdr.size = sizeof(struct dm_status);
538 status.hdr.trans_id = atomic_inc_return(&trans_id);
541 status.num_committed = vm_memory_committed();
543 vmbus_sendpacket(dm->dev->channel, &status,
544 sizeof(struct dm_status),
546 VM_PKT_DATA_INBAND, 0);
552 static void free_balloon_pages(struct hv_dynmem_device *dm,
553 union dm_mem_page_range *range_array)
555 int num_pages = range_array->finfo.page_cnt;
556 __u64 start_frame = range_array->finfo.start_page;
560 for (i = 0; i < num_pages; i++) {
561 pg = pfn_to_page(i + start_frame);
563 dm->num_pages_ballooned--;
569 static int alloc_balloon_pages(struct hv_dynmem_device *dm, int num_pages,
570 struct dm_balloon_response *bl_resp, int alloc_unit,
576 if (num_pages < alloc_unit)
579 for (i = 0; (i * alloc_unit) < num_pages; i++) {
580 if (bl_resp->hdr.size + sizeof(union dm_mem_page_range) >
582 return i * alloc_unit;
585 * We execute this code in a thread context. Furthermore,
586 * we don't want the kernel to try too hard.
588 pg = alloc_pages(GFP_HIGHUSER | __GFP_NORETRY |
589 __GFP_NOMEMALLOC | __GFP_NOWARN,
590 get_order(alloc_unit << PAGE_SHIFT));
594 return i * alloc_unit;
598 dm->num_pages_ballooned += alloc_unit;
600 bl_resp->range_count++;
601 bl_resp->range_array[i].finfo.start_page =
603 bl_resp->range_array[i].finfo.page_cnt = alloc_unit;
604 bl_resp->hdr.size += sizeof(union dm_mem_page_range);
613 static void balloon_up(struct hv_dynmem_device *dm, struct dm_balloon *req)
615 int num_pages = req->num_pages;
616 int num_ballooned = 0;
617 struct dm_balloon_response *bl_resp;
620 bool alloc_error = false;
626 * Currently, we only support 4k allocations.
631 bl_resp = (struct dm_balloon_response *)send_buffer;
632 memset(send_buffer, 0, PAGE_SIZE);
633 bl_resp->hdr.type = DM_BALLOON_RESPONSE;
634 bl_resp->hdr.trans_id = atomic_inc_return(&trans_id);
635 bl_resp->hdr.size = sizeof(struct dm_balloon_response);
636 bl_resp->more_pages = 1;
639 num_pages -= num_ballooned;
640 num_ballooned = alloc_balloon_pages(dm, num_pages,
644 if ((alloc_error) || (num_ballooned == num_pages)) {
645 bl_resp->more_pages = 0;
647 dm->state = DM_INITIALIZED;
651 * We are pushing a lot of data through the channel;
652 * deal with transient failures caused because of the
653 * lack of space in the ring buffer.
657 ret = vmbus_sendpacket(dm_device.dev->channel,
661 VM_PKT_DATA_INBAND, 0);
666 } while (ret == -EAGAIN);
670 * Free up the memory we allocatted.
672 pr_info("Balloon response failed\n");
674 for (i = 0; i < bl_resp->range_count; i++)
675 free_balloon_pages(dm,
676 &bl_resp->range_array[i]);
684 static void balloon_down(struct hv_dynmem_device *dm,
685 struct dm_unballoon_request *req)
687 union dm_mem_page_range *range_array = req->range_array;
688 int range_count = req->range_count;
689 struct dm_unballoon_response resp;
692 for (i = 0; i < range_count; i++)
693 free_balloon_pages(dm, &range_array[i]);
695 if (req->more_pages == 1)
698 memset(&resp, 0, sizeof(struct dm_unballoon_response));
699 resp.hdr.type = DM_UNBALLOON_RESPONSE;
700 resp.hdr.trans_id = atomic_inc_return(&trans_id);
701 resp.hdr.size = sizeof(struct dm_unballoon_response);
703 vmbus_sendpacket(dm_device.dev->channel, &resp,
704 sizeof(struct dm_unballoon_response),
706 VM_PKT_DATA_INBAND, 0);
708 dm->state = DM_INITIALIZED;
711 static void balloon_onchannelcallback(void *context);
713 static int dm_thread_func(void *dm_dev)
715 struct hv_dynmem_device *dm = dm_dev;
717 unsigned long scan_start;
719 while (!kthread_should_stop()) {
720 t = wait_for_completion_timeout(&dm_device.config_event, 1*HZ);
722 * The host expects us to post information on the memory
723 * pressure every second.
729 scan_start = jiffies;
732 balloon_up(dm, (struct dm_balloon *)recv_buffer);
736 hot_add_req(dm, (struct dm_hot_add *)recv_buffer);
742 if (!time_in_range(jiffies, scan_start, scan_start + HZ))
751 static void version_resp(struct hv_dynmem_device *dm,
752 struct dm_version_response *vresp)
754 struct dm_version_request version_req;
757 if (vresp->is_accepted) {
759 * We are done; wakeup the
760 * context waiting for version
763 complete(&dm->host_event);
767 * If there are more versions to try, continue
768 * with negotiations; if not
769 * shutdown the service since we are not able
770 * to negotiate a suitable version number
773 if (dm->next_version == 0)
776 dm->next_version = 0;
777 memset(&version_req, 0, sizeof(struct dm_version_request));
778 version_req.hdr.type = DM_VERSION_REQUEST;
779 version_req.hdr.size = sizeof(struct dm_version_request);
780 version_req.hdr.trans_id = atomic_inc_return(&trans_id);
781 version_req.version.version = DYNMEM_PROTOCOL_VERSION_WIN7;
782 version_req.is_last_attempt = 1;
784 ret = vmbus_sendpacket(dm->dev->channel, &version_req,
785 sizeof(struct dm_version_request),
787 VM_PKT_DATA_INBAND, 0);
795 dm->state = DM_INIT_ERROR;
796 complete(&dm->host_event);
799 static void cap_resp(struct hv_dynmem_device *dm,
800 struct dm_capabilities_resp_msg *cap_resp)
802 if (!cap_resp->is_accepted) {
803 pr_info("Capabilities not accepted by host\n");
804 dm->state = DM_INIT_ERROR;
806 complete(&dm->host_event);
809 static void balloon_onchannelcallback(void *context)
811 struct hv_device *dev = context;
814 struct dm_message *dm_msg;
815 struct dm_header *dm_hdr;
816 struct hv_dynmem_device *dm = hv_get_drvdata(dev);
818 memset(recv_buffer, 0, sizeof(recv_buffer));
819 vmbus_recvpacket(dev->channel, recv_buffer,
820 PAGE_SIZE, &recvlen, &requestid);
823 dm_msg = (struct dm_message *)recv_buffer;
824 dm_hdr = &dm_msg->hdr;
826 switch (dm_hdr->type) {
827 case DM_VERSION_RESPONSE:
829 (struct dm_version_response *)dm_msg);
832 case DM_CAPABILITIES_RESPONSE:
834 (struct dm_capabilities_resp_msg *)dm_msg);
837 case DM_BALLOON_REQUEST:
838 dm->state = DM_BALLOON_UP;
839 complete(&dm->config_event);
842 case DM_UNBALLOON_REQUEST:
843 dm->state = DM_BALLOON_DOWN;
845 (struct dm_unballoon_request *)recv_buffer);
848 case DM_MEM_HOT_ADD_REQUEST:
849 dm->state = DM_HOT_ADD;
850 complete(&dm->config_event);
853 case DM_INFO_MESSAGE:
854 process_info(dm, (struct dm_info_msg *)dm_msg);
858 pr_err("Unhandled message: type: %d\n", dm_hdr->type);
865 static int balloon_probe(struct hv_device *dev,
866 const struct hv_vmbus_device_id *dev_id)
869 struct dm_version_request version_req;
870 struct dm_capabilities cap_msg;
872 do_hot_add = hot_add;
875 * First allocate a send buffer.
878 send_buffer = kmalloc(PAGE_SIZE, GFP_KERNEL);
882 ret = vmbus_open(dev->channel, dm_ring_size, dm_ring_size, NULL, 0,
883 balloon_onchannelcallback, dev);
889 dm_device.state = DM_INITIALIZING;
890 dm_device.next_version = DYNMEM_PROTOCOL_VERSION_WIN7;
891 init_completion(&dm_device.host_event);
892 init_completion(&dm_device.config_event);
895 kthread_run(dm_thread_func, &dm_device, "hv_balloon");
896 if (IS_ERR(dm_device.thread)) {
897 ret = PTR_ERR(dm_device.thread);
901 hv_set_drvdata(dev, &dm_device);
903 * Initiate the hand shake with the host and negotiate
904 * a version that the host can support. We start with the
905 * highest version number and go down if the host cannot
908 memset(&version_req, 0, sizeof(struct dm_version_request));
909 version_req.hdr.type = DM_VERSION_REQUEST;
910 version_req.hdr.size = sizeof(struct dm_version_request);
911 version_req.hdr.trans_id = atomic_inc_return(&trans_id);
912 version_req.version.version = DYNMEM_PROTOCOL_VERSION_WIN8;
913 version_req.is_last_attempt = 0;
915 ret = vmbus_sendpacket(dev->channel, &version_req,
916 sizeof(struct dm_version_request),
919 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
923 t = wait_for_completion_timeout(&dm_device.host_event, 5*HZ);
930 * If we could not negotiate a compatible version with the host
931 * fail the probe function.
933 if (dm_device.state == DM_INIT_ERROR) {
938 * Now submit our capabilities to the host.
940 memset(&cap_msg, 0, sizeof(struct dm_capabilities));
941 cap_msg.hdr.type = DM_CAPABILITIES_REPORT;
942 cap_msg.hdr.size = sizeof(struct dm_capabilities);
943 cap_msg.hdr.trans_id = atomic_inc_return(&trans_id);
945 cap_msg.caps.cap_bits.balloon = 1;
947 * While we currently don't support hot-add,
948 * we still advertise this capability since the
949 * host requires that guests partcipating in the
950 * dynamic memory protocol support hot add.
952 cap_msg.caps.cap_bits.hot_add = 1;
955 * Currently the host does not use these
956 * values and we set them to what is done in the
959 cap_msg.min_page_cnt = 0;
960 cap_msg.max_page_number = -1;
962 ret = vmbus_sendpacket(dev->channel, &cap_msg,
963 sizeof(struct dm_capabilities),
966 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
970 t = wait_for_completion_timeout(&dm_device.host_event, 5*HZ);
977 * If the host does not like our capabilities,
978 * fail the probe function.
980 if (dm_device.state == DM_INIT_ERROR) {
985 dm_device.state = DM_INITIALIZED;
990 kthread_stop(dm_device.thread);
993 vmbus_close(dev->channel);
999 static int balloon_remove(struct hv_device *dev)
1001 struct hv_dynmem_device *dm = hv_get_drvdata(dev);
1003 if (dm->num_pages_ballooned != 0)
1004 pr_warn("Ballooned pages: %d\n", dm->num_pages_ballooned);
1006 vmbus_close(dev->channel);
1007 kthread_stop(dm->thread);
1013 static const struct hv_vmbus_device_id id_table[] = {
1014 /* Dynamic Memory Class ID */
1015 /* 525074DC-8985-46e2-8057-A307DC18A502 */
1016 { VMBUS_DEVICE(0xdc, 0x74, 0x50, 0X52, 0x85, 0x89, 0xe2, 0x46,
1017 0x80, 0x57, 0xa3, 0x07, 0xdc, 0x18, 0xa5, 0x02)
1022 MODULE_DEVICE_TABLE(vmbus, id_table);
1024 static struct hv_driver balloon_drv = {
1025 .name = "hv_balloon",
1026 .id_table = id_table,
1027 .probe = balloon_probe,
1028 .remove = balloon_remove,
1031 static int __init init_balloon_drv(void)
1034 return vmbus_driver_register(&balloon_drv);
1037 static void exit_balloon_drv(void)
1040 vmbus_driver_unregister(&balloon_drv);
1043 module_init(init_balloon_drv);
1044 module_exit(exit_balloon_drv);
1046 MODULE_DESCRIPTION("Hyper-V Balloon");
1047 MODULE_VERSION(HV_DRV_VERSION);
1048 MODULE_LICENSE("GPL");