xref: /linux/net/vmw_vsock/virtio_transport_common.c (revision 7f71507851fc7764b36a3221839607d3a45c2025)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * common code for virtio vsock
4  *
5  * Copyright (C) 2013-2015 Red Hat, Inc.
6  * Author: Asias He <asias@redhat.com>
7  *         Stefan Hajnoczi <stefanha@redhat.com>
8  */
9 #include <linux/spinlock.h>
10 #include <linux/module.h>
11 #include <linux/sched/signal.h>
12 #include <linux/ctype.h>
13 #include <linux/list.h>
14 #include <linux/virtio_vsock.h>
15 #include <uapi/linux/vsockmon.h>
16 
17 #include <net/sock.h>
18 #include <net/af_vsock.h>
19 
20 #define CREATE_TRACE_POINTS
21 #include <trace/events/vsock_virtio_transport_common.h>
22 
23 /* How long to wait for graceful shutdown of a connection */
24 #define VSOCK_CLOSE_TIMEOUT (8 * HZ)
25 
26 /* Threshold for detecting small packets to copy */
27 #define GOOD_COPY_LEN  128
28 
29 static const struct virtio_transport *
30 virtio_transport_get_ops(struct vsock_sock *vsk)
31 {
32 	const struct vsock_transport *t = vsock_core_get_transport(vsk);
33 
34 	if (WARN_ON(!t))
35 		return NULL;
36 
37 	return container_of(t, struct virtio_transport, transport);
38 }
39 
40 static bool virtio_transport_can_zcopy(const struct virtio_transport *t_ops,
41 				       struct virtio_vsock_pkt_info *info,
42 				       size_t pkt_len)
43 {
44 	struct iov_iter *iov_iter;
45 
46 	if (!info->msg)
47 		return false;
48 
49 	iov_iter = &info->msg->msg_iter;
50 
51 	if (iov_iter->iov_offset)
52 		return false;
53 
54 	/* We can't send whole iov. */
55 	if (iov_iter->count > pkt_len)
56 		return false;
57 
58 	/* Check that transport can send data in zerocopy mode. */
59 	t_ops = virtio_transport_get_ops(info->vsk);
60 
61 	if (t_ops->can_msgzerocopy) {
62 		int pages_to_send = iov_iter_npages(iov_iter, MAX_SKB_FRAGS);
63 
64 		/* +1 is for packet header. */
65 		return t_ops->can_msgzerocopy(pages_to_send + 1);
66 	}
67 
68 	return true;
69 }
70 
71 static int virtio_transport_init_zcopy_skb(struct vsock_sock *vsk,
72 					   struct sk_buff *skb,
73 					   struct msghdr *msg,
74 					   bool zerocopy)
75 {
76 	struct ubuf_info *uarg;
77 
78 	if (msg->msg_ubuf) {
79 		uarg = msg->msg_ubuf;
80 		net_zcopy_get(uarg);
81 	} else {
82 		struct iov_iter *iter = &msg->msg_iter;
83 		struct ubuf_info_msgzc *uarg_zc;
84 
85 		uarg = msg_zerocopy_realloc(sk_vsock(vsk),
86 					    iter->count,
87 					    NULL);
88 		if (!uarg)
89 			return -1;
90 
91 		uarg_zc = uarg_to_msgzc(uarg);
92 		uarg_zc->zerocopy = zerocopy ? 1 : 0;
93 	}
94 
95 	skb_zcopy_init(skb, uarg);
96 
97 	return 0;
98 }
99 
100 static int virtio_transport_fill_skb(struct sk_buff *skb,
101 				     struct virtio_vsock_pkt_info *info,
102 				     size_t len,
103 				     bool zcopy)
104 {
105 	if (zcopy)
106 		return __zerocopy_sg_from_iter(info->msg, NULL, skb,
107 					       &info->msg->msg_iter,
108 					       len);
109 
110 	return memcpy_from_msg(skb_put(skb, len), info->msg, len);
111 }
112 
113 static void virtio_transport_init_hdr(struct sk_buff *skb,
114 				      struct virtio_vsock_pkt_info *info,
115 				      size_t payload_len,
116 				      u32 src_cid,
117 				      u32 src_port,
118 				      u32 dst_cid,
119 				      u32 dst_port)
120 {
121 	struct virtio_vsock_hdr *hdr;
122 
123 	hdr = virtio_vsock_hdr(skb);
124 	hdr->type	= cpu_to_le16(info->type);
125 	hdr->op		= cpu_to_le16(info->op);
126 	hdr->src_cid	= cpu_to_le64(src_cid);
127 	hdr->dst_cid	= cpu_to_le64(dst_cid);
128 	hdr->src_port	= cpu_to_le32(src_port);
129 	hdr->dst_port	= cpu_to_le32(dst_port);
130 	hdr->flags	= cpu_to_le32(info->flags);
131 	hdr->len	= cpu_to_le32(payload_len);
132 	hdr->buf_alloc	= cpu_to_le32(0);
133 	hdr->fwd_cnt	= cpu_to_le32(0);
134 }
135 
136 static void virtio_transport_copy_nonlinear_skb(const struct sk_buff *skb,
137 						void *dst,
138 						size_t len)
139 {
140 	struct iov_iter iov_iter = { 0 };
141 	struct kvec kvec;
142 	size_t to_copy;
143 
144 	kvec.iov_base = dst;
145 	kvec.iov_len = len;
146 
147 	iov_iter.iter_type = ITER_KVEC;
148 	iov_iter.kvec = &kvec;
149 	iov_iter.nr_segs = 1;
150 
151 	to_copy = min_t(size_t, len, skb->len);
152 
153 	skb_copy_datagram_iter(skb, VIRTIO_VSOCK_SKB_CB(skb)->offset,
154 			       &iov_iter, to_copy);
155 }
156 
157 /* Packet capture */
158 static struct sk_buff *virtio_transport_build_skb(void *opaque)
159 {
160 	struct virtio_vsock_hdr *pkt_hdr;
161 	struct sk_buff *pkt = opaque;
162 	struct af_vsockmon_hdr *hdr;
163 	struct sk_buff *skb;
164 	size_t payload_len;
165 
166 	/* A packet could be split to fit the RX buffer, so we can retrieve
167 	 * the payload length from the header and the buffer pointer taking
168 	 * care of the offset in the original packet.
169 	 */
170 	pkt_hdr = virtio_vsock_hdr(pkt);
171 	payload_len = pkt->len;
172 
173 	skb = alloc_skb(sizeof(*hdr) + sizeof(*pkt_hdr) + payload_len,
174 			GFP_ATOMIC);
175 	if (!skb)
176 		return NULL;
177 
178 	hdr = skb_put(skb, sizeof(*hdr));
179 
180 	/* pkt->hdr is little-endian so no need to byteswap here */
181 	hdr->src_cid = pkt_hdr->src_cid;
182 	hdr->src_port = pkt_hdr->src_port;
183 	hdr->dst_cid = pkt_hdr->dst_cid;
184 	hdr->dst_port = pkt_hdr->dst_port;
185 
186 	hdr->transport = cpu_to_le16(AF_VSOCK_TRANSPORT_VIRTIO);
187 	hdr->len = cpu_to_le16(sizeof(*pkt_hdr));
188 	memset(hdr->reserved, 0, sizeof(hdr->reserved));
189 
190 	switch (le16_to_cpu(pkt_hdr->op)) {
191 	case VIRTIO_VSOCK_OP_REQUEST:
192 	case VIRTIO_VSOCK_OP_RESPONSE:
193 		hdr->op = cpu_to_le16(AF_VSOCK_OP_CONNECT);
194 		break;
195 	case VIRTIO_VSOCK_OP_RST:
196 	case VIRTIO_VSOCK_OP_SHUTDOWN:
197 		hdr->op = cpu_to_le16(AF_VSOCK_OP_DISCONNECT);
198 		break;
199 	case VIRTIO_VSOCK_OP_RW:
200 		hdr->op = cpu_to_le16(AF_VSOCK_OP_PAYLOAD);
201 		break;
202 	case VIRTIO_VSOCK_OP_CREDIT_UPDATE:
203 	case VIRTIO_VSOCK_OP_CREDIT_REQUEST:
204 		hdr->op = cpu_to_le16(AF_VSOCK_OP_CONTROL);
205 		break;
206 	default:
207 		hdr->op = cpu_to_le16(AF_VSOCK_OP_UNKNOWN);
208 		break;
209 	}
210 
211 	skb_put_data(skb, pkt_hdr, sizeof(*pkt_hdr));
212 
213 	if (payload_len) {
214 		if (skb_is_nonlinear(pkt)) {
215 			void *data = skb_put(skb, payload_len);
216 
217 			virtio_transport_copy_nonlinear_skb(pkt, data, payload_len);
218 		} else {
219 			skb_put_data(skb, pkt->data, payload_len);
220 		}
221 	}
222 
223 	return skb;
224 }
225 
226 void virtio_transport_deliver_tap_pkt(struct sk_buff *skb)
227 {
228 	if (virtio_vsock_skb_tap_delivered(skb))
229 		return;
230 
231 	vsock_deliver_tap(virtio_transport_build_skb, skb);
232 	virtio_vsock_skb_set_tap_delivered(skb);
233 }
234 EXPORT_SYMBOL_GPL(virtio_transport_deliver_tap_pkt);
235 
236 static u16 virtio_transport_get_type(struct sock *sk)
237 {
238 	if (sk->sk_type == SOCK_STREAM)
239 		return VIRTIO_VSOCK_TYPE_STREAM;
240 	else
241 		return VIRTIO_VSOCK_TYPE_SEQPACKET;
242 }
243 
244 /* Returns new sk_buff on success, otherwise returns NULL. */
245 static struct sk_buff *virtio_transport_alloc_skb(struct virtio_vsock_pkt_info *info,
246 						  size_t payload_len,
247 						  bool zcopy,
248 						  u32 src_cid,
249 						  u32 src_port,
250 						  u32 dst_cid,
251 						  u32 dst_port)
252 {
253 	struct vsock_sock *vsk;
254 	struct sk_buff *skb;
255 	size_t skb_len;
256 
257 	skb_len = VIRTIO_VSOCK_SKB_HEADROOM;
258 
259 	if (!zcopy)
260 		skb_len += payload_len;
261 
262 	skb = virtio_vsock_alloc_skb(skb_len, GFP_KERNEL);
263 	if (!skb)
264 		return NULL;
265 
266 	virtio_transport_init_hdr(skb, info, payload_len, src_cid, src_port,
267 				  dst_cid, dst_port);
268 
269 	vsk = info->vsk;
270 
271 	/* If 'vsk' != NULL then payload is always present, so we
272 	 * will never call '__zerocopy_sg_from_iter()' below without
273 	 * setting skb owner in 'skb_set_owner_w()'. The only case
274 	 * when 'vsk' == NULL is VIRTIO_VSOCK_OP_RST control message
275 	 * without payload.
276 	 */
277 	WARN_ON_ONCE(!(vsk && (info->msg && payload_len)) && zcopy);
278 
279 	/* Set owner here, because '__zerocopy_sg_from_iter()' uses
280 	 * owner of skb without check to update 'sk_wmem_alloc'.
281 	 */
282 	if (vsk)
283 		skb_set_owner_w(skb, sk_vsock(vsk));
284 
285 	if (info->msg && payload_len > 0) {
286 		int err;
287 
288 		err = virtio_transport_fill_skb(skb, info, payload_len, zcopy);
289 		if (err)
290 			goto out;
291 
292 		if (msg_data_left(info->msg) == 0 &&
293 		    info->type == VIRTIO_VSOCK_TYPE_SEQPACKET) {
294 			struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
295 
296 			hdr->flags |= cpu_to_le32(VIRTIO_VSOCK_SEQ_EOM);
297 
298 			if (info->msg->msg_flags & MSG_EOR)
299 				hdr->flags |= cpu_to_le32(VIRTIO_VSOCK_SEQ_EOR);
300 		}
301 	}
302 
303 	if (info->reply)
304 		virtio_vsock_skb_set_reply(skb);
305 
306 	trace_virtio_transport_alloc_pkt(src_cid, src_port,
307 					 dst_cid, dst_port,
308 					 payload_len,
309 					 info->type,
310 					 info->op,
311 					 info->flags,
312 					 zcopy);
313 
314 	return skb;
315 out:
316 	kfree_skb(skb);
317 	return NULL;
318 }
319 
320 /* This function can only be used on connecting/connected sockets,
321  * since a socket assigned to a transport is required.
322  *
323  * Do not use on listener sockets!
324  */
325 static int virtio_transport_send_pkt_info(struct vsock_sock *vsk,
326 					  struct virtio_vsock_pkt_info *info)
327 {
328 	u32 max_skb_len = VIRTIO_VSOCK_MAX_PKT_BUF_SIZE;
329 	u32 src_cid, src_port, dst_cid, dst_port;
330 	const struct virtio_transport *t_ops;
331 	struct virtio_vsock_sock *vvs;
332 	u32 pkt_len = info->pkt_len;
333 	bool can_zcopy = false;
334 	u32 rest_len;
335 	int ret;
336 
337 	info->type = virtio_transport_get_type(sk_vsock(vsk));
338 
339 	t_ops = virtio_transport_get_ops(vsk);
340 	if (unlikely(!t_ops))
341 		return -EFAULT;
342 
343 	src_cid = t_ops->transport.get_local_cid();
344 	src_port = vsk->local_addr.svm_port;
345 	if (!info->remote_cid) {
346 		dst_cid	= vsk->remote_addr.svm_cid;
347 		dst_port = vsk->remote_addr.svm_port;
348 	} else {
349 		dst_cid = info->remote_cid;
350 		dst_port = info->remote_port;
351 	}
352 
353 	vvs = vsk->trans;
354 
355 	/* virtio_transport_get_credit might return less than pkt_len credit */
356 	pkt_len = virtio_transport_get_credit(vvs, pkt_len);
357 
358 	/* Do not send zero length OP_RW pkt */
359 	if (pkt_len == 0 && info->op == VIRTIO_VSOCK_OP_RW)
360 		return pkt_len;
361 
362 	if (info->msg) {
363 		/* If zerocopy is not enabled by 'setsockopt()', we behave as
364 		 * there is no MSG_ZEROCOPY flag set.
365 		 */
366 		if (!sock_flag(sk_vsock(vsk), SOCK_ZEROCOPY))
367 			info->msg->msg_flags &= ~MSG_ZEROCOPY;
368 
369 		if (info->msg->msg_flags & MSG_ZEROCOPY)
370 			can_zcopy = virtio_transport_can_zcopy(t_ops, info, pkt_len);
371 
372 		if (can_zcopy)
373 			max_skb_len = min_t(u32, VIRTIO_VSOCK_MAX_PKT_BUF_SIZE,
374 					    (MAX_SKB_FRAGS * PAGE_SIZE));
375 	}
376 
377 	rest_len = pkt_len;
378 
379 	do {
380 		struct sk_buff *skb;
381 		size_t skb_len;
382 
383 		skb_len = min(max_skb_len, rest_len);
384 
385 		skb = virtio_transport_alloc_skb(info, skb_len, can_zcopy,
386 						 src_cid, src_port,
387 						 dst_cid, dst_port);
388 		if (!skb) {
389 			ret = -ENOMEM;
390 			break;
391 		}
392 
393 		/* We process buffer part by part, allocating skb on
394 		 * each iteration. If this is last skb for this buffer
395 		 * and MSG_ZEROCOPY mode is in use - we must allocate
396 		 * completion for the current syscall.
397 		 */
398 		if (info->msg && info->msg->msg_flags & MSG_ZEROCOPY &&
399 		    skb_len == rest_len && info->op == VIRTIO_VSOCK_OP_RW) {
400 			if (virtio_transport_init_zcopy_skb(vsk, skb,
401 							    info->msg,
402 							    can_zcopy)) {
403 				kfree_skb(skb);
404 				ret = -ENOMEM;
405 				break;
406 			}
407 		}
408 
409 		virtio_transport_inc_tx_pkt(vvs, skb);
410 
411 		ret = t_ops->send_pkt(skb);
412 		if (ret < 0)
413 			break;
414 
415 		/* Both virtio and vhost 'send_pkt()' returns 'skb_len',
416 		 * but for reliability use 'ret' instead of 'skb_len'.
417 		 * Also if partial send happens (e.g. 'ret' != 'skb_len')
418 		 * somehow, we break this loop, but account such returned
419 		 * value in 'virtio_transport_put_credit()'.
420 		 */
421 		rest_len -= ret;
422 
423 		if (WARN_ONCE(ret != skb_len,
424 			      "'send_pkt()' returns %i, but %zu expected\n",
425 			      ret, skb_len))
426 			break;
427 	} while (rest_len);
428 
429 	virtio_transport_put_credit(vvs, rest_len);
430 
431 	/* Return number of bytes, if any data has been sent. */
432 	if (rest_len != pkt_len)
433 		ret = pkt_len - rest_len;
434 
435 	return ret;
436 }
437 
438 static bool virtio_transport_inc_rx_pkt(struct virtio_vsock_sock *vvs,
439 					u32 len)
440 {
441 	if (vvs->rx_bytes + len > vvs->buf_alloc)
442 		return false;
443 
444 	vvs->rx_bytes += len;
445 	return true;
446 }
447 
448 static void virtio_transport_dec_rx_pkt(struct virtio_vsock_sock *vvs,
449 					u32 len)
450 {
451 	vvs->rx_bytes -= len;
452 	vvs->fwd_cnt += len;
453 }
454 
455 void virtio_transport_inc_tx_pkt(struct virtio_vsock_sock *vvs, struct sk_buff *skb)
456 {
457 	struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
458 
459 	spin_lock_bh(&vvs->rx_lock);
460 	vvs->last_fwd_cnt = vvs->fwd_cnt;
461 	hdr->fwd_cnt = cpu_to_le32(vvs->fwd_cnt);
462 	hdr->buf_alloc = cpu_to_le32(vvs->buf_alloc);
463 	spin_unlock_bh(&vvs->rx_lock);
464 }
465 EXPORT_SYMBOL_GPL(virtio_transport_inc_tx_pkt);
466 
467 void virtio_transport_consume_skb_sent(struct sk_buff *skb, bool consume)
468 {
469 	struct sock *s = skb->sk;
470 
471 	if (s && skb->len) {
472 		struct vsock_sock *vs = vsock_sk(s);
473 		struct virtio_vsock_sock *vvs;
474 
475 		vvs = vs->trans;
476 
477 		spin_lock_bh(&vvs->tx_lock);
478 		vvs->bytes_unsent -= skb->len;
479 		spin_unlock_bh(&vvs->tx_lock);
480 	}
481 
482 	if (consume)
483 		consume_skb(skb);
484 }
485 EXPORT_SYMBOL_GPL(virtio_transport_consume_skb_sent);
486 
487 u32 virtio_transport_get_credit(struct virtio_vsock_sock *vvs, u32 credit)
488 {
489 	u32 ret;
490 
491 	if (!credit)
492 		return 0;
493 
494 	spin_lock_bh(&vvs->tx_lock);
495 	ret = vvs->peer_buf_alloc - (vvs->tx_cnt - vvs->peer_fwd_cnt);
496 	if (ret > credit)
497 		ret = credit;
498 	vvs->tx_cnt += ret;
499 	vvs->bytes_unsent += ret;
500 	spin_unlock_bh(&vvs->tx_lock);
501 
502 	return ret;
503 }
504 EXPORT_SYMBOL_GPL(virtio_transport_get_credit);
505 
506 void virtio_transport_put_credit(struct virtio_vsock_sock *vvs, u32 credit)
507 {
508 	if (!credit)
509 		return;
510 
511 	spin_lock_bh(&vvs->tx_lock);
512 	vvs->tx_cnt -= credit;
513 	vvs->bytes_unsent -= credit;
514 	spin_unlock_bh(&vvs->tx_lock);
515 }
516 EXPORT_SYMBOL_GPL(virtio_transport_put_credit);
517 
518 static int virtio_transport_send_credit_update(struct vsock_sock *vsk)
519 {
520 	struct virtio_vsock_pkt_info info = {
521 		.op = VIRTIO_VSOCK_OP_CREDIT_UPDATE,
522 		.vsk = vsk,
523 	};
524 
525 	return virtio_transport_send_pkt_info(vsk, &info);
526 }
527 
528 static ssize_t
529 virtio_transport_stream_do_peek(struct vsock_sock *vsk,
530 				struct msghdr *msg,
531 				size_t len)
532 {
533 	struct virtio_vsock_sock *vvs = vsk->trans;
534 	struct sk_buff *skb;
535 	size_t total = 0;
536 	int err;
537 
538 	spin_lock_bh(&vvs->rx_lock);
539 
540 	skb_queue_walk(&vvs->rx_queue, skb) {
541 		size_t bytes;
542 
543 		bytes = len - total;
544 		if (bytes > skb->len)
545 			bytes = skb->len;
546 
547 		spin_unlock_bh(&vvs->rx_lock);
548 
549 		/* sk_lock is held by caller so no one else can dequeue.
550 		 * Unlock rx_lock since skb_copy_datagram_iter() may sleep.
551 		 */
552 		err = skb_copy_datagram_iter(skb, VIRTIO_VSOCK_SKB_CB(skb)->offset,
553 					     &msg->msg_iter, bytes);
554 		if (err)
555 			goto out;
556 
557 		total += bytes;
558 
559 		spin_lock_bh(&vvs->rx_lock);
560 
561 		if (total == len)
562 			break;
563 	}
564 
565 	spin_unlock_bh(&vvs->rx_lock);
566 
567 	return total;
568 
569 out:
570 	if (total)
571 		err = total;
572 	return err;
573 }
574 
575 static ssize_t
576 virtio_transport_stream_do_dequeue(struct vsock_sock *vsk,
577 				   struct msghdr *msg,
578 				   size_t len)
579 {
580 	struct virtio_vsock_sock *vvs = vsk->trans;
581 	size_t bytes, total = 0;
582 	struct sk_buff *skb;
583 	u32 fwd_cnt_delta;
584 	bool low_rx_bytes;
585 	int err = -EFAULT;
586 	u32 free_space;
587 
588 	spin_lock_bh(&vvs->rx_lock);
589 
590 	if (WARN_ONCE(skb_queue_empty(&vvs->rx_queue) && vvs->rx_bytes,
591 		      "rx_queue is empty, but rx_bytes is non-zero\n")) {
592 		spin_unlock_bh(&vvs->rx_lock);
593 		return err;
594 	}
595 
596 	while (total < len && !skb_queue_empty(&vvs->rx_queue)) {
597 		skb = skb_peek(&vvs->rx_queue);
598 
599 		bytes = min_t(size_t, len - total,
600 			      skb->len - VIRTIO_VSOCK_SKB_CB(skb)->offset);
601 
602 		/* sk_lock is held by caller so no one else can dequeue.
603 		 * Unlock rx_lock since skb_copy_datagram_iter() may sleep.
604 		 */
605 		spin_unlock_bh(&vvs->rx_lock);
606 
607 		err = skb_copy_datagram_iter(skb,
608 					     VIRTIO_VSOCK_SKB_CB(skb)->offset,
609 					     &msg->msg_iter, bytes);
610 		if (err)
611 			goto out;
612 
613 		spin_lock_bh(&vvs->rx_lock);
614 
615 		total += bytes;
616 
617 		VIRTIO_VSOCK_SKB_CB(skb)->offset += bytes;
618 
619 		if (skb->len == VIRTIO_VSOCK_SKB_CB(skb)->offset) {
620 			u32 pkt_len = le32_to_cpu(virtio_vsock_hdr(skb)->len);
621 
622 			virtio_transport_dec_rx_pkt(vvs, pkt_len);
623 			__skb_unlink(skb, &vvs->rx_queue);
624 			consume_skb(skb);
625 		}
626 	}
627 
628 	fwd_cnt_delta = vvs->fwd_cnt - vvs->last_fwd_cnt;
629 	free_space = vvs->buf_alloc - fwd_cnt_delta;
630 	low_rx_bytes = (vvs->rx_bytes <
631 			sock_rcvlowat(sk_vsock(vsk), 0, INT_MAX));
632 
633 	spin_unlock_bh(&vvs->rx_lock);
634 
635 	/* To reduce the number of credit update messages,
636 	 * don't update credits as long as lots of space is available.
637 	 * Note: the limit chosen here is arbitrary. Setting the limit
638 	 * too high causes extra messages. Too low causes transmitter
639 	 * stalls. As stalls are in theory more expensive than extra
640 	 * messages, we set the limit to a high value. TODO: experiment
641 	 * with different values. Also send credit update message when
642 	 * number of bytes in rx queue is not enough to wake up reader.
643 	 */
644 	if (fwd_cnt_delta &&
645 	    (free_space < VIRTIO_VSOCK_MAX_PKT_BUF_SIZE || low_rx_bytes))
646 		virtio_transport_send_credit_update(vsk);
647 
648 	return total;
649 
650 out:
651 	if (total)
652 		err = total;
653 	return err;
654 }
655 
656 static ssize_t
657 virtio_transport_seqpacket_do_peek(struct vsock_sock *vsk,
658 				   struct msghdr *msg)
659 {
660 	struct virtio_vsock_sock *vvs = vsk->trans;
661 	struct sk_buff *skb;
662 	size_t total, len;
663 
664 	spin_lock_bh(&vvs->rx_lock);
665 
666 	if (!vvs->msg_count) {
667 		spin_unlock_bh(&vvs->rx_lock);
668 		return 0;
669 	}
670 
671 	total = 0;
672 	len = msg_data_left(msg);
673 
674 	skb_queue_walk(&vvs->rx_queue, skb) {
675 		struct virtio_vsock_hdr *hdr;
676 
677 		if (total < len) {
678 			size_t bytes;
679 			int err;
680 
681 			bytes = len - total;
682 			if (bytes > skb->len)
683 				bytes = skb->len;
684 
685 			spin_unlock_bh(&vvs->rx_lock);
686 
687 			/* sk_lock is held by caller so no one else can dequeue.
688 			 * Unlock rx_lock since skb_copy_datagram_iter() may sleep.
689 			 */
690 			err = skb_copy_datagram_iter(skb, VIRTIO_VSOCK_SKB_CB(skb)->offset,
691 						     &msg->msg_iter, bytes);
692 			if (err)
693 				return err;
694 
695 			spin_lock_bh(&vvs->rx_lock);
696 		}
697 
698 		total += skb->len;
699 		hdr = virtio_vsock_hdr(skb);
700 
701 		if (le32_to_cpu(hdr->flags) & VIRTIO_VSOCK_SEQ_EOM) {
702 			if (le32_to_cpu(hdr->flags) & VIRTIO_VSOCK_SEQ_EOR)
703 				msg->msg_flags |= MSG_EOR;
704 
705 			break;
706 		}
707 	}
708 
709 	spin_unlock_bh(&vvs->rx_lock);
710 
711 	return total;
712 }
713 
714 static int virtio_transport_seqpacket_do_dequeue(struct vsock_sock *vsk,
715 						 struct msghdr *msg,
716 						 int flags)
717 {
718 	struct virtio_vsock_sock *vvs = vsk->trans;
719 	int dequeued_len = 0;
720 	size_t user_buf_len = msg_data_left(msg);
721 	bool msg_ready = false;
722 	struct sk_buff *skb;
723 
724 	spin_lock_bh(&vvs->rx_lock);
725 
726 	if (vvs->msg_count == 0) {
727 		spin_unlock_bh(&vvs->rx_lock);
728 		return 0;
729 	}
730 
731 	while (!msg_ready) {
732 		struct virtio_vsock_hdr *hdr;
733 		size_t pkt_len;
734 
735 		skb = __skb_dequeue(&vvs->rx_queue);
736 		if (!skb)
737 			break;
738 		hdr = virtio_vsock_hdr(skb);
739 		pkt_len = (size_t)le32_to_cpu(hdr->len);
740 
741 		if (dequeued_len >= 0) {
742 			size_t bytes_to_copy;
743 
744 			bytes_to_copy = min(user_buf_len, pkt_len);
745 
746 			if (bytes_to_copy) {
747 				int err;
748 
749 				/* sk_lock is held by caller so no one else can dequeue.
750 				 * Unlock rx_lock since skb_copy_datagram_iter() may sleep.
751 				 */
752 				spin_unlock_bh(&vvs->rx_lock);
753 
754 				err = skb_copy_datagram_iter(skb, 0,
755 							     &msg->msg_iter,
756 							     bytes_to_copy);
757 				if (err) {
758 					/* Copy of message failed. Rest of
759 					 * fragments will be freed without copy.
760 					 */
761 					dequeued_len = err;
762 				} else {
763 					user_buf_len -= bytes_to_copy;
764 				}
765 
766 				spin_lock_bh(&vvs->rx_lock);
767 			}
768 
769 			if (dequeued_len >= 0)
770 				dequeued_len += pkt_len;
771 		}
772 
773 		if (le32_to_cpu(hdr->flags) & VIRTIO_VSOCK_SEQ_EOM) {
774 			msg_ready = true;
775 			vvs->msg_count--;
776 
777 			if (le32_to_cpu(hdr->flags) & VIRTIO_VSOCK_SEQ_EOR)
778 				msg->msg_flags |= MSG_EOR;
779 		}
780 
781 		virtio_transport_dec_rx_pkt(vvs, pkt_len);
782 		kfree_skb(skb);
783 	}
784 
785 	spin_unlock_bh(&vvs->rx_lock);
786 
787 	virtio_transport_send_credit_update(vsk);
788 
789 	return dequeued_len;
790 }
791 
792 ssize_t
793 virtio_transport_stream_dequeue(struct vsock_sock *vsk,
794 				struct msghdr *msg,
795 				size_t len, int flags)
796 {
797 	if (flags & MSG_PEEK)
798 		return virtio_transport_stream_do_peek(vsk, msg, len);
799 	else
800 		return virtio_transport_stream_do_dequeue(vsk, msg, len);
801 }
802 EXPORT_SYMBOL_GPL(virtio_transport_stream_dequeue);
803 
804 ssize_t
805 virtio_transport_seqpacket_dequeue(struct vsock_sock *vsk,
806 				   struct msghdr *msg,
807 				   int flags)
808 {
809 	if (flags & MSG_PEEK)
810 		return virtio_transport_seqpacket_do_peek(vsk, msg);
811 	else
812 		return virtio_transport_seqpacket_do_dequeue(vsk, msg, flags);
813 }
814 EXPORT_SYMBOL_GPL(virtio_transport_seqpacket_dequeue);
815 
816 int
817 virtio_transport_seqpacket_enqueue(struct vsock_sock *vsk,
818 				   struct msghdr *msg,
819 				   size_t len)
820 {
821 	struct virtio_vsock_sock *vvs = vsk->trans;
822 
823 	spin_lock_bh(&vvs->tx_lock);
824 
825 	if (len > vvs->peer_buf_alloc) {
826 		spin_unlock_bh(&vvs->tx_lock);
827 		return -EMSGSIZE;
828 	}
829 
830 	spin_unlock_bh(&vvs->tx_lock);
831 
832 	return virtio_transport_stream_enqueue(vsk, msg, len);
833 }
834 EXPORT_SYMBOL_GPL(virtio_transport_seqpacket_enqueue);
835 
836 int
837 virtio_transport_dgram_dequeue(struct vsock_sock *vsk,
838 			       struct msghdr *msg,
839 			       size_t len, int flags)
840 {
841 	return -EOPNOTSUPP;
842 }
843 EXPORT_SYMBOL_GPL(virtio_transport_dgram_dequeue);
844 
845 s64 virtio_transport_stream_has_data(struct vsock_sock *vsk)
846 {
847 	struct virtio_vsock_sock *vvs = vsk->trans;
848 	s64 bytes;
849 
850 	spin_lock_bh(&vvs->rx_lock);
851 	bytes = vvs->rx_bytes;
852 	spin_unlock_bh(&vvs->rx_lock);
853 
854 	return bytes;
855 }
856 EXPORT_SYMBOL_GPL(virtio_transport_stream_has_data);
857 
858 u32 virtio_transport_seqpacket_has_data(struct vsock_sock *vsk)
859 {
860 	struct virtio_vsock_sock *vvs = vsk->trans;
861 	u32 msg_count;
862 
863 	spin_lock_bh(&vvs->rx_lock);
864 	msg_count = vvs->msg_count;
865 	spin_unlock_bh(&vvs->rx_lock);
866 
867 	return msg_count;
868 }
869 EXPORT_SYMBOL_GPL(virtio_transport_seqpacket_has_data);
870 
871 static s64 virtio_transport_has_space(struct vsock_sock *vsk)
872 {
873 	struct virtio_vsock_sock *vvs = vsk->trans;
874 	s64 bytes;
875 
876 	bytes = (s64)vvs->peer_buf_alloc - (vvs->tx_cnt - vvs->peer_fwd_cnt);
877 	if (bytes < 0)
878 		bytes = 0;
879 
880 	return bytes;
881 }
882 
883 s64 virtio_transport_stream_has_space(struct vsock_sock *vsk)
884 {
885 	struct virtio_vsock_sock *vvs = vsk->trans;
886 	s64 bytes;
887 
888 	spin_lock_bh(&vvs->tx_lock);
889 	bytes = virtio_transport_has_space(vsk);
890 	spin_unlock_bh(&vvs->tx_lock);
891 
892 	return bytes;
893 }
894 EXPORT_SYMBOL_GPL(virtio_transport_stream_has_space);
895 
896 int virtio_transport_do_socket_init(struct vsock_sock *vsk,
897 				    struct vsock_sock *psk)
898 {
899 	struct virtio_vsock_sock *vvs;
900 
901 	vvs = kzalloc(sizeof(*vvs), GFP_KERNEL);
902 	if (!vvs)
903 		return -ENOMEM;
904 
905 	vsk->trans = vvs;
906 	vvs->vsk = vsk;
907 	if (psk && psk->trans) {
908 		struct virtio_vsock_sock *ptrans = psk->trans;
909 
910 		vvs->peer_buf_alloc = ptrans->peer_buf_alloc;
911 	}
912 
913 	if (vsk->buffer_size > VIRTIO_VSOCK_MAX_BUF_SIZE)
914 		vsk->buffer_size = VIRTIO_VSOCK_MAX_BUF_SIZE;
915 
916 	vvs->buf_alloc = vsk->buffer_size;
917 
918 	spin_lock_init(&vvs->rx_lock);
919 	spin_lock_init(&vvs->tx_lock);
920 	skb_queue_head_init(&vvs->rx_queue);
921 
922 	return 0;
923 }
924 EXPORT_SYMBOL_GPL(virtio_transport_do_socket_init);
925 
926 /* sk_lock held by the caller */
927 void virtio_transport_notify_buffer_size(struct vsock_sock *vsk, u64 *val)
928 {
929 	struct virtio_vsock_sock *vvs = vsk->trans;
930 
931 	if (*val > VIRTIO_VSOCK_MAX_BUF_SIZE)
932 		*val = VIRTIO_VSOCK_MAX_BUF_SIZE;
933 
934 	vvs->buf_alloc = *val;
935 
936 	virtio_transport_send_credit_update(vsk);
937 }
938 EXPORT_SYMBOL_GPL(virtio_transport_notify_buffer_size);
939 
940 int
941 virtio_transport_notify_poll_in(struct vsock_sock *vsk,
942 				size_t target,
943 				bool *data_ready_now)
944 {
945 	*data_ready_now = vsock_stream_has_data(vsk) >= target;
946 
947 	return 0;
948 }
949 EXPORT_SYMBOL_GPL(virtio_transport_notify_poll_in);
950 
951 int
952 virtio_transport_notify_poll_out(struct vsock_sock *vsk,
953 				 size_t target,
954 				 bool *space_avail_now)
955 {
956 	s64 free_space;
957 
958 	free_space = vsock_stream_has_space(vsk);
959 	if (free_space > 0)
960 		*space_avail_now = true;
961 	else if (free_space == 0)
962 		*space_avail_now = false;
963 
964 	return 0;
965 }
966 EXPORT_SYMBOL_GPL(virtio_transport_notify_poll_out);
967 
968 int virtio_transport_notify_recv_init(struct vsock_sock *vsk,
969 	size_t target, struct vsock_transport_recv_notify_data *data)
970 {
971 	return 0;
972 }
973 EXPORT_SYMBOL_GPL(virtio_transport_notify_recv_init);
974 
975 int virtio_transport_notify_recv_pre_block(struct vsock_sock *vsk,
976 	size_t target, struct vsock_transport_recv_notify_data *data)
977 {
978 	return 0;
979 }
980 EXPORT_SYMBOL_GPL(virtio_transport_notify_recv_pre_block);
981 
982 int virtio_transport_notify_recv_pre_dequeue(struct vsock_sock *vsk,
983 	size_t target, struct vsock_transport_recv_notify_data *data)
984 {
985 	return 0;
986 }
987 EXPORT_SYMBOL_GPL(virtio_transport_notify_recv_pre_dequeue);
988 
989 int virtio_transport_notify_recv_post_dequeue(struct vsock_sock *vsk,
990 	size_t target, ssize_t copied, bool data_read,
991 	struct vsock_transport_recv_notify_data *data)
992 {
993 	return 0;
994 }
995 EXPORT_SYMBOL_GPL(virtio_transport_notify_recv_post_dequeue);
996 
997 int virtio_transport_notify_send_init(struct vsock_sock *vsk,
998 	struct vsock_transport_send_notify_data *data)
999 {
1000 	return 0;
1001 }
1002 EXPORT_SYMBOL_GPL(virtio_transport_notify_send_init);
1003 
1004 int virtio_transport_notify_send_pre_block(struct vsock_sock *vsk,
1005 	struct vsock_transport_send_notify_data *data)
1006 {
1007 	return 0;
1008 }
1009 EXPORT_SYMBOL_GPL(virtio_transport_notify_send_pre_block);
1010 
1011 int virtio_transport_notify_send_pre_enqueue(struct vsock_sock *vsk,
1012 	struct vsock_transport_send_notify_data *data)
1013 {
1014 	return 0;
1015 }
1016 EXPORT_SYMBOL_GPL(virtio_transport_notify_send_pre_enqueue);
1017 
1018 int virtio_transport_notify_send_post_enqueue(struct vsock_sock *vsk,
1019 	ssize_t written, struct vsock_transport_send_notify_data *data)
1020 {
1021 	return 0;
1022 }
1023 EXPORT_SYMBOL_GPL(virtio_transport_notify_send_post_enqueue);
1024 
1025 u64 virtio_transport_stream_rcvhiwat(struct vsock_sock *vsk)
1026 {
1027 	return vsk->buffer_size;
1028 }
1029 EXPORT_SYMBOL_GPL(virtio_transport_stream_rcvhiwat);
1030 
1031 bool virtio_transport_stream_is_active(struct vsock_sock *vsk)
1032 {
1033 	return true;
1034 }
1035 EXPORT_SYMBOL_GPL(virtio_transport_stream_is_active);
1036 
1037 bool virtio_transport_stream_allow(u32 cid, u32 port)
1038 {
1039 	return true;
1040 }
1041 EXPORT_SYMBOL_GPL(virtio_transport_stream_allow);
1042 
1043 int virtio_transport_dgram_bind(struct vsock_sock *vsk,
1044 				struct sockaddr_vm *addr)
1045 {
1046 	return -EOPNOTSUPP;
1047 }
1048 EXPORT_SYMBOL_GPL(virtio_transport_dgram_bind);
1049 
1050 bool virtio_transport_dgram_allow(u32 cid, u32 port)
1051 {
1052 	return false;
1053 }
1054 EXPORT_SYMBOL_GPL(virtio_transport_dgram_allow);
1055 
1056 int virtio_transport_connect(struct vsock_sock *vsk)
1057 {
1058 	struct virtio_vsock_pkt_info info = {
1059 		.op = VIRTIO_VSOCK_OP_REQUEST,
1060 		.vsk = vsk,
1061 	};
1062 
1063 	return virtio_transport_send_pkt_info(vsk, &info);
1064 }
1065 EXPORT_SYMBOL_GPL(virtio_transport_connect);
1066 
1067 int virtio_transport_shutdown(struct vsock_sock *vsk, int mode)
1068 {
1069 	struct virtio_vsock_pkt_info info = {
1070 		.op = VIRTIO_VSOCK_OP_SHUTDOWN,
1071 		.flags = (mode & RCV_SHUTDOWN ?
1072 			  VIRTIO_VSOCK_SHUTDOWN_RCV : 0) |
1073 			 (mode & SEND_SHUTDOWN ?
1074 			  VIRTIO_VSOCK_SHUTDOWN_SEND : 0),
1075 		.vsk = vsk,
1076 	};
1077 
1078 	return virtio_transport_send_pkt_info(vsk, &info);
1079 }
1080 EXPORT_SYMBOL_GPL(virtio_transport_shutdown);
1081 
1082 int
1083 virtio_transport_dgram_enqueue(struct vsock_sock *vsk,
1084 			       struct sockaddr_vm *remote_addr,
1085 			       struct msghdr *msg,
1086 			       size_t dgram_len)
1087 {
1088 	return -EOPNOTSUPP;
1089 }
1090 EXPORT_SYMBOL_GPL(virtio_transport_dgram_enqueue);
1091 
1092 ssize_t
1093 virtio_transport_stream_enqueue(struct vsock_sock *vsk,
1094 				struct msghdr *msg,
1095 				size_t len)
1096 {
1097 	struct virtio_vsock_pkt_info info = {
1098 		.op = VIRTIO_VSOCK_OP_RW,
1099 		.msg = msg,
1100 		.pkt_len = len,
1101 		.vsk = vsk,
1102 	};
1103 
1104 	return virtio_transport_send_pkt_info(vsk, &info);
1105 }
1106 EXPORT_SYMBOL_GPL(virtio_transport_stream_enqueue);
1107 
1108 void virtio_transport_destruct(struct vsock_sock *vsk)
1109 {
1110 	struct virtio_vsock_sock *vvs = vsk->trans;
1111 
1112 	kfree(vvs);
1113 	vsk->trans = NULL;
1114 }
1115 EXPORT_SYMBOL_GPL(virtio_transport_destruct);
1116 
1117 ssize_t virtio_transport_unsent_bytes(struct vsock_sock *vsk)
1118 {
1119 	struct virtio_vsock_sock *vvs = vsk->trans;
1120 	size_t ret;
1121 
1122 	spin_lock_bh(&vvs->tx_lock);
1123 	ret = vvs->bytes_unsent;
1124 	spin_unlock_bh(&vvs->tx_lock);
1125 
1126 	return ret;
1127 }
1128 EXPORT_SYMBOL_GPL(virtio_transport_unsent_bytes);
1129 
1130 static int virtio_transport_reset(struct vsock_sock *vsk,
1131 				  struct sk_buff *skb)
1132 {
1133 	struct virtio_vsock_pkt_info info = {
1134 		.op = VIRTIO_VSOCK_OP_RST,
1135 		.reply = !!skb,
1136 		.vsk = vsk,
1137 	};
1138 
1139 	/* Send RST only if the original pkt is not a RST pkt */
1140 	if (skb && le16_to_cpu(virtio_vsock_hdr(skb)->op) == VIRTIO_VSOCK_OP_RST)
1141 		return 0;
1142 
1143 	return virtio_transport_send_pkt_info(vsk, &info);
1144 }
1145 
1146 /* Normally packets are associated with a socket.  There may be no socket if an
1147  * attempt was made to connect to a socket that does not exist.
1148  */
1149 static int virtio_transport_reset_no_sock(const struct virtio_transport *t,
1150 					  struct sk_buff *skb)
1151 {
1152 	struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
1153 	struct virtio_vsock_pkt_info info = {
1154 		.op = VIRTIO_VSOCK_OP_RST,
1155 		.type = le16_to_cpu(hdr->type),
1156 		.reply = true,
1157 	};
1158 	struct sk_buff *reply;
1159 
1160 	/* Send RST only if the original pkt is not a RST pkt */
1161 	if (le16_to_cpu(hdr->op) == VIRTIO_VSOCK_OP_RST)
1162 		return 0;
1163 
1164 	if (!t)
1165 		return -ENOTCONN;
1166 
1167 	reply = virtio_transport_alloc_skb(&info, 0, false,
1168 					   le64_to_cpu(hdr->dst_cid),
1169 					   le32_to_cpu(hdr->dst_port),
1170 					   le64_to_cpu(hdr->src_cid),
1171 					   le32_to_cpu(hdr->src_port));
1172 	if (!reply)
1173 		return -ENOMEM;
1174 
1175 	return t->send_pkt(reply);
1176 }
1177 
1178 /* This function should be called with sk_lock held and SOCK_DONE set */
1179 static void virtio_transport_remove_sock(struct vsock_sock *vsk)
1180 {
1181 	struct virtio_vsock_sock *vvs = vsk->trans;
1182 
1183 	/* We don't need to take rx_lock, as the socket is closing and we are
1184 	 * removing it.
1185 	 */
1186 	__skb_queue_purge(&vvs->rx_queue);
1187 	vsock_remove_sock(vsk);
1188 }
1189 
1190 static void virtio_transport_wait_close(struct sock *sk, long timeout)
1191 {
1192 	if (timeout) {
1193 		DEFINE_WAIT_FUNC(wait, woken_wake_function);
1194 
1195 		add_wait_queue(sk_sleep(sk), &wait);
1196 
1197 		do {
1198 			if (sk_wait_event(sk, &timeout,
1199 					  sock_flag(sk, SOCK_DONE), &wait))
1200 				break;
1201 		} while (!signal_pending(current) && timeout);
1202 
1203 		remove_wait_queue(sk_sleep(sk), &wait);
1204 	}
1205 }
1206 
1207 static void virtio_transport_do_close(struct vsock_sock *vsk,
1208 				      bool cancel_timeout)
1209 {
1210 	struct sock *sk = sk_vsock(vsk);
1211 
1212 	sock_set_flag(sk, SOCK_DONE);
1213 	vsk->peer_shutdown = SHUTDOWN_MASK;
1214 	if (vsock_stream_has_data(vsk) <= 0)
1215 		sk->sk_state = TCP_CLOSING;
1216 	sk->sk_state_change(sk);
1217 
1218 	if (vsk->close_work_scheduled &&
1219 	    (!cancel_timeout || cancel_delayed_work(&vsk->close_work))) {
1220 		vsk->close_work_scheduled = false;
1221 
1222 		virtio_transport_remove_sock(vsk);
1223 
1224 		/* Release refcnt obtained when we scheduled the timeout */
1225 		sock_put(sk);
1226 	}
1227 }
1228 
1229 static void virtio_transport_close_timeout(struct work_struct *work)
1230 {
1231 	struct vsock_sock *vsk =
1232 		container_of(work, struct vsock_sock, close_work.work);
1233 	struct sock *sk = sk_vsock(vsk);
1234 
1235 	sock_hold(sk);
1236 	lock_sock(sk);
1237 
1238 	if (!sock_flag(sk, SOCK_DONE)) {
1239 		(void)virtio_transport_reset(vsk, NULL);
1240 
1241 		virtio_transport_do_close(vsk, false);
1242 	}
1243 
1244 	vsk->close_work_scheduled = false;
1245 
1246 	release_sock(sk);
1247 	sock_put(sk);
1248 }
1249 
1250 /* User context, vsk->sk is locked */
1251 static bool virtio_transport_close(struct vsock_sock *vsk)
1252 {
1253 	struct sock *sk = &vsk->sk;
1254 
1255 	if (!(sk->sk_state == TCP_ESTABLISHED ||
1256 	      sk->sk_state == TCP_CLOSING))
1257 		return true;
1258 
1259 	/* Already received SHUTDOWN from peer, reply with RST */
1260 	if ((vsk->peer_shutdown & SHUTDOWN_MASK) == SHUTDOWN_MASK) {
1261 		(void)virtio_transport_reset(vsk, NULL);
1262 		return true;
1263 	}
1264 
1265 	if ((sk->sk_shutdown & SHUTDOWN_MASK) != SHUTDOWN_MASK)
1266 		(void)virtio_transport_shutdown(vsk, SHUTDOWN_MASK);
1267 
1268 	if (sock_flag(sk, SOCK_LINGER) && !(current->flags & PF_EXITING))
1269 		virtio_transport_wait_close(sk, sk->sk_lingertime);
1270 
1271 	if (sock_flag(sk, SOCK_DONE)) {
1272 		return true;
1273 	}
1274 
1275 	sock_hold(sk);
1276 	INIT_DELAYED_WORK(&vsk->close_work,
1277 			  virtio_transport_close_timeout);
1278 	vsk->close_work_scheduled = true;
1279 	schedule_delayed_work(&vsk->close_work, VSOCK_CLOSE_TIMEOUT);
1280 	return false;
1281 }
1282 
1283 void virtio_transport_release(struct vsock_sock *vsk)
1284 {
1285 	struct sock *sk = &vsk->sk;
1286 	bool remove_sock = true;
1287 
1288 	if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET)
1289 		remove_sock = virtio_transport_close(vsk);
1290 
1291 	if (remove_sock) {
1292 		sock_set_flag(sk, SOCK_DONE);
1293 		virtio_transport_remove_sock(vsk);
1294 	}
1295 }
1296 EXPORT_SYMBOL_GPL(virtio_transport_release);
1297 
1298 static int
1299 virtio_transport_recv_connecting(struct sock *sk,
1300 				 struct sk_buff *skb)
1301 {
1302 	struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
1303 	struct vsock_sock *vsk = vsock_sk(sk);
1304 	int skerr;
1305 	int err;
1306 
1307 	switch (le16_to_cpu(hdr->op)) {
1308 	case VIRTIO_VSOCK_OP_RESPONSE:
1309 		sk->sk_state = TCP_ESTABLISHED;
1310 		sk->sk_socket->state = SS_CONNECTED;
1311 		vsock_insert_connected(vsk);
1312 		sk->sk_state_change(sk);
1313 		break;
1314 	case VIRTIO_VSOCK_OP_INVALID:
1315 		break;
1316 	case VIRTIO_VSOCK_OP_RST:
1317 		skerr = ECONNRESET;
1318 		err = 0;
1319 		goto destroy;
1320 	default:
1321 		skerr = EPROTO;
1322 		err = -EINVAL;
1323 		goto destroy;
1324 	}
1325 	return 0;
1326 
1327 destroy:
1328 	virtio_transport_reset(vsk, skb);
1329 	sk->sk_state = TCP_CLOSE;
1330 	sk->sk_err = skerr;
1331 	sk_error_report(sk);
1332 	return err;
1333 }
1334 
1335 static void
1336 virtio_transport_recv_enqueue(struct vsock_sock *vsk,
1337 			      struct sk_buff *skb)
1338 {
1339 	struct virtio_vsock_sock *vvs = vsk->trans;
1340 	bool can_enqueue, free_pkt = false;
1341 	struct virtio_vsock_hdr *hdr;
1342 	u32 len;
1343 
1344 	hdr = virtio_vsock_hdr(skb);
1345 	len = le32_to_cpu(hdr->len);
1346 
1347 	spin_lock_bh(&vvs->rx_lock);
1348 
1349 	can_enqueue = virtio_transport_inc_rx_pkt(vvs, len);
1350 	if (!can_enqueue) {
1351 		free_pkt = true;
1352 		goto out;
1353 	}
1354 
1355 	if (le32_to_cpu(hdr->flags) & VIRTIO_VSOCK_SEQ_EOM)
1356 		vvs->msg_count++;
1357 
1358 	/* Try to copy small packets into the buffer of last packet queued,
1359 	 * to avoid wasting memory queueing the entire buffer with a small
1360 	 * payload.
1361 	 */
1362 	if (len <= GOOD_COPY_LEN && !skb_queue_empty(&vvs->rx_queue)) {
1363 		struct virtio_vsock_hdr *last_hdr;
1364 		struct sk_buff *last_skb;
1365 
1366 		last_skb = skb_peek_tail(&vvs->rx_queue);
1367 		last_hdr = virtio_vsock_hdr(last_skb);
1368 
1369 		/* If there is space in the last packet queued, we copy the
1370 		 * new packet in its buffer. We avoid this if the last packet
1371 		 * queued has VIRTIO_VSOCK_SEQ_EOM set, because this is
1372 		 * delimiter of SEQPACKET message, so 'pkt' is the first packet
1373 		 * of a new message.
1374 		 */
1375 		if (skb->len < skb_tailroom(last_skb) &&
1376 		    !(le32_to_cpu(last_hdr->flags) & VIRTIO_VSOCK_SEQ_EOM)) {
1377 			memcpy(skb_put(last_skb, skb->len), skb->data, skb->len);
1378 			free_pkt = true;
1379 			last_hdr->flags |= hdr->flags;
1380 			le32_add_cpu(&last_hdr->len, len);
1381 			goto out;
1382 		}
1383 	}
1384 
1385 	__skb_queue_tail(&vvs->rx_queue, skb);
1386 
1387 out:
1388 	spin_unlock_bh(&vvs->rx_lock);
1389 	if (free_pkt)
1390 		kfree_skb(skb);
1391 }
1392 
1393 static int
1394 virtio_transport_recv_connected(struct sock *sk,
1395 				struct sk_buff *skb)
1396 {
1397 	struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
1398 	struct vsock_sock *vsk = vsock_sk(sk);
1399 	int err = 0;
1400 
1401 	switch (le16_to_cpu(hdr->op)) {
1402 	case VIRTIO_VSOCK_OP_RW:
1403 		virtio_transport_recv_enqueue(vsk, skb);
1404 		vsock_data_ready(sk);
1405 		return err;
1406 	case VIRTIO_VSOCK_OP_CREDIT_REQUEST:
1407 		virtio_transport_send_credit_update(vsk);
1408 		break;
1409 	case VIRTIO_VSOCK_OP_CREDIT_UPDATE:
1410 		sk->sk_write_space(sk);
1411 		break;
1412 	case VIRTIO_VSOCK_OP_SHUTDOWN:
1413 		if (le32_to_cpu(hdr->flags) & VIRTIO_VSOCK_SHUTDOWN_RCV)
1414 			vsk->peer_shutdown |= RCV_SHUTDOWN;
1415 		if (le32_to_cpu(hdr->flags) & VIRTIO_VSOCK_SHUTDOWN_SEND)
1416 			vsk->peer_shutdown |= SEND_SHUTDOWN;
1417 		if (vsk->peer_shutdown == SHUTDOWN_MASK) {
1418 			if (vsock_stream_has_data(vsk) <= 0 && !sock_flag(sk, SOCK_DONE)) {
1419 				(void)virtio_transport_reset(vsk, NULL);
1420 				virtio_transport_do_close(vsk, true);
1421 			}
1422 			/* Remove this socket anyway because the remote peer sent
1423 			 * the shutdown. This way a new connection will succeed
1424 			 * if the remote peer uses the same source port,
1425 			 * even if the old socket is still unreleased, but now disconnected.
1426 			 */
1427 			vsock_remove_sock(vsk);
1428 		}
1429 		if (le32_to_cpu(virtio_vsock_hdr(skb)->flags))
1430 			sk->sk_state_change(sk);
1431 		break;
1432 	case VIRTIO_VSOCK_OP_RST:
1433 		virtio_transport_do_close(vsk, true);
1434 		break;
1435 	default:
1436 		err = -EINVAL;
1437 		break;
1438 	}
1439 
1440 	kfree_skb(skb);
1441 	return err;
1442 }
1443 
1444 static void
1445 virtio_transport_recv_disconnecting(struct sock *sk,
1446 				    struct sk_buff *skb)
1447 {
1448 	struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
1449 	struct vsock_sock *vsk = vsock_sk(sk);
1450 
1451 	if (le16_to_cpu(hdr->op) == VIRTIO_VSOCK_OP_RST)
1452 		virtio_transport_do_close(vsk, true);
1453 }
1454 
1455 static int
1456 virtio_transport_send_response(struct vsock_sock *vsk,
1457 			       struct sk_buff *skb)
1458 {
1459 	struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
1460 	struct virtio_vsock_pkt_info info = {
1461 		.op = VIRTIO_VSOCK_OP_RESPONSE,
1462 		.remote_cid = le64_to_cpu(hdr->src_cid),
1463 		.remote_port = le32_to_cpu(hdr->src_port),
1464 		.reply = true,
1465 		.vsk = vsk,
1466 	};
1467 
1468 	return virtio_transport_send_pkt_info(vsk, &info);
1469 }
1470 
1471 static bool virtio_transport_space_update(struct sock *sk,
1472 					  struct sk_buff *skb)
1473 {
1474 	struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
1475 	struct vsock_sock *vsk = vsock_sk(sk);
1476 	struct virtio_vsock_sock *vvs = vsk->trans;
1477 	bool space_available;
1478 
1479 	/* Listener sockets are not associated with any transport, so we are
1480 	 * not able to take the state to see if there is space available in the
1481 	 * remote peer, but since they are only used to receive requests, we
1482 	 * can assume that there is always space available in the other peer.
1483 	 */
1484 	if (!vvs)
1485 		return true;
1486 
1487 	/* buf_alloc and fwd_cnt is always included in the hdr */
1488 	spin_lock_bh(&vvs->tx_lock);
1489 	vvs->peer_buf_alloc = le32_to_cpu(hdr->buf_alloc);
1490 	vvs->peer_fwd_cnt = le32_to_cpu(hdr->fwd_cnt);
1491 	space_available = virtio_transport_has_space(vsk);
1492 	spin_unlock_bh(&vvs->tx_lock);
1493 	return space_available;
1494 }
1495 
1496 /* Handle server socket */
1497 static int
1498 virtio_transport_recv_listen(struct sock *sk, struct sk_buff *skb,
1499 			     struct virtio_transport *t)
1500 {
1501 	struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
1502 	struct vsock_sock *vsk = vsock_sk(sk);
1503 	struct vsock_sock *vchild;
1504 	struct sock *child;
1505 	int ret;
1506 
1507 	if (le16_to_cpu(hdr->op) != VIRTIO_VSOCK_OP_REQUEST) {
1508 		virtio_transport_reset_no_sock(t, skb);
1509 		return -EINVAL;
1510 	}
1511 
1512 	if (sk_acceptq_is_full(sk)) {
1513 		virtio_transport_reset_no_sock(t, skb);
1514 		return -ENOMEM;
1515 	}
1516 
1517 	/* __vsock_release() might have already flushed accept_queue.
1518 	 * Subsequent enqueues would lead to a memory leak.
1519 	 */
1520 	if (sk->sk_shutdown == SHUTDOWN_MASK) {
1521 		virtio_transport_reset_no_sock(t, skb);
1522 		return -ESHUTDOWN;
1523 	}
1524 
1525 	child = vsock_create_connected(sk);
1526 	if (!child) {
1527 		virtio_transport_reset_no_sock(t, skb);
1528 		return -ENOMEM;
1529 	}
1530 
1531 	sk_acceptq_added(sk);
1532 
1533 	lock_sock_nested(child, SINGLE_DEPTH_NESTING);
1534 
1535 	child->sk_state = TCP_ESTABLISHED;
1536 
1537 	vchild = vsock_sk(child);
1538 	vsock_addr_init(&vchild->local_addr, le64_to_cpu(hdr->dst_cid),
1539 			le32_to_cpu(hdr->dst_port));
1540 	vsock_addr_init(&vchild->remote_addr, le64_to_cpu(hdr->src_cid),
1541 			le32_to_cpu(hdr->src_port));
1542 
1543 	ret = vsock_assign_transport(vchild, vsk);
1544 	/* Transport assigned (looking at remote_addr) must be the same
1545 	 * where we received the request.
1546 	 */
1547 	if (ret || vchild->transport != &t->transport) {
1548 		release_sock(child);
1549 		virtio_transport_reset_no_sock(t, skb);
1550 		sock_put(child);
1551 		return ret;
1552 	}
1553 
1554 	if (virtio_transport_space_update(child, skb))
1555 		child->sk_write_space(child);
1556 
1557 	vsock_insert_connected(vchild);
1558 	vsock_enqueue_accept(sk, child);
1559 	virtio_transport_send_response(vchild, skb);
1560 
1561 	release_sock(child);
1562 
1563 	sk->sk_data_ready(sk);
1564 	return 0;
1565 }
1566 
1567 static bool virtio_transport_valid_type(u16 type)
1568 {
1569 	return (type == VIRTIO_VSOCK_TYPE_STREAM) ||
1570 	       (type == VIRTIO_VSOCK_TYPE_SEQPACKET);
1571 }
1572 
1573 /* We are under the virtio-vsock's vsock->rx_lock or vhost-vsock's vq->mutex
1574  * lock.
1575  */
1576 void virtio_transport_recv_pkt(struct virtio_transport *t,
1577 			       struct sk_buff *skb)
1578 {
1579 	struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
1580 	struct sockaddr_vm src, dst;
1581 	struct vsock_sock *vsk;
1582 	struct sock *sk;
1583 	bool space_available;
1584 
1585 	vsock_addr_init(&src, le64_to_cpu(hdr->src_cid),
1586 			le32_to_cpu(hdr->src_port));
1587 	vsock_addr_init(&dst, le64_to_cpu(hdr->dst_cid),
1588 			le32_to_cpu(hdr->dst_port));
1589 
1590 	trace_virtio_transport_recv_pkt(src.svm_cid, src.svm_port,
1591 					dst.svm_cid, dst.svm_port,
1592 					le32_to_cpu(hdr->len),
1593 					le16_to_cpu(hdr->type),
1594 					le16_to_cpu(hdr->op),
1595 					le32_to_cpu(hdr->flags),
1596 					le32_to_cpu(hdr->buf_alloc),
1597 					le32_to_cpu(hdr->fwd_cnt));
1598 
1599 	if (!virtio_transport_valid_type(le16_to_cpu(hdr->type))) {
1600 		(void)virtio_transport_reset_no_sock(t, skb);
1601 		goto free_pkt;
1602 	}
1603 
1604 	/* The socket must be in connected or bound table
1605 	 * otherwise send reset back
1606 	 */
1607 	sk = vsock_find_connected_socket(&src, &dst);
1608 	if (!sk) {
1609 		sk = vsock_find_bound_socket(&dst);
1610 		if (!sk) {
1611 			(void)virtio_transport_reset_no_sock(t, skb);
1612 			goto free_pkt;
1613 		}
1614 	}
1615 
1616 	if (virtio_transport_get_type(sk) != le16_to_cpu(hdr->type)) {
1617 		(void)virtio_transport_reset_no_sock(t, skb);
1618 		sock_put(sk);
1619 		goto free_pkt;
1620 	}
1621 
1622 	if (!skb_set_owner_sk_safe(skb, sk)) {
1623 		WARN_ONCE(1, "receiving vsock socket has sk_refcnt == 0\n");
1624 		goto free_pkt;
1625 	}
1626 
1627 	vsk = vsock_sk(sk);
1628 
1629 	lock_sock(sk);
1630 
1631 	/* Check if sk has been closed before lock_sock */
1632 	if (sock_flag(sk, SOCK_DONE)) {
1633 		(void)virtio_transport_reset_no_sock(t, skb);
1634 		release_sock(sk);
1635 		sock_put(sk);
1636 		goto free_pkt;
1637 	}
1638 
1639 	space_available = virtio_transport_space_update(sk, skb);
1640 
1641 	/* Update CID in case it has changed after a transport reset event */
1642 	if (vsk->local_addr.svm_cid != VMADDR_CID_ANY)
1643 		vsk->local_addr.svm_cid = dst.svm_cid;
1644 
1645 	if (space_available)
1646 		sk->sk_write_space(sk);
1647 
1648 	switch (sk->sk_state) {
1649 	case TCP_LISTEN:
1650 		virtio_transport_recv_listen(sk, skb, t);
1651 		kfree_skb(skb);
1652 		break;
1653 	case TCP_SYN_SENT:
1654 		virtio_transport_recv_connecting(sk, skb);
1655 		kfree_skb(skb);
1656 		break;
1657 	case TCP_ESTABLISHED:
1658 		virtio_transport_recv_connected(sk, skb);
1659 		break;
1660 	case TCP_CLOSING:
1661 		virtio_transport_recv_disconnecting(sk, skb);
1662 		kfree_skb(skb);
1663 		break;
1664 	default:
1665 		(void)virtio_transport_reset_no_sock(t, skb);
1666 		kfree_skb(skb);
1667 		break;
1668 	}
1669 
1670 	release_sock(sk);
1671 
1672 	/* Release refcnt obtained when we fetched this socket out of the
1673 	 * bound or connected list.
1674 	 */
1675 	sock_put(sk);
1676 	return;
1677 
1678 free_pkt:
1679 	kfree_skb(skb);
1680 }
1681 EXPORT_SYMBOL_GPL(virtio_transport_recv_pkt);
1682 
1683 /* Remove skbs found in a queue that have a vsk that matches.
1684  *
1685  * Each skb is freed.
1686  *
1687  * Returns the count of skbs that were reply packets.
1688  */
1689 int virtio_transport_purge_skbs(void *vsk, struct sk_buff_head *queue)
1690 {
1691 	struct sk_buff_head freeme;
1692 	struct sk_buff *skb, *tmp;
1693 	int cnt = 0;
1694 
1695 	skb_queue_head_init(&freeme);
1696 
1697 	spin_lock_bh(&queue->lock);
1698 	skb_queue_walk_safe(queue, skb, tmp) {
1699 		if (vsock_sk(skb->sk) != vsk)
1700 			continue;
1701 
1702 		__skb_unlink(skb, queue);
1703 		__skb_queue_tail(&freeme, skb);
1704 
1705 		if (virtio_vsock_skb_reply(skb))
1706 			cnt++;
1707 	}
1708 	spin_unlock_bh(&queue->lock);
1709 
1710 	__skb_queue_purge(&freeme);
1711 
1712 	return cnt;
1713 }
1714 EXPORT_SYMBOL_GPL(virtio_transport_purge_skbs);
1715 
1716 int virtio_transport_read_skb(struct vsock_sock *vsk, skb_read_actor_t recv_actor)
1717 {
1718 	struct virtio_vsock_sock *vvs = vsk->trans;
1719 	struct sock *sk = sk_vsock(vsk);
1720 	struct virtio_vsock_hdr *hdr;
1721 	struct sk_buff *skb;
1722 	int off = 0;
1723 	int err;
1724 
1725 	spin_lock_bh(&vvs->rx_lock);
1726 	/* Use __skb_recv_datagram() for race-free handling of the receive. It
1727 	 * works for types other than dgrams.
1728 	 */
1729 	skb = __skb_recv_datagram(sk, &vvs->rx_queue, MSG_DONTWAIT, &off, &err);
1730 	if (!skb) {
1731 		spin_unlock_bh(&vvs->rx_lock);
1732 		return err;
1733 	}
1734 
1735 	hdr = virtio_vsock_hdr(skb);
1736 	if (le32_to_cpu(hdr->flags) & VIRTIO_VSOCK_SEQ_EOM)
1737 		vvs->msg_count--;
1738 
1739 	virtio_transport_dec_rx_pkt(vvs, le32_to_cpu(hdr->len));
1740 	spin_unlock_bh(&vvs->rx_lock);
1741 
1742 	virtio_transport_send_credit_update(vsk);
1743 
1744 	return recv_actor(sk, skb);
1745 }
1746 EXPORT_SYMBOL_GPL(virtio_transport_read_skb);
1747 
1748 int virtio_transport_notify_set_rcvlowat(struct vsock_sock *vsk, int val)
1749 {
1750 	struct virtio_vsock_sock *vvs = vsk->trans;
1751 	bool send_update;
1752 
1753 	spin_lock_bh(&vvs->rx_lock);
1754 
1755 	/* If number of available bytes is less than new SO_RCVLOWAT value,
1756 	 * kick sender to send more data, because sender may sleep in its
1757 	 * 'send()' syscall waiting for enough space at our side. Also
1758 	 * don't send credit update when peer already knows actual value -
1759 	 * such transmission will be useless.
1760 	 */
1761 	send_update = (vvs->rx_bytes < val) &&
1762 		      (vvs->fwd_cnt != vvs->last_fwd_cnt);
1763 
1764 	spin_unlock_bh(&vvs->rx_lock);
1765 
1766 	if (send_update) {
1767 		int err;
1768 
1769 		err = virtio_transport_send_credit_update(vsk);
1770 		if (err < 0)
1771 			return err;
1772 	}
1773 
1774 	return 0;
1775 }
1776 EXPORT_SYMBOL_GPL(virtio_transport_notify_set_rcvlowat);
1777 
1778 MODULE_LICENSE("GPL v2");
1779 MODULE_AUTHOR("Asias He");
1780 MODULE_DESCRIPTION("common code for virtio vsock");
1781