xref: /openbmc/linux/net/vmw_vsock/af_vsock.c (revision ffcdf473)
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 	.sendpage = sock_no_sendpage,
1310 	.read_skb = vsock_read_skb,
1311 };
1312 
1313 static int vsock_transport_cancel_pkt(struct vsock_sock *vsk)
1314 {
1315 	const struct vsock_transport *transport = vsk->transport;
1316 
1317 	if (!transport || !transport->cancel_pkt)
1318 		return -EOPNOTSUPP;
1319 
1320 	return transport->cancel_pkt(vsk);
1321 }
1322 
1323 static void vsock_connect_timeout(struct work_struct *work)
1324 {
1325 	struct sock *sk;
1326 	struct vsock_sock *vsk;
1327 
1328 	vsk = container_of(work, struct vsock_sock, connect_work.work);
1329 	sk = sk_vsock(vsk);
1330 
1331 	lock_sock(sk);
1332 	if (sk->sk_state == TCP_SYN_SENT &&
1333 	    (sk->sk_shutdown != SHUTDOWN_MASK)) {
1334 		sk->sk_state = TCP_CLOSE;
1335 		sk->sk_socket->state = SS_UNCONNECTED;
1336 		sk->sk_err = ETIMEDOUT;
1337 		sk_error_report(sk);
1338 		vsock_transport_cancel_pkt(vsk);
1339 	}
1340 	release_sock(sk);
1341 
1342 	sock_put(sk);
1343 }
1344 
1345 static int vsock_connect(struct socket *sock, struct sockaddr *addr,
1346 			 int addr_len, int flags)
1347 {
1348 	int err;
1349 	struct sock *sk;
1350 	struct vsock_sock *vsk;
1351 	const struct vsock_transport *transport;
1352 	struct sockaddr_vm *remote_addr;
1353 	long timeout;
1354 	DEFINE_WAIT(wait);
1355 
1356 	err = 0;
1357 	sk = sock->sk;
1358 	vsk = vsock_sk(sk);
1359 
1360 	lock_sock(sk);
1361 
1362 	/* XXX AF_UNSPEC should make us disconnect like AF_INET. */
1363 	switch (sock->state) {
1364 	case SS_CONNECTED:
1365 		err = -EISCONN;
1366 		goto out;
1367 	case SS_DISCONNECTING:
1368 		err = -EINVAL;
1369 		goto out;
1370 	case SS_CONNECTING:
1371 		/* This continues on so we can move sock into the SS_CONNECTED
1372 		 * state once the connection has completed (at which point err
1373 		 * will be set to zero also).  Otherwise, we will either wait
1374 		 * for the connection or return -EALREADY should this be a
1375 		 * non-blocking call.
1376 		 */
1377 		err = -EALREADY;
1378 		if (flags & O_NONBLOCK)
1379 			goto out;
1380 		break;
1381 	default:
1382 		if ((sk->sk_state == TCP_LISTEN) ||
1383 		    vsock_addr_cast(addr, addr_len, &remote_addr) != 0) {
1384 			err = -EINVAL;
1385 			goto out;
1386 		}
1387 
1388 		/* Set the remote address that we are connecting to. */
1389 		memcpy(&vsk->remote_addr, remote_addr,
1390 		       sizeof(vsk->remote_addr));
1391 
1392 		err = vsock_assign_transport(vsk, NULL);
1393 		if (err)
1394 			goto out;
1395 
1396 		transport = vsk->transport;
1397 
1398 		/* The hypervisor and well-known contexts do not have socket
1399 		 * endpoints.
1400 		 */
1401 		if (!transport ||
1402 		    !transport->stream_allow(remote_addr->svm_cid,
1403 					     remote_addr->svm_port)) {
1404 			err = -ENETUNREACH;
1405 			goto out;
1406 		}
1407 
1408 		err = vsock_auto_bind(vsk);
1409 		if (err)
1410 			goto out;
1411 
1412 		sk->sk_state = TCP_SYN_SENT;
1413 
1414 		err = transport->connect(vsk);
1415 		if (err < 0)
1416 			goto out;
1417 
1418 		/* Mark sock as connecting and set the error code to in
1419 		 * progress in case this is a non-blocking connect.
1420 		 */
1421 		sock->state = SS_CONNECTING;
1422 		err = -EINPROGRESS;
1423 	}
1424 
1425 	/* The receive path will handle all communication until we are able to
1426 	 * enter the connected state.  Here we wait for the connection to be
1427 	 * completed or a notification of an error.
1428 	 */
1429 	timeout = vsk->connect_timeout;
1430 	prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1431 
1432 	while (sk->sk_state != TCP_ESTABLISHED && sk->sk_err == 0) {
1433 		if (flags & O_NONBLOCK) {
1434 			/* If we're not going to block, we schedule a timeout
1435 			 * function to generate a timeout on the connection
1436 			 * attempt, in case the peer doesn't respond in a
1437 			 * timely manner. We hold on to the socket until the
1438 			 * timeout fires.
1439 			 */
1440 			sock_hold(sk);
1441 
1442 			/* If the timeout function is already scheduled,
1443 			 * reschedule it, then ungrab the socket refcount to
1444 			 * keep it balanced.
1445 			 */
1446 			if (mod_delayed_work(system_wq, &vsk->connect_work,
1447 					     timeout))
1448 				sock_put(sk);
1449 
1450 			/* Skip ahead to preserve error code set above. */
1451 			goto out_wait;
1452 		}
1453 
1454 		release_sock(sk);
1455 		timeout = schedule_timeout(timeout);
1456 		lock_sock(sk);
1457 
1458 		if (signal_pending(current)) {
1459 			err = sock_intr_errno(timeout);
1460 			sk->sk_state = sk->sk_state == TCP_ESTABLISHED ? TCP_CLOSING : TCP_CLOSE;
1461 			sock->state = SS_UNCONNECTED;
1462 			vsock_transport_cancel_pkt(vsk);
1463 			vsock_remove_connected(vsk);
1464 			goto out_wait;
1465 		} else if ((sk->sk_state != TCP_ESTABLISHED) && (timeout == 0)) {
1466 			err = -ETIMEDOUT;
1467 			sk->sk_state = TCP_CLOSE;
1468 			sock->state = SS_UNCONNECTED;
1469 			vsock_transport_cancel_pkt(vsk);
1470 			goto out_wait;
1471 		}
1472 
1473 		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1474 	}
1475 
1476 	if (sk->sk_err) {
1477 		err = -sk->sk_err;
1478 		sk->sk_state = TCP_CLOSE;
1479 		sock->state = SS_UNCONNECTED;
1480 	} else {
1481 		err = 0;
1482 	}
1483 
1484 out_wait:
1485 	finish_wait(sk_sleep(sk), &wait);
1486 out:
1487 	release_sock(sk);
1488 	return err;
1489 }
1490 
1491 static int vsock_accept(struct socket *sock, struct socket *newsock, int flags,
1492 			bool kern)
1493 {
1494 	struct sock *listener;
1495 	int err;
1496 	struct sock *connected;
1497 	struct vsock_sock *vconnected;
1498 	long timeout;
1499 	DEFINE_WAIT(wait);
1500 
1501 	err = 0;
1502 	listener = sock->sk;
1503 
1504 	lock_sock(listener);
1505 
1506 	if (!sock_type_connectible(sock->type)) {
1507 		err = -EOPNOTSUPP;
1508 		goto out;
1509 	}
1510 
1511 	if (listener->sk_state != TCP_LISTEN) {
1512 		err = -EINVAL;
1513 		goto out;
1514 	}
1515 
1516 	/* Wait for children sockets to appear; these are the new sockets
1517 	 * created upon connection establishment.
1518 	 */
1519 	timeout = sock_rcvtimeo(listener, flags & O_NONBLOCK);
1520 	prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1521 
1522 	while ((connected = vsock_dequeue_accept(listener)) == NULL &&
1523 	       listener->sk_err == 0) {
1524 		release_sock(listener);
1525 		timeout = schedule_timeout(timeout);
1526 		finish_wait(sk_sleep(listener), &wait);
1527 		lock_sock(listener);
1528 
1529 		if (signal_pending(current)) {
1530 			err = sock_intr_errno(timeout);
1531 			goto out;
1532 		} else if (timeout == 0) {
1533 			err = -EAGAIN;
1534 			goto out;
1535 		}
1536 
1537 		prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1538 	}
1539 	finish_wait(sk_sleep(listener), &wait);
1540 
1541 	if (listener->sk_err)
1542 		err = -listener->sk_err;
1543 
1544 	if (connected) {
1545 		sk_acceptq_removed(listener);
1546 
1547 		lock_sock_nested(connected, SINGLE_DEPTH_NESTING);
1548 		vconnected = vsock_sk(connected);
1549 
1550 		/* If the listener socket has received an error, then we should
1551 		 * reject this socket and return.  Note that we simply mark the
1552 		 * socket rejected, drop our reference, and let the cleanup
1553 		 * function handle the cleanup; the fact that we found it in
1554 		 * the listener's accept queue guarantees that the cleanup
1555 		 * function hasn't run yet.
1556 		 */
1557 		if (err) {
1558 			vconnected->rejected = true;
1559 		} else {
1560 			newsock->state = SS_CONNECTED;
1561 			sock_graft(connected, newsock);
1562 		}
1563 
1564 		release_sock(connected);
1565 		sock_put(connected);
1566 	}
1567 
1568 out:
1569 	release_sock(listener);
1570 	return err;
1571 }
1572 
1573 static int vsock_listen(struct socket *sock, int backlog)
1574 {
1575 	int err;
1576 	struct sock *sk;
1577 	struct vsock_sock *vsk;
1578 
1579 	sk = sock->sk;
1580 
1581 	lock_sock(sk);
1582 
1583 	if (!sock_type_connectible(sk->sk_type)) {
1584 		err = -EOPNOTSUPP;
1585 		goto out;
1586 	}
1587 
1588 	if (sock->state != SS_UNCONNECTED) {
1589 		err = -EINVAL;
1590 		goto out;
1591 	}
1592 
1593 	vsk = vsock_sk(sk);
1594 
1595 	if (!vsock_addr_bound(&vsk->local_addr)) {
1596 		err = -EINVAL;
1597 		goto out;
1598 	}
1599 
1600 	sk->sk_max_ack_backlog = backlog;
1601 	sk->sk_state = TCP_LISTEN;
1602 
1603 	err = 0;
1604 
1605 out:
1606 	release_sock(sk);
1607 	return err;
1608 }
1609 
1610 static void vsock_update_buffer_size(struct vsock_sock *vsk,
1611 				     const struct vsock_transport *transport,
1612 				     u64 val)
1613 {
1614 	if (val > vsk->buffer_max_size)
1615 		val = vsk->buffer_max_size;
1616 
1617 	if (val < vsk->buffer_min_size)
1618 		val = vsk->buffer_min_size;
1619 
1620 	if (val != vsk->buffer_size &&
1621 	    transport && transport->notify_buffer_size)
1622 		transport->notify_buffer_size(vsk, &val);
1623 
1624 	vsk->buffer_size = val;
1625 }
1626 
1627 static int vsock_connectible_setsockopt(struct socket *sock,
1628 					int level,
1629 					int optname,
1630 					sockptr_t optval,
1631 					unsigned int optlen)
1632 {
1633 	int err;
1634 	struct sock *sk;
1635 	struct vsock_sock *vsk;
1636 	const struct vsock_transport *transport;
1637 	u64 val;
1638 
1639 	if (level != AF_VSOCK)
1640 		return -ENOPROTOOPT;
1641 
1642 #define COPY_IN(_v)                                       \
1643 	do {						  \
1644 		if (optlen < sizeof(_v)) {		  \
1645 			err = -EINVAL;			  \
1646 			goto exit;			  \
1647 		}					  \
1648 		if (copy_from_sockptr(&_v, optval, sizeof(_v)) != 0) {	\
1649 			err = -EFAULT;					\
1650 			goto exit;					\
1651 		}							\
1652 	} while (0)
1653 
1654 	err = 0;
1655 	sk = sock->sk;
1656 	vsk = vsock_sk(sk);
1657 
1658 	lock_sock(sk);
1659 
1660 	transport = vsk->transport;
1661 
1662 	switch (optname) {
1663 	case SO_VM_SOCKETS_BUFFER_SIZE:
1664 		COPY_IN(val);
1665 		vsock_update_buffer_size(vsk, transport, val);
1666 		break;
1667 
1668 	case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1669 		COPY_IN(val);
1670 		vsk->buffer_max_size = val;
1671 		vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
1672 		break;
1673 
1674 	case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1675 		COPY_IN(val);
1676 		vsk->buffer_min_size = val;
1677 		vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
1678 		break;
1679 
1680 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
1681 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD: {
1682 		struct __kernel_sock_timeval tv;
1683 
1684 		err = sock_copy_user_timeval(&tv, optval, optlen,
1685 					     optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
1686 		if (err)
1687 			break;
1688 		if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC &&
1689 		    tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) {
1690 			vsk->connect_timeout = tv.tv_sec * HZ +
1691 				DIV_ROUND_UP((unsigned long)tv.tv_usec, (USEC_PER_SEC / HZ));
1692 			if (vsk->connect_timeout == 0)
1693 				vsk->connect_timeout =
1694 				    VSOCK_DEFAULT_CONNECT_TIMEOUT;
1695 
1696 		} else {
1697 			err = -ERANGE;
1698 		}
1699 		break;
1700 	}
1701 
1702 	default:
1703 		err = -ENOPROTOOPT;
1704 		break;
1705 	}
1706 
1707 #undef COPY_IN
1708 
1709 exit:
1710 	release_sock(sk);
1711 	return err;
1712 }
1713 
1714 static int vsock_connectible_getsockopt(struct socket *sock,
1715 					int level, int optname,
1716 					char __user *optval,
1717 					int __user *optlen)
1718 {
1719 	struct sock *sk = sock->sk;
1720 	struct vsock_sock *vsk = vsock_sk(sk);
1721 
1722 	union {
1723 		u64 val64;
1724 		struct old_timeval32 tm32;
1725 		struct __kernel_old_timeval tm;
1726 		struct  __kernel_sock_timeval stm;
1727 	} v;
1728 
1729 	int lv = sizeof(v.val64);
1730 	int len;
1731 
1732 	if (level != AF_VSOCK)
1733 		return -ENOPROTOOPT;
1734 
1735 	if (get_user(len, optlen))
1736 		return -EFAULT;
1737 
1738 	memset(&v, 0, sizeof(v));
1739 
1740 	switch (optname) {
1741 	case SO_VM_SOCKETS_BUFFER_SIZE:
1742 		v.val64 = vsk->buffer_size;
1743 		break;
1744 
1745 	case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1746 		v.val64 = vsk->buffer_max_size;
1747 		break;
1748 
1749 	case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1750 		v.val64 = vsk->buffer_min_size;
1751 		break;
1752 
1753 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
1754 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD:
1755 		lv = sock_get_timeout(vsk->connect_timeout, &v,
1756 				      optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
1757 		break;
1758 
1759 	default:
1760 		return -ENOPROTOOPT;
1761 	}
1762 
1763 	if (len < lv)
1764 		return -EINVAL;
1765 	if (len > lv)
1766 		len = lv;
1767 	if (copy_to_user(optval, &v, len))
1768 		return -EFAULT;
1769 
1770 	if (put_user(len, optlen))
1771 		return -EFAULT;
1772 
1773 	return 0;
1774 }
1775 
1776 static int vsock_connectible_sendmsg(struct socket *sock, struct msghdr *msg,
1777 				     size_t len)
1778 {
1779 	struct sock *sk;
1780 	struct vsock_sock *vsk;
1781 	const struct vsock_transport *transport;
1782 	ssize_t total_written;
1783 	long timeout;
1784 	int err;
1785 	struct vsock_transport_send_notify_data send_data;
1786 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1787 
1788 	sk = sock->sk;
1789 	vsk = vsock_sk(sk);
1790 	total_written = 0;
1791 	err = 0;
1792 
1793 	if (msg->msg_flags & MSG_OOB)
1794 		return -EOPNOTSUPP;
1795 
1796 	lock_sock(sk);
1797 
1798 	transport = vsk->transport;
1799 
1800 	/* Callers should not provide a destination with connection oriented
1801 	 * sockets.
1802 	 */
1803 	if (msg->msg_namelen) {
1804 		err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
1805 		goto out;
1806 	}
1807 
1808 	/* Send data only if both sides are not shutdown in the direction. */
1809 	if (sk->sk_shutdown & SEND_SHUTDOWN ||
1810 	    vsk->peer_shutdown & RCV_SHUTDOWN) {
1811 		err = -EPIPE;
1812 		goto out;
1813 	}
1814 
1815 	if (!transport || sk->sk_state != TCP_ESTABLISHED ||
1816 	    !vsock_addr_bound(&vsk->local_addr)) {
1817 		err = -ENOTCONN;
1818 		goto out;
1819 	}
1820 
1821 	if (!vsock_addr_bound(&vsk->remote_addr)) {
1822 		err = -EDESTADDRREQ;
1823 		goto out;
1824 	}
1825 
1826 	/* Wait for room in the produce queue to enqueue our user's data. */
1827 	timeout = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1828 
1829 	err = transport->notify_send_init(vsk, &send_data);
1830 	if (err < 0)
1831 		goto out;
1832 
1833 	while (total_written < len) {
1834 		ssize_t written;
1835 
1836 		add_wait_queue(sk_sleep(sk), &wait);
1837 		while (vsock_stream_has_space(vsk) == 0 &&
1838 		       sk->sk_err == 0 &&
1839 		       !(sk->sk_shutdown & SEND_SHUTDOWN) &&
1840 		       !(vsk->peer_shutdown & RCV_SHUTDOWN)) {
1841 
1842 			/* Don't wait for non-blocking sockets. */
1843 			if (timeout == 0) {
1844 				err = -EAGAIN;
1845 				remove_wait_queue(sk_sleep(sk), &wait);
1846 				goto out_err;
1847 			}
1848 
1849 			err = transport->notify_send_pre_block(vsk, &send_data);
1850 			if (err < 0) {
1851 				remove_wait_queue(sk_sleep(sk), &wait);
1852 				goto out_err;
1853 			}
1854 
1855 			release_sock(sk);
1856 			timeout = wait_woken(&wait, TASK_INTERRUPTIBLE, timeout);
1857 			lock_sock(sk);
1858 			if (signal_pending(current)) {
1859 				err = sock_intr_errno(timeout);
1860 				remove_wait_queue(sk_sleep(sk), &wait);
1861 				goto out_err;
1862 			} else if (timeout == 0) {
1863 				err = -EAGAIN;
1864 				remove_wait_queue(sk_sleep(sk), &wait);
1865 				goto out_err;
1866 			}
1867 		}
1868 		remove_wait_queue(sk_sleep(sk), &wait);
1869 
1870 		/* These checks occur both as part of and after the loop
1871 		 * conditional since we need to check before and after
1872 		 * sleeping.
1873 		 */
1874 		if (sk->sk_err) {
1875 			err = -sk->sk_err;
1876 			goto out_err;
1877 		} else if ((sk->sk_shutdown & SEND_SHUTDOWN) ||
1878 			   (vsk->peer_shutdown & RCV_SHUTDOWN)) {
1879 			err = -EPIPE;
1880 			goto out_err;
1881 		}
1882 
1883 		err = transport->notify_send_pre_enqueue(vsk, &send_data);
1884 		if (err < 0)
1885 			goto out_err;
1886 
1887 		/* Note that enqueue will only write as many bytes as are free
1888 		 * in the produce queue, so we don't need to ensure len is
1889 		 * smaller than the queue size.  It is the caller's
1890 		 * responsibility to check how many bytes we were able to send.
1891 		 */
1892 
1893 		if (sk->sk_type == SOCK_SEQPACKET) {
1894 			written = transport->seqpacket_enqueue(vsk,
1895 						msg, len - total_written);
1896 		} else {
1897 			written = transport->stream_enqueue(vsk,
1898 					msg, len - total_written);
1899 		}
1900 
1901 		if (written < 0) {
1902 			err = written;
1903 			goto out_err;
1904 		}
1905 
1906 		total_written += written;
1907 
1908 		err = transport->notify_send_post_enqueue(
1909 				vsk, written, &send_data);
1910 		if (err < 0)
1911 			goto out_err;
1912 
1913 	}
1914 
1915 out_err:
1916 	if (total_written > 0) {
1917 		/* Return number of written bytes only if:
1918 		 * 1) SOCK_STREAM socket.
1919 		 * 2) SOCK_SEQPACKET socket when whole buffer is sent.
1920 		 */
1921 		if (sk->sk_type == SOCK_STREAM || total_written == len)
1922 			err = total_written;
1923 	}
1924 out:
1925 	release_sock(sk);
1926 	return err;
1927 }
1928 
1929 static int vsock_connectible_wait_data(struct sock *sk,
1930 				       struct wait_queue_entry *wait,
1931 				       long timeout,
1932 				       struct vsock_transport_recv_notify_data *recv_data,
1933 				       size_t target)
1934 {
1935 	const struct vsock_transport *transport;
1936 	struct vsock_sock *vsk;
1937 	s64 data;
1938 	int err;
1939 
1940 	vsk = vsock_sk(sk);
1941 	err = 0;
1942 	transport = vsk->transport;
1943 
1944 	while (1) {
1945 		prepare_to_wait(sk_sleep(sk), wait, TASK_INTERRUPTIBLE);
1946 		data = vsock_connectible_has_data(vsk);
1947 		if (data != 0)
1948 			break;
1949 
1950 		if (sk->sk_err != 0 ||
1951 		    (sk->sk_shutdown & RCV_SHUTDOWN) ||
1952 		    (vsk->peer_shutdown & SEND_SHUTDOWN)) {
1953 			break;
1954 		}
1955 
1956 		/* Don't wait for non-blocking sockets. */
1957 		if (timeout == 0) {
1958 			err = -EAGAIN;
1959 			break;
1960 		}
1961 
1962 		if (recv_data) {
1963 			err = transport->notify_recv_pre_block(vsk, target, recv_data);
1964 			if (err < 0)
1965 				break;
1966 		}
1967 
1968 		release_sock(sk);
1969 		timeout = schedule_timeout(timeout);
1970 		lock_sock(sk);
1971 
1972 		if (signal_pending(current)) {
1973 			err = sock_intr_errno(timeout);
1974 			break;
1975 		} else if (timeout == 0) {
1976 			err = -EAGAIN;
1977 			break;
1978 		}
1979 	}
1980 
1981 	finish_wait(sk_sleep(sk), wait);
1982 
1983 	if (err)
1984 		return err;
1985 
1986 	/* Internal transport error when checking for available
1987 	 * data. XXX This should be changed to a connection
1988 	 * reset in a later change.
1989 	 */
1990 	if (data < 0)
1991 		return -ENOMEM;
1992 
1993 	return data;
1994 }
1995 
1996 static int __vsock_stream_recvmsg(struct sock *sk, struct msghdr *msg,
1997 				  size_t len, int flags)
1998 {
1999 	struct vsock_transport_recv_notify_data recv_data;
2000 	const struct vsock_transport *transport;
2001 	struct vsock_sock *vsk;
2002 	ssize_t copied;
2003 	size_t target;
2004 	long timeout;
2005 	int err;
2006 
2007 	DEFINE_WAIT(wait);
2008 
2009 	vsk = vsock_sk(sk);
2010 	transport = vsk->transport;
2011 
2012 	/* We must not copy less than target bytes into the user's buffer
2013 	 * before returning successfully, so we wait for the consume queue to
2014 	 * have that much data to consume before dequeueing.  Note that this
2015 	 * makes it impossible to handle cases where target is greater than the
2016 	 * queue size.
2017 	 */
2018 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2019 	if (target >= transport->stream_rcvhiwat(vsk)) {
2020 		err = -ENOMEM;
2021 		goto out;
2022 	}
2023 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2024 	copied = 0;
2025 
2026 	err = transport->notify_recv_init(vsk, target, &recv_data);
2027 	if (err < 0)
2028 		goto out;
2029 
2030 
2031 	while (1) {
2032 		ssize_t read;
2033 
2034 		err = vsock_connectible_wait_data(sk, &wait, timeout,
2035 						  &recv_data, target);
2036 		if (err <= 0)
2037 			break;
2038 
2039 		err = transport->notify_recv_pre_dequeue(vsk, target,
2040 							 &recv_data);
2041 		if (err < 0)
2042 			break;
2043 
2044 		read = transport->stream_dequeue(vsk, msg, len - copied, flags);
2045 		if (read < 0) {
2046 			err = read;
2047 			break;
2048 		}
2049 
2050 		copied += read;
2051 
2052 		err = transport->notify_recv_post_dequeue(vsk, target, read,
2053 						!(flags & MSG_PEEK), &recv_data);
2054 		if (err < 0)
2055 			goto out;
2056 
2057 		if (read >= target || flags & MSG_PEEK)
2058 			break;
2059 
2060 		target -= read;
2061 	}
2062 
2063 	if (sk->sk_err)
2064 		err = -sk->sk_err;
2065 	else if (sk->sk_shutdown & RCV_SHUTDOWN)
2066 		err = 0;
2067 
2068 	if (copied > 0)
2069 		err = copied;
2070 
2071 out:
2072 	return err;
2073 }
2074 
2075 static int __vsock_seqpacket_recvmsg(struct sock *sk, struct msghdr *msg,
2076 				     size_t len, int flags)
2077 {
2078 	const struct vsock_transport *transport;
2079 	struct vsock_sock *vsk;
2080 	ssize_t msg_len;
2081 	long timeout;
2082 	int err = 0;
2083 	DEFINE_WAIT(wait);
2084 
2085 	vsk = vsock_sk(sk);
2086 	transport = vsk->transport;
2087 
2088 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2089 
2090 	err = vsock_connectible_wait_data(sk, &wait, timeout, NULL, 0);
2091 	if (err <= 0)
2092 		goto out;
2093 
2094 	msg_len = transport->seqpacket_dequeue(vsk, msg, flags);
2095 
2096 	if (msg_len < 0) {
2097 		err = msg_len;
2098 		goto out;
2099 	}
2100 
2101 	if (sk->sk_err) {
2102 		err = -sk->sk_err;
2103 	} else if (sk->sk_shutdown & RCV_SHUTDOWN) {
2104 		err = 0;
2105 	} else {
2106 		/* User sets MSG_TRUNC, so return real length of
2107 		 * packet.
2108 		 */
2109 		if (flags & MSG_TRUNC)
2110 			err = msg_len;
2111 		else
2112 			err = len - msg_data_left(msg);
2113 
2114 		/* Always set MSG_TRUNC if real length of packet is
2115 		 * bigger than user's buffer.
2116 		 */
2117 		if (msg_len > len)
2118 			msg->msg_flags |= MSG_TRUNC;
2119 	}
2120 
2121 out:
2122 	return err;
2123 }
2124 
2125 int
2126 vsock_connectible_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
2127 			  int flags)
2128 {
2129 	struct sock *sk;
2130 	struct vsock_sock *vsk;
2131 	const struct vsock_transport *transport;
2132 #ifdef CONFIG_BPF_SYSCALL
2133 	const struct proto *prot;
2134 #endif
2135 	int err;
2136 
2137 	sk = sock->sk;
2138 	vsk = vsock_sk(sk);
2139 	err = 0;
2140 
2141 	lock_sock(sk);
2142 
2143 	transport = vsk->transport;
2144 
2145 	if (!transport || sk->sk_state != TCP_ESTABLISHED) {
2146 		/* Recvmsg is supposed to return 0 if a peer performs an
2147 		 * orderly shutdown. Differentiate between that case and when a
2148 		 * peer has not connected or a local shutdown occurred with the
2149 		 * SOCK_DONE flag.
2150 		 */
2151 		if (sock_flag(sk, SOCK_DONE))
2152 			err = 0;
2153 		else
2154 			err = -ENOTCONN;
2155 
2156 		goto out;
2157 	}
2158 
2159 	if (flags & MSG_OOB) {
2160 		err = -EOPNOTSUPP;
2161 		goto out;
2162 	}
2163 
2164 	/* We don't check peer_shutdown flag here since peer may actually shut
2165 	 * down, but there can be data in the queue that a local socket can
2166 	 * receive.
2167 	 */
2168 	if (sk->sk_shutdown & RCV_SHUTDOWN) {
2169 		err = 0;
2170 		goto out;
2171 	}
2172 
2173 	/* It is valid on Linux to pass in a zero-length receive buffer.  This
2174 	 * is not an error.  We may as well bail out now.
2175 	 */
2176 	if (!len) {
2177 		err = 0;
2178 		goto out;
2179 	}
2180 
2181 #ifdef CONFIG_BPF_SYSCALL
2182 	prot = READ_ONCE(sk->sk_prot);
2183 	if (prot != &vsock_proto) {
2184 		release_sock(sk);
2185 		return prot->recvmsg(sk, msg, len, flags, NULL);
2186 	}
2187 #endif
2188 
2189 	if (sk->sk_type == SOCK_STREAM)
2190 		err = __vsock_stream_recvmsg(sk, msg, len, flags);
2191 	else
2192 		err = __vsock_seqpacket_recvmsg(sk, msg, len, flags);
2193 
2194 out:
2195 	release_sock(sk);
2196 	return err;
2197 }
2198 EXPORT_SYMBOL_GPL(vsock_connectible_recvmsg);
2199 
2200 static int vsock_set_rcvlowat(struct sock *sk, int val)
2201 {
2202 	const struct vsock_transport *transport;
2203 	struct vsock_sock *vsk;
2204 
2205 	vsk = vsock_sk(sk);
2206 
2207 	if (val > vsk->buffer_size)
2208 		return -EINVAL;
2209 
2210 	transport = vsk->transport;
2211 
2212 	if (transport && transport->set_rcvlowat)
2213 		return transport->set_rcvlowat(vsk, val);
2214 
2215 	WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
2216 	return 0;
2217 }
2218 
2219 static const struct proto_ops vsock_stream_ops = {
2220 	.family = PF_VSOCK,
2221 	.owner = THIS_MODULE,
2222 	.release = vsock_release,
2223 	.bind = vsock_bind,
2224 	.connect = vsock_connect,
2225 	.socketpair = sock_no_socketpair,
2226 	.accept = vsock_accept,
2227 	.getname = vsock_getname,
2228 	.poll = vsock_poll,
2229 	.ioctl = sock_no_ioctl,
2230 	.listen = vsock_listen,
2231 	.shutdown = vsock_shutdown,
2232 	.setsockopt = vsock_connectible_setsockopt,
2233 	.getsockopt = vsock_connectible_getsockopt,
2234 	.sendmsg = vsock_connectible_sendmsg,
2235 	.recvmsg = vsock_connectible_recvmsg,
2236 	.mmap = sock_no_mmap,
2237 	.sendpage = sock_no_sendpage,
2238 	.set_rcvlowat = vsock_set_rcvlowat,
2239 	.read_skb = vsock_read_skb,
2240 };
2241 
2242 static const struct proto_ops vsock_seqpacket_ops = {
2243 	.family = PF_VSOCK,
2244 	.owner = THIS_MODULE,
2245 	.release = vsock_release,
2246 	.bind = vsock_bind,
2247 	.connect = vsock_connect,
2248 	.socketpair = sock_no_socketpair,
2249 	.accept = vsock_accept,
2250 	.getname = vsock_getname,
2251 	.poll = vsock_poll,
2252 	.ioctl = sock_no_ioctl,
2253 	.listen = vsock_listen,
2254 	.shutdown = vsock_shutdown,
2255 	.setsockopt = vsock_connectible_setsockopt,
2256 	.getsockopt = vsock_connectible_getsockopt,
2257 	.sendmsg = vsock_connectible_sendmsg,
2258 	.recvmsg = vsock_connectible_recvmsg,
2259 	.mmap = sock_no_mmap,
2260 	.sendpage = sock_no_sendpage,
2261 	.read_skb = vsock_read_skb,
2262 };
2263 
2264 static int vsock_create(struct net *net, struct socket *sock,
2265 			int protocol, int kern)
2266 {
2267 	struct vsock_sock *vsk;
2268 	struct sock *sk;
2269 	int ret;
2270 
2271 	if (!sock)
2272 		return -EINVAL;
2273 
2274 	if (protocol && protocol != PF_VSOCK)
2275 		return -EPROTONOSUPPORT;
2276 
2277 	switch (sock->type) {
2278 	case SOCK_DGRAM:
2279 		sock->ops = &vsock_dgram_ops;
2280 		break;
2281 	case SOCK_STREAM:
2282 		sock->ops = &vsock_stream_ops;
2283 		break;
2284 	case SOCK_SEQPACKET:
2285 		sock->ops = &vsock_seqpacket_ops;
2286 		break;
2287 	default:
2288 		return -ESOCKTNOSUPPORT;
2289 	}
2290 
2291 	sock->state = SS_UNCONNECTED;
2292 
2293 	sk = __vsock_create(net, sock, NULL, GFP_KERNEL, 0, kern);
2294 	if (!sk)
2295 		return -ENOMEM;
2296 
2297 	vsk = vsock_sk(sk);
2298 
2299 	if (sock->type == SOCK_DGRAM) {
2300 		ret = vsock_assign_transport(vsk, NULL);
2301 		if (ret < 0) {
2302 			sock_put(sk);
2303 			return ret;
2304 		}
2305 	}
2306 
2307 	vsock_insert_unbound(vsk);
2308 
2309 	return 0;
2310 }
2311 
2312 static const struct net_proto_family vsock_family_ops = {
2313 	.family = AF_VSOCK,
2314 	.create = vsock_create,
2315 	.owner = THIS_MODULE,
2316 };
2317 
2318 static long vsock_dev_do_ioctl(struct file *filp,
2319 			       unsigned int cmd, void __user *ptr)
2320 {
2321 	u32 __user *p = ptr;
2322 	u32 cid = VMADDR_CID_ANY;
2323 	int retval = 0;
2324 
2325 	switch (cmd) {
2326 	case IOCTL_VM_SOCKETS_GET_LOCAL_CID:
2327 		/* To be compatible with the VMCI behavior, we prioritize the
2328 		 * guest CID instead of well-know host CID (VMADDR_CID_HOST).
2329 		 */
2330 		if (transport_g2h)
2331 			cid = transport_g2h->get_local_cid();
2332 		else if (transport_h2g)
2333 			cid = transport_h2g->get_local_cid();
2334 
2335 		if (put_user(cid, p) != 0)
2336 			retval = -EFAULT;
2337 		break;
2338 
2339 	default:
2340 		retval = -ENOIOCTLCMD;
2341 	}
2342 
2343 	return retval;
2344 }
2345 
2346 static long vsock_dev_ioctl(struct file *filp,
2347 			    unsigned int cmd, unsigned long arg)
2348 {
2349 	return vsock_dev_do_ioctl(filp, cmd, (void __user *)arg);
2350 }
2351 
2352 #ifdef CONFIG_COMPAT
2353 static long vsock_dev_compat_ioctl(struct file *filp,
2354 				   unsigned int cmd, unsigned long arg)
2355 {
2356 	return vsock_dev_do_ioctl(filp, cmd, compat_ptr(arg));
2357 }
2358 #endif
2359 
2360 static const struct file_operations vsock_device_ops = {
2361 	.owner		= THIS_MODULE,
2362 	.unlocked_ioctl	= vsock_dev_ioctl,
2363 #ifdef CONFIG_COMPAT
2364 	.compat_ioctl	= vsock_dev_compat_ioctl,
2365 #endif
2366 	.open		= nonseekable_open,
2367 };
2368 
2369 static struct miscdevice vsock_device = {
2370 	.name		= "vsock",
2371 	.fops		= &vsock_device_ops,
2372 };
2373 
2374 static int __init vsock_init(void)
2375 {
2376 	int err = 0;
2377 
2378 	vsock_init_tables();
2379 
2380 	vsock_proto.owner = THIS_MODULE;
2381 	vsock_device.minor = MISC_DYNAMIC_MINOR;
2382 	err = misc_register(&vsock_device);
2383 	if (err) {
2384 		pr_err("Failed to register misc device\n");
2385 		goto err_reset_transport;
2386 	}
2387 
2388 	err = proto_register(&vsock_proto, 1);	/* we want our slab */
2389 	if (err) {
2390 		pr_err("Cannot register vsock protocol\n");
2391 		goto err_deregister_misc;
2392 	}
2393 
2394 	err = sock_register(&vsock_family_ops);
2395 	if (err) {
2396 		pr_err("could not register af_vsock (%d) address family: %d\n",
2397 		       AF_VSOCK, err);
2398 		goto err_unregister_proto;
2399 	}
2400 
2401 	vsock_bpf_build_proto();
2402 
2403 	return 0;
2404 
2405 err_unregister_proto:
2406 	proto_unregister(&vsock_proto);
2407 err_deregister_misc:
2408 	misc_deregister(&vsock_device);
2409 err_reset_transport:
2410 	return err;
2411 }
2412 
2413 static void __exit vsock_exit(void)
2414 {
2415 	misc_deregister(&vsock_device);
2416 	sock_unregister(AF_VSOCK);
2417 	proto_unregister(&vsock_proto);
2418 }
2419 
2420 const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)
2421 {
2422 	return vsk->transport;
2423 }
2424 EXPORT_SYMBOL_GPL(vsock_core_get_transport);
2425 
2426 int vsock_core_register(const struct vsock_transport *t, int features)
2427 {
2428 	const struct vsock_transport *t_h2g, *t_g2h, *t_dgram, *t_local;
2429 	int err = mutex_lock_interruptible(&vsock_register_mutex);
2430 
2431 	if (err)
2432 		return err;
2433 
2434 	t_h2g = transport_h2g;
2435 	t_g2h = transport_g2h;
2436 	t_dgram = transport_dgram;
2437 	t_local = transport_local;
2438 
2439 	if (features & VSOCK_TRANSPORT_F_H2G) {
2440 		if (t_h2g) {
2441 			err = -EBUSY;
2442 			goto err_busy;
2443 		}
2444 		t_h2g = t;
2445 	}
2446 
2447 	if (features & VSOCK_TRANSPORT_F_G2H) {
2448 		if (t_g2h) {
2449 			err = -EBUSY;
2450 			goto err_busy;
2451 		}
2452 		t_g2h = t;
2453 	}
2454 
2455 	if (features & VSOCK_TRANSPORT_F_DGRAM) {
2456 		if (t_dgram) {
2457 			err = -EBUSY;
2458 			goto err_busy;
2459 		}
2460 		t_dgram = t;
2461 	}
2462 
2463 	if (features & VSOCK_TRANSPORT_F_LOCAL) {
2464 		if (t_local) {
2465 			err = -EBUSY;
2466 			goto err_busy;
2467 		}
2468 		t_local = t;
2469 	}
2470 
2471 	transport_h2g = t_h2g;
2472 	transport_g2h = t_g2h;
2473 	transport_dgram = t_dgram;
2474 	transport_local = t_local;
2475 
2476 err_busy:
2477 	mutex_unlock(&vsock_register_mutex);
2478 	return err;
2479 }
2480 EXPORT_SYMBOL_GPL(vsock_core_register);
2481 
2482 void vsock_core_unregister(const struct vsock_transport *t)
2483 {
2484 	mutex_lock(&vsock_register_mutex);
2485 
2486 	if (transport_h2g == t)
2487 		transport_h2g = NULL;
2488 
2489 	if (transport_g2h == t)
2490 		transport_g2h = NULL;
2491 
2492 	if (transport_dgram == t)
2493 		transport_dgram = NULL;
2494 
2495 	if (transport_local == t)
2496 		transport_local = NULL;
2497 
2498 	mutex_unlock(&vsock_register_mutex);
2499 }
2500 EXPORT_SYMBOL_GPL(vsock_core_unregister);
2501 
2502 module_init(vsock_init);
2503 module_exit(vsock_exit);
2504 
2505 MODULE_AUTHOR("VMware, Inc.");
2506 MODULE_DESCRIPTION("VMware Virtual Socket Family");
2507 MODULE_VERSION("1.0.2.0-k");
2508 MODULE_LICENSE("GPL v2");
2509