xref: /linux/net/vmw_vsock/af_vsock.c (revision 0c7c237b1c35011ef0b8d30c1d5c20bc6ae7b69b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * VMware vSockets Driver
4  *
5  * Copyright (C) 2007-2013 VMware, Inc. All rights reserved.
6  */
7 
8 /* Implementation notes:
9  *
10  * - There are two kinds of sockets: those created by user action (such as
11  * calling socket(2)) and those created by incoming connection request packets.
12  *
13  * - There are two "global" tables, one for bound sockets (sockets that have
14  * specified an address that they are responsible for) and one for connected
15  * sockets (sockets that have established a connection with another socket).
16  * These tables are "global" in that all sockets on the system are placed
17  * within them. - Note, though, that the bound table contains an extra entry
18  * for a list of unbound sockets and SOCK_DGRAM sockets will always remain in
19  * that list. The bound table is used solely for lookup of sockets when packets
20  * are received and that's not necessary for SOCK_DGRAM sockets since we create
21  * a datagram handle for each and need not perform a lookup.  Keeping SOCK_DGRAM
22  * sockets out of the bound hash buckets will reduce the chance of collisions
23  * when looking for SOCK_STREAM sockets and prevents us from having to check the
24  * socket type in the hash table lookups.
25  *
26  * - Sockets created by user action will either be "client" sockets that
27  * initiate a connection or "server" sockets that listen for connections; we do
28  * not support simultaneous connects (two "client" sockets connecting).
29  *
30  * - "Server" sockets are referred to as listener sockets throughout this
31  * implementation because they are in the TCP_LISTEN state.  When a
32  * connection request is received (the second kind of socket mentioned above),
33  * we create a new socket and refer to it as a pending socket.  These pending
34  * sockets are placed on the pending connection list of the listener socket.
35  * When future packets are received for the address the listener socket is
36  * bound to, we check if the source of the packet is from one that has an
37  * existing pending connection.  If it does, we process the packet for the
38  * pending socket.  When that socket reaches the connected state, it is removed
39  * from the listener socket's pending list and enqueued in the listener
40  * socket's accept queue.  Callers of accept(2) will accept connected sockets
41  * from the listener socket's accept queue.  If the socket cannot be accepted
42  * for some reason then it is marked rejected.  Once the connection is
43  * accepted, it is owned by the user process and the responsibility for cleanup
44  * falls with that user process.
45  *
46  * - It is possible that these pending sockets will never reach the connected
47  * state; in fact, we may never receive another packet after the connection
48  * request.  Because of this, we must schedule a cleanup function to run in the
49  * future, after some amount of time passes where a connection should have been
50  * established.  This function ensures that the socket is off all lists so it
51  * cannot be retrieved, then drops all references to the socket so it is cleaned
52  * up (sock_put() -> sk_free() -> our sk_destruct implementation).  Note this
53  * function will also cleanup rejected sockets, those that reach the connected
54  * state but leave it before they have been accepted.
55  *
56  * - Lock ordering for pending or accept queue sockets is:
57  *
58  *     lock_sock(listener);
59  *     lock_sock_nested(pending, SINGLE_DEPTH_NESTING);
60  *
61  * Using explicit nested locking keeps lockdep happy since normally only one
62  * lock of a given class may be taken at a time.
63  *
64  * - Sockets created by user action will be cleaned up when the user process
65  * calls close(2), causing our release implementation to be called. Our release
66  * implementation will perform some cleanup then drop the last reference so our
67  * sk_destruct implementation is invoked.  Our sk_destruct implementation will
68  * perform additional cleanup that's common for both types of sockets.
69  *
70  * - A socket's reference count is what ensures that the structure won't be
71  * freed.  Each entry in a list (such as the "global" bound and connected tables
72  * and the listener socket's pending list and connected queue) ensures a
73  * reference.  When we defer work until process context and pass a socket as our
74  * argument, we must ensure the reference count is increased to ensure the
75  * socket isn't freed before the function is run; the deferred function will
76  * then drop the reference.
77  *
78  * - sk->sk_state uses the TCP state constants because they are widely used by
79  * other address families and exposed to userspace tools like ss(8):
80  *
81  *   TCP_CLOSE - unconnected
82  *   TCP_SYN_SENT - connecting
83  *   TCP_ESTABLISHED - connected
84  *   TCP_CLOSING - disconnecting
85  *   TCP_LISTEN - listening
86  */
87 
88 #include <linux/compat.h>
89 #include <linux/types.h>
90 #include <linux/bitops.h>
91 #include <linux/cred.h>
92 #include <linux/init.h>
93 #include <linux/io.h>
94 #include <linux/kernel.h>
95 #include <linux/sched/signal.h>
96 #include <linux/kmod.h>
97 #include <linux/list.h>
98 #include <linux/miscdevice.h>
99 #include <linux/module.h>
100 #include <linux/mutex.h>
101 #include <linux/net.h>
102 #include <linux/poll.h>
103 #include <linux/random.h>
104 #include <linux/skbuff.h>
105 #include <linux/smp.h>
106 #include <linux/socket.h>
107 #include <linux/stddef.h>
108 #include <linux/unistd.h>
109 #include <linux/wait.h>
110 #include <linux/workqueue.h>
111 #include <net/sock.h>
112 #include <net/af_vsock.h>
113 
114 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr);
115 static void vsock_sk_destruct(struct sock *sk);
116 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb);
117 
118 /* Protocol family. */
119 struct proto vsock_proto = {
120 	.name = "AF_VSOCK",
121 	.owner = THIS_MODULE,
122 	.obj_size = sizeof(struct vsock_sock),
123 #ifdef CONFIG_BPF_SYSCALL
124 	.psock_update_sk_prot = vsock_bpf_update_proto,
125 #endif
126 };
127 
128 /* The default peer timeout indicates how long we will wait for a peer response
129  * to a control message.
130  */
131 #define VSOCK_DEFAULT_CONNECT_TIMEOUT (2 * HZ)
132 
133 #define VSOCK_DEFAULT_BUFFER_SIZE     (1024 * 256)
134 #define VSOCK_DEFAULT_BUFFER_MAX_SIZE (1024 * 256)
135 #define VSOCK_DEFAULT_BUFFER_MIN_SIZE 128
136 
137 /* Transport used for host->guest communication */
138 static const struct vsock_transport *transport_h2g;
139 /* Transport used for guest->host communication */
140 static const struct vsock_transport *transport_g2h;
141 /* Transport used for DGRAM communication */
142 static const struct vsock_transport *transport_dgram;
143 /* Transport used for local communication */
144 static const struct vsock_transport *transport_local;
145 static DEFINE_MUTEX(vsock_register_mutex);
146 
147 /**** UTILS ****/
148 
149 /* Each bound VSocket is stored in the bind hash table and each connected
150  * VSocket is stored in the connected hash table.
151  *
152  * Unbound sockets are all put on the same list attached to the end of the hash
153  * table (vsock_unbound_sockets).  Bound sockets are added to the hash table in
154  * the bucket that their local address hashes to (vsock_bound_sockets(addr)
155  * represents the list that addr hashes to).
156  *
157  * Specifically, we initialize the vsock_bind_table array to a size of
158  * VSOCK_HASH_SIZE + 1 so that vsock_bind_table[0] through
159  * vsock_bind_table[VSOCK_HASH_SIZE - 1] are for bound sockets and
160  * vsock_bind_table[VSOCK_HASH_SIZE] is for unbound sockets.  The hash function
161  * mods with VSOCK_HASH_SIZE to ensure this.
162  */
163 #define MAX_PORT_RETRIES        24
164 
165 #define VSOCK_HASH(addr)        ((addr)->svm_port % VSOCK_HASH_SIZE)
166 #define vsock_bound_sockets(addr) (&vsock_bind_table[VSOCK_HASH(addr)])
167 #define vsock_unbound_sockets     (&vsock_bind_table[VSOCK_HASH_SIZE])
168 
169 /* XXX This can probably be implemented in a better way. */
170 #define VSOCK_CONN_HASH(src, dst)				\
171 	(((src)->svm_cid ^ (dst)->svm_port) % VSOCK_HASH_SIZE)
172 #define vsock_connected_sockets(src, dst)		\
173 	(&vsock_connected_table[VSOCK_CONN_HASH(src, dst)])
174 #define vsock_connected_sockets_vsk(vsk)				\
175 	vsock_connected_sockets(&(vsk)->remote_addr, &(vsk)->local_addr)
176 
177 struct list_head vsock_bind_table[VSOCK_HASH_SIZE + 1];
178 EXPORT_SYMBOL_GPL(vsock_bind_table);
179 struct list_head vsock_connected_table[VSOCK_HASH_SIZE];
180 EXPORT_SYMBOL_GPL(vsock_connected_table);
181 DEFINE_SPINLOCK(vsock_table_lock);
182 EXPORT_SYMBOL_GPL(vsock_table_lock);
183 
184 /* Autobind this socket to the local address if necessary. */
185 static int vsock_auto_bind(struct vsock_sock *vsk)
186 {
187 	struct sock *sk = sk_vsock(vsk);
188 	struct sockaddr_vm local_addr;
189 
190 	if (vsock_addr_bound(&vsk->local_addr))
191 		return 0;
192 	vsock_addr_init(&local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
193 	return __vsock_bind(sk, &local_addr);
194 }
195 
196 static void vsock_init_tables(void)
197 {
198 	int i;
199 
200 	for (i = 0; i < ARRAY_SIZE(vsock_bind_table); i++)
201 		INIT_LIST_HEAD(&vsock_bind_table[i]);
202 
203 	for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++)
204 		INIT_LIST_HEAD(&vsock_connected_table[i]);
205 }
206 
207 static void __vsock_insert_bound(struct list_head *list,
208 				 struct vsock_sock *vsk)
209 {
210 	sock_hold(&vsk->sk);
211 	list_add(&vsk->bound_table, list);
212 }
213 
214 static void __vsock_insert_connected(struct list_head *list,
215 				     struct vsock_sock *vsk)
216 {
217 	sock_hold(&vsk->sk);
218 	list_add(&vsk->connected_table, list);
219 }
220 
221 static void __vsock_remove_bound(struct vsock_sock *vsk)
222 {
223 	list_del_init(&vsk->bound_table);
224 	sock_put(&vsk->sk);
225 }
226 
227 static void __vsock_remove_connected(struct vsock_sock *vsk)
228 {
229 	list_del_init(&vsk->connected_table);
230 	sock_put(&vsk->sk);
231 }
232 
233 static struct sock *__vsock_find_bound_socket(struct sockaddr_vm *addr)
234 {
235 	struct vsock_sock *vsk;
236 
237 	list_for_each_entry(vsk, vsock_bound_sockets(addr), bound_table) {
238 		if (vsock_addr_equals_addr(addr, &vsk->local_addr))
239 			return sk_vsock(vsk);
240 
241 		if (addr->svm_port == vsk->local_addr.svm_port &&
242 		    (vsk->local_addr.svm_cid == VMADDR_CID_ANY ||
243 		     addr->svm_cid == VMADDR_CID_ANY))
244 			return sk_vsock(vsk);
245 	}
246 
247 	return NULL;
248 }
249 
250 static struct sock *__vsock_find_connected_socket(struct sockaddr_vm *src,
251 						  struct sockaddr_vm *dst)
252 {
253 	struct vsock_sock *vsk;
254 
255 	list_for_each_entry(vsk, vsock_connected_sockets(src, dst),
256 			    connected_table) {
257 		if (vsock_addr_equals_addr(src, &vsk->remote_addr) &&
258 		    dst->svm_port == vsk->local_addr.svm_port) {
259 			return sk_vsock(vsk);
260 		}
261 	}
262 
263 	return NULL;
264 }
265 
266 static void vsock_insert_unbound(struct vsock_sock *vsk)
267 {
268 	spin_lock_bh(&vsock_table_lock);
269 	__vsock_insert_bound(vsock_unbound_sockets, vsk);
270 	spin_unlock_bh(&vsock_table_lock);
271 }
272 
273 void vsock_insert_connected(struct vsock_sock *vsk)
274 {
275 	struct list_head *list = vsock_connected_sockets(
276 		&vsk->remote_addr, &vsk->local_addr);
277 
278 	spin_lock_bh(&vsock_table_lock);
279 	__vsock_insert_connected(list, vsk);
280 	spin_unlock_bh(&vsock_table_lock);
281 }
282 EXPORT_SYMBOL_GPL(vsock_insert_connected);
283 
284 void vsock_remove_bound(struct vsock_sock *vsk)
285 {
286 	spin_lock_bh(&vsock_table_lock);
287 	if (__vsock_in_bound_table(vsk))
288 		__vsock_remove_bound(vsk);
289 	spin_unlock_bh(&vsock_table_lock);
290 }
291 EXPORT_SYMBOL_GPL(vsock_remove_bound);
292 
293 void vsock_remove_connected(struct vsock_sock *vsk)
294 {
295 	spin_lock_bh(&vsock_table_lock);
296 	if (__vsock_in_connected_table(vsk))
297 		__vsock_remove_connected(vsk);
298 	spin_unlock_bh(&vsock_table_lock);
299 }
300 EXPORT_SYMBOL_GPL(vsock_remove_connected);
301 
302 struct sock *vsock_find_bound_socket(struct sockaddr_vm *addr)
303 {
304 	struct sock *sk;
305 
306 	spin_lock_bh(&vsock_table_lock);
307 	sk = __vsock_find_bound_socket(addr);
308 	if (sk)
309 		sock_hold(sk);
310 
311 	spin_unlock_bh(&vsock_table_lock);
312 
313 	return sk;
314 }
315 EXPORT_SYMBOL_GPL(vsock_find_bound_socket);
316 
317 struct sock *vsock_find_connected_socket(struct sockaddr_vm *src,
318 					 struct sockaddr_vm *dst)
319 {
320 	struct sock *sk;
321 
322 	spin_lock_bh(&vsock_table_lock);
323 	sk = __vsock_find_connected_socket(src, dst);
324 	if (sk)
325 		sock_hold(sk);
326 
327 	spin_unlock_bh(&vsock_table_lock);
328 
329 	return sk;
330 }
331 EXPORT_SYMBOL_GPL(vsock_find_connected_socket);
332 
333 void vsock_remove_sock(struct vsock_sock *vsk)
334 {
335 	vsock_remove_bound(vsk);
336 	vsock_remove_connected(vsk);
337 }
338 EXPORT_SYMBOL_GPL(vsock_remove_sock);
339 
340 void vsock_for_each_connected_socket(struct vsock_transport *transport,
341 				     void (*fn)(struct sock *sk))
342 {
343 	int i;
344 
345 	spin_lock_bh(&vsock_table_lock);
346 
347 	for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++) {
348 		struct vsock_sock *vsk;
349 		list_for_each_entry(vsk, &vsock_connected_table[i],
350 				    connected_table) {
351 			if (vsk->transport != transport)
352 				continue;
353 
354 			fn(sk_vsock(vsk));
355 		}
356 	}
357 
358 	spin_unlock_bh(&vsock_table_lock);
359 }
360 EXPORT_SYMBOL_GPL(vsock_for_each_connected_socket);
361 
362 void vsock_add_pending(struct sock *listener, struct sock *pending)
363 {
364 	struct vsock_sock *vlistener;
365 	struct vsock_sock *vpending;
366 
367 	vlistener = vsock_sk(listener);
368 	vpending = vsock_sk(pending);
369 
370 	sock_hold(pending);
371 	sock_hold(listener);
372 	list_add_tail(&vpending->pending_links, &vlistener->pending_links);
373 }
374 EXPORT_SYMBOL_GPL(vsock_add_pending);
375 
376 void vsock_remove_pending(struct sock *listener, struct sock *pending)
377 {
378 	struct vsock_sock *vpending = vsock_sk(pending);
379 
380 	list_del_init(&vpending->pending_links);
381 	sock_put(listener);
382 	sock_put(pending);
383 }
384 EXPORT_SYMBOL_GPL(vsock_remove_pending);
385 
386 void vsock_enqueue_accept(struct sock *listener, struct sock *connected)
387 {
388 	struct vsock_sock *vlistener;
389 	struct vsock_sock *vconnected;
390 
391 	vlistener = vsock_sk(listener);
392 	vconnected = vsock_sk(connected);
393 
394 	sock_hold(connected);
395 	sock_hold(listener);
396 	list_add_tail(&vconnected->accept_queue, &vlistener->accept_queue);
397 }
398 EXPORT_SYMBOL_GPL(vsock_enqueue_accept);
399 
400 static bool vsock_use_local_transport(unsigned int remote_cid)
401 {
402 	if (!transport_local)
403 		return false;
404 
405 	if (remote_cid == VMADDR_CID_LOCAL)
406 		return true;
407 
408 	if (transport_g2h) {
409 		return remote_cid == transport_g2h->get_local_cid();
410 	} else {
411 		return remote_cid == VMADDR_CID_HOST;
412 	}
413 }
414 
415 static void vsock_deassign_transport(struct vsock_sock *vsk)
416 {
417 	if (!vsk->transport)
418 		return;
419 
420 	vsk->transport->destruct(vsk);
421 	module_put(vsk->transport->module);
422 	vsk->transport = NULL;
423 }
424 
425 /* Assign a transport to a socket and call the .init transport callback.
426  *
427  * Note: for connection oriented socket this must be called when vsk->remote_addr
428  * is set (e.g. during the connect() or when a connection request on a listener
429  * socket is received).
430  * The vsk->remote_addr is used to decide which transport to use:
431  *  - remote CID == VMADDR_CID_LOCAL or g2h->local_cid or VMADDR_CID_HOST if
432  *    g2h is not loaded, will use local transport;
433  *  - remote CID <= VMADDR_CID_HOST or h2g is not loaded or remote flags field
434  *    includes VMADDR_FLAG_TO_HOST flag value, will use guest->host transport;
435  *  - remote CID > VMADDR_CID_HOST will use host->guest transport;
436  */
437 int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)
438 {
439 	const struct vsock_transport *new_transport;
440 	struct sock *sk = sk_vsock(vsk);
441 	unsigned int remote_cid = vsk->remote_addr.svm_cid;
442 	__u8 remote_flags;
443 	int ret;
444 
445 	/* If the packet is coming with the source and destination CIDs higher
446 	 * than VMADDR_CID_HOST, then a vsock channel where all the packets are
447 	 * forwarded to the host should be established. Then the host will
448 	 * need to forward the packets to the guest.
449 	 *
450 	 * The flag is set on the (listen) receive path (psk is not NULL). On
451 	 * the connect path the flag can be set by the user space application.
452 	 */
453 	if (psk && vsk->local_addr.svm_cid > VMADDR_CID_HOST &&
454 	    vsk->remote_addr.svm_cid > VMADDR_CID_HOST)
455 		vsk->remote_addr.svm_flags |= VMADDR_FLAG_TO_HOST;
456 
457 	remote_flags = vsk->remote_addr.svm_flags;
458 
459 	switch (sk->sk_type) {
460 	case SOCK_DGRAM:
461 		new_transport = transport_dgram;
462 		break;
463 	case SOCK_STREAM:
464 	case SOCK_SEQPACKET:
465 		if (vsock_use_local_transport(remote_cid))
466 			new_transport = transport_local;
467 		else if (remote_cid <= VMADDR_CID_HOST || !transport_h2g ||
468 			 (remote_flags & VMADDR_FLAG_TO_HOST))
469 			new_transport = transport_g2h;
470 		else
471 			new_transport = transport_h2g;
472 		break;
473 	default:
474 		return -ESOCKTNOSUPPORT;
475 	}
476 
477 	if (vsk->transport) {
478 		if (vsk->transport == new_transport)
479 			return 0;
480 
481 		/* transport->release() must be called with sock lock acquired.
482 		 * This path can only be taken during vsock_connect(), where we
483 		 * have already held the sock lock. In the other cases, this
484 		 * function is called on a new socket which is not assigned to
485 		 * any transport.
486 		 */
487 		vsk->transport->release(vsk);
488 		vsock_deassign_transport(vsk);
489 	}
490 
491 	/* We increase the module refcnt to prevent the transport unloading
492 	 * while there are open sockets assigned to it.
493 	 */
494 	if (!new_transport || !try_module_get(new_transport->module))
495 		return -ENODEV;
496 
497 	if (sk->sk_type == SOCK_SEQPACKET) {
498 		if (!new_transport->seqpacket_allow ||
499 		    !new_transport->seqpacket_allow(remote_cid)) {
500 			module_put(new_transport->module);
501 			return -ESOCKTNOSUPPORT;
502 		}
503 	}
504 
505 	ret = new_transport->init(vsk, psk);
506 	if (ret) {
507 		module_put(new_transport->module);
508 		return ret;
509 	}
510 
511 	vsk->transport = new_transport;
512 
513 	return 0;
514 }
515 EXPORT_SYMBOL_GPL(vsock_assign_transport);
516 
517 bool vsock_find_cid(unsigned int cid)
518 {
519 	if (transport_g2h && cid == transport_g2h->get_local_cid())
520 		return true;
521 
522 	if (transport_h2g && cid == VMADDR_CID_HOST)
523 		return true;
524 
525 	if (transport_local && cid == VMADDR_CID_LOCAL)
526 		return true;
527 
528 	return false;
529 }
530 EXPORT_SYMBOL_GPL(vsock_find_cid);
531 
532 static struct sock *vsock_dequeue_accept(struct sock *listener)
533 {
534 	struct vsock_sock *vlistener;
535 	struct vsock_sock *vconnected;
536 
537 	vlistener = vsock_sk(listener);
538 
539 	if (list_empty(&vlistener->accept_queue))
540 		return NULL;
541 
542 	vconnected = list_entry(vlistener->accept_queue.next,
543 				struct vsock_sock, accept_queue);
544 
545 	list_del_init(&vconnected->accept_queue);
546 	sock_put(listener);
547 	/* The caller will need a reference on the connected socket so we let
548 	 * it call sock_put().
549 	 */
550 
551 	return sk_vsock(vconnected);
552 }
553 
554 static bool vsock_is_accept_queue_empty(struct sock *sk)
555 {
556 	struct vsock_sock *vsk = vsock_sk(sk);
557 	return list_empty(&vsk->accept_queue);
558 }
559 
560 static bool vsock_is_pending(struct sock *sk)
561 {
562 	struct vsock_sock *vsk = vsock_sk(sk);
563 	return !list_empty(&vsk->pending_links);
564 }
565 
566 static int vsock_send_shutdown(struct sock *sk, int mode)
567 {
568 	struct vsock_sock *vsk = vsock_sk(sk);
569 
570 	if (!vsk->transport)
571 		return -ENODEV;
572 
573 	return vsk->transport->shutdown(vsk, mode);
574 }
575 
576 static void vsock_pending_work(struct work_struct *work)
577 {
578 	struct sock *sk;
579 	struct sock *listener;
580 	struct vsock_sock *vsk;
581 	bool cleanup;
582 
583 	vsk = container_of(work, struct vsock_sock, pending_work.work);
584 	sk = sk_vsock(vsk);
585 	listener = vsk->listener;
586 	cleanup = true;
587 
588 	lock_sock(listener);
589 	lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
590 
591 	if (vsock_is_pending(sk)) {
592 		vsock_remove_pending(listener, sk);
593 
594 		sk_acceptq_removed(listener);
595 	} else if (!vsk->rejected) {
596 		/* We are not on the pending list and accept() did not reject
597 		 * us, so we must have been accepted by our user process.  We
598 		 * just need to drop our references to the sockets and be on
599 		 * our way.
600 		 */
601 		cleanup = false;
602 		goto out;
603 	}
604 
605 	/* We need to remove ourself from the global connected sockets list so
606 	 * incoming packets can't find this socket, and to reduce the reference
607 	 * count.
608 	 */
609 	vsock_remove_connected(vsk);
610 
611 	sk->sk_state = TCP_CLOSE;
612 
613 out:
614 	release_sock(sk);
615 	release_sock(listener);
616 	if (cleanup)
617 		sock_put(sk);
618 
619 	sock_put(sk);
620 	sock_put(listener);
621 }
622 
623 /**** SOCKET OPERATIONS ****/
624 
625 static int __vsock_bind_connectible(struct vsock_sock *vsk,
626 				    struct sockaddr_vm *addr)
627 {
628 	static u32 port;
629 	struct sockaddr_vm new_addr;
630 
631 	if (!port)
632 		port = get_random_u32_above(LAST_RESERVED_PORT);
633 
634 	vsock_addr_init(&new_addr, addr->svm_cid, addr->svm_port);
635 
636 	if (addr->svm_port == VMADDR_PORT_ANY) {
637 		bool found = false;
638 		unsigned int i;
639 
640 		for (i = 0; i < MAX_PORT_RETRIES; i++) {
641 			if (port <= LAST_RESERVED_PORT)
642 				port = LAST_RESERVED_PORT + 1;
643 
644 			new_addr.svm_port = port++;
645 
646 			if (!__vsock_find_bound_socket(&new_addr)) {
647 				found = true;
648 				break;
649 			}
650 		}
651 
652 		if (!found)
653 			return -EADDRNOTAVAIL;
654 	} else {
655 		/* If port is in reserved range, ensure caller
656 		 * has necessary privileges.
657 		 */
658 		if (addr->svm_port <= LAST_RESERVED_PORT &&
659 		    !capable(CAP_NET_BIND_SERVICE)) {
660 			return -EACCES;
661 		}
662 
663 		if (__vsock_find_bound_socket(&new_addr))
664 			return -EADDRINUSE;
665 	}
666 
667 	vsock_addr_init(&vsk->local_addr, new_addr.svm_cid, new_addr.svm_port);
668 
669 	/* Remove connection oriented sockets from the unbound list and add them
670 	 * to the hash table for easy lookup by its address.  The unbound list
671 	 * is simply an extra entry at the end of the hash table, a trick used
672 	 * by AF_UNIX.
673 	 */
674 	__vsock_remove_bound(vsk);
675 	__vsock_insert_bound(vsock_bound_sockets(&vsk->local_addr), vsk);
676 
677 	return 0;
678 }
679 
680 static int __vsock_bind_dgram(struct vsock_sock *vsk,
681 			      struct sockaddr_vm *addr)
682 {
683 	return vsk->transport->dgram_bind(vsk, addr);
684 }
685 
686 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr)
687 {
688 	struct vsock_sock *vsk = vsock_sk(sk);
689 	int retval;
690 
691 	/* First ensure this socket isn't already bound. */
692 	if (vsock_addr_bound(&vsk->local_addr))
693 		return -EINVAL;
694 
695 	/* Now bind to the provided address or select appropriate values if
696 	 * none are provided (VMADDR_CID_ANY and VMADDR_PORT_ANY).  Note that
697 	 * like AF_INET prevents binding to a non-local IP address (in most
698 	 * cases), we only allow binding to a local CID.
699 	 */
700 	if (addr->svm_cid != VMADDR_CID_ANY && !vsock_find_cid(addr->svm_cid))
701 		return -EADDRNOTAVAIL;
702 
703 	switch (sk->sk_socket->type) {
704 	case SOCK_STREAM:
705 	case SOCK_SEQPACKET:
706 		spin_lock_bh(&vsock_table_lock);
707 		retval = __vsock_bind_connectible(vsk, addr);
708 		spin_unlock_bh(&vsock_table_lock);
709 		break;
710 
711 	case SOCK_DGRAM:
712 		retval = __vsock_bind_dgram(vsk, addr);
713 		break;
714 
715 	default:
716 		retval = -EINVAL;
717 		break;
718 	}
719 
720 	return retval;
721 }
722 
723 static void vsock_connect_timeout(struct work_struct *work);
724 
725 static struct sock *__vsock_create(struct net *net,
726 				   struct socket *sock,
727 				   struct sock *parent,
728 				   gfp_t priority,
729 				   unsigned short type,
730 				   int kern)
731 {
732 	struct sock *sk;
733 	struct vsock_sock *psk;
734 	struct vsock_sock *vsk;
735 
736 	sk = sk_alloc(net, AF_VSOCK, priority, &vsock_proto, kern);
737 	if (!sk)
738 		return NULL;
739 
740 	sock_init_data(sock, sk);
741 
742 	/* sk->sk_type is normally set in sock_init_data, but only if sock is
743 	 * non-NULL. We make sure that our sockets always have a type by
744 	 * setting it here if needed.
745 	 */
746 	if (!sock)
747 		sk->sk_type = type;
748 
749 	vsk = vsock_sk(sk);
750 	vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
751 	vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
752 
753 	sk->sk_destruct = vsock_sk_destruct;
754 	sk->sk_backlog_rcv = vsock_queue_rcv_skb;
755 	sock_reset_flag(sk, SOCK_DONE);
756 
757 	INIT_LIST_HEAD(&vsk->bound_table);
758 	INIT_LIST_HEAD(&vsk->connected_table);
759 	vsk->listener = NULL;
760 	INIT_LIST_HEAD(&vsk->pending_links);
761 	INIT_LIST_HEAD(&vsk->accept_queue);
762 	vsk->rejected = false;
763 	vsk->sent_request = false;
764 	vsk->ignore_connecting_rst = false;
765 	vsk->peer_shutdown = 0;
766 	INIT_DELAYED_WORK(&vsk->connect_work, vsock_connect_timeout);
767 	INIT_DELAYED_WORK(&vsk->pending_work, vsock_pending_work);
768 
769 	psk = parent ? vsock_sk(parent) : NULL;
770 	if (parent) {
771 		vsk->trusted = psk->trusted;
772 		vsk->owner = get_cred(psk->owner);
773 		vsk->connect_timeout = psk->connect_timeout;
774 		vsk->buffer_size = psk->buffer_size;
775 		vsk->buffer_min_size = psk->buffer_min_size;
776 		vsk->buffer_max_size = psk->buffer_max_size;
777 		security_sk_clone(parent, sk);
778 	} else {
779 		vsk->trusted = ns_capable_noaudit(&init_user_ns, CAP_NET_ADMIN);
780 		vsk->owner = get_current_cred();
781 		vsk->connect_timeout = VSOCK_DEFAULT_CONNECT_TIMEOUT;
782 		vsk->buffer_size = VSOCK_DEFAULT_BUFFER_SIZE;
783 		vsk->buffer_min_size = VSOCK_DEFAULT_BUFFER_MIN_SIZE;
784 		vsk->buffer_max_size = VSOCK_DEFAULT_BUFFER_MAX_SIZE;
785 	}
786 
787 	return sk;
788 }
789 
790 static bool sock_type_connectible(u16 type)
791 {
792 	return (type == SOCK_STREAM) || (type == SOCK_SEQPACKET);
793 }
794 
795 static void __vsock_release(struct sock *sk, int level)
796 {
797 	if (sk) {
798 		struct sock *pending;
799 		struct vsock_sock *vsk;
800 
801 		vsk = vsock_sk(sk);
802 		pending = NULL;	/* Compiler warning. */
803 
804 		/* When "level" is SINGLE_DEPTH_NESTING, use the nested
805 		 * version to avoid the warning "possible recursive locking
806 		 * detected". When "level" is 0, lock_sock_nested(sk, level)
807 		 * is the same as lock_sock(sk).
808 		 */
809 		lock_sock_nested(sk, level);
810 
811 		if (vsk->transport)
812 			vsk->transport->release(vsk);
813 		else if (sock_type_connectible(sk->sk_type))
814 			vsock_remove_sock(vsk);
815 
816 		sock_orphan(sk);
817 		sk->sk_shutdown = SHUTDOWN_MASK;
818 
819 		skb_queue_purge(&sk->sk_receive_queue);
820 
821 		/* Clean up any sockets that never were accepted. */
822 		while ((pending = vsock_dequeue_accept(sk)) != NULL) {
823 			__vsock_release(pending, SINGLE_DEPTH_NESTING);
824 			sock_put(pending);
825 		}
826 
827 		release_sock(sk);
828 		sock_put(sk);
829 	}
830 }
831 
832 static void vsock_sk_destruct(struct sock *sk)
833 {
834 	struct vsock_sock *vsk = vsock_sk(sk);
835 
836 	vsock_deassign_transport(vsk);
837 
838 	/* When clearing these addresses, there's no need to set the family and
839 	 * possibly register the address family with the kernel.
840 	 */
841 	vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
842 	vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
843 
844 	put_cred(vsk->owner);
845 }
846 
847 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
848 {
849 	int err;
850 
851 	err = sock_queue_rcv_skb(sk, skb);
852 	if (err)
853 		kfree_skb(skb);
854 
855 	return err;
856 }
857 
858 struct sock *vsock_create_connected(struct sock *parent)
859 {
860 	return __vsock_create(sock_net(parent), NULL, parent, GFP_KERNEL,
861 			      parent->sk_type, 0);
862 }
863 EXPORT_SYMBOL_GPL(vsock_create_connected);
864 
865 s64 vsock_stream_has_data(struct vsock_sock *vsk)
866 {
867 	return vsk->transport->stream_has_data(vsk);
868 }
869 EXPORT_SYMBOL_GPL(vsock_stream_has_data);
870 
871 s64 vsock_connectible_has_data(struct vsock_sock *vsk)
872 {
873 	struct sock *sk = sk_vsock(vsk);
874 
875 	if (sk->sk_type == SOCK_SEQPACKET)
876 		return vsk->transport->seqpacket_has_data(vsk);
877 	else
878 		return vsock_stream_has_data(vsk);
879 }
880 EXPORT_SYMBOL_GPL(vsock_connectible_has_data);
881 
882 s64 vsock_stream_has_space(struct vsock_sock *vsk)
883 {
884 	return vsk->transport->stream_has_space(vsk);
885 }
886 EXPORT_SYMBOL_GPL(vsock_stream_has_space);
887 
888 void vsock_data_ready(struct sock *sk)
889 {
890 	struct vsock_sock *vsk = vsock_sk(sk);
891 
892 	if (vsock_stream_has_data(vsk) >= sk->sk_rcvlowat ||
893 	    sock_flag(sk, SOCK_DONE))
894 		sk->sk_data_ready(sk);
895 }
896 EXPORT_SYMBOL_GPL(vsock_data_ready);
897 
898 static int vsock_release(struct socket *sock)
899 {
900 	__vsock_release(sock->sk, 0);
901 	sock->sk = NULL;
902 	sock->state = SS_FREE;
903 
904 	return 0;
905 }
906 
907 static int
908 vsock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
909 {
910 	int err;
911 	struct sock *sk;
912 	struct sockaddr_vm *vm_addr;
913 
914 	sk = sock->sk;
915 
916 	if (vsock_addr_cast(addr, addr_len, &vm_addr) != 0)
917 		return -EINVAL;
918 
919 	lock_sock(sk);
920 	err = __vsock_bind(sk, vm_addr);
921 	release_sock(sk);
922 
923 	return err;
924 }
925 
926 static int vsock_getname(struct socket *sock,
927 			 struct sockaddr *addr, int peer)
928 {
929 	int err;
930 	struct sock *sk;
931 	struct vsock_sock *vsk;
932 	struct sockaddr_vm *vm_addr;
933 
934 	sk = sock->sk;
935 	vsk = vsock_sk(sk);
936 	err = 0;
937 
938 	lock_sock(sk);
939 
940 	if (peer) {
941 		if (sock->state != SS_CONNECTED) {
942 			err = -ENOTCONN;
943 			goto out;
944 		}
945 		vm_addr = &vsk->remote_addr;
946 	} else {
947 		vm_addr = &vsk->local_addr;
948 	}
949 
950 	if (!vm_addr) {
951 		err = -EINVAL;
952 		goto out;
953 	}
954 
955 	/* sys_getsockname() and sys_getpeername() pass us a
956 	 * MAX_SOCK_ADDR-sized buffer and don't set addr_len.  Unfortunately
957 	 * that macro is defined in socket.c instead of .h, so we hardcode its
958 	 * value here.
959 	 */
960 	BUILD_BUG_ON(sizeof(*vm_addr) > 128);
961 	memcpy(addr, vm_addr, sizeof(*vm_addr));
962 	err = sizeof(*vm_addr);
963 
964 out:
965 	release_sock(sk);
966 	return err;
967 }
968 
969 static int vsock_shutdown(struct socket *sock, int mode)
970 {
971 	int err;
972 	struct sock *sk;
973 
974 	/* User level uses SHUT_RD (0) and SHUT_WR (1), but the kernel uses
975 	 * RCV_SHUTDOWN (1) and SEND_SHUTDOWN (2), so we must increment mode
976 	 * here like the other address families do.  Note also that the
977 	 * increment makes SHUT_RDWR (2) into RCV_SHUTDOWN | SEND_SHUTDOWN (3),
978 	 * which is what we want.
979 	 */
980 	mode++;
981 
982 	if ((mode & ~SHUTDOWN_MASK) || !mode)
983 		return -EINVAL;
984 
985 	/* If this is a connection oriented socket and it is not connected then
986 	 * bail out immediately.  If it is a DGRAM socket then we must first
987 	 * kick the socket so that it wakes up from any sleeping calls, for
988 	 * example recv(), and then afterwards return the error.
989 	 */
990 
991 	sk = sock->sk;
992 
993 	lock_sock(sk);
994 	if (sock->state == SS_UNCONNECTED) {
995 		err = -ENOTCONN;
996 		if (sock_type_connectible(sk->sk_type))
997 			goto out;
998 	} else {
999 		sock->state = SS_DISCONNECTING;
1000 		err = 0;
1001 	}
1002 
1003 	/* Receive and send shutdowns are treated alike. */
1004 	mode = mode & (RCV_SHUTDOWN | SEND_SHUTDOWN);
1005 	if (mode) {
1006 		sk->sk_shutdown |= mode;
1007 		sk->sk_state_change(sk);
1008 
1009 		if (sock_type_connectible(sk->sk_type)) {
1010 			sock_reset_flag(sk, SOCK_DONE);
1011 			vsock_send_shutdown(sk, mode);
1012 		}
1013 	}
1014 
1015 out:
1016 	release_sock(sk);
1017 	return err;
1018 }
1019 
1020 static __poll_t vsock_poll(struct file *file, struct socket *sock,
1021 			       poll_table *wait)
1022 {
1023 	struct sock *sk;
1024 	__poll_t mask;
1025 	struct vsock_sock *vsk;
1026 
1027 	sk = sock->sk;
1028 	vsk = vsock_sk(sk);
1029 
1030 	poll_wait(file, sk_sleep(sk), wait);
1031 	mask = 0;
1032 
1033 	if (sk->sk_err)
1034 		/* Signify that there has been an error on this socket. */
1035 		mask |= EPOLLERR;
1036 
1037 	/* INET sockets treat local write shutdown and peer write shutdown as a
1038 	 * case of EPOLLHUP set.
1039 	 */
1040 	if ((sk->sk_shutdown == SHUTDOWN_MASK) ||
1041 	    ((sk->sk_shutdown & SEND_SHUTDOWN) &&
1042 	     (vsk->peer_shutdown & SEND_SHUTDOWN))) {
1043 		mask |= EPOLLHUP;
1044 	}
1045 
1046 	if (sk->sk_shutdown & RCV_SHUTDOWN ||
1047 	    vsk->peer_shutdown & SEND_SHUTDOWN) {
1048 		mask |= EPOLLRDHUP;
1049 	}
1050 
1051 	if (sock->type == SOCK_DGRAM) {
1052 		/* For datagram sockets we can read if there is something in
1053 		 * the queue and write as long as the socket isn't shutdown for
1054 		 * sending.
1055 		 */
1056 		if (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
1057 		    (sk->sk_shutdown & RCV_SHUTDOWN)) {
1058 			mask |= EPOLLIN | EPOLLRDNORM;
1059 		}
1060 
1061 		if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1062 			mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
1063 
1064 	} else if (sock_type_connectible(sk->sk_type)) {
1065 		const struct vsock_transport *transport;
1066 
1067 		lock_sock(sk);
1068 
1069 		transport = vsk->transport;
1070 
1071 		/* Listening sockets that have connections in their accept
1072 		 * queue can be read.
1073 		 */
1074 		if (sk->sk_state == TCP_LISTEN
1075 		    && !vsock_is_accept_queue_empty(sk))
1076 			mask |= EPOLLIN | EPOLLRDNORM;
1077 
1078 		/* If there is something in the queue then we can read. */
1079 		if (transport && transport->stream_is_active(vsk) &&
1080 		    !(sk->sk_shutdown & RCV_SHUTDOWN)) {
1081 			bool data_ready_now = false;
1082 			int target = sock_rcvlowat(sk, 0, INT_MAX);
1083 			int ret = transport->notify_poll_in(
1084 					vsk, target, &data_ready_now);
1085 			if (ret < 0) {
1086 				mask |= EPOLLERR;
1087 			} else {
1088 				if (data_ready_now)
1089 					mask |= EPOLLIN | EPOLLRDNORM;
1090 
1091 			}
1092 		}
1093 
1094 		/* Sockets whose connections have been closed, reset, or
1095 		 * terminated should also be considered read, and we check the
1096 		 * shutdown flag for that.
1097 		 */
1098 		if (sk->sk_shutdown & RCV_SHUTDOWN ||
1099 		    vsk->peer_shutdown & SEND_SHUTDOWN) {
1100 			mask |= EPOLLIN | EPOLLRDNORM;
1101 		}
1102 
1103 		/* Connected sockets that can produce data can be written. */
1104 		if (transport && sk->sk_state == TCP_ESTABLISHED) {
1105 			if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
1106 				bool space_avail_now = false;
1107 				int ret = transport->notify_poll_out(
1108 						vsk, 1, &space_avail_now);
1109 				if (ret < 0) {
1110 					mask |= EPOLLERR;
1111 				} else {
1112 					if (space_avail_now)
1113 						/* Remove EPOLLWRBAND since INET
1114 						 * sockets are not setting it.
1115 						 */
1116 						mask |= EPOLLOUT | EPOLLWRNORM;
1117 
1118 				}
1119 			}
1120 		}
1121 
1122 		/* Simulate INET socket poll behaviors, which sets
1123 		 * EPOLLOUT|EPOLLWRNORM when peer is closed and nothing to read,
1124 		 * but local send is not shutdown.
1125 		 */
1126 		if (sk->sk_state == TCP_CLOSE || sk->sk_state == TCP_CLOSING) {
1127 			if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1128 				mask |= EPOLLOUT | EPOLLWRNORM;
1129 
1130 		}
1131 
1132 		release_sock(sk);
1133 	}
1134 
1135 	return mask;
1136 }
1137 
1138 static int vsock_read_skb(struct sock *sk, skb_read_actor_t read_actor)
1139 {
1140 	struct vsock_sock *vsk = vsock_sk(sk);
1141 
1142 	return vsk->transport->read_skb(vsk, read_actor);
1143 }
1144 
1145 static int vsock_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
1146 			       size_t len)
1147 {
1148 	int err;
1149 	struct sock *sk;
1150 	struct vsock_sock *vsk;
1151 	struct sockaddr_vm *remote_addr;
1152 	const struct vsock_transport *transport;
1153 
1154 	if (msg->msg_flags & MSG_OOB)
1155 		return -EOPNOTSUPP;
1156 
1157 	/* For now, MSG_DONTWAIT is always assumed... */
1158 	err = 0;
1159 	sk = sock->sk;
1160 	vsk = vsock_sk(sk);
1161 
1162 	lock_sock(sk);
1163 
1164 	transport = vsk->transport;
1165 
1166 	err = vsock_auto_bind(vsk);
1167 	if (err)
1168 		goto out;
1169 
1170 
1171 	/* If the provided message contains an address, use that.  Otherwise
1172 	 * fall back on the socket's remote handle (if it has been connected).
1173 	 */
1174 	if (msg->msg_name &&
1175 	    vsock_addr_cast(msg->msg_name, msg->msg_namelen,
1176 			    &remote_addr) == 0) {
1177 		/* Ensure this address is of the right type and is a valid
1178 		 * destination.
1179 		 */
1180 
1181 		if (remote_addr->svm_cid == VMADDR_CID_ANY)
1182 			remote_addr->svm_cid = transport->get_local_cid();
1183 
1184 		if (!vsock_addr_bound(remote_addr)) {
1185 			err = -EINVAL;
1186 			goto out;
1187 		}
1188 	} else if (sock->state == SS_CONNECTED) {
1189 		remote_addr = &vsk->remote_addr;
1190 
1191 		if (remote_addr->svm_cid == VMADDR_CID_ANY)
1192 			remote_addr->svm_cid = transport->get_local_cid();
1193 
1194 		/* XXX Should connect() or this function ensure remote_addr is
1195 		 * bound?
1196 		 */
1197 		if (!vsock_addr_bound(&vsk->remote_addr)) {
1198 			err = -EINVAL;
1199 			goto out;
1200 		}
1201 	} else {
1202 		err = -EINVAL;
1203 		goto out;
1204 	}
1205 
1206 	if (!transport->dgram_allow(remote_addr->svm_cid,
1207 				    remote_addr->svm_port)) {
1208 		err = -EINVAL;
1209 		goto out;
1210 	}
1211 
1212 	err = transport->dgram_enqueue(vsk, remote_addr, msg, len);
1213 
1214 out:
1215 	release_sock(sk);
1216 	return err;
1217 }
1218 
1219 static int vsock_dgram_connect(struct socket *sock,
1220 			       struct sockaddr *addr, int addr_len, int flags)
1221 {
1222 	int err;
1223 	struct sock *sk;
1224 	struct vsock_sock *vsk;
1225 	struct sockaddr_vm *remote_addr;
1226 
1227 	sk = sock->sk;
1228 	vsk = vsock_sk(sk);
1229 
1230 	err = vsock_addr_cast(addr, addr_len, &remote_addr);
1231 	if (err == -EAFNOSUPPORT && remote_addr->svm_family == AF_UNSPEC) {
1232 		lock_sock(sk);
1233 		vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY,
1234 				VMADDR_PORT_ANY);
1235 		sock->state = SS_UNCONNECTED;
1236 		release_sock(sk);
1237 		return 0;
1238 	} else if (err != 0)
1239 		return -EINVAL;
1240 
1241 	lock_sock(sk);
1242 
1243 	err = vsock_auto_bind(vsk);
1244 	if (err)
1245 		goto out;
1246 
1247 	if (!vsk->transport->dgram_allow(remote_addr->svm_cid,
1248 					 remote_addr->svm_port)) {
1249 		err = -EINVAL;
1250 		goto out;
1251 	}
1252 
1253 	memcpy(&vsk->remote_addr, remote_addr, sizeof(vsk->remote_addr));
1254 	sock->state = SS_CONNECTED;
1255 
1256 	/* sock map disallows redirection of non-TCP sockets with sk_state !=
1257 	 * TCP_ESTABLISHED (see sock_map_redirect_allowed()), so we set
1258 	 * TCP_ESTABLISHED here to allow redirection of connected vsock dgrams.
1259 	 *
1260 	 * This doesn't seem to be abnormal state for datagram sockets, as the
1261 	 * same approach can be see in other datagram socket types as well
1262 	 * (such as unix sockets).
1263 	 */
1264 	sk->sk_state = TCP_ESTABLISHED;
1265 
1266 out:
1267 	release_sock(sk);
1268 	return err;
1269 }
1270 
1271 int vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
1272 			size_t len, int flags)
1273 {
1274 #ifdef CONFIG_BPF_SYSCALL
1275 	const struct proto *prot;
1276 #endif
1277 	struct vsock_sock *vsk;
1278 	struct sock *sk;
1279 
1280 	sk = sock->sk;
1281 	vsk = vsock_sk(sk);
1282 
1283 #ifdef CONFIG_BPF_SYSCALL
1284 	prot = READ_ONCE(sk->sk_prot);
1285 	if (prot != &vsock_proto)
1286 		return prot->recvmsg(sk, msg, len, flags, NULL);
1287 #endif
1288 
1289 	return vsk->transport->dgram_dequeue(vsk, msg, len, flags);
1290 }
1291 EXPORT_SYMBOL_GPL(vsock_dgram_recvmsg);
1292 
1293 static const struct proto_ops vsock_dgram_ops = {
1294 	.family = PF_VSOCK,
1295 	.owner = THIS_MODULE,
1296 	.release = vsock_release,
1297 	.bind = vsock_bind,
1298 	.connect = vsock_dgram_connect,
1299 	.socketpair = sock_no_socketpair,
1300 	.accept = sock_no_accept,
1301 	.getname = vsock_getname,
1302 	.poll = vsock_poll,
1303 	.ioctl = sock_no_ioctl,
1304 	.listen = sock_no_listen,
1305 	.shutdown = vsock_shutdown,
1306 	.sendmsg = vsock_dgram_sendmsg,
1307 	.recvmsg = vsock_dgram_recvmsg,
1308 	.mmap = sock_no_mmap,
1309 	.read_skb = vsock_read_skb,
1310 };
1311 
1312 static int vsock_transport_cancel_pkt(struct vsock_sock *vsk)
1313 {
1314 	const struct vsock_transport *transport = vsk->transport;
1315 
1316 	if (!transport || !transport->cancel_pkt)
1317 		return -EOPNOTSUPP;
1318 
1319 	return transport->cancel_pkt(vsk);
1320 }
1321 
1322 static void vsock_connect_timeout(struct work_struct *work)
1323 {
1324 	struct sock *sk;
1325 	struct vsock_sock *vsk;
1326 
1327 	vsk = container_of(work, struct vsock_sock, connect_work.work);
1328 	sk = sk_vsock(vsk);
1329 
1330 	lock_sock(sk);
1331 	if (sk->sk_state == TCP_SYN_SENT &&
1332 	    (sk->sk_shutdown != SHUTDOWN_MASK)) {
1333 		sk->sk_state = TCP_CLOSE;
1334 		sk->sk_socket->state = SS_UNCONNECTED;
1335 		sk->sk_err = ETIMEDOUT;
1336 		sk_error_report(sk);
1337 		vsock_transport_cancel_pkt(vsk);
1338 	}
1339 	release_sock(sk);
1340 
1341 	sock_put(sk);
1342 }
1343 
1344 static int vsock_connect(struct socket *sock, struct sockaddr *addr,
1345 			 int addr_len, int flags)
1346 {
1347 	int err;
1348 	struct sock *sk;
1349 	struct vsock_sock *vsk;
1350 	const struct vsock_transport *transport;
1351 	struct sockaddr_vm *remote_addr;
1352 	long timeout;
1353 	DEFINE_WAIT(wait);
1354 
1355 	err = 0;
1356 	sk = sock->sk;
1357 	vsk = vsock_sk(sk);
1358 
1359 	lock_sock(sk);
1360 
1361 	/* XXX AF_UNSPEC should make us disconnect like AF_INET. */
1362 	switch (sock->state) {
1363 	case SS_CONNECTED:
1364 		err = -EISCONN;
1365 		goto out;
1366 	case SS_DISCONNECTING:
1367 		err = -EINVAL;
1368 		goto out;
1369 	case SS_CONNECTING:
1370 		/* This continues on so we can move sock into the SS_CONNECTED
1371 		 * state once the connection has completed (at which point err
1372 		 * will be set to zero also).  Otherwise, we will either wait
1373 		 * for the connection or return -EALREADY should this be a
1374 		 * non-blocking call.
1375 		 */
1376 		err = -EALREADY;
1377 		if (flags & O_NONBLOCK)
1378 			goto out;
1379 		break;
1380 	default:
1381 		if ((sk->sk_state == TCP_LISTEN) ||
1382 		    vsock_addr_cast(addr, addr_len, &remote_addr) != 0) {
1383 			err = -EINVAL;
1384 			goto out;
1385 		}
1386 
1387 		/* Set the remote address that we are connecting to. */
1388 		memcpy(&vsk->remote_addr, remote_addr,
1389 		       sizeof(vsk->remote_addr));
1390 
1391 		err = vsock_assign_transport(vsk, NULL);
1392 		if (err)
1393 			goto out;
1394 
1395 		transport = vsk->transport;
1396 
1397 		/* The hypervisor and well-known contexts do not have socket
1398 		 * endpoints.
1399 		 */
1400 		if (!transport ||
1401 		    !transport->stream_allow(remote_addr->svm_cid,
1402 					     remote_addr->svm_port)) {
1403 			err = -ENETUNREACH;
1404 			goto out;
1405 		}
1406 
1407 		err = vsock_auto_bind(vsk);
1408 		if (err)
1409 			goto out;
1410 
1411 		sk->sk_state = TCP_SYN_SENT;
1412 
1413 		err = transport->connect(vsk);
1414 		if (err < 0)
1415 			goto out;
1416 
1417 		/* Mark sock as connecting and set the error code to in
1418 		 * progress in case this is a non-blocking connect.
1419 		 */
1420 		sock->state = SS_CONNECTING;
1421 		err = -EINPROGRESS;
1422 	}
1423 
1424 	/* The receive path will handle all communication until we are able to
1425 	 * enter the connected state.  Here we wait for the connection to be
1426 	 * completed or a notification of an error.
1427 	 */
1428 	timeout = vsk->connect_timeout;
1429 	prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1430 
1431 	while (sk->sk_state != TCP_ESTABLISHED && sk->sk_err == 0) {
1432 		if (flags & O_NONBLOCK) {
1433 			/* If we're not going to block, we schedule a timeout
1434 			 * function to generate a timeout on the connection
1435 			 * attempt, in case the peer doesn't respond in a
1436 			 * timely manner. We hold on to the socket until the
1437 			 * timeout fires.
1438 			 */
1439 			sock_hold(sk);
1440 
1441 			/* If the timeout function is already scheduled,
1442 			 * reschedule it, then ungrab the socket refcount to
1443 			 * keep it balanced.
1444 			 */
1445 			if (mod_delayed_work(system_wq, &vsk->connect_work,
1446 					     timeout))
1447 				sock_put(sk);
1448 
1449 			/* Skip ahead to preserve error code set above. */
1450 			goto out_wait;
1451 		}
1452 
1453 		release_sock(sk);
1454 		timeout = schedule_timeout(timeout);
1455 		lock_sock(sk);
1456 
1457 		if (signal_pending(current)) {
1458 			err = sock_intr_errno(timeout);
1459 			sk->sk_state = sk->sk_state == TCP_ESTABLISHED ? TCP_CLOSING : TCP_CLOSE;
1460 			sock->state = SS_UNCONNECTED;
1461 			vsock_transport_cancel_pkt(vsk);
1462 			vsock_remove_connected(vsk);
1463 			goto out_wait;
1464 		} else if ((sk->sk_state != TCP_ESTABLISHED) && (timeout == 0)) {
1465 			err = -ETIMEDOUT;
1466 			sk->sk_state = TCP_CLOSE;
1467 			sock->state = SS_UNCONNECTED;
1468 			vsock_transport_cancel_pkt(vsk);
1469 			goto out_wait;
1470 		}
1471 
1472 		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1473 	}
1474 
1475 	if (sk->sk_err) {
1476 		err = -sk->sk_err;
1477 		sk->sk_state = TCP_CLOSE;
1478 		sock->state = SS_UNCONNECTED;
1479 	} else {
1480 		err = 0;
1481 	}
1482 
1483 out_wait:
1484 	finish_wait(sk_sleep(sk), &wait);
1485 out:
1486 	release_sock(sk);
1487 	return err;
1488 }
1489 
1490 static int vsock_accept(struct socket *sock, struct socket *newsock, int flags,
1491 			bool kern)
1492 {
1493 	struct sock *listener;
1494 	int err;
1495 	struct sock *connected;
1496 	struct vsock_sock *vconnected;
1497 	long timeout;
1498 	DEFINE_WAIT(wait);
1499 
1500 	err = 0;
1501 	listener = sock->sk;
1502 
1503 	lock_sock(listener);
1504 
1505 	if (!sock_type_connectible(sock->type)) {
1506 		err = -EOPNOTSUPP;
1507 		goto out;
1508 	}
1509 
1510 	if (listener->sk_state != TCP_LISTEN) {
1511 		err = -EINVAL;
1512 		goto out;
1513 	}
1514 
1515 	/* Wait for children sockets to appear; these are the new sockets
1516 	 * created upon connection establishment.
1517 	 */
1518 	timeout = sock_rcvtimeo(listener, flags & O_NONBLOCK);
1519 	prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1520 
1521 	while ((connected = vsock_dequeue_accept(listener)) == NULL &&
1522 	       listener->sk_err == 0) {
1523 		release_sock(listener);
1524 		timeout = schedule_timeout(timeout);
1525 		finish_wait(sk_sleep(listener), &wait);
1526 		lock_sock(listener);
1527 
1528 		if (signal_pending(current)) {
1529 			err = sock_intr_errno(timeout);
1530 			goto out;
1531 		} else if (timeout == 0) {
1532 			err = -EAGAIN;
1533 			goto out;
1534 		}
1535 
1536 		prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1537 	}
1538 	finish_wait(sk_sleep(listener), &wait);
1539 
1540 	if (listener->sk_err)
1541 		err = -listener->sk_err;
1542 
1543 	if (connected) {
1544 		sk_acceptq_removed(listener);
1545 
1546 		lock_sock_nested(connected, SINGLE_DEPTH_NESTING);
1547 		vconnected = vsock_sk(connected);
1548 
1549 		/* If the listener socket has received an error, then we should
1550 		 * reject this socket and return.  Note that we simply mark the
1551 		 * socket rejected, drop our reference, and let the cleanup
1552 		 * function handle the cleanup; the fact that we found it in
1553 		 * the listener's accept queue guarantees that the cleanup
1554 		 * function hasn't run yet.
1555 		 */
1556 		if (err) {
1557 			vconnected->rejected = true;
1558 		} else {
1559 			newsock->state = SS_CONNECTED;
1560 			sock_graft(connected, newsock);
1561 		}
1562 
1563 		release_sock(connected);
1564 		sock_put(connected);
1565 	}
1566 
1567 out:
1568 	release_sock(listener);
1569 	return err;
1570 }
1571 
1572 static int vsock_listen(struct socket *sock, int backlog)
1573 {
1574 	int err;
1575 	struct sock *sk;
1576 	struct vsock_sock *vsk;
1577 
1578 	sk = sock->sk;
1579 
1580 	lock_sock(sk);
1581 
1582 	if (!sock_type_connectible(sk->sk_type)) {
1583 		err = -EOPNOTSUPP;
1584 		goto out;
1585 	}
1586 
1587 	if (sock->state != SS_UNCONNECTED) {
1588 		err = -EINVAL;
1589 		goto out;
1590 	}
1591 
1592 	vsk = vsock_sk(sk);
1593 
1594 	if (!vsock_addr_bound(&vsk->local_addr)) {
1595 		err = -EINVAL;
1596 		goto out;
1597 	}
1598 
1599 	sk->sk_max_ack_backlog = backlog;
1600 	sk->sk_state = TCP_LISTEN;
1601 
1602 	err = 0;
1603 
1604 out:
1605 	release_sock(sk);
1606 	return err;
1607 }
1608 
1609 static void vsock_update_buffer_size(struct vsock_sock *vsk,
1610 				     const struct vsock_transport *transport,
1611 				     u64 val)
1612 {
1613 	if (val > vsk->buffer_max_size)
1614 		val = vsk->buffer_max_size;
1615 
1616 	if (val < vsk->buffer_min_size)
1617 		val = vsk->buffer_min_size;
1618 
1619 	if (val != vsk->buffer_size &&
1620 	    transport && transport->notify_buffer_size)
1621 		transport->notify_buffer_size(vsk, &val);
1622 
1623 	vsk->buffer_size = val;
1624 }
1625 
1626 static int vsock_connectible_setsockopt(struct socket *sock,
1627 					int level,
1628 					int optname,
1629 					sockptr_t optval,
1630 					unsigned int optlen)
1631 {
1632 	int err;
1633 	struct sock *sk;
1634 	struct vsock_sock *vsk;
1635 	const struct vsock_transport *transport;
1636 	u64 val;
1637 
1638 	if (level != AF_VSOCK)
1639 		return -ENOPROTOOPT;
1640 
1641 #define COPY_IN(_v)                                       \
1642 	do {						  \
1643 		if (optlen < sizeof(_v)) {		  \
1644 			err = -EINVAL;			  \
1645 			goto exit;			  \
1646 		}					  \
1647 		if (copy_from_sockptr(&_v, optval, sizeof(_v)) != 0) {	\
1648 			err = -EFAULT;					\
1649 			goto exit;					\
1650 		}							\
1651 	} while (0)
1652 
1653 	err = 0;
1654 	sk = sock->sk;
1655 	vsk = vsock_sk(sk);
1656 
1657 	lock_sock(sk);
1658 
1659 	transport = vsk->transport;
1660 
1661 	switch (optname) {
1662 	case SO_VM_SOCKETS_BUFFER_SIZE:
1663 		COPY_IN(val);
1664 		vsock_update_buffer_size(vsk, transport, val);
1665 		break;
1666 
1667 	case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1668 		COPY_IN(val);
1669 		vsk->buffer_max_size = val;
1670 		vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
1671 		break;
1672 
1673 	case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1674 		COPY_IN(val);
1675 		vsk->buffer_min_size = val;
1676 		vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
1677 		break;
1678 
1679 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
1680 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD: {
1681 		struct __kernel_sock_timeval tv;
1682 
1683 		err = sock_copy_user_timeval(&tv, optval, optlen,
1684 					     optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
1685 		if (err)
1686 			break;
1687 		if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC &&
1688 		    tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) {
1689 			vsk->connect_timeout = tv.tv_sec * HZ +
1690 				DIV_ROUND_UP((unsigned long)tv.tv_usec, (USEC_PER_SEC / HZ));
1691 			if (vsk->connect_timeout == 0)
1692 				vsk->connect_timeout =
1693 				    VSOCK_DEFAULT_CONNECT_TIMEOUT;
1694 
1695 		} else {
1696 			err = -ERANGE;
1697 		}
1698 		break;
1699 	}
1700 
1701 	default:
1702 		err = -ENOPROTOOPT;
1703 		break;
1704 	}
1705 
1706 #undef COPY_IN
1707 
1708 exit:
1709 	release_sock(sk);
1710 	return err;
1711 }
1712 
1713 static int vsock_connectible_getsockopt(struct socket *sock,
1714 					int level, int optname,
1715 					char __user *optval,
1716 					int __user *optlen)
1717 {
1718 	struct sock *sk = sock->sk;
1719 	struct vsock_sock *vsk = vsock_sk(sk);
1720 
1721 	union {
1722 		u64 val64;
1723 		struct old_timeval32 tm32;
1724 		struct __kernel_old_timeval tm;
1725 		struct  __kernel_sock_timeval stm;
1726 	} v;
1727 
1728 	int lv = sizeof(v.val64);
1729 	int len;
1730 
1731 	if (level != AF_VSOCK)
1732 		return -ENOPROTOOPT;
1733 
1734 	if (get_user(len, optlen))
1735 		return -EFAULT;
1736 
1737 	memset(&v, 0, sizeof(v));
1738 
1739 	switch (optname) {
1740 	case SO_VM_SOCKETS_BUFFER_SIZE:
1741 		v.val64 = vsk->buffer_size;
1742 		break;
1743 
1744 	case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1745 		v.val64 = vsk->buffer_max_size;
1746 		break;
1747 
1748 	case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1749 		v.val64 = vsk->buffer_min_size;
1750 		break;
1751 
1752 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
1753 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD:
1754 		lv = sock_get_timeout(vsk->connect_timeout, &v,
1755 				      optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
1756 		break;
1757 
1758 	default:
1759 		return -ENOPROTOOPT;
1760 	}
1761 
1762 	if (len < lv)
1763 		return -EINVAL;
1764 	if (len > lv)
1765 		len = lv;
1766 	if (copy_to_user(optval, &v, len))
1767 		return -EFAULT;
1768 
1769 	if (put_user(len, optlen))
1770 		return -EFAULT;
1771 
1772 	return 0;
1773 }
1774 
1775 static int vsock_connectible_sendmsg(struct socket *sock, struct msghdr *msg,
1776 				     size_t len)
1777 {
1778 	struct sock *sk;
1779 	struct vsock_sock *vsk;
1780 	const struct vsock_transport *transport;
1781 	ssize_t total_written;
1782 	long timeout;
1783 	int err;
1784 	struct vsock_transport_send_notify_data send_data;
1785 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1786 
1787 	sk = sock->sk;
1788 	vsk = vsock_sk(sk);
1789 	total_written = 0;
1790 	err = 0;
1791 
1792 	if (msg->msg_flags & MSG_OOB)
1793 		return -EOPNOTSUPP;
1794 
1795 	lock_sock(sk);
1796 
1797 	transport = vsk->transport;
1798 
1799 	/* Callers should not provide a destination with connection oriented
1800 	 * sockets.
1801 	 */
1802 	if (msg->msg_namelen) {
1803 		err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
1804 		goto out;
1805 	}
1806 
1807 	/* Send data only if both sides are not shutdown in the direction. */
1808 	if (sk->sk_shutdown & SEND_SHUTDOWN ||
1809 	    vsk->peer_shutdown & RCV_SHUTDOWN) {
1810 		err = -EPIPE;
1811 		goto out;
1812 	}
1813 
1814 	if (!transport || sk->sk_state != TCP_ESTABLISHED ||
1815 	    !vsock_addr_bound(&vsk->local_addr)) {
1816 		err = -ENOTCONN;
1817 		goto out;
1818 	}
1819 
1820 	if (!vsock_addr_bound(&vsk->remote_addr)) {
1821 		err = -EDESTADDRREQ;
1822 		goto out;
1823 	}
1824 
1825 	/* Wait for room in the produce queue to enqueue our user's data. */
1826 	timeout = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1827 
1828 	err = transport->notify_send_init(vsk, &send_data);
1829 	if (err < 0)
1830 		goto out;
1831 
1832 	while (total_written < len) {
1833 		ssize_t written;
1834 
1835 		add_wait_queue(sk_sleep(sk), &wait);
1836 		while (vsock_stream_has_space(vsk) == 0 &&
1837 		       sk->sk_err == 0 &&
1838 		       !(sk->sk_shutdown & SEND_SHUTDOWN) &&
1839 		       !(vsk->peer_shutdown & RCV_SHUTDOWN)) {
1840 
1841 			/* Don't wait for non-blocking sockets. */
1842 			if (timeout == 0) {
1843 				err = -EAGAIN;
1844 				remove_wait_queue(sk_sleep(sk), &wait);
1845 				goto out_err;
1846 			}
1847 
1848 			err = transport->notify_send_pre_block(vsk, &send_data);
1849 			if (err < 0) {
1850 				remove_wait_queue(sk_sleep(sk), &wait);
1851 				goto out_err;
1852 			}
1853 
1854 			release_sock(sk);
1855 			timeout = wait_woken(&wait, TASK_INTERRUPTIBLE, timeout);
1856 			lock_sock(sk);
1857 			if (signal_pending(current)) {
1858 				err = sock_intr_errno(timeout);
1859 				remove_wait_queue(sk_sleep(sk), &wait);
1860 				goto out_err;
1861 			} else if (timeout == 0) {
1862 				err = -EAGAIN;
1863 				remove_wait_queue(sk_sleep(sk), &wait);
1864 				goto out_err;
1865 			}
1866 		}
1867 		remove_wait_queue(sk_sleep(sk), &wait);
1868 
1869 		/* These checks occur both as part of and after the loop
1870 		 * conditional since we need to check before and after
1871 		 * sleeping.
1872 		 */
1873 		if (sk->sk_err) {
1874 			err = -sk->sk_err;
1875 			goto out_err;
1876 		} else if ((sk->sk_shutdown & SEND_SHUTDOWN) ||
1877 			   (vsk->peer_shutdown & RCV_SHUTDOWN)) {
1878 			err = -EPIPE;
1879 			goto out_err;
1880 		}
1881 
1882 		err = transport->notify_send_pre_enqueue(vsk, &send_data);
1883 		if (err < 0)
1884 			goto out_err;
1885 
1886 		/* Note that enqueue will only write as many bytes as are free
1887 		 * in the produce queue, so we don't need to ensure len is
1888 		 * smaller than the queue size.  It is the caller's
1889 		 * responsibility to check how many bytes we were able to send.
1890 		 */
1891 
1892 		if (sk->sk_type == SOCK_SEQPACKET) {
1893 			written = transport->seqpacket_enqueue(vsk,
1894 						msg, len - total_written);
1895 		} else {
1896 			written = transport->stream_enqueue(vsk,
1897 					msg, len - total_written);
1898 		}
1899 
1900 		if (written < 0) {
1901 			err = written;
1902 			goto out_err;
1903 		}
1904 
1905 		total_written += written;
1906 
1907 		err = transport->notify_send_post_enqueue(
1908 				vsk, written, &send_data);
1909 		if (err < 0)
1910 			goto out_err;
1911 
1912 	}
1913 
1914 out_err:
1915 	if (total_written > 0) {
1916 		/* Return number of written bytes only if:
1917 		 * 1) SOCK_STREAM socket.
1918 		 * 2) SOCK_SEQPACKET socket when whole buffer is sent.
1919 		 */
1920 		if (sk->sk_type == SOCK_STREAM || total_written == len)
1921 			err = total_written;
1922 	}
1923 out:
1924 	release_sock(sk);
1925 	return err;
1926 }
1927 
1928 static int vsock_connectible_wait_data(struct sock *sk,
1929 				       struct wait_queue_entry *wait,
1930 				       long timeout,
1931 				       struct vsock_transport_recv_notify_data *recv_data,
1932 				       size_t target)
1933 {
1934 	const struct vsock_transport *transport;
1935 	struct vsock_sock *vsk;
1936 	s64 data;
1937 	int err;
1938 
1939 	vsk = vsock_sk(sk);
1940 	err = 0;
1941 	transport = vsk->transport;
1942 
1943 	while (1) {
1944 		prepare_to_wait(sk_sleep(sk), wait, TASK_INTERRUPTIBLE);
1945 		data = vsock_connectible_has_data(vsk);
1946 		if (data != 0)
1947 			break;
1948 
1949 		if (sk->sk_err != 0 ||
1950 		    (sk->sk_shutdown & RCV_SHUTDOWN) ||
1951 		    (vsk->peer_shutdown & SEND_SHUTDOWN)) {
1952 			break;
1953 		}
1954 
1955 		/* Don't wait for non-blocking sockets. */
1956 		if (timeout == 0) {
1957 			err = -EAGAIN;
1958 			break;
1959 		}
1960 
1961 		if (recv_data) {
1962 			err = transport->notify_recv_pre_block(vsk, target, recv_data);
1963 			if (err < 0)
1964 				break;
1965 		}
1966 
1967 		release_sock(sk);
1968 		timeout = schedule_timeout(timeout);
1969 		lock_sock(sk);
1970 
1971 		if (signal_pending(current)) {
1972 			err = sock_intr_errno(timeout);
1973 			break;
1974 		} else if (timeout == 0) {
1975 			err = -EAGAIN;
1976 			break;
1977 		}
1978 	}
1979 
1980 	finish_wait(sk_sleep(sk), wait);
1981 
1982 	if (err)
1983 		return err;
1984 
1985 	/* Internal transport error when checking for available
1986 	 * data. XXX This should be changed to a connection
1987 	 * reset in a later change.
1988 	 */
1989 	if (data < 0)
1990 		return -ENOMEM;
1991 
1992 	return data;
1993 }
1994 
1995 static int __vsock_stream_recvmsg(struct sock *sk, struct msghdr *msg,
1996 				  size_t len, int flags)
1997 {
1998 	struct vsock_transport_recv_notify_data recv_data;
1999 	const struct vsock_transport *transport;
2000 	struct vsock_sock *vsk;
2001 	ssize_t copied;
2002 	size_t target;
2003 	long timeout;
2004 	int err;
2005 
2006 	DEFINE_WAIT(wait);
2007 
2008 	vsk = vsock_sk(sk);
2009 	transport = vsk->transport;
2010 
2011 	/* We must not copy less than target bytes into the user's buffer
2012 	 * before returning successfully, so we wait for the consume queue to
2013 	 * have that much data to consume before dequeueing.  Note that this
2014 	 * makes it impossible to handle cases where target is greater than the
2015 	 * queue size.
2016 	 */
2017 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2018 	if (target >= transport->stream_rcvhiwat(vsk)) {
2019 		err = -ENOMEM;
2020 		goto out;
2021 	}
2022 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2023 	copied = 0;
2024 
2025 	err = transport->notify_recv_init(vsk, target, &recv_data);
2026 	if (err < 0)
2027 		goto out;
2028 
2029 
2030 	while (1) {
2031 		ssize_t read;
2032 
2033 		err = vsock_connectible_wait_data(sk, &wait, timeout,
2034 						  &recv_data, target);
2035 		if (err <= 0)
2036 			break;
2037 
2038 		err = transport->notify_recv_pre_dequeue(vsk, target,
2039 							 &recv_data);
2040 		if (err < 0)
2041 			break;
2042 
2043 		read = transport->stream_dequeue(vsk, msg, len - copied, flags);
2044 		if (read < 0) {
2045 			err = read;
2046 			break;
2047 		}
2048 
2049 		copied += read;
2050 
2051 		err = transport->notify_recv_post_dequeue(vsk, target, read,
2052 						!(flags & MSG_PEEK), &recv_data);
2053 		if (err < 0)
2054 			goto out;
2055 
2056 		if (read >= target || flags & MSG_PEEK)
2057 			break;
2058 
2059 		target -= read;
2060 	}
2061 
2062 	if (sk->sk_err)
2063 		err = -sk->sk_err;
2064 	else if (sk->sk_shutdown & RCV_SHUTDOWN)
2065 		err = 0;
2066 
2067 	if (copied > 0)
2068 		err = copied;
2069 
2070 out:
2071 	return err;
2072 }
2073 
2074 static int __vsock_seqpacket_recvmsg(struct sock *sk, struct msghdr *msg,
2075 				     size_t len, int flags)
2076 {
2077 	const struct vsock_transport *transport;
2078 	struct vsock_sock *vsk;
2079 	ssize_t msg_len;
2080 	long timeout;
2081 	int err = 0;
2082 	DEFINE_WAIT(wait);
2083 
2084 	vsk = vsock_sk(sk);
2085 	transport = vsk->transport;
2086 
2087 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2088 
2089 	err = vsock_connectible_wait_data(sk, &wait, timeout, NULL, 0);
2090 	if (err <= 0)
2091 		goto out;
2092 
2093 	msg_len = transport->seqpacket_dequeue(vsk, msg, flags);
2094 
2095 	if (msg_len < 0) {
2096 		err = msg_len;
2097 		goto out;
2098 	}
2099 
2100 	if (sk->sk_err) {
2101 		err = -sk->sk_err;
2102 	} else if (sk->sk_shutdown & RCV_SHUTDOWN) {
2103 		err = 0;
2104 	} else {
2105 		/* User sets MSG_TRUNC, so return real length of
2106 		 * packet.
2107 		 */
2108 		if (flags & MSG_TRUNC)
2109 			err = msg_len;
2110 		else
2111 			err = len - msg_data_left(msg);
2112 
2113 		/* Always set MSG_TRUNC if real length of packet is
2114 		 * bigger than user's buffer.
2115 		 */
2116 		if (msg_len > len)
2117 			msg->msg_flags |= MSG_TRUNC;
2118 	}
2119 
2120 out:
2121 	return err;
2122 }
2123 
2124 int
2125 vsock_connectible_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
2126 			  int flags)
2127 {
2128 	struct sock *sk;
2129 	struct vsock_sock *vsk;
2130 	const struct vsock_transport *transport;
2131 #ifdef CONFIG_BPF_SYSCALL
2132 	const struct proto *prot;
2133 #endif
2134 	int err;
2135 
2136 	sk = sock->sk;
2137 	vsk = vsock_sk(sk);
2138 	err = 0;
2139 
2140 	lock_sock(sk);
2141 
2142 	transport = vsk->transport;
2143 
2144 	if (!transport || sk->sk_state != TCP_ESTABLISHED) {
2145 		/* Recvmsg is supposed to return 0 if a peer performs an
2146 		 * orderly shutdown. Differentiate between that case and when a
2147 		 * peer has not connected or a local shutdown occurred with the
2148 		 * SOCK_DONE flag.
2149 		 */
2150 		if (sock_flag(sk, SOCK_DONE))
2151 			err = 0;
2152 		else
2153 			err = -ENOTCONN;
2154 
2155 		goto out;
2156 	}
2157 
2158 	if (flags & MSG_OOB) {
2159 		err = -EOPNOTSUPP;
2160 		goto out;
2161 	}
2162 
2163 	/* We don't check peer_shutdown flag here since peer may actually shut
2164 	 * down, but there can be data in the queue that a local socket can
2165 	 * receive.
2166 	 */
2167 	if (sk->sk_shutdown & RCV_SHUTDOWN) {
2168 		err = 0;
2169 		goto out;
2170 	}
2171 
2172 	/* It is valid on Linux to pass in a zero-length receive buffer.  This
2173 	 * is not an error.  We may as well bail out now.
2174 	 */
2175 	if (!len) {
2176 		err = 0;
2177 		goto out;
2178 	}
2179 
2180 #ifdef CONFIG_BPF_SYSCALL
2181 	prot = READ_ONCE(sk->sk_prot);
2182 	if (prot != &vsock_proto) {
2183 		release_sock(sk);
2184 		return prot->recvmsg(sk, msg, len, flags, NULL);
2185 	}
2186 #endif
2187 
2188 	if (sk->sk_type == SOCK_STREAM)
2189 		err = __vsock_stream_recvmsg(sk, msg, len, flags);
2190 	else
2191 		err = __vsock_seqpacket_recvmsg(sk, msg, len, flags);
2192 
2193 out:
2194 	release_sock(sk);
2195 	return err;
2196 }
2197 EXPORT_SYMBOL_GPL(vsock_connectible_recvmsg);
2198 
2199 static int vsock_set_rcvlowat(struct sock *sk, int val)
2200 {
2201 	const struct vsock_transport *transport;
2202 	struct vsock_sock *vsk;
2203 
2204 	vsk = vsock_sk(sk);
2205 
2206 	if (val > vsk->buffer_size)
2207 		return -EINVAL;
2208 
2209 	transport = vsk->transport;
2210 
2211 	if (transport && transport->set_rcvlowat)
2212 		return transport->set_rcvlowat(vsk, val);
2213 
2214 	WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
2215 	return 0;
2216 }
2217 
2218 static const struct proto_ops vsock_stream_ops = {
2219 	.family = PF_VSOCK,
2220 	.owner = THIS_MODULE,
2221 	.release = vsock_release,
2222 	.bind = vsock_bind,
2223 	.connect = vsock_connect,
2224 	.socketpair = sock_no_socketpair,
2225 	.accept = vsock_accept,
2226 	.getname = vsock_getname,
2227 	.poll = vsock_poll,
2228 	.ioctl = sock_no_ioctl,
2229 	.listen = vsock_listen,
2230 	.shutdown = vsock_shutdown,
2231 	.setsockopt = vsock_connectible_setsockopt,
2232 	.getsockopt = vsock_connectible_getsockopt,
2233 	.sendmsg = vsock_connectible_sendmsg,
2234 	.recvmsg = vsock_connectible_recvmsg,
2235 	.mmap = sock_no_mmap,
2236 	.set_rcvlowat = vsock_set_rcvlowat,
2237 	.read_skb = vsock_read_skb,
2238 };
2239 
2240 static const struct proto_ops vsock_seqpacket_ops = {
2241 	.family = PF_VSOCK,
2242 	.owner = THIS_MODULE,
2243 	.release = vsock_release,
2244 	.bind = vsock_bind,
2245 	.connect = vsock_connect,
2246 	.socketpair = sock_no_socketpair,
2247 	.accept = vsock_accept,
2248 	.getname = vsock_getname,
2249 	.poll = vsock_poll,
2250 	.ioctl = sock_no_ioctl,
2251 	.listen = vsock_listen,
2252 	.shutdown = vsock_shutdown,
2253 	.setsockopt = vsock_connectible_setsockopt,
2254 	.getsockopt = vsock_connectible_getsockopt,
2255 	.sendmsg = vsock_connectible_sendmsg,
2256 	.recvmsg = vsock_connectible_recvmsg,
2257 	.mmap = sock_no_mmap,
2258 	.read_skb = vsock_read_skb,
2259 };
2260 
2261 static int vsock_create(struct net *net, struct socket *sock,
2262 			int protocol, int kern)
2263 {
2264 	struct vsock_sock *vsk;
2265 	struct sock *sk;
2266 	int ret;
2267 
2268 	if (!sock)
2269 		return -EINVAL;
2270 
2271 	if (protocol && protocol != PF_VSOCK)
2272 		return -EPROTONOSUPPORT;
2273 
2274 	switch (sock->type) {
2275 	case SOCK_DGRAM:
2276 		sock->ops = &vsock_dgram_ops;
2277 		break;
2278 	case SOCK_STREAM:
2279 		sock->ops = &vsock_stream_ops;
2280 		break;
2281 	case SOCK_SEQPACKET:
2282 		sock->ops = &vsock_seqpacket_ops;
2283 		break;
2284 	default:
2285 		return -ESOCKTNOSUPPORT;
2286 	}
2287 
2288 	sock->state = SS_UNCONNECTED;
2289 
2290 	sk = __vsock_create(net, sock, NULL, GFP_KERNEL, 0, kern);
2291 	if (!sk)
2292 		return -ENOMEM;
2293 
2294 	vsk = vsock_sk(sk);
2295 
2296 	if (sock->type == SOCK_DGRAM) {
2297 		ret = vsock_assign_transport(vsk, NULL);
2298 		if (ret < 0) {
2299 			sock_put(sk);
2300 			return ret;
2301 		}
2302 	}
2303 
2304 	vsock_insert_unbound(vsk);
2305 
2306 	return 0;
2307 }
2308 
2309 static const struct net_proto_family vsock_family_ops = {
2310 	.family = AF_VSOCK,
2311 	.create = vsock_create,
2312 	.owner = THIS_MODULE,
2313 };
2314 
2315 static long vsock_dev_do_ioctl(struct file *filp,
2316 			       unsigned int cmd, void __user *ptr)
2317 {
2318 	u32 __user *p = ptr;
2319 	u32 cid = VMADDR_CID_ANY;
2320 	int retval = 0;
2321 
2322 	switch (cmd) {
2323 	case IOCTL_VM_SOCKETS_GET_LOCAL_CID:
2324 		/* To be compatible with the VMCI behavior, we prioritize the
2325 		 * guest CID instead of well-know host CID (VMADDR_CID_HOST).
2326 		 */
2327 		if (transport_g2h)
2328 			cid = transport_g2h->get_local_cid();
2329 		else if (transport_h2g)
2330 			cid = transport_h2g->get_local_cid();
2331 
2332 		if (put_user(cid, p) != 0)
2333 			retval = -EFAULT;
2334 		break;
2335 
2336 	default:
2337 		retval = -ENOIOCTLCMD;
2338 	}
2339 
2340 	return retval;
2341 }
2342 
2343 static long vsock_dev_ioctl(struct file *filp,
2344 			    unsigned int cmd, unsigned long arg)
2345 {
2346 	return vsock_dev_do_ioctl(filp, cmd, (void __user *)arg);
2347 }
2348 
2349 #ifdef CONFIG_COMPAT
2350 static long vsock_dev_compat_ioctl(struct file *filp,
2351 				   unsigned int cmd, unsigned long arg)
2352 {
2353 	return vsock_dev_do_ioctl(filp, cmd, compat_ptr(arg));
2354 }
2355 #endif
2356 
2357 static const struct file_operations vsock_device_ops = {
2358 	.owner		= THIS_MODULE,
2359 	.unlocked_ioctl	= vsock_dev_ioctl,
2360 #ifdef CONFIG_COMPAT
2361 	.compat_ioctl	= vsock_dev_compat_ioctl,
2362 #endif
2363 	.open		= nonseekable_open,
2364 };
2365 
2366 static struct miscdevice vsock_device = {
2367 	.name		= "vsock",
2368 	.fops		= &vsock_device_ops,
2369 };
2370 
2371 static int __init vsock_init(void)
2372 {
2373 	int err = 0;
2374 
2375 	vsock_init_tables();
2376 
2377 	vsock_proto.owner = THIS_MODULE;
2378 	vsock_device.minor = MISC_DYNAMIC_MINOR;
2379 	err = misc_register(&vsock_device);
2380 	if (err) {
2381 		pr_err("Failed to register misc device\n");
2382 		goto err_reset_transport;
2383 	}
2384 
2385 	err = proto_register(&vsock_proto, 1);	/* we want our slab */
2386 	if (err) {
2387 		pr_err("Cannot register vsock protocol\n");
2388 		goto err_deregister_misc;
2389 	}
2390 
2391 	err = sock_register(&vsock_family_ops);
2392 	if (err) {
2393 		pr_err("could not register af_vsock (%d) address family: %d\n",
2394 		       AF_VSOCK, err);
2395 		goto err_unregister_proto;
2396 	}
2397 
2398 	vsock_bpf_build_proto();
2399 
2400 	return 0;
2401 
2402 err_unregister_proto:
2403 	proto_unregister(&vsock_proto);
2404 err_deregister_misc:
2405 	misc_deregister(&vsock_device);
2406 err_reset_transport:
2407 	return err;
2408 }
2409 
2410 static void __exit vsock_exit(void)
2411 {
2412 	misc_deregister(&vsock_device);
2413 	sock_unregister(AF_VSOCK);
2414 	proto_unregister(&vsock_proto);
2415 }
2416 
2417 const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)
2418 {
2419 	return vsk->transport;
2420 }
2421 EXPORT_SYMBOL_GPL(vsock_core_get_transport);
2422 
2423 int vsock_core_register(const struct vsock_transport *t, int features)
2424 {
2425 	const struct vsock_transport *t_h2g, *t_g2h, *t_dgram, *t_local;
2426 	int err = mutex_lock_interruptible(&vsock_register_mutex);
2427 
2428 	if (err)
2429 		return err;
2430 
2431 	t_h2g = transport_h2g;
2432 	t_g2h = transport_g2h;
2433 	t_dgram = transport_dgram;
2434 	t_local = transport_local;
2435 
2436 	if (features & VSOCK_TRANSPORT_F_H2G) {
2437 		if (t_h2g) {
2438 			err = -EBUSY;
2439 			goto err_busy;
2440 		}
2441 		t_h2g = t;
2442 	}
2443 
2444 	if (features & VSOCK_TRANSPORT_F_G2H) {
2445 		if (t_g2h) {
2446 			err = -EBUSY;
2447 			goto err_busy;
2448 		}
2449 		t_g2h = t;
2450 	}
2451 
2452 	if (features & VSOCK_TRANSPORT_F_DGRAM) {
2453 		if (t_dgram) {
2454 			err = -EBUSY;
2455 			goto err_busy;
2456 		}
2457 		t_dgram = t;
2458 	}
2459 
2460 	if (features & VSOCK_TRANSPORT_F_LOCAL) {
2461 		if (t_local) {
2462 			err = -EBUSY;
2463 			goto err_busy;
2464 		}
2465 		t_local = t;
2466 	}
2467 
2468 	transport_h2g = t_h2g;
2469 	transport_g2h = t_g2h;
2470 	transport_dgram = t_dgram;
2471 	transport_local = t_local;
2472 
2473 err_busy:
2474 	mutex_unlock(&vsock_register_mutex);
2475 	return err;
2476 }
2477 EXPORT_SYMBOL_GPL(vsock_core_register);
2478 
2479 void vsock_core_unregister(const struct vsock_transport *t)
2480 {
2481 	mutex_lock(&vsock_register_mutex);
2482 
2483 	if (transport_h2g == t)
2484 		transport_h2g = NULL;
2485 
2486 	if (transport_g2h == t)
2487 		transport_g2h = NULL;
2488 
2489 	if (transport_dgram == t)
2490 		transport_dgram = NULL;
2491 
2492 	if (transport_local == t)
2493 		transport_local = NULL;
2494 
2495 	mutex_unlock(&vsock_register_mutex);
2496 }
2497 EXPORT_SYMBOL_GPL(vsock_core_unregister);
2498 
2499 module_init(vsock_init);
2500 module_exit(vsock_exit);
2501 
2502 MODULE_AUTHOR("VMware, Inc.");
2503 MODULE_DESCRIPTION("VMware Virtual Socket Family");
2504 MODULE_VERSION("1.0.2.0-k");
2505 MODULE_LICENSE("GPL v2");
2506