1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Hyper-V transport for vsock
4  *
5  * Hyper-V Sockets supplies a byte-stream based communication mechanism
6  * between the host and the VM. This driver implements the necessary
7  * support in the VM by introducing the new vsock transport.
8  *
9  * Copyright (c) 2017, Microsoft Corporation.
10  */
11 #include <linux/module.h>
12 #include <linux/vmalloc.h>
13 #include <linux/hyperv.h>
14 #include <net/sock.h>
15 #include <net/af_vsock.h>
16 #include <asm/hyperv-tlfs.h>
17 
18 /* Older (VMBUS version 'VERSION_WIN10' or before) Windows hosts have some
19  * stricter requirements on the hv_sock ring buffer size of six 4K pages.
20  * hyperv-tlfs defines HV_HYP_PAGE_SIZE as 4K. Newer hosts don't have this
21  * limitation; but, keep the defaults the same for compat.
22  */
23 #define RINGBUFFER_HVS_RCV_SIZE (HV_HYP_PAGE_SIZE * 6)
24 #define RINGBUFFER_HVS_SND_SIZE (HV_HYP_PAGE_SIZE * 6)
25 #define RINGBUFFER_HVS_MAX_SIZE (HV_HYP_PAGE_SIZE * 64)
26 
27 /* The MTU is 16KB per the host side's design */
28 #define HVS_MTU_SIZE		(1024 * 16)
29 
30 /* How long to wait for graceful shutdown of a connection */
31 #define HVS_CLOSE_TIMEOUT (8 * HZ)
32 
33 struct vmpipe_proto_header {
34 	u32 pkt_type;
35 	u32 data_size;
36 };
37 
38 /* For recv, we use the VMBus in-place packet iterator APIs to directly copy
39  * data from the ringbuffer into the userspace buffer.
40  */
41 struct hvs_recv_buf {
42 	/* The header before the payload data */
43 	struct vmpipe_proto_header hdr;
44 
45 	/* The payload */
46 	u8 data[HVS_MTU_SIZE];
47 };
48 
49 /* We can send up to HVS_MTU_SIZE bytes of payload to the host, but let's use
50  * a smaller size, i.e. HVS_SEND_BUF_SIZE, to maximize concurrency between the
51  * guest and the host processing as one VMBUS packet is the smallest processing
52  * unit.
53  *
54  * Note: the buffer can be eliminated in the future when we add new VMBus
55  * ringbuffer APIs that allow us to directly copy data from userspace buffer
56  * to VMBus ringbuffer.
57  */
58 #define HVS_SEND_BUF_SIZE \
59 		(HV_HYP_PAGE_SIZE - sizeof(struct vmpipe_proto_header))
60 
61 struct hvs_send_buf {
62 	/* The header before the payload data */
63 	struct vmpipe_proto_header hdr;
64 
65 	/* The payload */
66 	u8 data[HVS_SEND_BUF_SIZE];
67 };
68 
69 #define HVS_HEADER_LEN	(sizeof(struct vmpacket_descriptor) + \
70 			 sizeof(struct vmpipe_proto_header))
71 
72 /* See 'prev_indices' in hv_ringbuffer_read(), hv_ringbuffer_write(), and
73  * __hv_pkt_iter_next().
74  */
75 #define VMBUS_PKT_TRAILER_SIZE	(sizeof(u64))
76 
77 #define HVS_PKT_LEN(payload_len)	(HVS_HEADER_LEN + \
78 					 ALIGN((payload_len), 8) + \
79 					 VMBUS_PKT_TRAILER_SIZE)
80 
81 union hvs_service_id {
82 	guid_t	srv_id;
83 
84 	struct {
85 		unsigned int svm_port;
86 		unsigned char b[sizeof(guid_t) - sizeof(unsigned int)];
87 	};
88 };
89 
90 /* Per-socket state (accessed via vsk->trans) */
91 struct hvsock {
92 	struct vsock_sock *vsk;
93 
94 	guid_t vm_srv_id;
95 	guid_t host_srv_id;
96 
97 	struct vmbus_channel *chan;
98 	struct vmpacket_descriptor *recv_desc;
99 
100 	/* The length of the payload not delivered to userland yet */
101 	u32 recv_data_len;
102 	/* The offset of the payload */
103 	u32 recv_data_off;
104 
105 	/* Have we sent the zero-length packet (FIN)? */
106 	bool fin_sent;
107 };
108 
109 /* In the VM, we support Hyper-V Sockets with AF_VSOCK, and the endpoint is
110  * <cid, port> (see struct sockaddr_vm). Note: cid is not really used here:
111  * when we write apps to connect to the host, we can only use VMADDR_CID_ANY
112  * or VMADDR_CID_HOST (both are equivalent) as the remote cid, and when we
113  * write apps to bind() & listen() in the VM, we can only use VMADDR_CID_ANY
114  * as the local cid.
115  *
116  * On the host, Hyper-V Sockets are supported by Winsock AF_HYPERV:
117  * https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-
118  * guide/make-integration-service, and the endpoint is <VmID, ServiceId> with
119  * the below sockaddr:
120  *
121  * struct SOCKADDR_HV
122  * {
123  *    ADDRESS_FAMILY Family;
124  *    USHORT Reserved;
125  *    GUID VmId;
126  *    GUID ServiceId;
127  * };
128  * Note: VmID is not used by Linux VM and actually it isn't transmitted via
129  * VMBus, because here it's obvious the host and the VM can easily identify
130  * each other. Though the VmID is useful on the host, especially in the case
131  * of Windows container, Linux VM doesn't need it at all.
132  *
133  * To make use of the AF_VSOCK infrastructure in Linux VM, we have to limit
134  * the available GUID space of SOCKADDR_HV so that we can create a mapping
135  * between AF_VSOCK port and SOCKADDR_HV Service GUID. The rule of writing
136  * Hyper-V Sockets apps on the host and in Linux VM is:
137  *
138  ****************************************************************************
139  * The only valid Service GUIDs, from the perspectives of both the host and *
140  * Linux VM, that can be connected by the other end, must conform to this   *
141  * format: <port>-facb-11e6-bd58-64006a7986d3.                              *
142  ****************************************************************************
143  *
144  * When we write apps on the host to connect(), the GUID ServiceID is used.
145  * When we write apps in Linux VM to connect(), we only need to specify the
146  * port and the driver will form the GUID and use that to request the host.
147  *
148  */
149 
150 /* 00000000-facb-11e6-bd58-64006a7986d3 */
151 static const guid_t srv_id_template =
152 	GUID_INIT(0x00000000, 0xfacb, 0x11e6, 0xbd, 0x58,
153 		  0x64, 0x00, 0x6a, 0x79, 0x86, 0xd3);
154 
155 static bool hvs_check_transport(struct vsock_sock *vsk);
156 
157 static bool is_valid_srv_id(const guid_t *id)
158 {
159 	return !memcmp(&id->b[4], &srv_id_template.b[4], sizeof(guid_t) - 4);
160 }
161 
162 static unsigned int get_port_by_srv_id(const guid_t *svr_id)
163 {
164 	return *((unsigned int *)svr_id);
165 }
166 
167 static void hvs_addr_init(struct sockaddr_vm *addr, const guid_t *svr_id)
168 {
169 	unsigned int port = get_port_by_srv_id(svr_id);
170 
171 	vsock_addr_init(addr, VMADDR_CID_ANY, port);
172 }
173 
174 static void hvs_set_channel_pending_send_size(struct vmbus_channel *chan)
175 {
176 	set_channel_pending_send_size(chan,
177 				      HVS_PKT_LEN(HVS_SEND_BUF_SIZE));
178 
179 	virt_mb();
180 }
181 
182 static bool hvs_channel_readable(struct vmbus_channel *chan)
183 {
184 	u32 readable = hv_get_bytes_to_read(&chan->inbound);
185 
186 	/* 0-size payload means FIN */
187 	return readable >= HVS_PKT_LEN(0);
188 }
189 
190 static int hvs_channel_readable_payload(struct vmbus_channel *chan)
191 {
192 	u32 readable = hv_get_bytes_to_read(&chan->inbound);
193 
194 	if (readable > HVS_PKT_LEN(0)) {
195 		/* At least we have 1 byte to read. We don't need to return
196 		 * the exact readable bytes: see vsock_stream_recvmsg() ->
197 		 * vsock_stream_has_data().
198 		 */
199 		return 1;
200 	}
201 
202 	if (readable == HVS_PKT_LEN(0)) {
203 		/* 0-size payload means FIN */
204 		return 0;
205 	}
206 
207 	/* No payload or FIN */
208 	return -1;
209 }
210 
211 static size_t hvs_channel_writable_bytes(struct vmbus_channel *chan)
212 {
213 	u32 writeable = hv_get_bytes_to_write(&chan->outbound);
214 	size_t ret;
215 
216 	/* The ringbuffer mustn't be 100% full, and we should reserve a
217 	 * zero-length-payload packet for the FIN: see hv_ringbuffer_write()
218 	 * and hvs_shutdown().
219 	 */
220 	if (writeable <= HVS_PKT_LEN(1) + HVS_PKT_LEN(0))
221 		return 0;
222 
223 	ret = writeable - HVS_PKT_LEN(1) - HVS_PKT_LEN(0);
224 
225 	return round_down(ret, 8);
226 }
227 
228 static int __hvs_send_data(struct vmbus_channel *chan,
229 			   struct vmpipe_proto_header *hdr,
230 			   size_t to_write)
231 {
232 	hdr->pkt_type = 1;
233 	hdr->data_size = to_write;
234 	return vmbus_sendpacket(chan, hdr, sizeof(*hdr) + to_write,
235 				0, VM_PKT_DATA_INBAND, 0);
236 }
237 
238 static int hvs_send_data(struct vmbus_channel *chan,
239 			 struct hvs_send_buf *send_buf, size_t to_write)
240 {
241 	return __hvs_send_data(chan, &send_buf->hdr, to_write);
242 }
243 
244 static void hvs_channel_cb(void *ctx)
245 {
246 	struct sock *sk = (struct sock *)ctx;
247 	struct vsock_sock *vsk = vsock_sk(sk);
248 	struct hvsock *hvs = vsk->trans;
249 	struct vmbus_channel *chan = hvs->chan;
250 
251 	if (hvs_channel_readable(chan))
252 		sk->sk_data_ready(sk);
253 
254 	if (hv_get_bytes_to_write(&chan->outbound) > 0)
255 		sk->sk_write_space(sk);
256 }
257 
258 static void hvs_do_close_lock_held(struct vsock_sock *vsk,
259 				   bool cancel_timeout)
260 {
261 	struct sock *sk = sk_vsock(vsk);
262 
263 	sock_set_flag(sk, SOCK_DONE);
264 	vsk->peer_shutdown = SHUTDOWN_MASK;
265 	if (vsock_stream_has_data(vsk) <= 0)
266 		sk->sk_state = TCP_CLOSING;
267 	sk->sk_state_change(sk);
268 	if (vsk->close_work_scheduled &&
269 	    (!cancel_timeout || cancel_delayed_work(&vsk->close_work))) {
270 		vsk->close_work_scheduled = false;
271 		vsock_remove_sock(vsk);
272 
273 		/* Release the reference taken while scheduling the timeout */
274 		sock_put(sk);
275 	}
276 }
277 
278 static void hvs_close_connection(struct vmbus_channel *chan)
279 {
280 	struct sock *sk = get_per_channel_state(chan);
281 
282 	lock_sock(sk);
283 	hvs_do_close_lock_held(vsock_sk(sk), true);
284 	release_sock(sk);
285 
286 	/* Release the refcnt for the channel that's opened in
287 	 * hvs_open_connection().
288 	 */
289 	sock_put(sk);
290 }
291 
292 static void hvs_open_connection(struct vmbus_channel *chan)
293 {
294 	guid_t *if_instance, *if_type;
295 	unsigned char conn_from_host;
296 
297 	struct sockaddr_vm addr;
298 	struct sock *sk, *new = NULL;
299 	struct vsock_sock *vnew = NULL;
300 	struct hvsock *hvs = NULL;
301 	struct hvsock *hvs_new = NULL;
302 	int rcvbuf;
303 	int ret;
304 	int sndbuf;
305 
306 	if_type = &chan->offermsg.offer.if_type;
307 	if_instance = &chan->offermsg.offer.if_instance;
308 	conn_from_host = chan->offermsg.offer.u.pipe.user_def[0];
309 	if (!is_valid_srv_id(if_type))
310 		return;
311 
312 	hvs_addr_init(&addr, conn_from_host ? if_type : if_instance);
313 	sk = vsock_find_bound_socket(&addr);
314 	if (!sk)
315 		return;
316 
317 	lock_sock(sk);
318 	if ((conn_from_host && sk->sk_state != TCP_LISTEN) ||
319 	    (!conn_from_host && sk->sk_state != TCP_SYN_SENT))
320 		goto out;
321 
322 	if (conn_from_host) {
323 		if (sk->sk_ack_backlog >= sk->sk_max_ack_backlog)
324 			goto out;
325 
326 		new = vsock_create_connected(sk);
327 		if (!new)
328 			goto out;
329 
330 		new->sk_state = TCP_SYN_SENT;
331 		vnew = vsock_sk(new);
332 
333 		hvs_addr_init(&vnew->local_addr, if_type);
334 
335 		/* Remote peer is always the host */
336 		vsock_addr_init(&vnew->remote_addr,
337 				VMADDR_CID_HOST, VMADDR_PORT_ANY);
338 		vnew->remote_addr.svm_port = get_port_by_srv_id(if_instance);
339 		ret = vsock_assign_transport(vnew, vsock_sk(sk));
340 		/* Transport assigned (looking at remote_addr) must be the
341 		 * same where we received the request.
342 		 */
343 		if (ret || !hvs_check_transport(vnew)) {
344 			sock_put(new);
345 			goto out;
346 		}
347 		hvs_new = vnew->trans;
348 		hvs_new->chan = chan;
349 	} else {
350 		hvs = vsock_sk(sk)->trans;
351 		hvs->chan = chan;
352 	}
353 
354 	set_channel_read_mode(chan, HV_CALL_DIRECT);
355 
356 	/* Use the socket buffer sizes as hints for the VMBUS ring size. For
357 	 * server side sockets, 'sk' is the parent socket and thus, this will
358 	 * allow the child sockets to inherit the size from the parent. Keep
359 	 * the mins to the default value and align to page size as per VMBUS
360 	 * requirements.
361 	 * For the max, the socket core library will limit the socket buffer
362 	 * size that can be set by the user, but, since currently, the hv_sock
363 	 * VMBUS ring buffer is physically contiguous allocation, restrict it
364 	 * further.
365 	 * Older versions of hv_sock host side code cannot handle bigger VMBUS
366 	 * ring buffer size. Use the version number to limit the change to newer
367 	 * versions.
368 	 */
369 	if (vmbus_proto_version < VERSION_WIN10_V5) {
370 		sndbuf = RINGBUFFER_HVS_SND_SIZE;
371 		rcvbuf = RINGBUFFER_HVS_RCV_SIZE;
372 	} else {
373 		sndbuf = max_t(int, sk->sk_sndbuf, RINGBUFFER_HVS_SND_SIZE);
374 		sndbuf = min_t(int, sndbuf, RINGBUFFER_HVS_MAX_SIZE);
375 		sndbuf = ALIGN(sndbuf, HV_HYP_PAGE_SIZE);
376 		rcvbuf = max_t(int, sk->sk_rcvbuf, RINGBUFFER_HVS_RCV_SIZE);
377 		rcvbuf = min_t(int, rcvbuf, RINGBUFFER_HVS_MAX_SIZE);
378 		rcvbuf = ALIGN(rcvbuf, HV_HYP_PAGE_SIZE);
379 	}
380 
381 	ret = vmbus_open(chan, sndbuf, rcvbuf, NULL, 0, hvs_channel_cb,
382 			 conn_from_host ? new : sk);
383 	if (ret != 0) {
384 		if (conn_from_host) {
385 			hvs_new->chan = NULL;
386 			sock_put(new);
387 		} else {
388 			hvs->chan = NULL;
389 		}
390 		goto out;
391 	}
392 
393 	set_per_channel_state(chan, conn_from_host ? new : sk);
394 
395 	/* This reference will be dropped by hvs_close_connection(). */
396 	sock_hold(conn_from_host ? new : sk);
397 	vmbus_set_chn_rescind_callback(chan, hvs_close_connection);
398 
399 	/* Set the pending send size to max packet size to always get
400 	 * notifications from the host when there is enough writable space.
401 	 * The host is optimized to send notifications only when the pending
402 	 * size boundary is crossed, and not always.
403 	 */
404 	hvs_set_channel_pending_send_size(chan);
405 
406 	if (conn_from_host) {
407 		new->sk_state = TCP_ESTABLISHED;
408 		sk_acceptq_added(sk);
409 
410 		hvs_new->vm_srv_id = *if_type;
411 		hvs_new->host_srv_id = *if_instance;
412 
413 		vsock_insert_connected(vnew);
414 
415 		vsock_enqueue_accept(sk, new);
416 	} else {
417 		sk->sk_state = TCP_ESTABLISHED;
418 		sk->sk_socket->state = SS_CONNECTED;
419 
420 		vsock_insert_connected(vsock_sk(sk));
421 	}
422 
423 	sk->sk_state_change(sk);
424 
425 out:
426 	/* Release refcnt obtained when we called vsock_find_bound_socket() */
427 	sock_put(sk);
428 
429 	release_sock(sk);
430 }
431 
432 static u32 hvs_get_local_cid(void)
433 {
434 	return VMADDR_CID_ANY;
435 }
436 
437 static int hvs_sock_init(struct vsock_sock *vsk, struct vsock_sock *psk)
438 {
439 	struct hvsock *hvs;
440 	struct sock *sk = sk_vsock(vsk);
441 
442 	hvs = kzalloc(sizeof(*hvs), GFP_KERNEL);
443 	if (!hvs)
444 		return -ENOMEM;
445 
446 	vsk->trans = hvs;
447 	hvs->vsk = vsk;
448 	sk->sk_sndbuf = RINGBUFFER_HVS_SND_SIZE;
449 	sk->sk_rcvbuf = RINGBUFFER_HVS_RCV_SIZE;
450 	return 0;
451 }
452 
453 static int hvs_connect(struct vsock_sock *vsk)
454 {
455 	union hvs_service_id vm, host;
456 	struct hvsock *h = vsk->trans;
457 
458 	vm.srv_id = srv_id_template;
459 	vm.svm_port = vsk->local_addr.svm_port;
460 	h->vm_srv_id = vm.srv_id;
461 
462 	host.srv_id = srv_id_template;
463 	host.svm_port = vsk->remote_addr.svm_port;
464 	h->host_srv_id = host.srv_id;
465 
466 	return vmbus_send_tl_connect_request(&h->vm_srv_id, &h->host_srv_id);
467 }
468 
469 static void hvs_shutdown_lock_held(struct hvsock *hvs, int mode)
470 {
471 	struct vmpipe_proto_header hdr;
472 
473 	if (hvs->fin_sent || !hvs->chan)
474 		return;
475 
476 	/* It can't fail: see hvs_channel_writable_bytes(). */
477 	(void)__hvs_send_data(hvs->chan, &hdr, 0);
478 	hvs->fin_sent = true;
479 }
480 
481 static int hvs_shutdown(struct vsock_sock *vsk, int mode)
482 {
483 	if (!(mode & SEND_SHUTDOWN))
484 		return 0;
485 
486 	hvs_shutdown_lock_held(vsk->trans, mode);
487 	return 0;
488 }
489 
490 static void hvs_close_timeout(struct work_struct *work)
491 {
492 	struct vsock_sock *vsk =
493 		container_of(work, struct vsock_sock, close_work.work);
494 	struct sock *sk = sk_vsock(vsk);
495 
496 	sock_hold(sk);
497 	lock_sock(sk);
498 	if (!sock_flag(sk, SOCK_DONE))
499 		hvs_do_close_lock_held(vsk, false);
500 
501 	vsk->close_work_scheduled = false;
502 	release_sock(sk);
503 	sock_put(sk);
504 }
505 
506 /* Returns true, if it is safe to remove socket; false otherwise */
507 static bool hvs_close_lock_held(struct vsock_sock *vsk)
508 {
509 	struct sock *sk = sk_vsock(vsk);
510 
511 	if (!(sk->sk_state == TCP_ESTABLISHED ||
512 	      sk->sk_state == TCP_CLOSING))
513 		return true;
514 
515 	if ((sk->sk_shutdown & SHUTDOWN_MASK) != SHUTDOWN_MASK)
516 		hvs_shutdown_lock_held(vsk->trans, SHUTDOWN_MASK);
517 
518 	if (sock_flag(sk, SOCK_DONE))
519 		return true;
520 
521 	/* This reference will be dropped by the delayed close routine */
522 	sock_hold(sk);
523 	INIT_DELAYED_WORK(&vsk->close_work, hvs_close_timeout);
524 	vsk->close_work_scheduled = true;
525 	schedule_delayed_work(&vsk->close_work, HVS_CLOSE_TIMEOUT);
526 	return false;
527 }
528 
529 static void hvs_release(struct vsock_sock *vsk)
530 {
531 	bool remove_sock;
532 
533 	remove_sock = hvs_close_lock_held(vsk);
534 	if (remove_sock)
535 		vsock_remove_sock(vsk);
536 }
537 
538 static void hvs_destruct(struct vsock_sock *vsk)
539 {
540 	struct hvsock *hvs = vsk->trans;
541 	struct vmbus_channel *chan = hvs->chan;
542 
543 	if (chan)
544 		vmbus_hvsock_device_unregister(chan);
545 
546 	kfree(hvs);
547 }
548 
549 static int hvs_dgram_bind(struct vsock_sock *vsk, struct sockaddr_vm *addr)
550 {
551 	return -EOPNOTSUPP;
552 }
553 
554 static int hvs_dgram_dequeue(struct vsock_sock *vsk, struct msghdr *msg,
555 			     size_t len, int flags)
556 {
557 	return -EOPNOTSUPP;
558 }
559 
560 static int hvs_dgram_enqueue(struct vsock_sock *vsk,
561 			     struct sockaddr_vm *remote, struct msghdr *msg,
562 			     size_t dgram_len)
563 {
564 	return -EOPNOTSUPP;
565 }
566 
567 static bool hvs_dgram_allow(u32 cid, u32 port)
568 {
569 	return false;
570 }
571 
572 static int hvs_update_recv_data(struct hvsock *hvs)
573 {
574 	struct hvs_recv_buf *recv_buf;
575 	u32 payload_len;
576 
577 	recv_buf = (struct hvs_recv_buf *)(hvs->recv_desc + 1);
578 	payload_len = recv_buf->hdr.data_size;
579 
580 	if (payload_len > HVS_MTU_SIZE)
581 		return -EIO;
582 
583 	if (payload_len == 0)
584 		hvs->vsk->peer_shutdown |= SEND_SHUTDOWN;
585 
586 	hvs->recv_data_len = payload_len;
587 	hvs->recv_data_off = 0;
588 
589 	return 0;
590 }
591 
592 static ssize_t hvs_stream_dequeue(struct vsock_sock *vsk, struct msghdr *msg,
593 				  size_t len, int flags)
594 {
595 	struct hvsock *hvs = vsk->trans;
596 	bool need_refill = !hvs->recv_desc;
597 	struct hvs_recv_buf *recv_buf;
598 	u32 to_read;
599 	int ret;
600 
601 	if (flags & MSG_PEEK)
602 		return -EOPNOTSUPP;
603 
604 	if (need_refill) {
605 		hvs->recv_desc = hv_pkt_iter_first_raw(hvs->chan);
606 		if (!hvs->recv_desc)
607 			return -ENOBUFS;
608 		ret = hvs_update_recv_data(hvs);
609 		if (ret)
610 			return ret;
611 	}
612 
613 	recv_buf = (struct hvs_recv_buf *)(hvs->recv_desc + 1);
614 	to_read = min_t(u32, len, hvs->recv_data_len);
615 	ret = memcpy_to_msg(msg, recv_buf->data + hvs->recv_data_off, to_read);
616 	if (ret != 0)
617 		return ret;
618 
619 	hvs->recv_data_len -= to_read;
620 	if (hvs->recv_data_len == 0) {
621 		hvs->recv_desc = hv_pkt_iter_next_raw(hvs->chan, hvs->recv_desc);
622 		if (hvs->recv_desc) {
623 			ret = hvs_update_recv_data(hvs);
624 			if (ret)
625 				return ret;
626 		}
627 	} else {
628 		hvs->recv_data_off += to_read;
629 	}
630 
631 	return to_read;
632 }
633 
634 static ssize_t hvs_stream_enqueue(struct vsock_sock *vsk, struct msghdr *msg,
635 				  size_t len)
636 {
637 	struct hvsock *hvs = vsk->trans;
638 	struct vmbus_channel *chan = hvs->chan;
639 	struct hvs_send_buf *send_buf;
640 	ssize_t to_write, max_writable;
641 	ssize_t ret = 0;
642 	ssize_t bytes_written = 0;
643 
644 	BUILD_BUG_ON(sizeof(*send_buf) != HV_HYP_PAGE_SIZE);
645 
646 	send_buf = kmalloc(sizeof(*send_buf), GFP_KERNEL);
647 	if (!send_buf)
648 		return -ENOMEM;
649 
650 	/* Reader(s) could be draining data from the channel as we write.
651 	 * Maximize bandwidth, by iterating until the channel is found to be
652 	 * full.
653 	 */
654 	while (len) {
655 		max_writable = hvs_channel_writable_bytes(chan);
656 		if (!max_writable)
657 			break;
658 		to_write = min_t(ssize_t, len, max_writable);
659 		to_write = min_t(ssize_t, to_write, HVS_SEND_BUF_SIZE);
660 		/* memcpy_from_msg is safe for loop as it advances the offsets
661 		 * within the message iterator.
662 		 */
663 		ret = memcpy_from_msg(send_buf->data, msg, to_write);
664 		if (ret < 0)
665 			goto out;
666 
667 		ret = hvs_send_data(hvs->chan, send_buf, to_write);
668 		if (ret < 0)
669 			goto out;
670 
671 		bytes_written += to_write;
672 		len -= to_write;
673 	}
674 out:
675 	/* If any data has been sent, return that */
676 	if (bytes_written)
677 		ret = bytes_written;
678 	kfree(send_buf);
679 	return ret;
680 }
681 
682 static s64 hvs_stream_has_data(struct vsock_sock *vsk)
683 {
684 	struct hvsock *hvs = vsk->trans;
685 	s64 ret;
686 
687 	if (hvs->recv_data_len > 0)
688 		return 1;
689 
690 	switch (hvs_channel_readable_payload(hvs->chan)) {
691 	case 1:
692 		ret = 1;
693 		break;
694 	case 0:
695 		vsk->peer_shutdown |= SEND_SHUTDOWN;
696 		ret = 0;
697 		break;
698 	default: /* -1 */
699 		ret = 0;
700 		break;
701 	}
702 
703 	return ret;
704 }
705 
706 static s64 hvs_stream_has_space(struct vsock_sock *vsk)
707 {
708 	struct hvsock *hvs = vsk->trans;
709 
710 	return hvs_channel_writable_bytes(hvs->chan);
711 }
712 
713 static u64 hvs_stream_rcvhiwat(struct vsock_sock *vsk)
714 {
715 	return HVS_MTU_SIZE + 1;
716 }
717 
718 static bool hvs_stream_is_active(struct vsock_sock *vsk)
719 {
720 	struct hvsock *hvs = vsk->trans;
721 
722 	return hvs->chan != NULL;
723 }
724 
725 static bool hvs_stream_allow(u32 cid, u32 port)
726 {
727 	if (cid == VMADDR_CID_HOST)
728 		return true;
729 
730 	return false;
731 }
732 
733 static
734 int hvs_notify_poll_in(struct vsock_sock *vsk, size_t target, bool *readable)
735 {
736 	struct hvsock *hvs = vsk->trans;
737 
738 	*readable = hvs_channel_readable(hvs->chan);
739 	return 0;
740 }
741 
742 static
743 int hvs_notify_poll_out(struct vsock_sock *vsk, size_t target, bool *writable)
744 {
745 	*writable = hvs_stream_has_space(vsk) > 0;
746 
747 	return 0;
748 }
749 
750 static
751 int hvs_notify_recv_init(struct vsock_sock *vsk, size_t target,
752 			 struct vsock_transport_recv_notify_data *d)
753 {
754 	return 0;
755 }
756 
757 static
758 int hvs_notify_recv_pre_block(struct vsock_sock *vsk, size_t target,
759 			      struct vsock_transport_recv_notify_data *d)
760 {
761 	return 0;
762 }
763 
764 static
765 int hvs_notify_recv_pre_dequeue(struct vsock_sock *vsk, size_t target,
766 				struct vsock_transport_recv_notify_data *d)
767 {
768 	return 0;
769 }
770 
771 static
772 int hvs_notify_recv_post_dequeue(struct vsock_sock *vsk, size_t target,
773 				 ssize_t copied, bool data_read,
774 				 struct vsock_transport_recv_notify_data *d)
775 {
776 	return 0;
777 }
778 
779 static
780 int hvs_notify_send_init(struct vsock_sock *vsk,
781 			 struct vsock_transport_send_notify_data *d)
782 {
783 	return 0;
784 }
785 
786 static
787 int hvs_notify_send_pre_block(struct vsock_sock *vsk,
788 			      struct vsock_transport_send_notify_data *d)
789 {
790 	return 0;
791 }
792 
793 static
794 int hvs_notify_send_pre_enqueue(struct vsock_sock *vsk,
795 				struct vsock_transport_send_notify_data *d)
796 {
797 	return 0;
798 }
799 
800 static
801 int hvs_notify_send_post_enqueue(struct vsock_sock *vsk, ssize_t written,
802 				 struct vsock_transport_send_notify_data *d)
803 {
804 	return 0;
805 }
806 
807 static struct vsock_transport hvs_transport = {
808 	.module                   = THIS_MODULE,
809 
810 	.get_local_cid            = hvs_get_local_cid,
811 
812 	.init                     = hvs_sock_init,
813 	.destruct                 = hvs_destruct,
814 	.release                  = hvs_release,
815 	.connect                  = hvs_connect,
816 	.shutdown                 = hvs_shutdown,
817 
818 	.dgram_bind               = hvs_dgram_bind,
819 	.dgram_dequeue            = hvs_dgram_dequeue,
820 	.dgram_enqueue            = hvs_dgram_enqueue,
821 	.dgram_allow              = hvs_dgram_allow,
822 
823 	.stream_dequeue           = hvs_stream_dequeue,
824 	.stream_enqueue           = hvs_stream_enqueue,
825 	.stream_has_data          = hvs_stream_has_data,
826 	.stream_has_space         = hvs_stream_has_space,
827 	.stream_rcvhiwat          = hvs_stream_rcvhiwat,
828 	.stream_is_active         = hvs_stream_is_active,
829 	.stream_allow             = hvs_stream_allow,
830 
831 	.notify_poll_in           = hvs_notify_poll_in,
832 	.notify_poll_out          = hvs_notify_poll_out,
833 	.notify_recv_init         = hvs_notify_recv_init,
834 	.notify_recv_pre_block    = hvs_notify_recv_pre_block,
835 	.notify_recv_pre_dequeue  = hvs_notify_recv_pre_dequeue,
836 	.notify_recv_post_dequeue = hvs_notify_recv_post_dequeue,
837 	.notify_send_init         = hvs_notify_send_init,
838 	.notify_send_pre_block    = hvs_notify_send_pre_block,
839 	.notify_send_pre_enqueue  = hvs_notify_send_pre_enqueue,
840 	.notify_send_post_enqueue = hvs_notify_send_post_enqueue,
841 
842 };
843 
844 static bool hvs_check_transport(struct vsock_sock *vsk)
845 {
846 	return vsk->transport == &hvs_transport;
847 }
848 
849 static int hvs_probe(struct hv_device *hdev,
850 		     const struct hv_vmbus_device_id *dev_id)
851 {
852 	struct vmbus_channel *chan = hdev->channel;
853 
854 	hvs_open_connection(chan);
855 
856 	/* Always return success to suppress the unnecessary error message
857 	 * in vmbus_probe(): on error the host will rescind the device in
858 	 * 30 seconds and we can do cleanup at that time in
859 	 * vmbus_onoffer_rescind().
860 	 */
861 	return 0;
862 }
863 
864 static int hvs_remove(struct hv_device *hdev)
865 {
866 	struct vmbus_channel *chan = hdev->channel;
867 
868 	vmbus_close(chan);
869 
870 	return 0;
871 }
872 
873 /* hv_sock connections can not persist across hibernation, and all the hv_sock
874  * channels are forced to be rescinded before hibernation: see
875  * vmbus_bus_suspend(). Here the dummy hvs_suspend() and hvs_resume()
876  * are only needed because hibernation requires that every vmbus device's
877  * driver should have a .suspend and .resume callback: see vmbus_suspend().
878  */
879 static int hvs_suspend(struct hv_device *hv_dev)
880 {
881 	/* Dummy */
882 	return 0;
883 }
884 
885 static int hvs_resume(struct hv_device *dev)
886 {
887 	/* Dummy */
888 	return 0;
889 }
890 
891 /* This isn't really used. See vmbus_match() and vmbus_probe() */
892 static const struct hv_vmbus_device_id id_table[] = {
893 	{},
894 };
895 
896 static struct hv_driver hvs_drv = {
897 	.name		= "hv_sock",
898 	.hvsock		= true,
899 	.id_table	= id_table,
900 	.probe		= hvs_probe,
901 	.remove		= hvs_remove,
902 	.suspend	= hvs_suspend,
903 	.resume		= hvs_resume,
904 };
905 
906 static int __init hvs_init(void)
907 {
908 	int ret;
909 
910 	if (vmbus_proto_version < VERSION_WIN10)
911 		return -ENODEV;
912 
913 	ret = vmbus_driver_register(&hvs_drv);
914 	if (ret != 0)
915 		return ret;
916 
917 	ret = vsock_core_register(&hvs_transport, VSOCK_TRANSPORT_F_G2H);
918 	if (ret) {
919 		vmbus_driver_unregister(&hvs_drv);
920 		return ret;
921 	}
922 
923 	return 0;
924 }
925 
926 static void __exit hvs_exit(void)
927 {
928 	vsock_core_unregister(&hvs_transport);
929 	vmbus_driver_unregister(&hvs_drv);
930 }
931 
932 module_init(hvs_init);
933 module_exit(hvs_exit);
934 
935 MODULE_DESCRIPTION("Hyper-V Sockets");
936 MODULE_VERSION("1.0.0");
937 MODULE_LICENSE("GPL");
938 MODULE_ALIAS_NETPROTO(PF_VSOCK);
939