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 	guid_t	srv_id;
81 
82 	struct {
83 		unsigned int svm_port;
84 		unsigned char b[sizeof(guid_t) - sizeof(unsigned int)];
85 	};
86 };
87 
88 /* Per-socket state (accessed via vsk->trans) */
89 struct hvsock {
90 	struct vsock_sock *vsk;
91 
92 	guid_t vm_srv_id;
93 	guid_t 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 guid_t srv_id_template =
163 	GUID_INIT(0x00000000, 0xfacb, 0x11e6, 0xbd, 0x58,
164 		  0x64, 0x00, 0x6a, 0x79, 0x86, 0xd3);
165 
166 static bool is_valid_srv_id(const guid_t *id)
167 {
168 	return !memcmp(&id->b[4], &srv_id_template.b[4], sizeof(guid_t) - 4);
169 }
170 
171 static unsigned int get_port_by_srv_id(const guid_t *svr_id)
172 {
173 	return *((unsigned int *)svr_id);
174 }
175 
176 static void hvs_addr_init(struct sockaddr_vm *addr, const guid_t *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 	virt_mb();
216 }
217 
218 static bool hvs_channel_readable(struct vmbus_channel *chan)
219 {
220 	u32 readable = hv_get_bytes_to_read(&chan->inbound);
221 
222 	/* 0-size payload means FIN */
223 	return readable >= HVS_PKT_LEN(0);
224 }
225 
226 static int hvs_channel_readable_payload(struct vmbus_channel *chan)
227 {
228 	u32 readable = hv_get_bytes_to_read(&chan->inbound);
229 
230 	if (readable > HVS_PKT_LEN(0)) {
231 		/* At least we have 1 byte to read. We don't need to return
232 		 * the exact readable bytes: see vsock_stream_recvmsg() ->
233 		 * vsock_stream_has_data().
234 		 */
235 		return 1;
236 	}
237 
238 	if (readable == HVS_PKT_LEN(0)) {
239 		/* 0-size payload means FIN */
240 		return 0;
241 	}
242 
243 	/* No payload or FIN */
244 	return -1;
245 }
246 
247 static size_t hvs_channel_writable_bytes(struct vmbus_channel *chan)
248 {
249 	u32 writeable = hv_get_bytes_to_write(&chan->outbound);
250 	size_t ret;
251 
252 	/* The ringbuffer mustn't be 100% full, and we should reserve a
253 	 * zero-length-payload packet for the FIN: see hv_ringbuffer_write()
254 	 * and hvs_shutdown().
255 	 */
256 	if (writeable <= HVS_PKT_LEN(1) + HVS_PKT_LEN(0))
257 		return 0;
258 
259 	ret = writeable - HVS_PKT_LEN(1) - HVS_PKT_LEN(0);
260 
261 	return round_down(ret, 8);
262 }
263 
264 static int hvs_send_data(struct vmbus_channel *chan,
265 			 struct hvs_send_buf *send_buf, size_t to_write)
266 {
267 	send_buf->hdr.pkt_type = 1;
268 	send_buf->hdr.data_size = to_write;
269 	return vmbus_sendpacket(chan, &send_buf->hdr,
270 				sizeof(send_buf->hdr) + to_write,
271 				0, VM_PKT_DATA_INBAND, 0);
272 }
273 
274 static void hvs_channel_cb(void *ctx)
275 {
276 	struct sock *sk = (struct sock *)ctx;
277 	struct vsock_sock *vsk = vsock_sk(sk);
278 	struct hvsock *hvs = vsk->trans;
279 	struct vmbus_channel *chan = hvs->chan;
280 
281 	if (hvs_channel_readable(chan))
282 		sk->sk_data_ready(sk);
283 
284 	if (hv_get_bytes_to_write(&chan->outbound) > 0)
285 		sk->sk_write_space(sk);
286 }
287 
288 static void hvs_do_close_lock_held(struct vsock_sock *vsk,
289 				   bool cancel_timeout)
290 {
291 	struct sock *sk = sk_vsock(vsk);
292 
293 	sock_set_flag(sk, SOCK_DONE);
294 	vsk->peer_shutdown = SHUTDOWN_MASK;
295 	if (vsock_stream_has_data(vsk) <= 0)
296 		sk->sk_state = TCP_CLOSING;
297 	sk->sk_state_change(sk);
298 	if (vsk->close_work_scheduled &&
299 	    (!cancel_timeout || cancel_delayed_work(&vsk->close_work))) {
300 		vsk->close_work_scheduled = false;
301 		vsock_remove_sock(vsk);
302 
303 		/* Release the reference taken while scheduling the timeout */
304 		sock_put(sk);
305 	}
306 }
307 
308 static void hvs_close_connection(struct vmbus_channel *chan)
309 {
310 	struct sock *sk = get_per_channel_state(chan);
311 
312 	lock_sock(sk);
313 	hvs_do_close_lock_held(vsock_sk(sk), true);
314 	release_sock(sk);
315 }
316 
317 static void hvs_open_connection(struct vmbus_channel *chan)
318 {
319 	guid_t *if_instance, *if_type;
320 	unsigned char conn_from_host;
321 
322 	struct sockaddr_vm addr;
323 	struct sock *sk, *new = NULL;
324 	struct vsock_sock *vnew = NULL;
325 	struct hvsock *hvs = NULL;
326 	struct hvsock *hvs_new = NULL;
327 	int rcvbuf;
328 	int ret;
329 	int sndbuf;
330 
331 	if_type = &chan->offermsg.offer.if_type;
332 	if_instance = &chan->offermsg.offer.if_instance;
333 	conn_from_host = chan->offermsg.offer.u.pipe.user_def[0];
334 
335 	/* The host or the VM should only listen on a port in
336 	 * [0, MAX_LISTEN_PORT]
337 	 */
338 	if (!is_valid_srv_id(if_type) ||
339 	    get_port_by_srv_id(if_type) > MAX_LISTEN_PORT)
340 		return;
341 
342 	hvs_addr_init(&addr, conn_from_host ? if_type : if_instance);
343 	sk = vsock_find_bound_socket(&addr);
344 	if (!sk)
345 		return;
346 
347 	lock_sock(sk);
348 	if ((conn_from_host && sk->sk_state != TCP_LISTEN) ||
349 	    (!conn_from_host && sk->sk_state != TCP_SYN_SENT))
350 		goto out;
351 
352 	if (conn_from_host) {
353 		if (sk->sk_ack_backlog >= sk->sk_max_ack_backlog)
354 			goto out;
355 
356 		new = __vsock_create(sock_net(sk), NULL, sk, GFP_KERNEL,
357 				     sk->sk_type, 0);
358 		if (!new)
359 			goto out;
360 
361 		new->sk_state = TCP_SYN_SENT;
362 		vnew = vsock_sk(new);
363 		hvs_new = vnew->trans;
364 		hvs_new->chan = chan;
365 	} else {
366 		hvs = vsock_sk(sk)->trans;
367 		hvs->chan = chan;
368 	}
369 
370 	set_channel_read_mode(chan, HV_CALL_DIRECT);
371 
372 	/* Use the socket buffer sizes as hints for the VMBUS ring size. For
373 	 * server side sockets, 'sk' is the parent socket and thus, this will
374 	 * allow the child sockets to inherit the size from the parent. Keep
375 	 * the mins to the default value and align to page size as per VMBUS
376 	 * requirements.
377 	 * For the max, the socket core library will limit the socket buffer
378 	 * size that can be set by the user, but, since currently, the hv_sock
379 	 * VMBUS ring buffer is physically contiguous allocation, restrict it
380 	 * further.
381 	 * Older versions of hv_sock host side code cannot handle bigger VMBUS
382 	 * ring buffer size. Use the version number to limit the change to newer
383 	 * versions.
384 	 */
385 	if (vmbus_proto_version < VERSION_WIN10_V5) {
386 		sndbuf = RINGBUFFER_HVS_SND_SIZE;
387 		rcvbuf = RINGBUFFER_HVS_RCV_SIZE;
388 	} else {
389 		sndbuf = max_t(int, sk->sk_sndbuf, RINGBUFFER_HVS_SND_SIZE);
390 		sndbuf = min_t(int, sndbuf, RINGBUFFER_HVS_MAX_SIZE);
391 		sndbuf = ALIGN(sndbuf, PAGE_SIZE);
392 		rcvbuf = max_t(int, sk->sk_rcvbuf, RINGBUFFER_HVS_RCV_SIZE);
393 		rcvbuf = min_t(int, rcvbuf, RINGBUFFER_HVS_MAX_SIZE);
394 		rcvbuf = ALIGN(rcvbuf, PAGE_SIZE);
395 	}
396 
397 	ret = vmbus_open(chan, sndbuf, rcvbuf, NULL, 0, hvs_channel_cb,
398 			 conn_from_host ? new : sk);
399 	if (ret != 0) {
400 		if (conn_from_host) {
401 			hvs_new->chan = NULL;
402 			sock_put(new);
403 		} else {
404 			hvs->chan = NULL;
405 		}
406 		goto out;
407 	}
408 
409 	set_per_channel_state(chan, conn_from_host ? new : sk);
410 	vmbus_set_chn_rescind_callback(chan, hvs_close_connection);
411 
412 	/* Set the pending send size to max packet size to always get
413 	 * notifications from the host when there is enough writable space.
414 	 * The host is optimized to send notifications only when the pending
415 	 * size boundary is crossed, and not always.
416 	 */
417 	hvs_set_channel_pending_send_size(chan);
418 
419 	if (conn_from_host) {
420 		new->sk_state = TCP_ESTABLISHED;
421 		sk->sk_ack_backlog++;
422 
423 		hvs_addr_init(&vnew->local_addr, if_type);
424 		hvs_remote_addr_init(&vnew->remote_addr, &vnew->local_addr);
425 
426 		hvs_new->vm_srv_id = *if_type;
427 		hvs_new->host_srv_id = *if_instance;
428 
429 		vsock_insert_connected(vnew);
430 
431 		vsock_enqueue_accept(sk, new);
432 	} else {
433 		sk->sk_state = TCP_ESTABLISHED;
434 		sk->sk_socket->state = SS_CONNECTED;
435 
436 		vsock_insert_connected(vsock_sk(sk));
437 	}
438 
439 	sk->sk_state_change(sk);
440 
441 out:
442 	/* Release refcnt obtained when we called vsock_find_bound_socket() */
443 	sock_put(sk);
444 
445 	release_sock(sk);
446 }
447 
448 static u32 hvs_get_local_cid(void)
449 {
450 	return VMADDR_CID_ANY;
451 }
452 
453 static int hvs_sock_init(struct vsock_sock *vsk, struct vsock_sock *psk)
454 {
455 	struct hvsock *hvs;
456 	struct sock *sk = sk_vsock(vsk);
457 
458 	hvs = kzalloc(sizeof(*hvs), GFP_KERNEL);
459 	if (!hvs)
460 		return -ENOMEM;
461 
462 	vsk->trans = hvs;
463 	hvs->vsk = vsk;
464 	sk->sk_sndbuf = RINGBUFFER_HVS_SND_SIZE;
465 	sk->sk_rcvbuf = RINGBUFFER_HVS_RCV_SIZE;
466 	return 0;
467 }
468 
469 static int hvs_connect(struct vsock_sock *vsk)
470 {
471 	union hvs_service_id vm, host;
472 	struct hvsock *h = vsk->trans;
473 
474 	vm.srv_id = srv_id_template;
475 	vm.svm_port = vsk->local_addr.svm_port;
476 	h->vm_srv_id = vm.srv_id;
477 
478 	host.srv_id = srv_id_template;
479 	host.svm_port = vsk->remote_addr.svm_port;
480 	h->host_srv_id = host.srv_id;
481 
482 	return vmbus_send_tl_connect_request(&h->vm_srv_id, &h->host_srv_id);
483 }
484 
485 static void hvs_shutdown_lock_held(struct hvsock *hvs, int mode)
486 {
487 	struct vmpipe_proto_header hdr;
488 
489 	if (hvs->fin_sent || !hvs->chan)
490 		return;
491 
492 	/* It can't fail: see hvs_channel_writable_bytes(). */
493 	(void)hvs_send_data(hvs->chan, (struct hvs_send_buf *)&hdr, 0);
494 	hvs->fin_sent = true;
495 }
496 
497 static int hvs_shutdown(struct vsock_sock *vsk, int mode)
498 {
499 	struct sock *sk = sk_vsock(vsk);
500 
501 	if (!(mode & SEND_SHUTDOWN))
502 		return 0;
503 
504 	lock_sock(sk);
505 	hvs_shutdown_lock_held(vsk->trans, mode);
506 	release_sock(sk);
507 	return 0;
508 }
509 
510 static void hvs_close_timeout(struct work_struct *work)
511 {
512 	struct vsock_sock *vsk =
513 		container_of(work, struct vsock_sock, close_work.work);
514 	struct sock *sk = sk_vsock(vsk);
515 
516 	sock_hold(sk);
517 	lock_sock(sk);
518 	if (!sock_flag(sk, SOCK_DONE))
519 		hvs_do_close_lock_held(vsk, false);
520 
521 	vsk->close_work_scheduled = false;
522 	release_sock(sk);
523 	sock_put(sk);
524 }
525 
526 /* Returns true, if it is safe to remove socket; false otherwise */
527 static bool hvs_close_lock_held(struct vsock_sock *vsk)
528 {
529 	struct sock *sk = sk_vsock(vsk);
530 
531 	if (!(sk->sk_state == TCP_ESTABLISHED ||
532 	      sk->sk_state == TCP_CLOSING))
533 		return true;
534 
535 	if ((sk->sk_shutdown & SHUTDOWN_MASK) != SHUTDOWN_MASK)
536 		hvs_shutdown_lock_held(vsk->trans, SHUTDOWN_MASK);
537 
538 	if (sock_flag(sk, SOCK_DONE))
539 		return true;
540 
541 	/* This reference will be dropped by the delayed close routine */
542 	sock_hold(sk);
543 	INIT_DELAYED_WORK(&vsk->close_work, hvs_close_timeout);
544 	vsk->close_work_scheduled = true;
545 	schedule_delayed_work(&vsk->close_work, HVS_CLOSE_TIMEOUT);
546 	return false;
547 }
548 
549 static void hvs_release(struct vsock_sock *vsk)
550 {
551 	struct sock *sk = sk_vsock(vsk);
552 	bool remove_sock;
553 
554 	lock_sock(sk);
555 	remove_sock = hvs_close_lock_held(vsk);
556 	release_sock(sk);
557 	if (remove_sock)
558 		vsock_remove_sock(vsk);
559 }
560 
561 static void hvs_destruct(struct vsock_sock *vsk)
562 {
563 	struct hvsock *hvs = vsk->trans;
564 	struct vmbus_channel *chan = hvs->chan;
565 
566 	if (chan)
567 		vmbus_hvsock_device_unregister(chan);
568 
569 	kfree(hvs);
570 }
571 
572 static int hvs_dgram_bind(struct vsock_sock *vsk, struct sockaddr_vm *addr)
573 {
574 	return -EOPNOTSUPP;
575 }
576 
577 static int hvs_dgram_dequeue(struct vsock_sock *vsk, struct msghdr *msg,
578 			     size_t len, int flags)
579 {
580 	return -EOPNOTSUPP;
581 }
582 
583 static int hvs_dgram_enqueue(struct vsock_sock *vsk,
584 			     struct sockaddr_vm *remote, struct msghdr *msg,
585 			     size_t dgram_len)
586 {
587 	return -EOPNOTSUPP;
588 }
589 
590 static bool hvs_dgram_allow(u32 cid, u32 port)
591 {
592 	return false;
593 }
594 
595 static int hvs_update_recv_data(struct hvsock *hvs)
596 {
597 	struct hvs_recv_buf *recv_buf;
598 	u32 payload_len;
599 
600 	recv_buf = (struct hvs_recv_buf *)(hvs->recv_desc + 1);
601 	payload_len = recv_buf->hdr.data_size;
602 
603 	if (payload_len > HVS_MTU_SIZE)
604 		return -EIO;
605 
606 	if (payload_len == 0)
607 		hvs->vsk->peer_shutdown |= SEND_SHUTDOWN;
608 
609 	hvs->recv_data_len = payload_len;
610 	hvs->recv_data_off = 0;
611 
612 	return 0;
613 }
614 
615 static ssize_t hvs_stream_dequeue(struct vsock_sock *vsk, struct msghdr *msg,
616 				  size_t len, int flags)
617 {
618 	struct hvsock *hvs = vsk->trans;
619 	bool need_refill = !hvs->recv_desc;
620 	struct hvs_recv_buf *recv_buf;
621 	u32 to_read;
622 	int ret;
623 
624 	if (flags & MSG_PEEK)
625 		return -EOPNOTSUPP;
626 
627 	if (need_refill) {
628 		hvs->recv_desc = hv_pkt_iter_first(hvs->chan);
629 		ret = hvs_update_recv_data(hvs);
630 		if (ret)
631 			return ret;
632 	}
633 
634 	recv_buf = (struct hvs_recv_buf *)(hvs->recv_desc + 1);
635 	to_read = min_t(u32, len, hvs->recv_data_len);
636 	ret = memcpy_to_msg(msg, recv_buf->data + hvs->recv_data_off, to_read);
637 	if (ret != 0)
638 		return ret;
639 
640 	hvs->recv_data_len -= to_read;
641 	if (hvs->recv_data_len == 0) {
642 		hvs->recv_desc = hv_pkt_iter_next(hvs->chan, hvs->recv_desc);
643 		if (hvs->recv_desc) {
644 			ret = hvs_update_recv_data(hvs);
645 			if (ret)
646 				return ret;
647 		}
648 	} else {
649 		hvs->recv_data_off += to_read;
650 	}
651 
652 	return to_read;
653 }
654 
655 static ssize_t hvs_stream_enqueue(struct vsock_sock *vsk, struct msghdr *msg,
656 				  size_t len)
657 {
658 	struct hvsock *hvs = vsk->trans;
659 	struct vmbus_channel *chan = hvs->chan;
660 	struct hvs_send_buf *send_buf;
661 	ssize_t to_write, max_writable;
662 	ssize_t ret = 0;
663 	ssize_t bytes_written = 0;
664 
665 	BUILD_BUG_ON(sizeof(*send_buf) != PAGE_SIZE_4K);
666 
667 	send_buf = kmalloc(sizeof(*send_buf), GFP_KERNEL);
668 	if (!send_buf)
669 		return -ENOMEM;
670 
671 	/* Reader(s) could be draining data from the channel as we write.
672 	 * Maximize bandwidth, by iterating until the channel is found to be
673 	 * full.
674 	 */
675 	while (len) {
676 		max_writable = hvs_channel_writable_bytes(chan);
677 		if (!max_writable)
678 			break;
679 		to_write = min_t(ssize_t, len, max_writable);
680 		to_write = min_t(ssize_t, to_write, HVS_SEND_BUF_SIZE);
681 		/* memcpy_from_msg is safe for loop as it advances the offsets
682 		 * within the message iterator.
683 		 */
684 		ret = memcpy_from_msg(send_buf->data, msg, to_write);
685 		if (ret < 0)
686 			goto out;
687 
688 		ret = hvs_send_data(hvs->chan, send_buf, to_write);
689 		if (ret < 0)
690 			goto out;
691 
692 		bytes_written += to_write;
693 		len -= to_write;
694 	}
695 out:
696 	/* If any data has been sent, return that */
697 	if (bytes_written)
698 		ret = bytes_written;
699 	kfree(send_buf);
700 	return ret;
701 }
702 
703 static s64 hvs_stream_has_data(struct vsock_sock *vsk)
704 {
705 	struct hvsock *hvs = vsk->trans;
706 	s64 ret;
707 
708 	if (hvs->recv_data_len > 0)
709 		return 1;
710 
711 	switch (hvs_channel_readable_payload(hvs->chan)) {
712 	case 1:
713 		ret = 1;
714 		break;
715 	case 0:
716 		vsk->peer_shutdown |= SEND_SHUTDOWN;
717 		ret = 0;
718 		break;
719 	default: /* -1 */
720 		ret = 0;
721 		break;
722 	}
723 
724 	return ret;
725 }
726 
727 static s64 hvs_stream_has_space(struct vsock_sock *vsk)
728 {
729 	struct hvsock *hvs = vsk->trans;
730 
731 	return hvs_channel_writable_bytes(hvs->chan);
732 }
733 
734 static u64 hvs_stream_rcvhiwat(struct vsock_sock *vsk)
735 {
736 	return HVS_MTU_SIZE + 1;
737 }
738 
739 static bool hvs_stream_is_active(struct vsock_sock *vsk)
740 {
741 	struct hvsock *hvs = vsk->trans;
742 
743 	return hvs->chan != NULL;
744 }
745 
746 static bool hvs_stream_allow(u32 cid, u32 port)
747 {
748 	/* The host's port range [MIN_HOST_EPHEMERAL_PORT, 0xFFFFFFFF) is
749 	 * reserved as ephemeral ports, which are used as the host's ports
750 	 * when the host initiates connections.
751 	 *
752 	 * Perform this check in the guest so an immediate error is produced
753 	 * instead of a timeout.
754 	 */
755 	if (port > MAX_HOST_LISTEN_PORT)
756 		return false;
757 
758 	if (cid == VMADDR_CID_HOST)
759 		return true;
760 
761 	return false;
762 }
763 
764 static
765 int hvs_notify_poll_in(struct vsock_sock *vsk, size_t target, bool *readable)
766 {
767 	struct hvsock *hvs = vsk->trans;
768 
769 	*readable = hvs_channel_readable(hvs->chan);
770 	return 0;
771 }
772 
773 static
774 int hvs_notify_poll_out(struct vsock_sock *vsk, size_t target, bool *writable)
775 {
776 	*writable = hvs_stream_has_space(vsk) > 0;
777 
778 	return 0;
779 }
780 
781 static
782 int hvs_notify_recv_init(struct vsock_sock *vsk, size_t target,
783 			 struct vsock_transport_recv_notify_data *d)
784 {
785 	return 0;
786 }
787 
788 static
789 int hvs_notify_recv_pre_block(struct vsock_sock *vsk, size_t target,
790 			      struct vsock_transport_recv_notify_data *d)
791 {
792 	return 0;
793 }
794 
795 static
796 int hvs_notify_recv_pre_dequeue(struct vsock_sock *vsk, size_t target,
797 				struct vsock_transport_recv_notify_data *d)
798 {
799 	return 0;
800 }
801 
802 static
803 int hvs_notify_recv_post_dequeue(struct vsock_sock *vsk, size_t target,
804 				 ssize_t copied, bool data_read,
805 				 struct vsock_transport_recv_notify_data *d)
806 {
807 	return 0;
808 }
809 
810 static
811 int hvs_notify_send_init(struct vsock_sock *vsk,
812 			 struct vsock_transport_send_notify_data *d)
813 {
814 	return 0;
815 }
816 
817 static
818 int hvs_notify_send_pre_block(struct vsock_sock *vsk,
819 			      struct vsock_transport_send_notify_data *d)
820 {
821 	return 0;
822 }
823 
824 static
825 int hvs_notify_send_pre_enqueue(struct vsock_sock *vsk,
826 				struct vsock_transport_send_notify_data *d)
827 {
828 	return 0;
829 }
830 
831 static
832 int hvs_notify_send_post_enqueue(struct vsock_sock *vsk, ssize_t written,
833 				 struct vsock_transport_send_notify_data *d)
834 {
835 	return 0;
836 }
837 
838 static void hvs_set_buffer_size(struct vsock_sock *vsk, u64 val)
839 {
840 	/* Ignored. */
841 }
842 
843 static void hvs_set_min_buffer_size(struct vsock_sock *vsk, u64 val)
844 {
845 	/* Ignored. */
846 }
847 
848 static void hvs_set_max_buffer_size(struct vsock_sock *vsk, u64 val)
849 {
850 	/* Ignored. */
851 }
852 
853 static u64 hvs_get_buffer_size(struct vsock_sock *vsk)
854 {
855 	return -ENOPROTOOPT;
856 }
857 
858 static u64 hvs_get_min_buffer_size(struct vsock_sock *vsk)
859 {
860 	return -ENOPROTOOPT;
861 }
862 
863 static u64 hvs_get_max_buffer_size(struct vsock_sock *vsk)
864 {
865 	return -ENOPROTOOPT;
866 }
867 
868 static struct vsock_transport hvs_transport = {
869 	.get_local_cid            = hvs_get_local_cid,
870 
871 	.init                     = hvs_sock_init,
872 	.destruct                 = hvs_destruct,
873 	.release                  = hvs_release,
874 	.connect                  = hvs_connect,
875 	.shutdown                 = hvs_shutdown,
876 
877 	.dgram_bind               = hvs_dgram_bind,
878 	.dgram_dequeue            = hvs_dgram_dequeue,
879 	.dgram_enqueue            = hvs_dgram_enqueue,
880 	.dgram_allow              = hvs_dgram_allow,
881 
882 	.stream_dequeue           = hvs_stream_dequeue,
883 	.stream_enqueue           = hvs_stream_enqueue,
884 	.stream_has_data          = hvs_stream_has_data,
885 	.stream_has_space         = hvs_stream_has_space,
886 	.stream_rcvhiwat          = hvs_stream_rcvhiwat,
887 	.stream_is_active         = hvs_stream_is_active,
888 	.stream_allow             = hvs_stream_allow,
889 
890 	.notify_poll_in           = hvs_notify_poll_in,
891 	.notify_poll_out          = hvs_notify_poll_out,
892 	.notify_recv_init         = hvs_notify_recv_init,
893 	.notify_recv_pre_block    = hvs_notify_recv_pre_block,
894 	.notify_recv_pre_dequeue  = hvs_notify_recv_pre_dequeue,
895 	.notify_recv_post_dequeue = hvs_notify_recv_post_dequeue,
896 	.notify_send_init         = hvs_notify_send_init,
897 	.notify_send_pre_block    = hvs_notify_send_pre_block,
898 	.notify_send_pre_enqueue  = hvs_notify_send_pre_enqueue,
899 	.notify_send_post_enqueue = hvs_notify_send_post_enqueue,
900 
901 	.set_buffer_size          = hvs_set_buffer_size,
902 	.set_min_buffer_size      = hvs_set_min_buffer_size,
903 	.set_max_buffer_size      = hvs_set_max_buffer_size,
904 	.get_buffer_size          = hvs_get_buffer_size,
905 	.get_min_buffer_size      = hvs_get_min_buffer_size,
906 	.get_max_buffer_size      = hvs_get_max_buffer_size,
907 };
908 
909 static int hvs_probe(struct hv_device *hdev,
910 		     const struct hv_vmbus_device_id *dev_id)
911 {
912 	struct vmbus_channel *chan = hdev->channel;
913 
914 	hvs_open_connection(chan);
915 
916 	/* Always return success to suppress the unnecessary error message
917 	 * in vmbus_probe(): on error the host will rescind the device in
918 	 * 30 seconds and we can do cleanup at that time in
919 	 * vmbus_onoffer_rescind().
920 	 */
921 	return 0;
922 }
923 
924 static int hvs_remove(struct hv_device *hdev)
925 {
926 	struct vmbus_channel *chan = hdev->channel;
927 
928 	vmbus_close(chan);
929 
930 	return 0;
931 }
932 
933 /* This isn't really used. See vmbus_match() and vmbus_probe() */
934 static const struct hv_vmbus_device_id id_table[] = {
935 	{},
936 };
937 
938 static struct hv_driver hvs_drv = {
939 	.name		= "hv_sock",
940 	.hvsock		= true,
941 	.id_table	= id_table,
942 	.probe		= hvs_probe,
943 	.remove		= hvs_remove,
944 };
945 
946 static int __init hvs_init(void)
947 {
948 	int ret;
949 
950 	if (vmbus_proto_version < VERSION_WIN10)
951 		return -ENODEV;
952 
953 	ret = vmbus_driver_register(&hvs_drv);
954 	if (ret != 0)
955 		return ret;
956 
957 	ret = vsock_core_init(&hvs_transport);
958 	if (ret) {
959 		vmbus_driver_unregister(&hvs_drv);
960 		return ret;
961 	}
962 
963 	return 0;
964 }
965 
966 static void __exit hvs_exit(void)
967 {
968 	vsock_core_exit();
969 	vmbus_driver_unregister(&hvs_drv);
970 }
971 
972 module_init(hvs_init);
973 module_exit(hvs_exit);
974 
975 MODULE_DESCRIPTION("Hyper-V Sockets");
976 MODULE_VERSION("1.0.0");
977 MODULE_LICENSE("GPL");
978 MODULE_ALIAS_NETPROTO(PF_VSOCK);
979