Drivers: hv: vmbus: fix the race when querying & updating the percpu list
[cascardo/linux.git] / drivers / hv / channel.c
1 /*
2  * Copyright (c) 2009, Microsoft Corporation.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms and conditions of the GNU General Public License,
6  * version 2, as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
11  * more details.
12  *
13  * You should have received a copy of the GNU General Public License along with
14  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
15  * Place - Suite 330, Boston, MA 02111-1307 USA.
16  *
17  * Authors:
18  *   Haiyang Zhang <haiyangz@microsoft.com>
19  *   Hank Janssen  <hjanssen@microsoft.com>
20  */
21 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
22
23 #include <linux/kernel.h>
24 #include <linux/sched.h>
25 #include <linux/wait.h>
26 #include <linux/mm.h>
27 #include <linux/slab.h>
28 #include <linux/module.h>
29 #include <linux/hyperv.h>
30 #include <linux/uio.h>
31 #include <linux/interrupt.h>
32
33 #include "hyperv_vmbus.h"
34
35 #define NUM_PAGES_SPANNED(addr, len) \
36 ((PAGE_ALIGN(addr + len) >> PAGE_SHIFT) - (addr >> PAGE_SHIFT))
37
38 /*
39  * vmbus_setevent- Trigger an event notification on the specified
40  * channel.
41  */
42 static void vmbus_setevent(struct vmbus_channel *channel)
43 {
44         struct hv_monitor_page *monitorpage;
45
46         if (channel->offermsg.monitor_allocated) {
47                 /* Each u32 represents 32 channels */
48                 sync_set_bit(channel->offermsg.child_relid & 31,
49                         (unsigned long *) vmbus_connection.send_int_page +
50                         (channel->offermsg.child_relid >> 5));
51
52                 /* Get the child to parent monitor page */
53                 monitorpage = vmbus_connection.monitor_pages[1];
54
55                 sync_set_bit(channel->monitor_bit,
56                         (unsigned long *)&monitorpage->trigger_group
57                                         [channel->monitor_grp].pending);
58
59         } else {
60                 vmbus_set_event(channel);
61         }
62 }
63
64 /*
65  * vmbus_open - Open the specified channel.
66  */
67 int vmbus_open(struct vmbus_channel *newchannel, u32 send_ringbuffer_size,
68                      u32 recv_ringbuffer_size, void *userdata, u32 userdatalen,
69                      void (*onchannelcallback)(void *context), void *context)
70 {
71         struct vmbus_channel_open_channel *open_msg;
72         struct vmbus_channel_msginfo *open_info = NULL;
73         void *in, *out;
74         unsigned long flags;
75         int ret, err = 0;
76         struct page *page;
77
78         spin_lock_irqsave(&newchannel->lock, flags);
79         if (newchannel->state == CHANNEL_OPEN_STATE) {
80                 newchannel->state = CHANNEL_OPENING_STATE;
81         } else {
82                 spin_unlock_irqrestore(&newchannel->lock, flags);
83                 return -EINVAL;
84         }
85         spin_unlock_irqrestore(&newchannel->lock, flags);
86
87         newchannel->onchannel_callback = onchannelcallback;
88         newchannel->channel_callback_context = context;
89
90         /* Allocate the ring buffer */
91         page = alloc_pages_node(cpu_to_node(newchannel->target_cpu),
92                                 GFP_KERNEL|__GFP_ZERO,
93                                 get_order(send_ringbuffer_size +
94                                 recv_ringbuffer_size));
95
96         if (!page)
97                 out = (void *)__get_free_pages(GFP_KERNEL|__GFP_ZERO,
98                                                get_order(send_ringbuffer_size +
99                                                recv_ringbuffer_size));
100         else
101                 out = (void *)page_address(page);
102
103         if (!out) {
104                 err = -ENOMEM;
105                 goto error0;
106         }
107
108         in = (void *)((unsigned long)out + send_ringbuffer_size);
109
110         newchannel->ringbuffer_pages = out;
111         newchannel->ringbuffer_pagecount = (send_ringbuffer_size +
112                                            recv_ringbuffer_size) >> PAGE_SHIFT;
113
114         ret = hv_ringbuffer_init(
115                 &newchannel->outbound, out, send_ringbuffer_size);
116
117         if (ret != 0) {
118                 err = ret;
119                 goto error0;
120         }
121
122         ret = hv_ringbuffer_init(
123                 &newchannel->inbound, in, recv_ringbuffer_size);
124         if (ret != 0) {
125                 err = ret;
126                 goto error0;
127         }
128
129
130         /* Establish the gpadl for the ring buffer */
131         newchannel->ringbuffer_gpadlhandle = 0;
132
133         ret = vmbus_establish_gpadl(newchannel,
134                                          newchannel->outbound.ring_buffer,
135                                          send_ringbuffer_size +
136                                          recv_ringbuffer_size,
137                                          &newchannel->ringbuffer_gpadlhandle);
138
139         if (ret != 0) {
140                 err = ret;
141                 goto error0;
142         }
143
144         /* Create and init the channel open message */
145         open_info = kmalloc(sizeof(*open_info) +
146                            sizeof(struct vmbus_channel_open_channel),
147                            GFP_KERNEL);
148         if (!open_info) {
149                 err = -ENOMEM;
150                 goto error_gpadl;
151         }
152
153         init_completion(&open_info->waitevent);
154
155         open_msg = (struct vmbus_channel_open_channel *)open_info->msg;
156         open_msg->header.msgtype = CHANNELMSG_OPENCHANNEL;
157         open_msg->openid = newchannel->offermsg.child_relid;
158         open_msg->child_relid = newchannel->offermsg.child_relid;
159         open_msg->ringbuffer_gpadlhandle = newchannel->ringbuffer_gpadlhandle;
160         open_msg->downstream_ringbuffer_pageoffset = send_ringbuffer_size >>
161                                                   PAGE_SHIFT;
162         open_msg->target_vp = newchannel->target_vp;
163
164         if (userdatalen > MAX_USER_DEFINED_BYTES) {
165                 err = -EINVAL;
166                 goto error_gpadl;
167         }
168
169         if (userdatalen)
170                 memcpy(open_msg->userdata, userdata, userdatalen);
171
172         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
173         list_add_tail(&open_info->msglistentry,
174                       &vmbus_connection.chn_msg_list);
175         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
176
177         ret = vmbus_post_msg(open_msg,
178                                sizeof(struct vmbus_channel_open_channel));
179
180         if (ret != 0) {
181                 err = ret;
182                 goto error1;
183         }
184
185         wait_for_completion(&open_info->waitevent);
186
187         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
188         list_del(&open_info->msglistentry);
189         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
190
191         if (open_info->response.open_result.status) {
192                 err = -EAGAIN;
193                 goto error_gpadl;
194         }
195
196         newchannel->state = CHANNEL_OPENED_STATE;
197         kfree(open_info);
198         return 0;
199
200 error1:
201         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
202         list_del(&open_info->msglistentry);
203         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
204
205 error_gpadl:
206         vmbus_teardown_gpadl(newchannel, newchannel->ringbuffer_gpadlhandle);
207
208 error0:
209         free_pages((unsigned long)out,
210                 get_order(send_ringbuffer_size + recv_ringbuffer_size));
211         kfree(open_info);
212         newchannel->state = CHANNEL_OPEN_STATE;
213         return err;
214 }
215 EXPORT_SYMBOL_GPL(vmbus_open);
216
217 /* Used for Hyper-V Socket: a guest client's connect() to the host */
218 int vmbus_send_tl_connect_request(const uuid_le *shv_guest_servie_id,
219                                   const uuid_le *shv_host_servie_id)
220 {
221         struct vmbus_channel_tl_connect_request conn_msg;
222
223         memset(&conn_msg, 0, sizeof(conn_msg));
224         conn_msg.header.msgtype = CHANNELMSG_TL_CONNECT_REQUEST;
225         conn_msg.guest_endpoint_id = *shv_guest_servie_id;
226         conn_msg.host_service_id = *shv_host_servie_id;
227
228         return vmbus_post_msg(&conn_msg, sizeof(conn_msg));
229 }
230 EXPORT_SYMBOL_GPL(vmbus_send_tl_connect_request);
231
232 /*
233  * create_gpadl_header - Creates a gpadl for the specified buffer
234  */
235 static int create_gpadl_header(void *kbuffer, u32 size,
236                                struct vmbus_channel_msginfo **msginfo)
237 {
238         int i;
239         int pagecount;
240         struct vmbus_channel_gpadl_header *gpadl_header;
241         struct vmbus_channel_gpadl_body *gpadl_body;
242         struct vmbus_channel_msginfo *msgheader;
243         struct vmbus_channel_msginfo *msgbody = NULL;
244         u32 msgsize;
245
246         int pfnsum, pfncount, pfnleft, pfncurr, pfnsize;
247
248         pagecount = size >> PAGE_SHIFT;
249
250         /* do we need a gpadl body msg */
251         pfnsize = MAX_SIZE_CHANNEL_MESSAGE -
252                   sizeof(struct vmbus_channel_gpadl_header) -
253                   sizeof(struct gpa_range);
254         pfncount = pfnsize / sizeof(u64);
255
256         if (pagecount > pfncount) {
257                 /* we need a gpadl body */
258                 /* fill in the header */
259                 msgsize = sizeof(struct vmbus_channel_msginfo) +
260                           sizeof(struct vmbus_channel_gpadl_header) +
261                           sizeof(struct gpa_range) + pfncount * sizeof(u64);
262                 msgheader =  kzalloc(msgsize, GFP_KERNEL);
263                 if (!msgheader)
264                         goto nomem;
265
266                 INIT_LIST_HEAD(&msgheader->submsglist);
267                 msgheader->msgsize = msgsize;
268
269                 gpadl_header = (struct vmbus_channel_gpadl_header *)
270                         msgheader->msg;
271                 gpadl_header->rangecount = 1;
272                 gpadl_header->range_buflen = sizeof(struct gpa_range) +
273                                          pagecount * sizeof(u64);
274                 gpadl_header->range[0].byte_offset = 0;
275                 gpadl_header->range[0].byte_count = size;
276                 for (i = 0; i < pfncount; i++)
277                         gpadl_header->range[0].pfn_array[i] = slow_virt_to_phys(
278                                 kbuffer + PAGE_SIZE * i) >> PAGE_SHIFT;
279                 *msginfo = msgheader;
280
281                 pfnsum = pfncount;
282                 pfnleft = pagecount - pfncount;
283
284                 /* how many pfns can we fit */
285                 pfnsize = MAX_SIZE_CHANNEL_MESSAGE -
286                           sizeof(struct vmbus_channel_gpadl_body);
287                 pfncount = pfnsize / sizeof(u64);
288
289                 /* fill in the body */
290                 while (pfnleft) {
291                         if (pfnleft > pfncount)
292                                 pfncurr = pfncount;
293                         else
294                                 pfncurr = pfnleft;
295
296                         msgsize = sizeof(struct vmbus_channel_msginfo) +
297                                   sizeof(struct vmbus_channel_gpadl_body) +
298                                   pfncurr * sizeof(u64);
299                         msgbody = kzalloc(msgsize, GFP_KERNEL);
300
301                         if (!msgbody) {
302                                 struct vmbus_channel_msginfo *pos = NULL;
303                                 struct vmbus_channel_msginfo *tmp = NULL;
304                                 /*
305                                  * Free up all the allocated messages.
306                                  */
307                                 list_for_each_entry_safe(pos, tmp,
308                                         &msgheader->submsglist,
309                                         msglistentry) {
310
311                                         list_del(&pos->msglistentry);
312                                         kfree(pos);
313                                 }
314
315                                 goto nomem;
316                         }
317
318                         msgbody->msgsize = msgsize;
319                         gpadl_body =
320                                 (struct vmbus_channel_gpadl_body *)msgbody->msg;
321
322                         /*
323                          * Gpadl is u32 and we are using a pointer which could
324                          * be 64-bit
325                          * This is governed by the guest/host protocol and
326                          * so the hypervisor gurantees that this is ok.
327                          */
328                         for (i = 0; i < pfncurr; i++)
329                                 gpadl_body->pfn[i] = slow_virt_to_phys(
330                                         kbuffer + PAGE_SIZE * (pfnsum + i)) >>
331                                         PAGE_SHIFT;
332
333                         /* add to msg header */
334                         list_add_tail(&msgbody->msglistentry,
335                                       &msgheader->submsglist);
336                         pfnsum += pfncurr;
337                         pfnleft -= pfncurr;
338                 }
339         } else {
340                 /* everything fits in a header */
341                 msgsize = sizeof(struct vmbus_channel_msginfo) +
342                           sizeof(struct vmbus_channel_gpadl_header) +
343                           sizeof(struct gpa_range) + pagecount * sizeof(u64);
344                 msgheader = kzalloc(msgsize, GFP_KERNEL);
345                 if (msgheader == NULL)
346                         goto nomem;
347
348                 INIT_LIST_HEAD(&msgheader->submsglist);
349                 msgheader->msgsize = msgsize;
350
351                 gpadl_header = (struct vmbus_channel_gpadl_header *)
352                         msgheader->msg;
353                 gpadl_header->rangecount = 1;
354                 gpadl_header->range_buflen = sizeof(struct gpa_range) +
355                                          pagecount * sizeof(u64);
356                 gpadl_header->range[0].byte_offset = 0;
357                 gpadl_header->range[0].byte_count = size;
358                 for (i = 0; i < pagecount; i++)
359                         gpadl_header->range[0].pfn_array[i] = slow_virt_to_phys(
360                                 kbuffer + PAGE_SIZE * i) >> PAGE_SHIFT;
361
362                 *msginfo = msgheader;
363         }
364
365         return 0;
366 nomem:
367         kfree(msgheader);
368         kfree(msgbody);
369         return -ENOMEM;
370 }
371
372 /*
373  * vmbus_establish_gpadl - Estabish a GPADL for the specified buffer
374  *
375  * @channel: a channel
376  * @kbuffer: from kmalloc or vmalloc
377  * @size: page-size multiple
378  * @gpadl_handle: some funky thing
379  */
380 int vmbus_establish_gpadl(struct vmbus_channel *channel, void *kbuffer,
381                                u32 size, u32 *gpadl_handle)
382 {
383         struct vmbus_channel_gpadl_header *gpadlmsg;
384         struct vmbus_channel_gpadl_body *gpadl_body;
385         struct vmbus_channel_msginfo *msginfo = NULL;
386         struct vmbus_channel_msginfo *submsginfo, *tmp;
387         struct list_head *curr;
388         u32 next_gpadl_handle;
389         unsigned long flags;
390         int ret = 0;
391
392         next_gpadl_handle =
393                 (atomic_inc_return(&vmbus_connection.next_gpadl_handle) - 1);
394
395         ret = create_gpadl_header(kbuffer, size, &msginfo);
396         if (ret)
397                 return ret;
398
399         init_completion(&msginfo->waitevent);
400
401         gpadlmsg = (struct vmbus_channel_gpadl_header *)msginfo->msg;
402         gpadlmsg->header.msgtype = CHANNELMSG_GPADL_HEADER;
403         gpadlmsg->child_relid = channel->offermsg.child_relid;
404         gpadlmsg->gpadl = next_gpadl_handle;
405
406
407         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
408         list_add_tail(&msginfo->msglistentry,
409                       &vmbus_connection.chn_msg_list);
410
411         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
412
413         ret = vmbus_post_msg(gpadlmsg, msginfo->msgsize -
414                                sizeof(*msginfo));
415         if (ret != 0)
416                 goto cleanup;
417
418         list_for_each(curr, &msginfo->submsglist) {
419                 submsginfo = (struct vmbus_channel_msginfo *)curr;
420                 gpadl_body =
421                         (struct vmbus_channel_gpadl_body *)submsginfo->msg;
422
423                 gpadl_body->header.msgtype =
424                         CHANNELMSG_GPADL_BODY;
425                 gpadl_body->gpadl = next_gpadl_handle;
426
427                 ret = vmbus_post_msg(gpadl_body,
428                                      submsginfo->msgsize -
429                                      sizeof(*submsginfo));
430                 if (ret != 0)
431                         goto cleanup;
432
433         }
434         wait_for_completion(&msginfo->waitevent);
435
436         /* At this point, we received the gpadl created msg */
437         *gpadl_handle = gpadlmsg->gpadl;
438
439 cleanup:
440         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
441         list_del(&msginfo->msglistentry);
442         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
443         list_for_each_entry_safe(submsginfo, tmp, &msginfo->submsglist,
444                                  msglistentry) {
445                 kfree(submsginfo);
446         }
447
448         kfree(msginfo);
449         return ret;
450 }
451 EXPORT_SYMBOL_GPL(vmbus_establish_gpadl);
452
453 /*
454  * vmbus_teardown_gpadl -Teardown the specified GPADL handle
455  */
456 int vmbus_teardown_gpadl(struct vmbus_channel *channel, u32 gpadl_handle)
457 {
458         struct vmbus_channel_gpadl_teardown *msg;
459         struct vmbus_channel_msginfo *info;
460         unsigned long flags;
461         int ret;
462
463         info = kmalloc(sizeof(*info) +
464                        sizeof(struct vmbus_channel_gpadl_teardown), GFP_KERNEL);
465         if (!info)
466                 return -ENOMEM;
467
468         init_completion(&info->waitevent);
469
470         msg = (struct vmbus_channel_gpadl_teardown *)info->msg;
471
472         msg->header.msgtype = CHANNELMSG_GPADL_TEARDOWN;
473         msg->child_relid = channel->offermsg.child_relid;
474         msg->gpadl = gpadl_handle;
475
476         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
477         list_add_tail(&info->msglistentry,
478                       &vmbus_connection.chn_msg_list);
479         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
480         ret = vmbus_post_msg(msg,
481                                sizeof(struct vmbus_channel_gpadl_teardown));
482
483         if (ret)
484                 goto post_msg_err;
485
486         wait_for_completion(&info->waitevent);
487
488 post_msg_err:
489         spin_lock_irqsave(&vmbus_connection.channelmsg_lock, flags);
490         list_del(&info->msglistentry);
491         spin_unlock_irqrestore(&vmbus_connection.channelmsg_lock, flags);
492
493         kfree(info);
494         return ret;
495 }
496 EXPORT_SYMBOL_GPL(vmbus_teardown_gpadl);
497
498 static void reset_channel_cb(void *arg)
499 {
500         struct vmbus_channel *channel = arg;
501
502         channel->onchannel_callback = NULL;
503 }
504
505 static int vmbus_close_internal(struct vmbus_channel *channel)
506 {
507         struct vmbus_channel_close_channel *msg;
508         int ret;
509
510         /*
511          * process_chn_event(), running in the tasklet, can race
512          * with vmbus_close_internal() in the case of SMP guest, e.g., when
513          * the former is accessing channel->inbound.ring_buffer, the latter
514          * could be freeing the ring_buffer pages.
515          *
516          * To resolve the race, we can serialize them by disabling the
517          * tasklet when the latter is running here.
518          */
519         hv_event_tasklet_disable(channel);
520
521         /*
522          * In case a device driver's probe() fails (e.g.,
523          * util_probe() -> vmbus_open() returns -ENOMEM) and the device is
524          * rescinded later (e.g., we dynamically disble an Integrated Service
525          * in Hyper-V Manager), the driver's remove() invokes vmbus_close():
526          * here we should skip most of the below cleanup work.
527          */
528         if (channel->state != CHANNEL_OPENED_STATE) {
529                 ret = -EINVAL;
530                 goto out;
531         }
532
533         channel->state = CHANNEL_OPEN_STATE;
534         channel->sc_creation_callback = NULL;
535         /* Stop callback and cancel the timer asap */
536         if (channel->target_cpu != get_cpu()) {
537                 put_cpu();
538                 smp_call_function_single(channel->target_cpu, reset_channel_cb,
539                                          channel, true);
540         } else {
541                 reset_channel_cb(channel);
542                 put_cpu();
543         }
544
545         /* Send a closing message */
546
547         msg = &channel->close_msg.msg;
548
549         msg->header.msgtype = CHANNELMSG_CLOSECHANNEL;
550         msg->child_relid = channel->offermsg.child_relid;
551
552         ret = vmbus_post_msg(msg, sizeof(struct vmbus_channel_close_channel));
553
554         if (ret) {
555                 pr_err("Close failed: close post msg return is %d\n", ret);
556                 /*
557                  * If we failed to post the close msg,
558                  * it is perhaps better to leak memory.
559                  */
560                 goto out;
561         }
562
563         /* Tear down the gpadl for the channel's ring buffer */
564         if (channel->ringbuffer_gpadlhandle) {
565                 ret = vmbus_teardown_gpadl(channel,
566                                            channel->ringbuffer_gpadlhandle);
567                 if (ret) {
568                         pr_err("Close failed: teardown gpadl return %d\n", ret);
569                         /*
570                          * If we failed to teardown gpadl,
571                          * it is perhaps better to leak memory.
572                          */
573                         goto out;
574                 }
575         }
576
577         /* Cleanup the ring buffers for this channel */
578         hv_ringbuffer_cleanup(&channel->outbound);
579         hv_ringbuffer_cleanup(&channel->inbound);
580
581         free_pages((unsigned long)channel->ringbuffer_pages,
582                 get_order(channel->ringbuffer_pagecount * PAGE_SIZE));
583
584 out:
585         hv_event_tasklet_enable(channel);
586
587         return ret;
588 }
589
590 /*
591  * vmbus_close - Close the specified channel
592  */
593 void vmbus_close(struct vmbus_channel *channel)
594 {
595         struct list_head *cur, *tmp;
596         struct vmbus_channel *cur_channel;
597
598         if (channel->primary_channel != NULL) {
599                 /*
600                  * We will only close sub-channels when
601                  * the primary is closed.
602                  */
603                 return;
604         }
605         /*
606          * Close all the sub-channels first and then close the
607          * primary channel.
608          */
609         list_for_each_safe(cur, tmp, &channel->sc_list) {
610                 cur_channel = list_entry(cur, struct vmbus_channel, sc_list);
611                 if (cur_channel->state != CHANNEL_OPENED_STATE)
612                         continue;
613                 vmbus_close_internal(cur_channel);
614         }
615         /*
616          * Now close the primary.
617          */
618         vmbus_close_internal(channel);
619 }
620 EXPORT_SYMBOL_GPL(vmbus_close);
621
622 int vmbus_sendpacket_ctl(struct vmbus_channel *channel, void *buffer,
623                            u32 bufferlen, u64 requestid,
624                            enum vmbus_packet_type type, u32 flags, bool kick_q)
625 {
626         struct vmpacket_descriptor desc;
627         u32 packetlen = sizeof(struct vmpacket_descriptor) + bufferlen;
628         u32 packetlen_aligned = ALIGN(packetlen, sizeof(u64));
629         struct kvec bufferlist[3];
630         u64 aligned_data = 0;
631         int ret;
632         bool signal = false;
633         bool lock = channel->acquire_ring_lock;
634         int num_vecs = ((bufferlen != 0) ? 3 : 1);
635
636
637         /* Setup the descriptor */
638         desc.type = type; /* VmbusPacketTypeDataInBand; */
639         desc.flags = flags; /* VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED; */
640         /* in 8-bytes granularity */
641         desc.offset8 = sizeof(struct vmpacket_descriptor) >> 3;
642         desc.len8 = (u16)(packetlen_aligned >> 3);
643         desc.trans_id = requestid;
644
645         bufferlist[0].iov_base = &desc;
646         bufferlist[0].iov_len = sizeof(struct vmpacket_descriptor);
647         bufferlist[1].iov_base = buffer;
648         bufferlist[1].iov_len = bufferlen;
649         bufferlist[2].iov_base = &aligned_data;
650         bufferlist[2].iov_len = (packetlen_aligned - packetlen);
651
652         ret = hv_ringbuffer_write(&channel->outbound, bufferlist, num_vecs,
653                                   &signal, lock);
654
655         /*
656          * Signalling the host is conditional on many factors:
657          * 1. The ring state changed from being empty to non-empty.
658          *    This is tracked by the variable "signal".
659          * 2. The variable kick_q tracks if more data will be placed
660          *    on the ring. We will not signal if more data is
661          *    to be placed.
662          *
663          * Based on the channel signal state, we will decide
664          * which signaling policy will be applied.
665          *
666          * If we cannot write to the ring-buffer; signal the host
667          * even if we may not have written anything. This is a rare
668          * enough condition that it should not matter.
669          * NOTE: in this case, the hvsock channel is an exception, because
670          * it looks the host side's hvsock implementation has a throttling
671          * mechanism which can hurt the performance otherwise.
672          */
673
674         if (channel->signal_policy)
675                 signal = true;
676         else
677                 kick_q = true;
678
679         if (((ret == 0) && kick_q && signal) ||
680             (ret && !is_hvsock_channel(channel)))
681                 vmbus_setevent(channel);
682
683         return ret;
684 }
685 EXPORT_SYMBOL(vmbus_sendpacket_ctl);
686
687 /**
688  * vmbus_sendpacket() - Send the specified buffer on the given channel
689  * @channel: Pointer to vmbus_channel structure.
690  * @buffer: Pointer to the buffer you want to receive the data into.
691  * @bufferlen: Maximum size of what the the buffer will hold
692  * @requestid: Identifier of the request
693  * @type: Type of packet that is being send e.g. negotiate, time
694  * packet etc.
695  *
696  * Sends data in @buffer directly to hyper-v via the vmbus
697  * This will send the data unparsed to hyper-v.
698  *
699  * Mainly used by Hyper-V drivers.
700  */
701 int vmbus_sendpacket(struct vmbus_channel *channel, void *buffer,
702                            u32 bufferlen, u64 requestid,
703                            enum vmbus_packet_type type, u32 flags)
704 {
705         return vmbus_sendpacket_ctl(channel, buffer, bufferlen, requestid,
706                                     type, flags, true);
707 }
708 EXPORT_SYMBOL(vmbus_sendpacket);
709
710 /*
711  * vmbus_sendpacket_pagebuffer_ctl - Send a range of single-page buffer
712  * packets using a GPADL Direct packet type. This interface allows you
713  * to control notifying the host. This will be useful for sending
714  * batched data. Also the sender can control the send flags
715  * explicitly.
716  */
717 int vmbus_sendpacket_pagebuffer_ctl(struct vmbus_channel *channel,
718                                      struct hv_page_buffer pagebuffers[],
719                                      u32 pagecount, void *buffer, u32 bufferlen,
720                                      u64 requestid,
721                                      u32 flags,
722                                      bool kick_q)
723 {
724         int ret;
725         int i;
726         struct vmbus_channel_packet_page_buffer desc;
727         u32 descsize;
728         u32 packetlen;
729         u32 packetlen_aligned;
730         struct kvec bufferlist[3];
731         u64 aligned_data = 0;
732         bool signal = false;
733         bool lock = channel->acquire_ring_lock;
734
735         if (pagecount > MAX_PAGE_BUFFER_COUNT)
736                 return -EINVAL;
737
738
739         /*
740          * Adjust the size down since vmbus_channel_packet_page_buffer is the
741          * largest size we support
742          */
743         descsize = sizeof(struct vmbus_channel_packet_page_buffer) -
744                           ((MAX_PAGE_BUFFER_COUNT - pagecount) *
745                           sizeof(struct hv_page_buffer));
746         packetlen = descsize + bufferlen;
747         packetlen_aligned = ALIGN(packetlen, sizeof(u64));
748
749         /* Setup the descriptor */
750         desc.type = VM_PKT_DATA_USING_GPA_DIRECT;
751         desc.flags = flags;
752         desc.dataoffset8 = descsize >> 3; /* in 8-bytes grandularity */
753         desc.length8 = (u16)(packetlen_aligned >> 3);
754         desc.transactionid = requestid;
755         desc.rangecount = pagecount;
756
757         for (i = 0; i < pagecount; i++) {
758                 desc.range[i].len = pagebuffers[i].len;
759                 desc.range[i].offset = pagebuffers[i].offset;
760                 desc.range[i].pfn        = pagebuffers[i].pfn;
761         }
762
763         bufferlist[0].iov_base = &desc;
764         bufferlist[0].iov_len = descsize;
765         bufferlist[1].iov_base = buffer;
766         bufferlist[1].iov_len = bufferlen;
767         bufferlist[2].iov_base = &aligned_data;
768         bufferlist[2].iov_len = (packetlen_aligned - packetlen);
769
770         ret = hv_ringbuffer_write(&channel->outbound, bufferlist, 3,
771                                   &signal, lock);
772
773         /*
774          * Signalling the host is conditional on many factors:
775          * 1. The ring state changed from being empty to non-empty.
776          *    This is tracked by the variable "signal".
777          * 2. The variable kick_q tracks if more data will be placed
778          *    on the ring. We will not signal if more data is
779          *    to be placed.
780          *
781          * Based on the channel signal state, we will decide
782          * which signaling policy will be applied.
783          *
784          * If we cannot write to the ring-buffer; signal the host
785          * even if we may not have written anything. This is a rare
786          * enough condition that it should not matter.
787          */
788
789         if (channel->signal_policy)
790                 signal = true;
791         else
792                 kick_q = true;
793
794         if (((ret == 0) && kick_q && signal) || (ret))
795                 vmbus_setevent(channel);
796
797         return ret;
798 }
799 EXPORT_SYMBOL_GPL(vmbus_sendpacket_pagebuffer_ctl);
800
801 /*
802  * vmbus_sendpacket_pagebuffer - Send a range of single-page buffer
803  * packets using a GPADL Direct packet type.
804  */
805 int vmbus_sendpacket_pagebuffer(struct vmbus_channel *channel,
806                                      struct hv_page_buffer pagebuffers[],
807                                      u32 pagecount, void *buffer, u32 bufferlen,
808                                      u64 requestid)
809 {
810         u32 flags = VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
811         return vmbus_sendpacket_pagebuffer_ctl(channel, pagebuffers, pagecount,
812                                                buffer, bufferlen, requestid,
813                                                flags, true);
814
815 }
816 EXPORT_SYMBOL_GPL(vmbus_sendpacket_pagebuffer);
817
818 /*
819  * vmbus_sendpacket_multipagebuffer - Send a multi-page buffer packet
820  * using a GPADL Direct packet type.
821  * The buffer includes the vmbus descriptor.
822  */
823 int vmbus_sendpacket_mpb_desc(struct vmbus_channel *channel,
824                               struct vmbus_packet_mpb_array *desc,
825                               u32 desc_size,
826                               void *buffer, u32 bufferlen, u64 requestid)
827 {
828         int ret;
829         u32 packetlen;
830         u32 packetlen_aligned;
831         struct kvec bufferlist[3];
832         u64 aligned_data = 0;
833         bool signal = false;
834         bool lock = channel->acquire_ring_lock;
835
836         packetlen = desc_size + bufferlen;
837         packetlen_aligned = ALIGN(packetlen, sizeof(u64));
838
839         /* Setup the descriptor */
840         desc->type = VM_PKT_DATA_USING_GPA_DIRECT;
841         desc->flags = VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
842         desc->dataoffset8 = desc_size >> 3; /* in 8-bytes grandularity */
843         desc->length8 = (u16)(packetlen_aligned >> 3);
844         desc->transactionid = requestid;
845         desc->rangecount = 1;
846
847         bufferlist[0].iov_base = desc;
848         bufferlist[0].iov_len = desc_size;
849         bufferlist[1].iov_base = buffer;
850         bufferlist[1].iov_len = bufferlen;
851         bufferlist[2].iov_base = &aligned_data;
852         bufferlist[2].iov_len = (packetlen_aligned - packetlen);
853
854         ret = hv_ringbuffer_write(&channel->outbound, bufferlist, 3,
855                                   &signal, lock);
856
857         if (ret == 0 && signal)
858                 vmbus_setevent(channel);
859
860         return ret;
861 }
862 EXPORT_SYMBOL_GPL(vmbus_sendpacket_mpb_desc);
863
864 /*
865  * vmbus_sendpacket_multipagebuffer - Send a multi-page buffer packet
866  * using a GPADL Direct packet type.
867  */
868 int vmbus_sendpacket_multipagebuffer(struct vmbus_channel *channel,
869                                 struct hv_multipage_buffer *multi_pagebuffer,
870                                 void *buffer, u32 bufferlen, u64 requestid)
871 {
872         int ret;
873         struct vmbus_channel_packet_multipage_buffer desc;
874         u32 descsize;
875         u32 packetlen;
876         u32 packetlen_aligned;
877         struct kvec bufferlist[3];
878         u64 aligned_data = 0;
879         bool signal = false;
880         bool lock = channel->acquire_ring_lock;
881         u32 pfncount = NUM_PAGES_SPANNED(multi_pagebuffer->offset,
882                                          multi_pagebuffer->len);
883
884         if (pfncount > MAX_MULTIPAGE_BUFFER_COUNT)
885                 return -EINVAL;
886
887         /*
888          * Adjust the size down since vmbus_channel_packet_multipage_buffer is
889          * the largest size we support
890          */
891         descsize = sizeof(struct vmbus_channel_packet_multipage_buffer) -
892                           ((MAX_MULTIPAGE_BUFFER_COUNT - pfncount) *
893                           sizeof(u64));
894         packetlen = descsize + bufferlen;
895         packetlen_aligned = ALIGN(packetlen, sizeof(u64));
896
897
898         /* Setup the descriptor */
899         desc.type = VM_PKT_DATA_USING_GPA_DIRECT;
900         desc.flags = VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED;
901         desc.dataoffset8 = descsize >> 3; /* in 8-bytes grandularity */
902         desc.length8 = (u16)(packetlen_aligned >> 3);
903         desc.transactionid = requestid;
904         desc.rangecount = 1;
905
906         desc.range.len = multi_pagebuffer->len;
907         desc.range.offset = multi_pagebuffer->offset;
908
909         memcpy(desc.range.pfn_array, multi_pagebuffer->pfn_array,
910                pfncount * sizeof(u64));
911
912         bufferlist[0].iov_base = &desc;
913         bufferlist[0].iov_len = descsize;
914         bufferlist[1].iov_base = buffer;
915         bufferlist[1].iov_len = bufferlen;
916         bufferlist[2].iov_base = &aligned_data;
917         bufferlist[2].iov_len = (packetlen_aligned - packetlen);
918
919         ret = hv_ringbuffer_write(&channel->outbound, bufferlist, 3,
920                                   &signal, lock);
921
922         if (ret == 0 && signal)
923                 vmbus_setevent(channel);
924
925         return ret;
926 }
927 EXPORT_SYMBOL_GPL(vmbus_sendpacket_multipagebuffer);
928
929 /**
930  * vmbus_recvpacket() - Retrieve the user packet on the specified channel
931  * @channel: Pointer to vmbus_channel structure.
932  * @buffer: Pointer to the buffer you want to receive the data into.
933  * @bufferlen: Maximum size of what the the buffer will hold
934  * @buffer_actual_len: The actual size of the data after it was received
935  * @requestid: Identifier of the request
936  *
937  * Receives directly from the hyper-v vmbus and puts the data it received
938  * into Buffer. This will receive the data unparsed from hyper-v.
939  *
940  * Mainly used by Hyper-V drivers.
941  */
942 static inline int
943 __vmbus_recvpacket(struct vmbus_channel *channel, void *buffer,
944                    u32 bufferlen, u32 *buffer_actual_len, u64 *requestid,
945                    bool raw)
946 {
947         int ret;
948         bool signal = false;
949
950         ret = hv_ringbuffer_read(&channel->inbound, buffer, bufferlen,
951                                  buffer_actual_len, requestid, &signal, raw);
952
953         if (signal)
954                 vmbus_setevent(channel);
955
956         return ret;
957 }
958
959 int vmbus_recvpacket(struct vmbus_channel *channel, void *buffer,
960                      u32 bufferlen, u32 *buffer_actual_len,
961                      u64 *requestid)
962 {
963         return __vmbus_recvpacket(channel, buffer, bufferlen,
964                                   buffer_actual_len, requestid, false);
965 }
966 EXPORT_SYMBOL(vmbus_recvpacket);
967
968 /*
969  * vmbus_recvpacket_raw - Retrieve the raw packet on the specified channel
970  */
971 int vmbus_recvpacket_raw(struct vmbus_channel *channel, void *buffer,
972                               u32 bufferlen, u32 *buffer_actual_len,
973                               u64 *requestid)
974 {
975         return __vmbus_recvpacket(channel, buffer, bufferlen,
976                                   buffer_actual_len, requestid, true);
977 }
978 EXPORT_SYMBOL_GPL(vmbus_recvpacket_raw);