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