xref: /linux/net/vmw_vsock/af_vsock.c (revision 90e63d5354951d37fa2b3b91e6f17b95d2bf9bee)
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  * - Namespaces in vsock support two different modes: "local" and "global".
88  *   Each mode defines how the namespace interacts with CIDs.
89  *   Each namespace exposes two sysctl files:
90  *
91  *   - /proc/sys/net/vsock/ns_mode (read-only) reports the current namespace's
92  *     mode, which is set at namespace creation and immutable thereafter.
93  *   - /proc/sys/net/vsock/child_ns_mode (write-once) controls what mode future
94  *     child namespaces will inherit when created. The initial value matches
95  *     the namespace's own ns_mode.
96  *
97  *   Changing child_ns_mode only affects newly created namespaces, not the
98  *   current namespace or existing children. A "local" namespace cannot set
99  *   child_ns_mode to "global". child_ns_mode is write-once, so that it may be
100  *   configured and locked down by a namespace manager. Writing a different
101  *   value after the first write returns -EBUSY. At namespace creation, ns_mode
102  *   is inherited from the parent's child_ns_mode.
103  *
104  *   The init_net mode is "global" and cannot be modified. The init_net
105  *   child_ns_mode is also write-once, so an init process (e.g. systemd) can
106  *   set it to "local" to ensure all new namespaces inherit local mode.
107  *
108  *   The modes affect the allocation and accessibility of CIDs as follows:
109  *
110  *   - global - access and allocation are all system-wide
111  *      - all CID allocation from global namespaces draw from the same
112  *        system-wide pool.
113  *      - if one global namespace has already allocated some CID, another
114  *        global namespace will not be able to allocate the same CID.
115  *      - global mode AF_VSOCK sockets can reach any VM or socket in any global
116  *        namespace, they are not contained to only their own namespace.
117  *      - AF_VSOCK sockets in a global mode namespace cannot reach VMs or
118  *        sockets in any local mode namespace.
119  *   - local - access and allocation are contained within the namespace
120  *     - CID allocation draws only from a private pool local only to the
121  *       namespace, and does not affect the CIDs available for allocation in any
122  *       other namespace (global or local).
123  *     - VMs in a local namespace do not collide with CIDs in any other local
124  *       namespace or any global namespace. For example, if a VM in a local mode
125  *       namespace is given CID 10, then CID 10 is still available for
126  *       allocation in any other namespace, but not in the same namespace.
127  *     - AF_VSOCK sockets in a local mode namespace can connect only to VMs or
128  *       other sockets within their own namespace.
129  *     - sockets bound to VMADDR_CID_ANY in local namespaces will never resolve
130  *       to any transport that is not compatible with local mode. There is no
131  *       error that propagates to the user (as there is for connection attempts)
132  *       because it is possible for some packet to reach this socket from
133  *       a different transport that *does* support local mode. For
134  *       example, virtio-vsock may not support local mode, but the socket
135  *       may still accept a connection from vhost-vsock which does.
136  */
137 
138 #include <linux/compat.h>
139 #include <linux/types.h>
140 #include <linux/bitops.h>
141 #include <linux/cred.h>
142 #include <linux/errqueue.h>
143 #include <linux/init.h>
144 #include <linux/io.h>
145 #include <linux/kernel.h>
146 #include <linux/sched/signal.h>
147 #include <linux/kmod.h>
148 #include <linux/list.h>
149 #include <linux/miscdevice.h>
150 #include <linux/module.h>
151 #include <linux/mutex.h>
152 #include <linux/net.h>
153 #include <linux/proc_fs.h>
154 #include <linux/poll.h>
155 #include <linux/random.h>
156 #include <linux/skbuff.h>
157 #include <linux/smp.h>
158 #include <linux/uio.h>
159 #include <linux/socket.h>
160 #include <linux/stddef.h>
161 #include <linux/sysctl.h>
162 #include <linux/unistd.h>
163 #include <linux/wait.h>
164 #include <linux/workqueue.h>
165 #include <net/sock.h>
166 #include <net/af_vsock.h>
167 #include <net/netns/vsock.h>
168 #include <uapi/linux/vm_sockets.h>
169 #include <uapi/asm-generic/ioctls.h>
170 
171 #define VSOCK_NET_MODE_STR_GLOBAL "global"
172 #define VSOCK_NET_MODE_STR_LOCAL "local"
173 
174 /* 6 chars for "global", 1 for null-terminator, and 1 more for '\n'.
175  * The newline is added by proc_dostring() for read operations.
176  */
177 #define VSOCK_NET_MODE_STR_MAX 8
178 
179 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr);
180 static void vsock_sk_destruct(struct sock *sk);
181 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb);
182 static void vsock_close(struct sock *sk, long timeout);
183 
184 /* Protocol family. */
185 struct proto vsock_proto = {
186 	.name = "AF_VSOCK",
187 	.owner = THIS_MODULE,
188 	.obj_size = sizeof(struct vsock_sock),
189 	.close = vsock_close,
190 #ifdef CONFIG_BPF_SYSCALL
191 	.psock_update_sk_prot = vsock_bpf_update_proto,
192 #endif
193 };
194 
195 /* The default peer timeout indicates how long we will wait for a peer response
196  * to a control message.
197  */
198 #define VSOCK_DEFAULT_CONNECT_TIMEOUT (2 * HZ)
199 
200 #define VSOCK_DEFAULT_BUFFER_SIZE     (1024 * 256)
201 #define VSOCK_DEFAULT_BUFFER_MAX_SIZE (1024 * 256)
202 #define VSOCK_DEFAULT_BUFFER_MIN_SIZE 128
203 
204 /* Transport used for host->guest communication */
205 static const struct vsock_transport *transport_h2g;
206 /* Transport used for guest->host communication */
207 static const struct vsock_transport *transport_g2h;
208 /* Transport used for DGRAM communication */
209 static const struct vsock_transport *transport_dgram;
210 /* Transport used for local communication */
211 static const struct vsock_transport *transport_local;
212 static DEFINE_MUTEX(vsock_register_mutex);
213 
214 /**** UTILS ****/
215 
216 /* Each bound VSocket is stored in the bind hash table and each connected
217  * VSocket is stored in the connected hash table.
218  *
219  * Unbound sockets are all put on the same list attached to the end of the hash
220  * table (vsock_unbound_sockets).  Bound sockets are added to the hash table in
221  * the bucket that their local address hashes to (vsock_bound_sockets(addr)
222  * represents the list that addr hashes to).
223  *
224  * Specifically, we initialize the vsock_bind_table array to a size of
225  * VSOCK_HASH_SIZE + 1 so that vsock_bind_table[0] through
226  * vsock_bind_table[VSOCK_HASH_SIZE - 1] are for bound sockets and
227  * vsock_bind_table[VSOCK_HASH_SIZE] is for unbound sockets.  The hash function
228  * mods with VSOCK_HASH_SIZE to ensure this.
229  */
230 #define MAX_PORT_RETRIES        24
231 
232 #define VSOCK_HASH(addr)        ((addr)->svm_port % VSOCK_HASH_SIZE)
233 #define vsock_bound_sockets(addr) (&vsock_bind_table[VSOCK_HASH(addr)])
234 #define vsock_unbound_sockets     (&vsock_bind_table[VSOCK_HASH_SIZE])
235 
236 /* XXX This can probably be implemented in a better way. */
237 #define VSOCK_CONN_HASH(src, dst)				\
238 	(((src)->svm_cid ^ (dst)->svm_port) % VSOCK_HASH_SIZE)
239 #define vsock_connected_sockets(src, dst)		\
240 	(&vsock_connected_table[VSOCK_CONN_HASH(src, dst)])
241 #define vsock_connected_sockets_vsk(vsk)				\
242 	vsock_connected_sockets(&(vsk)->remote_addr, &(vsk)->local_addr)
243 
244 struct list_head vsock_bind_table[VSOCK_HASH_SIZE + 1];
245 EXPORT_SYMBOL_GPL(vsock_bind_table);
246 struct list_head vsock_connected_table[VSOCK_HASH_SIZE];
247 EXPORT_SYMBOL_GPL(vsock_connected_table);
248 DEFINE_SPINLOCK(vsock_table_lock);
249 EXPORT_SYMBOL_GPL(vsock_table_lock);
250 
251 /* Autobind this socket to the local address if necessary. */
252 static int vsock_auto_bind(struct vsock_sock *vsk)
253 {
254 	struct sock *sk = sk_vsock(vsk);
255 	struct sockaddr_vm local_addr;
256 
257 	if (vsock_addr_bound(&vsk->local_addr))
258 		return 0;
259 	vsock_addr_init(&local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
260 	return __vsock_bind(sk, &local_addr);
261 }
262 
263 static void vsock_init_tables(void)
264 {
265 	int i;
266 
267 	for (i = 0; i < ARRAY_SIZE(vsock_bind_table); i++)
268 		INIT_LIST_HEAD(&vsock_bind_table[i]);
269 
270 	for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++)
271 		INIT_LIST_HEAD(&vsock_connected_table[i]);
272 }
273 
274 static void __vsock_insert_bound(struct list_head *list,
275 				 struct vsock_sock *vsk)
276 {
277 	sock_hold(&vsk->sk);
278 	list_add(&vsk->bound_table, list);
279 }
280 
281 static void __vsock_insert_connected(struct list_head *list,
282 				     struct vsock_sock *vsk)
283 {
284 	sock_hold(&vsk->sk);
285 	list_add(&vsk->connected_table, list);
286 }
287 
288 static void __vsock_remove_bound(struct vsock_sock *vsk)
289 {
290 	list_del_init(&vsk->bound_table);
291 	sock_put(&vsk->sk);
292 }
293 
294 static void __vsock_remove_connected(struct vsock_sock *vsk)
295 {
296 	list_del_init(&vsk->connected_table);
297 	sock_put(&vsk->sk);
298 }
299 
300 static struct sock *__vsock_find_bound_socket_net(struct sockaddr_vm *addr,
301 						  struct net *net)
302 {
303 	struct vsock_sock *vsk;
304 
305 	list_for_each_entry(vsk, vsock_bound_sockets(addr), bound_table) {
306 		struct sock *sk = sk_vsock(vsk);
307 
308 		if (vsock_addr_equals_addr(addr, &vsk->local_addr) &&
309 		    vsock_net_check_mode(sock_net(sk), net))
310 			return sk;
311 
312 		if (addr->svm_port == vsk->local_addr.svm_port &&
313 		    (vsk->local_addr.svm_cid == VMADDR_CID_ANY ||
314 		     addr->svm_cid == VMADDR_CID_ANY) &&
315 		     vsock_net_check_mode(sock_net(sk), net))
316 			return sk;
317 	}
318 
319 	return NULL;
320 }
321 
322 static struct sock *
323 __vsock_find_connected_socket_net(struct sockaddr_vm *src,
324 				  struct sockaddr_vm *dst, struct net *net)
325 {
326 	struct vsock_sock *vsk;
327 
328 	list_for_each_entry(vsk, vsock_connected_sockets(src, dst),
329 			    connected_table) {
330 		struct sock *sk = sk_vsock(vsk);
331 
332 		if (vsock_addr_equals_addr(src, &vsk->remote_addr) &&
333 		    dst->svm_port == vsk->local_addr.svm_port &&
334 		    vsock_net_check_mode(sock_net(sk), net)) {
335 			return sk;
336 		}
337 	}
338 
339 	return NULL;
340 }
341 
342 static void vsock_insert_unbound(struct vsock_sock *vsk)
343 {
344 	spin_lock_bh(&vsock_table_lock);
345 	__vsock_insert_bound(vsock_unbound_sockets, vsk);
346 	spin_unlock_bh(&vsock_table_lock);
347 }
348 
349 void vsock_insert_connected(struct vsock_sock *vsk)
350 {
351 	struct list_head *list = vsock_connected_sockets(
352 		&vsk->remote_addr, &vsk->local_addr);
353 
354 	spin_lock_bh(&vsock_table_lock);
355 	__vsock_insert_connected(list, vsk);
356 	spin_unlock_bh(&vsock_table_lock);
357 }
358 EXPORT_SYMBOL_GPL(vsock_insert_connected);
359 
360 void vsock_remove_bound(struct vsock_sock *vsk)
361 {
362 	spin_lock_bh(&vsock_table_lock);
363 	if (__vsock_in_bound_table(vsk))
364 		__vsock_remove_bound(vsk);
365 	spin_unlock_bh(&vsock_table_lock);
366 }
367 EXPORT_SYMBOL_GPL(vsock_remove_bound);
368 
369 void vsock_remove_connected(struct vsock_sock *vsk)
370 {
371 	spin_lock_bh(&vsock_table_lock);
372 	if (__vsock_in_connected_table(vsk))
373 		__vsock_remove_connected(vsk);
374 	spin_unlock_bh(&vsock_table_lock);
375 }
376 EXPORT_SYMBOL_GPL(vsock_remove_connected);
377 
378 /* Find a bound socket, filtering by namespace and namespace mode.
379  *
380  * Use this in transports that are namespace-aware and can provide the
381  * network namespace context.
382  */
383 struct sock *vsock_find_bound_socket_net(struct sockaddr_vm *addr,
384 					 struct net *net)
385 {
386 	struct sock *sk;
387 
388 	spin_lock_bh(&vsock_table_lock);
389 	sk = __vsock_find_bound_socket_net(addr, net);
390 	if (sk)
391 		sock_hold(sk);
392 
393 	spin_unlock_bh(&vsock_table_lock);
394 
395 	return sk;
396 }
397 EXPORT_SYMBOL_GPL(vsock_find_bound_socket_net);
398 
399 /* Find a bound socket without namespace filtering.
400  *
401  * Use this in transports that lack namespace context. All sockets are
402  * treated as if in global mode.
403  */
404 struct sock *vsock_find_bound_socket(struct sockaddr_vm *addr)
405 {
406 	return vsock_find_bound_socket_net(addr, NULL);
407 }
408 EXPORT_SYMBOL_GPL(vsock_find_bound_socket);
409 
410 /* Find a connected socket, filtering by namespace and namespace mode.
411  *
412  * Use this in transports that are namespace-aware and can provide the
413  * network namespace context.
414  */
415 struct sock *vsock_find_connected_socket_net(struct sockaddr_vm *src,
416 					     struct sockaddr_vm *dst,
417 					     struct net *net)
418 {
419 	struct sock *sk;
420 
421 	spin_lock_bh(&vsock_table_lock);
422 	sk = __vsock_find_connected_socket_net(src, dst, net);
423 	if (sk)
424 		sock_hold(sk);
425 
426 	spin_unlock_bh(&vsock_table_lock);
427 
428 	return sk;
429 }
430 EXPORT_SYMBOL_GPL(vsock_find_connected_socket_net);
431 
432 /* Find a connected socket without namespace filtering.
433  *
434  * Use this in transports that lack namespace context. All sockets are
435  * treated as if in global mode.
436  */
437 struct sock *vsock_find_connected_socket(struct sockaddr_vm *src,
438 					 struct sockaddr_vm *dst)
439 {
440 	return vsock_find_connected_socket_net(src, dst, NULL);
441 }
442 EXPORT_SYMBOL_GPL(vsock_find_connected_socket);
443 
444 void vsock_remove_sock(struct vsock_sock *vsk)
445 {
446 	/* Transport reassignment must not remove the binding. */
447 	if (sock_flag(sk_vsock(vsk), SOCK_DEAD))
448 		vsock_remove_bound(vsk);
449 
450 	vsock_remove_connected(vsk);
451 }
452 EXPORT_SYMBOL_GPL(vsock_remove_sock);
453 
454 void vsock_for_each_connected_socket(struct vsock_transport *transport,
455 				     void (*fn)(struct sock *sk))
456 {
457 	int i;
458 
459 	spin_lock_bh(&vsock_table_lock);
460 
461 	for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++) {
462 		struct vsock_sock *vsk;
463 		list_for_each_entry(vsk, &vsock_connected_table[i],
464 				    connected_table) {
465 			if (vsk->transport != transport)
466 				continue;
467 
468 			fn(sk_vsock(vsk));
469 		}
470 	}
471 
472 	spin_unlock_bh(&vsock_table_lock);
473 }
474 EXPORT_SYMBOL_GPL(vsock_for_each_connected_socket);
475 
476 void vsock_add_pending(struct sock *listener, struct sock *pending)
477 {
478 	struct vsock_sock *vlistener;
479 	struct vsock_sock *vpending;
480 
481 	vlistener = vsock_sk(listener);
482 	vpending = vsock_sk(pending);
483 
484 	sock_hold(pending);
485 	sock_hold(listener);
486 	list_add_tail(&vpending->pending_links, &vlistener->pending_links);
487 }
488 EXPORT_SYMBOL_GPL(vsock_add_pending);
489 
490 void vsock_remove_pending(struct sock *listener, struct sock *pending)
491 {
492 	struct vsock_sock *vpending = vsock_sk(pending);
493 
494 	list_del_init(&vpending->pending_links);
495 	sock_put(listener);
496 	sock_put(pending);
497 }
498 EXPORT_SYMBOL_GPL(vsock_remove_pending);
499 
500 void vsock_enqueue_accept(struct sock *listener, struct sock *connected)
501 {
502 	struct vsock_sock *vlistener;
503 	struct vsock_sock *vconnected;
504 
505 	vlistener = vsock_sk(listener);
506 	vconnected = vsock_sk(connected);
507 
508 	sock_hold(connected);
509 	sock_hold(listener);
510 	list_add_tail(&vconnected->accept_queue, &vlistener->accept_queue);
511 }
512 EXPORT_SYMBOL_GPL(vsock_enqueue_accept);
513 
514 static bool vsock_use_local_transport(unsigned int remote_cid)
515 {
516 	lockdep_assert_held(&vsock_register_mutex);
517 
518 	if (!transport_local)
519 		return false;
520 
521 	if (remote_cid == VMADDR_CID_LOCAL)
522 		return true;
523 
524 	if (transport_g2h) {
525 		return remote_cid == transport_g2h->get_local_cid();
526 	} else {
527 		return remote_cid == VMADDR_CID_HOST;
528 	}
529 }
530 
531 static void vsock_deassign_transport(struct vsock_sock *vsk)
532 {
533 	if (!vsk->transport)
534 		return;
535 
536 	vsk->transport->destruct(vsk);
537 	module_put(vsk->transport->module);
538 	vsk->transport = NULL;
539 }
540 
541 /* Assign a transport to a socket and call the .init transport callback.
542  *
543  * Note: for connection oriented socket this must be called when vsk->remote_addr
544  * is set (e.g. during the connect() or when a connection request on a listener
545  * socket is received).
546  * The vsk->remote_addr is used to decide which transport to use:
547  *  - remote CID == VMADDR_CID_LOCAL or g2h->local_cid or VMADDR_CID_HOST if
548  *    g2h is not loaded, will use local transport;
549  *  - remote CID <= VMADDR_CID_HOST or remote flags field includes
550  *    VMADDR_FLAG_TO_HOST, will use guest->host transport;
551  *  - remote CID > VMADDR_CID_HOST and h2g is loaded and h2g claims that CID,
552  *    will use host->guest transport;
553  *  - h2g not loaded or h2g does not claim that CID and g2h claims the CID via
554  *    has_remote_cid, will use guest->host transport (when g2h_fallback=1)
555  *  - anything else goes to h2g or returns -ENODEV if no h2g is available
556  */
557 int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)
558 {
559 	const struct vsock_transport *new_transport;
560 	struct sock *sk = sk_vsock(vsk);
561 	unsigned int remote_cid = vsk->remote_addr.svm_cid;
562 	__u8 remote_flags;
563 	int ret;
564 
565 	/* If the packet is coming with the source and destination CIDs higher
566 	 * than VMADDR_CID_HOST, then a vsock channel where all the packets are
567 	 * forwarded to the host should be established. Then the host will
568 	 * need to forward the packets to the guest.
569 	 *
570 	 * The flag is set on the (listen) receive path (psk is not NULL). On
571 	 * the connect path the flag can be set by the user space application.
572 	 */
573 	if (psk && vsk->local_addr.svm_cid > VMADDR_CID_HOST &&
574 	    vsk->remote_addr.svm_cid > VMADDR_CID_HOST)
575 		vsk->remote_addr.svm_flags |= VMADDR_FLAG_TO_HOST;
576 
577 	remote_flags = vsk->remote_addr.svm_flags;
578 
579 	mutex_lock(&vsock_register_mutex);
580 
581 	switch (sk->sk_type) {
582 	case SOCK_DGRAM:
583 		new_transport = transport_dgram;
584 		break;
585 	case SOCK_STREAM:
586 	case SOCK_SEQPACKET:
587 		if (vsock_use_local_transport(remote_cid))
588 			new_transport = transport_local;
589 		else if (remote_cid <= VMADDR_CID_HOST ||
590 			 (remote_flags & VMADDR_FLAG_TO_HOST))
591 			new_transport = transport_g2h;
592 		else if (transport_h2g &&
593 			 (!transport_h2g->has_remote_cid ||
594 			  transport_h2g->has_remote_cid(vsk, remote_cid)))
595 			new_transport = transport_h2g;
596 		else if (sock_net(sk)->vsock.g2h_fallback &&
597 			 transport_g2h && transport_g2h->has_remote_cid &&
598 			 transport_g2h->has_remote_cid(vsk, remote_cid)) {
599 			vsk->remote_addr.svm_flags |= VMADDR_FLAG_TO_HOST;
600 			new_transport = transport_g2h;
601 		} else {
602 			new_transport = transport_h2g;
603 		}
604 		break;
605 	default:
606 		ret = -ESOCKTNOSUPPORT;
607 		goto err;
608 	}
609 
610 	if (vsk->transport && vsk->transport == new_transport) {
611 		ret = 0;
612 		goto err;
613 	}
614 
615 	/* We increase the module refcnt to prevent the transport unloading
616 	 * while there are open sockets assigned to it.
617 	 */
618 	if (!new_transport || !try_module_get(new_transport->module)) {
619 		ret = -ENODEV;
620 		goto err;
621 	}
622 
623 	/* It's safe to release the mutex after a successful try_module_get().
624 	 * Whichever transport `new_transport` points at, it won't go away until
625 	 * the last module_put() below or in vsock_deassign_transport().
626 	 */
627 	mutex_unlock(&vsock_register_mutex);
628 
629 	if (vsk->transport) {
630 		/* transport->release() must be called with sock lock acquired.
631 		 * This path can only be taken during vsock_connect(), where we
632 		 * have already held the sock lock. In the other cases, this
633 		 * function is called on a new socket which is not assigned to
634 		 * any transport.
635 		 */
636 		vsk->transport->release(vsk);
637 		vsock_deassign_transport(vsk);
638 
639 		/* transport's release() and destruct() can touch some socket
640 		 * state, since we are reassigning the socket to a new transport
641 		 * during vsock_connect(), let's reset these fields to have a
642 		 * clean state.
643 		 */
644 		sock_reset_flag(sk, SOCK_DONE);
645 		sk->sk_state = TCP_CLOSE;
646 		WRITE_ONCE(vsk->peer_shutdown, 0);
647 	}
648 
649 	if (sk->sk_type == SOCK_SEQPACKET) {
650 		if (!new_transport->seqpacket_allow ||
651 		    !new_transport->seqpacket_allow(vsk, remote_cid)) {
652 			module_put(new_transport->module);
653 			return -ESOCKTNOSUPPORT;
654 		}
655 	}
656 
657 	ret = new_transport->init(vsk, psk);
658 	if (ret) {
659 		module_put(new_transport->module);
660 		return ret;
661 	}
662 
663 	vsk->transport = new_transport;
664 
665 	return 0;
666 err:
667 	mutex_unlock(&vsock_register_mutex);
668 	return ret;
669 }
670 EXPORT_SYMBOL_GPL(vsock_assign_transport);
671 
672 /*
673  * Provide safe access to static transport_{h2g,g2h,dgram,local} callbacks.
674  * Otherwise we may race with module removal. Do not use on `vsk->transport`.
675  */
676 static u32 vsock_registered_transport_cid(const struct vsock_transport **transport)
677 {
678 	u32 cid = VMADDR_CID_ANY;
679 
680 	mutex_lock(&vsock_register_mutex);
681 	if (*transport)
682 		cid = (*transport)->get_local_cid();
683 	mutex_unlock(&vsock_register_mutex);
684 
685 	return cid;
686 }
687 
688 bool vsock_find_cid(unsigned int cid)
689 {
690 	if (cid == vsock_registered_transport_cid(&transport_g2h))
691 		return true;
692 
693 	if (transport_h2g && cid == VMADDR_CID_HOST)
694 		return true;
695 
696 	if (transport_local && cid == VMADDR_CID_LOCAL)
697 		return true;
698 
699 	return false;
700 }
701 EXPORT_SYMBOL_GPL(vsock_find_cid);
702 
703 static struct sock *vsock_dequeue_accept(struct sock *listener)
704 {
705 	struct vsock_sock *vlistener;
706 	struct vsock_sock *vconnected;
707 
708 	vlistener = vsock_sk(listener);
709 
710 	if (list_empty(&vlistener->accept_queue))
711 		return NULL;
712 
713 	vconnected = list_entry(vlistener->accept_queue.next,
714 				struct vsock_sock, accept_queue);
715 
716 	list_del_init(&vconnected->accept_queue);
717 	sock_put(listener);
718 	/* The caller will need a reference on the connected socket so we let
719 	 * it call sock_put().
720 	 */
721 
722 	return sk_vsock(vconnected);
723 }
724 
725 static bool vsock_is_accept_queue_empty(struct sock *sk)
726 {
727 	struct vsock_sock *vsk = vsock_sk(sk);
728 	return list_empty(&vsk->accept_queue);
729 }
730 
731 static bool vsock_is_pending(struct sock *sk)
732 {
733 	struct vsock_sock *vsk = vsock_sk(sk);
734 	return !list_empty(&vsk->pending_links);
735 }
736 
737 static int vsock_send_shutdown(struct sock *sk, int mode)
738 {
739 	struct vsock_sock *vsk = vsock_sk(sk);
740 
741 	if (!vsk->transport)
742 		return -ENODEV;
743 
744 	return vsk->transport->shutdown(vsk, mode);
745 }
746 
747 static void vsock_pending_work(struct work_struct *work)
748 {
749 	struct sock *sk;
750 	struct sock *listener;
751 	struct vsock_sock *vsk;
752 	bool cleanup;
753 
754 	vsk = container_of(work, struct vsock_sock, pending_work.work);
755 	sk = sk_vsock(vsk);
756 	listener = vsk->listener;
757 	cleanup = true;
758 
759 	lock_sock(listener);
760 	lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
761 
762 	if (vsock_is_pending(sk)) {
763 		vsock_remove_pending(listener, sk);
764 
765 		sk_acceptq_removed(listener);
766 	} else if (!vsk->rejected) {
767 		/* We are not on the pending list and accept() did not reject
768 		 * us, so we must have been accepted by our user process.  We
769 		 * just need to drop our references to the sockets and be on
770 		 * our way.
771 		 */
772 		cleanup = false;
773 		goto out;
774 	}
775 
776 	/* We need to remove ourself from the global connected sockets list so
777 	 * incoming packets can't find this socket, and to reduce the reference
778 	 * count.
779 	 */
780 	vsock_remove_connected(vsk);
781 
782 	sk->sk_state = TCP_CLOSE;
783 
784 out:
785 	release_sock(sk);
786 	release_sock(listener);
787 	if (cleanup)
788 		sock_put(sk);
789 
790 	sock_put(sk);
791 	sock_put(listener);
792 }
793 
794 /**** SOCKET OPERATIONS ****/
795 
796 static int __vsock_bind_connectible(struct vsock_sock *vsk,
797 				    struct sockaddr_vm *addr)
798 {
799 	struct net *net = sock_net(sk_vsock(vsk));
800 	struct sockaddr_vm new_addr;
801 
802 	if (!net->vsock.port)
803 		net->vsock.port = get_random_u32_above(LAST_RESERVED_PORT);
804 
805 	vsock_addr_init(&new_addr, addr->svm_cid, addr->svm_port);
806 
807 	if (addr->svm_port == VMADDR_PORT_ANY) {
808 		bool found = false;
809 		unsigned int i;
810 
811 		for (i = 0; i < MAX_PORT_RETRIES; i++) {
812 			if (net->vsock.port == VMADDR_PORT_ANY ||
813 			    net->vsock.port <= LAST_RESERVED_PORT)
814 				net->vsock.port = LAST_RESERVED_PORT + 1;
815 
816 			new_addr.svm_port = net->vsock.port++;
817 
818 			if (!__vsock_find_bound_socket_net(&new_addr, net)) {
819 				found = true;
820 				break;
821 			}
822 		}
823 
824 		if (!found)
825 			return -EADDRNOTAVAIL;
826 	} else {
827 		/* If port is in reserved range, ensure caller
828 		 * has necessary privileges.
829 		 */
830 		if (addr->svm_port <= LAST_RESERVED_PORT &&
831 		    !capable(CAP_NET_BIND_SERVICE)) {
832 			return -EACCES;
833 		}
834 
835 		if (__vsock_find_bound_socket_net(&new_addr, net))
836 			return -EADDRINUSE;
837 	}
838 
839 	vsock_addr_init(&vsk->local_addr, new_addr.svm_cid, new_addr.svm_port);
840 
841 	/* Remove connection oriented sockets from the unbound list and add them
842 	 * to the hash table for easy lookup by its address.  The unbound list
843 	 * is simply an extra entry at the end of the hash table, a trick used
844 	 * by AF_UNIX.
845 	 */
846 	__vsock_remove_bound(vsk);
847 	__vsock_insert_bound(vsock_bound_sockets(&vsk->local_addr), vsk);
848 
849 	return 0;
850 }
851 
852 static int __vsock_bind_dgram(struct vsock_sock *vsk,
853 			      struct sockaddr_vm *addr)
854 {
855 	return vsk->transport->dgram_bind(vsk, addr);
856 }
857 
858 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr)
859 {
860 	struct vsock_sock *vsk = vsock_sk(sk);
861 	int retval;
862 
863 	/* First ensure this socket isn't already bound. */
864 	if (vsock_addr_bound(&vsk->local_addr))
865 		return -EINVAL;
866 
867 	/* Now bind to the provided address or select appropriate values if
868 	 * none are provided (VMADDR_CID_ANY and VMADDR_PORT_ANY).  Note that
869 	 * like AF_INET prevents binding to a non-local IP address (in most
870 	 * cases), we only allow binding to a local CID.
871 	 */
872 	if (addr->svm_cid != VMADDR_CID_ANY && !vsock_find_cid(addr->svm_cid))
873 		return -EADDRNOTAVAIL;
874 
875 	switch (sk->sk_socket->type) {
876 	case SOCK_STREAM:
877 	case SOCK_SEQPACKET:
878 		spin_lock_bh(&vsock_table_lock);
879 		retval = __vsock_bind_connectible(vsk, addr);
880 		spin_unlock_bh(&vsock_table_lock);
881 		break;
882 
883 	case SOCK_DGRAM:
884 		retval = __vsock_bind_dgram(vsk, addr);
885 		break;
886 
887 	default:
888 		retval = -EINVAL;
889 		break;
890 	}
891 
892 	return retval;
893 }
894 
895 static void vsock_connect_timeout(struct work_struct *work);
896 
897 static struct sock *__vsock_create(struct net *net,
898 				   struct socket *sock,
899 				   struct sock *parent,
900 				   gfp_t priority,
901 				   unsigned short type,
902 				   int kern)
903 {
904 	struct sock *sk;
905 	struct vsock_sock *psk;
906 	struct vsock_sock *vsk;
907 
908 	sk = sk_alloc(net, AF_VSOCK, priority, &vsock_proto, kern);
909 	if (!sk)
910 		return NULL;
911 
912 	sock_init_data(sock, sk);
913 
914 	/* sk->sk_type is normally set in sock_init_data, but only if sock is
915 	 * non-NULL. We make sure that our sockets always have a type by
916 	 * setting it here if needed.
917 	 */
918 	if (!sock)
919 		sk->sk_type = type;
920 
921 	vsk = vsock_sk(sk);
922 	vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
923 	vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
924 
925 	sk->sk_destruct = vsock_sk_destruct;
926 	sk->sk_backlog_rcv = vsock_queue_rcv_skb;
927 	sock_reset_flag(sk, SOCK_DONE);
928 
929 	INIT_LIST_HEAD(&vsk->bound_table);
930 	INIT_LIST_HEAD(&vsk->connected_table);
931 	vsk->listener = NULL;
932 	INIT_LIST_HEAD(&vsk->pending_links);
933 	INIT_LIST_HEAD(&vsk->accept_queue);
934 	vsk->rejected = false;
935 	vsk->sent_request = false;
936 	vsk->ignore_connecting_rst = false;
937 	WRITE_ONCE(vsk->peer_shutdown, 0);
938 	INIT_DELAYED_WORK(&vsk->connect_work, vsock_connect_timeout);
939 	INIT_DELAYED_WORK(&vsk->pending_work, vsock_pending_work);
940 
941 	psk = parent ? vsock_sk(parent) : NULL;
942 	if (parent) {
943 		vsk->trusted = psk->trusted;
944 		vsk->owner = get_cred(psk->owner);
945 		vsk->connect_timeout = psk->connect_timeout;
946 		vsk->buffer_size = psk->buffer_size;
947 		vsk->buffer_min_size = psk->buffer_min_size;
948 		vsk->buffer_max_size = psk->buffer_max_size;
949 		security_sk_clone(parent, sk);
950 	} else {
951 		vsk->trusted = ns_capable_noaudit(&init_user_ns, CAP_NET_ADMIN);
952 		vsk->owner = get_current_cred();
953 		vsk->connect_timeout = VSOCK_DEFAULT_CONNECT_TIMEOUT;
954 		vsk->buffer_size = VSOCK_DEFAULT_BUFFER_SIZE;
955 		vsk->buffer_min_size = VSOCK_DEFAULT_BUFFER_MIN_SIZE;
956 		vsk->buffer_max_size = VSOCK_DEFAULT_BUFFER_MAX_SIZE;
957 	}
958 
959 	return sk;
960 }
961 
962 static bool sock_type_connectible(u16 type)
963 {
964 	return (type == SOCK_STREAM) || (type == SOCK_SEQPACKET);
965 }
966 
967 static void __vsock_release(struct sock *sk, int level)
968 {
969 	struct vsock_sock *vsk;
970 	struct sock *pending;
971 
972 	vsk = vsock_sk(sk);
973 	pending = NULL;	/* Compiler warning. */
974 
975 	/* When "level" is SINGLE_DEPTH_NESTING, use the nested
976 	 * version to avoid the warning "possible recursive locking
977 	 * detected". When "level" is 0, lock_sock_nested(sk, level)
978 	 * is the same as lock_sock(sk).
979 	 */
980 	lock_sock_nested(sk, level);
981 
982 	/* Indicate to vsock_remove_sock() that the socket is being released and
983 	 * can be removed from the bound_table. Unlike transport reassignment
984 	 * case, where the socket must remain bound despite vsock_remove_sock()
985 	 * being called from the transport release() callback.
986 	 */
987 	sock_set_flag(sk, SOCK_DEAD);
988 
989 	if (vsk->transport)
990 		vsk->transport->release(vsk);
991 	else if (sock_type_connectible(sk->sk_type))
992 		vsock_remove_sock(vsk);
993 
994 	sock_orphan(sk);
995 	sk->sk_shutdown = SHUTDOWN_MASK;
996 
997 	skb_queue_purge(&sk->sk_receive_queue);
998 
999 	/* Clean up any sockets that never were accepted. */
1000 	while ((pending = vsock_dequeue_accept(sk)) != NULL) {
1001 		__vsock_release(pending, SINGLE_DEPTH_NESTING);
1002 		sock_put(pending);
1003 	}
1004 
1005 	release_sock(sk);
1006 	sock_put(sk);
1007 }
1008 
1009 static void vsock_sk_destruct(struct sock *sk)
1010 {
1011 	struct vsock_sock *vsk = vsock_sk(sk);
1012 
1013 	/* Flush MSG_ZEROCOPY leftovers. */
1014 	__skb_queue_purge(&sk->sk_error_queue);
1015 
1016 	vsock_deassign_transport(vsk);
1017 
1018 	/* When clearing these addresses, there's no need to set the family and
1019 	 * possibly register the address family with the kernel.
1020 	 */
1021 	vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
1022 	vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
1023 
1024 	put_cred(vsk->owner);
1025 }
1026 
1027 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
1028 {
1029 	int err;
1030 
1031 	err = sock_queue_rcv_skb(sk, skb);
1032 	if (err)
1033 		kfree_skb(skb);
1034 
1035 	return err;
1036 }
1037 
1038 struct sock *vsock_create_connected(struct sock *parent)
1039 {
1040 	return __vsock_create(sock_net(parent), NULL, parent, GFP_KERNEL,
1041 			      parent->sk_type, 0);
1042 }
1043 EXPORT_SYMBOL_GPL(vsock_create_connected);
1044 
1045 s64 vsock_stream_has_data(struct vsock_sock *vsk)
1046 {
1047 	if (WARN_ON(!vsk->transport))
1048 		return 0;
1049 
1050 	return vsk->transport->stream_has_data(vsk);
1051 }
1052 EXPORT_SYMBOL_GPL(vsock_stream_has_data);
1053 
1054 s64 vsock_connectible_has_data(struct vsock_sock *vsk)
1055 {
1056 	struct sock *sk = sk_vsock(vsk);
1057 
1058 	if (WARN_ON(!vsk->transport))
1059 		return 0;
1060 
1061 	if (sk->sk_type == SOCK_SEQPACKET)
1062 		return vsk->transport->seqpacket_has_data(vsk);
1063 	else
1064 		return vsock_stream_has_data(vsk);
1065 }
1066 EXPORT_SYMBOL_GPL(vsock_connectible_has_data);
1067 
1068 s64 vsock_stream_has_space(struct vsock_sock *vsk)
1069 {
1070 	if (WARN_ON(!vsk->transport))
1071 		return 0;
1072 
1073 	return vsk->transport->stream_has_space(vsk);
1074 }
1075 EXPORT_SYMBOL_GPL(vsock_stream_has_space);
1076 
1077 void vsock_data_ready(struct sock *sk)
1078 {
1079 	struct vsock_sock *vsk = vsock_sk(sk);
1080 
1081 	if (vsock_stream_has_data(vsk) >= sk->sk_rcvlowat ||
1082 	    sock_flag(sk, SOCK_DONE))
1083 		sk->sk_data_ready(sk);
1084 }
1085 EXPORT_SYMBOL_GPL(vsock_data_ready);
1086 
1087 /* Dummy callback required by sockmap.
1088  * See unconditional call of saved_close() in sock_map_close().
1089  */
1090 static void vsock_close(struct sock *sk, long timeout)
1091 {
1092 }
1093 
1094 static int vsock_release(struct socket *sock)
1095 {
1096 	struct sock *sk = sock->sk;
1097 
1098 	if (!sk)
1099 		return 0;
1100 
1101 	sk->sk_prot->close(sk, 0);
1102 	__vsock_release(sk, 0);
1103 	sock->sk = NULL;
1104 	sock->state = SS_FREE;
1105 
1106 	return 0;
1107 }
1108 
1109 static int
1110 vsock_bind(struct socket *sock, struct sockaddr_unsized *addr, int addr_len)
1111 {
1112 	int err;
1113 	struct sock *sk;
1114 	struct sockaddr_vm *vm_addr;
1115 
1116 	sk = sock->sk;
1117 
1118 	if (vsock_addr_cast(addr, addr_len, &vm_addr) != 0)
1119 		return -EINVAL;
1120 
1121 	lock_sock(sk);
1122 	err = __vsock_bind(sk, vm_addr);
1123 	release_sock(sk);
1124 
1125 	return err;
1126 }
1127 
1128 static int vsock_getname(struct socket *sock,
1129 			 struct sockaddr *addr, int peer)
1130 {
1131 	int err;
1132 	struct sock *sk;
1133 	struct vsock_sock *vsk;
1134 	struct sockaddr_vm *vm_addr;
1135 
1136 	sk = sock->sk;
1137 	vsk = vsock_sk(sk);
1138 	err = 0;
1139 
1140 	lock_sock(sk);
1141 
1142 	if (peer) {
1143 		if (sock->state != SS_CONNECTED) {
1144 			err = -ENOTCONN;
1145 			goto out;
1146 		}
1147 		vm_addr = &vsk->remote_addr;
1148 	} else {
1149 		vm_addr = &vsk->local_addr;
1150 	}
1151 
1152 	BUILD_BUG_ON(sizeof(*vm_addr) > sizeof(struct sockaddr_storage));
1153 	memcpy(addr, vm_addr, sizeof(*vm_addr));
1154 	err = sizeof(*vm_addr);
1155 
1156 out:
1157 	release_sock(sk);
1158 	return err;
1159 }
1160 
1161 void vsock_linger(struct sock *sk)
1162 {
1163 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1164 	ssize_t (*unsent)(struct vsock_sock *vsk);
1165 	struct vsock_sock *vsk = vsock_sk(sk);
1166 	long timeout;
1167 
1168 	if (!sock_flag(sk, SOCK_LINGER))
1169 		return;
1170 
1171 	timeout = sk->sk_lingertime;
1172 	if (!timeout)
1173 		return;
1174 
1175 	/* Transports must implement `unsent_bytes` if they want to support
1176 	 * SOCK_LINGER through `vsock_linger()` since we use it to check when
1177 	 * the socket can be closed.
1178 	 */
1179 	unsent = vsk->transport->unsent_bytes;
1180 	if (!unsent)
1181 		return;
1182 
1183 	add_wait_queue(sk_sleep(sk), &wait);
1184 
1185 	do {
1186 		if (sk_wait_event(sk, &timeout, unsent(vsk) == 0, &wait))
1187 			break;
1188 	} while (!signal_pending(current) && timeout);
1189 
1190 	remove_wait_queue(sk_sleep(sk), &wait);
1191 }
1192 EXPORT_SYMBOL_GPL(vsock_linger);
1193 
1194 static int vsock_shutdown(struct socket *sock, int mode)
1195 {
1196 	int err;
1197 	struct sock *sk;
1198 
1199 	/* User level uses SHUT_RD (0) and SHUT_WR (1), but the kernel uses
1200 	 * RCV_SHUTDOWN (1) and SEND_SHUTDOWN (2), so we must increment mode
1201 	 * here like the other address families do.  Note also that the
1202 	 * increment makes SHUT_RDWR (2) into RCV_SHUTDOWN | SEND_SHUTDOWN (3),
1203 	 * which is what we want.
1204 	 */
1205 	mode++;
1206 
1207 	if ((mode & ~SHUTDOWN_MASK) || !mode)
1208 		return -EINVAL;
1209 
1210 	/* If this is a connection oriented socket and it is not connected then
1211 	 * bail out immediately.  If it is a DGRAM socket then we must first
1212 	 * kick the socket so that it wakes up from any sleeping calls, for
1213 	 * example recv(), and then afterwards return the error.
1214 	 */
1215 
1216 	sk = sock->sk;
1217 
1218 	lock_sock(sk);
1219 	if (sock->state == SS_UNCONNECTED) {
1220 		err = -ENOTCONN;
1221 		if (sock_type_connectible(sk->sk_type))
1222 			goto out;
1223 	} else {
1224 		sock->state = SS_DISCONNECTING;
1225 		err = 0;
1226 	}
1227 
1228 	/* Receive and send shutdowns are treated alike. */
1229 	mode = mode & (RCV_SHUTDOWN | SEND_SHUTDOWN);
1230 	if (mode) {
1231 		sk->sk_shutdown |= mode;
1232 		sk->sk_state_change(sk);
1233 
1234 		if (sock_type_connectible(sk->sk_type)) {
1235 			sock_reset_flag(sk, SOCK_DONE);
1236 			vsock_send_shutdown(sk, mode);
1237 		}
1238 	}
1239 
1240 out:
1241 	release_sock(sk);
1242 	return err;
1243 }
1244 
1245 static __poll_t vsock_poll_shutdown(struct sock *sk, u32 peer_shutdown)
1246 {
1247 	__poll_t mask = 0;
1248 
1249 	/* INET sockets treat local write shutdown and peer write shutdown as a
1250 	 * case of EPOLLHUP set.
1251 	 */
1252 	if (sk->sk_shutdown == SHUTDOWN_MASK ||
1253 	    ((sk->sk_shutdown & SEND_SHUTDOWN) &&
1254 	     (peer_shutdown & SEND_SHUTDOWN)))
1255 		mask |= EPOLLHUP;
1256 
1257 	if (sk->sk_shutdown & RCV_SHUTDOWN ||
1258 	    peer_shutdown & SEND_SHUTDOWN)
1259 		mask |= EPOLLRDHUP;
1260 
1261 	return mask;
1262 }
1263 
1264 static __poll_t vsock_poll(struct file *file, struct socket *sock,
1265 			       poll_table *wait)
1266 {
1267 	struct sock *sk;
1268 	__poll_t mask;
1269 	struct vsock_sock *vsk;
1270 
1271 	sk = sock->sk;
1272 	vsk = vsock_sk(sk);
1273 
1274 	poll_wait(file, sk_sleep(sk), wait);
1275 	mask = 0;
1276 
1277 	if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
1278 		/* Signify that there has been an error on this socket. */
1279 		mask |= EPOLLERR;
1280 
1281 	if (sk_is_readable(sk))
1282 		mask |= EPOLLIN | EPOLLRDNORM;
1283 
1284 	if (sock->type == SOCK_DGRAM) {
1285 		u32 peer_shutdown = READ_ONCE(vsk->peer_shutdown);
1286 
1287 		/* DGRAM sockets do not take lock_sock() in poll(), so use one
1288 		 * lockless snapshot for all shutdown-derived mask bits.
1289 		 */
1290 		mask |= vsock_poll_shutdown(sk, peer_shutdown);
1291 
1292 		/* For datagram sockets we can read if there is something in
1293 		 * the queue and write as long as the socket isn't shutdown for
1294 		 * sending.
1295 		 */
1296 		if (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
1297 		    (sk->sk_shutdown & RCV_SHUTDOWN)) {
1298 			mask |= EPOLLIN | EPOLLRDNORM;
1299 		}
1300 
1301 		if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1302 			mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
1303 
1304 	} else if (sock_type_connectible(sk->sk_type)) {
1305 		const struct vsock_transport *transport;
1306 		u32 peer_shutdown;
1307 
1308 		lock_sock(sk);
1309 
1310 		transport = vsk->transport;
1311 
1312 		/* Listening sockets that have connections in their accept
1313 		 * queue can be read.
1314 		 */
1315 		if (sk->sk_state == TCP_LISTEN
1316 		    && !vsock_is_accept_queue_empty(sk))
1317 			mask |= EPOLLIN | EPOLLRDNORM;
1318 
1319 		/* If there is something in the queue then we can read. */
1320 		if (transport && transport->stream_is_active(vsk) &&
1321 		    !(sk->sk_shutdown & RCV_SHUTDOWN)) {
1322 			bool data_ready_now = false;
1323 			int target = sock_rcvlowat(sk, 0, INT_MAX);
1324 			int ret = transport->notify_poll_in(
1325 					vsk, target, &data_ready_now);
1326 			if (ret < 0) {
1327 				mask |= EPOLLERR;
1328 			} else {
1329 				if (data_ready_now)
1330 					mask |= EPOLLIN | EPOLLRDNORM;
1331 
1332 			}
1333 		}
1334 
1335 		/* Sockets whose connections have been closed, reset, or
1336 		 * terminated should also be considered read, and we check the
1337 		 * shutdown flag for that.
1338 		 */
1339 		peer_shutdown = READ_ONCE(vsk->peer_shutdown);
1340 		mask |= vsock_poll_shutdown(sk, peer_shutdown);
1341 		if (sk->sk_shutdown & RCV_SHUTDOWN ||
1342 		    peer_shutdown & SEND_SHUTDOWN) {
1343 			mask |= EPOLLIN | EPOLLRDNORM;
1344 		}
1345 
1346 		/* Connected sockets that can produce data can be written. */
1347 		if (transport && sk->sk_state == TCP_ESTABLISHED) {
1348 			if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
1349 				bool space_avail_now = false;
1350 				int ret = transport->notify_poll_out(
1351 						vsk, 1, &space_avail_now);
1352 				if (ret < 0) {
1353 					mask |= EPOLLERR;
1354 				} else {
1355 					if (space_avail_now)
1356 						/* Remove EPOLLWRBAND since INET
1357 						 * sockets are not setting it.
1358 						 */
1359 						mask |= EPOLLOUT | EPOLLWRNORM;
1360 
1361 				}
1362 			}
1363 		}
1364 
1365 		/* Simulate INET socket poll behaviors, which sets
1366 		 * EPOLLOUT|EPOLLWRNORM when peer is closed and nothing to read,
1367 		 * but local send is not shutdown.
1368 		 */
1369 		if (sk->sk_state == TCP_CLOSE || sk->sk_state == TCP_CLOSING) {
1370 			if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1371 				mask |= EPOLLOUT | EPOLLWRNORM;
1372 
1373 		}
1374 
1375 		release_sock(sk);
1376 	}
1377 
1378 	return mask;
1379 }
1380 
1381 static int vsock_read_skb(struct sock *sk, skb_read_actor_t read_actor)
1382 {
1383 	struct vsock_sock *vsk = vsock_sk(sk);
1384 
1385 	if (WARN_ON_ONCE(!vsk->transport))
1386 		return -ENODEV;
1387 
1388 	return vsk->transport->read_skb(vsk, read_actor);
1389 }
1390 
1391 static int vsock_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
1392 			       size_t len)
1393 {
1394 	int err;
1395 	struct sock *sk;
1396 	struct vsock_sock *vsk;
1397 	struct sockaddr_vm *remote_addr;
1398 	const struct vsock_transport *transport;
1399 
1400 	if (msg->msg_flags & MSG_OOB)
1401 		return -EOPNOTSUPP;
1402 
1403 	/* For now, MSG_DONTWAIT is always assumed... */
1404 	err = 0;
1405 	sk = sock->sk;
1406 	vsk = vsock_sk(sk);
1407 
1408 	lock_sock(sk);
1409 
1410 	transport = vsk->transport;
1411 
1412 	err = vsock_auto_bind(vsk);
1413 	if (err)
1414 		goto out;
1415 
1416 
1417 	/* If the provided message contains an address, use that.  Otherwise
1418 	 * fall back on the socket's remote handle (if it has been connected).
1419 	 */
1420 	if (msg->msg_name &&
1421 	    vsock_addr_cast(msg->msg_name, msg->msg_namelen,
1422 			    &remote_addr) == 0) {
1423 		/* Ensure this address is of the right type and is a valid
1424 		 * destination.
1425 		 */
1426 
1427 		if (remote_addr->svm_cid == VMADDR_CID_ANY)
1428 			remote_addr->svm_cid = transport->get_local_cid();
1429 
1430 		if (!vsock_addr_bound(remote_addr)) {
1431 			err = -EINVAL;
1432 			goto out;
1433 		}
1434 	} else if (sock->state == SS_CONNECTED) {
1435 		remote_addr = &vsk->remote_addr;
1436 
1437 		if (remote_addr->svm_cid == VMADDR_CID_ANY)
1438 			remote_addr->svm_cid = transport->get_local_cid();
1439 
1440 		/* XXX Should connect() or this function ensure remote_addr is
1441 		 * bound?
1442 		 */
1443 		if (!vsock_addr_bound(&vsk->remote_addr)) {
1444 			err = -EINVAL;
1445 			goto out;
1446 		}
1447 	} else {
1448 		err = -EINVAL;
1449 		goto out;
1450 	}
1451 
1452 	if (!transport->dgram_allow(vsk, remote_addr->svm_cid,
1453 				    remote_addr->svm_port)) {
1454 		err = -EINVAL;
1455 		goto out;
1456 	}
1457 
1458 	err = transport->dgram_enqueue(vsk, remote_addr, msg, len);
1459 
1460 out:
1461 	release_sock(sk);
1462 	return err;
1463 }
1464 
1465 static int vsock_dgram_connect(struct socket *sock,
1466 			       struct sockaddr_unsized *addr, int addr_len, int flags)
1467 {
1468 	int err;
1469 	struct sock *sk;
1470 	struct vsock_sock *vsk;
1471 	struct sockaddr_vm *remote_addr;
1472 
1473 	sk = sock->sk;
1474 	vsk = vsock_sk(sk);
1475 
1476 	err = vsock_addr_cast(addr, addr_len, &remote_addr);
1477 	if (err == -EAFNOSUPPORT && remote_addr->svm_family == AF_UNSPEC) {
1478 		lock_sock(sk);
1479 		vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY,
1480 				VMADDR_PORT_ANY);
1481 		sock->state = SS_UNCONNECTED;
1482 		release_sock(sk);
1483 		return 0;
1484 	} else if (err != 0)
1485 		return -EINVAL;
1486 
1487 	lock_sock(sk);
1488 
1489 	err = vsock_auto_bind(vsk);
1490 	if (err)
1491 		goto out;
1492 
1493 	if (!vsk->transport->dgram_allow(vsk, remote_addr->svm_cid,
1494 					 remote_addr->svm_port)) {
1495 		err = -EINVAL;
1496 		goto out;
1497 	}
1498 
1499 	memcpy(&vsk->remote_addr, remote_addr, sizeof(vsk->remote_addr));
1500 	sock->state = SS_CONNECTED;
1501 
1502 	/* sock map disallows redirection of non-TCP sockets with sk_state !=
1503 	 * TCP_ESTABLISHED (see sock_map_redirect_allowed()), so we set
1504 	 * TCP_ESTABLISHED here to allow redirection of connected vsock dgrams.
1505 	 *
1506 	 * This doesn't seem to be abnormal state for datagram sockets, as the
1507 	 * same approach can be see in other datagram socket types as well
1508 	 * (such as unix sockets).
1509 	 */
1510 	sk->sk_state = TCP_ESTABLISHED;
1511 
1512 out:
1513 	release_sock(sk);
1514 	return err;
1515 }
1516 
1517 int __vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
1518 			  size_t len, int flags)
1519 {
1520 	struct sock *sk = sock->sk;
1521 	struct vsock_sock *vsk = vsock_sk(sk);
1522 
1523 	return vsk->transport->dgram_dequeue(vsk, msg, len, flags);
1524 }
1525 
1526 int vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
1527 			size_t len, int flags)
1528 {
1529 #ifdef CONFIG_BPF_SYSCALL
1530 	struct sock *sk = sock->sk;
1531 	const struct proto *prot;
1532 
1533 	prot = READ_ONCE(sk->sk_prot);
1534 	if (prot != &vsock_proto)
1535 		return prot->recvmsg(sk, msg, len, flags);
1536 #endif
1537 
1538 	return __vsock_dgram_recvmsg(sock, msg, len, flags);
1539 }
1540 EXPORT_SYMBOL_GPL(vsock_dgram_recvmsg);
1541 
1542 static int vsock_do_ioctl(struct socket *sock, unsigned int cmd,
1543 			  int __user *arg)
1544 {
1545 	struct sock *sk = sock->sk;
1546 	struct vsock_sock *vsk;
1547 	int ret;
1548 
1549 	vsk = vsock_sk(sk);
1550 
1551 	switch (cmd) {
1552 	case SIOCINQ: {
1553 		ssize_t n_bytes;
1554 
1555 		if (!vsk->transport) {
1556 			ret = -EOPNOTSUPP;
1557 			break;
1558 		}
1559 
1560 		if (sock_type_connectible(sk->sk_type) &&
1561 		    sk->sk_state == TCP_LISTEN) {
1562 			ret = -EINVAL;
1563 			break;
1564 		}
1565 
1566 		n_bytes = vsock_stream_has_data(vsk);
1567 		if (n_bytes < 0) {
1568 			ret = n_bytes;
1569 			break;
1570 		}
1571 		ret = put_user(n_bytes, arg);
1572 		break;
1573 	}
1574 	case SIOCOUTQ: {
1575 		ssize_t n_bytes;
1576 
1577 		if (!vsk->transport || !vsk->transport->unsent_bytes) {
1578 			ret = -EOPNOTSUPP;
1579 			break;
1580 		}
1581 
1582 		if (sock_type_connectible(sk->sk_type) && sk->sk_state == TCP_LISTEN) {
1583 			ret = -EINVAL;
1584 			break;
1585 		}
1586 
1587 		n_bytes = vsk->transport->unsent_bytes(vsk);
1588 		if (n_bytes < 0) {
1589 			ret = n_bytes;
1590 			break;
1591 		}
1592 
1593 		ret = put_user(n_bytes, arg);
1594 		break;
1595 	}
1596 	default:
1597 		ret = -ENOIOCTLCMD;
1598 	}
1599 
1600 	return ret;
1601 }
1602 
1603 static int vsock_ioctl(struct socket *sock, unsigned int cmd,
1604 		       unsigned long arg)
1605 {
1606 	int ret;
1607 
1608 	lock_sock(sock->sk);
1609 	ret = vsock_do_ioctl(sock, cmd, (int __user *)arg);
1610 	release_sock(sock->sk);
1611 
1612 	return ret;
1613 }
1614 
1615 static const struct proto_ops vsock_dgram_ops = {
1616 	.family = PF_VSOCK,
1617 	.owner = THIS_MODULE,
1618 	.release = vsock_release,
1619 	.bind = vsock_bind,
1620 	.connect = vsock_dgram_connect,
1621 	.socketpair = sock_no_socketpair,
1622 	.accept = sock_no_accept,
1623 	.getname = vsock_getname,
1624 	.poll = vsock_poll,
1625 	.ioctl = vsock_ioctl,
1626 	.listen = sock_no_listen,
1627 	.shutdown = vsock_shutdown,
1628 	.sendmsg = vsock_dgram_sendmsg,
1629 	.recvmsg = vsock_dgram_recvmsg,
1630 	.mmap = sock_no_mmap,
1631 	.read_skb = vsock_read_skb,
1632 };
1633 
1634 static int vsock_transport_cancel_pkt(struct vsock_sock *vsk)
1635 {
1636 	const struct vsock_transport *transport = vsk->transport;
1637 
1638 	if (!transport || !transport->cancel_pkt)
1639 		return -EOPNOTSUPP;
1640 
1641 	return transport->cancel_pkt(vsk);
1642 }
1643 
1644 static void vsock_connect_timeout(struct work_struct *work)
1645 {
1646 	struct sock *sk;
1647 	struct vsock_sock *vsk;
1648 
1649 	vsk = container_of(work, struct vsock_sock, connect_work.work);
1650 	sk = sk_vsock(vsk);
1651 
1652 	lock_sock(sk);
1653 	if (sk->sk_state == TCP_SYN_SENT &&
1654 	    (sk->sk_shutdown != SHUTDOWN_MASK)) {
1655 		sk->sk_state = TCP_CLOSE;
1656 		sk->sk_socket->state = SS_UNCONNECTED;
1657 		sk->sk_err = ETIMEDOUT;
1658 		sk_error_report(sk);
1659 		vsock_transport_cancel_pkt(vsk);
1660 	}
1661 	release_sock(sk);
1662 
1663 	sock_put(sk);
1664 }
1665 
1666 static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
1667 			 int addr_len, int flags)
1668 {
1669 	int err;
1670 	struct sock *sk;
1671 	struct vsock_sock *vsk;
1672 	const struct vsock_transport *transport;
1673 	struct sockaddr_vm *remote_addr;
1674 	long timeout;
1675 	DEFINE_WAIT(wait);
1676 
1677 	err = 0;
1678 	sk = sock->sk;
1679 	vsk = vsock_sk(sk);
1680 
1681 	lock_sock(sk);
1682 
1683 	/* XXX AF_UNSPEC should make us disconnect like AF_INET. */
1684 	switch (sock->state) {
1685 	case SS_CONNECTED:
1686 		err = -EISCONN;
1687 		goto out;
1688 	case SS_DISCONNECTING:
1689 		err = -EINVAL;
1690 		goto out;
1691 	case SS_CONNECTING:
1692 		/* This continues on so we can move sock into the SS_CONNECTED
1693 		 * state once the connection has completed (at which point err
1694 		 * will be set to zero also).  Otherwise, we will either wait
1695 		 * for the connection or return -EALREADY should this be a
1696 		 * non-blocking call.
1697 		 */
1698 		err = -EALREADY;
1699 		if (flags & O_NONBLOCK)
1700 			goto out;
1701 		break;
1702 	default:
1703 		if ((sk->sk_state == TCP_LISTEN) ||
1704 		    vsock_addr_cast(addr, addr_len, &remote_addr) != 0) {
1705 			err = -EINVAL;
1706 			goto out;
1707 		}
1708 
1709 		/* Set the remote address that we are connecting to. */
1710 		memcpy(&vsk->remote_addr, remote_addr,
1711 		       sizeof(vsk->remote_addr));
1712 
1713 		err = vsock_assign_transport(vsk, NULL);
1714 		if (err)
1715 			goto out;
1716 
1717 		transport = vsk->transport;
1718 
1719 		/* The hypervisor and well-known contexts do not have socket
1720 		 * endpoints.
1721 		 */
1722 		if (!transport ||
1723 		    !transport->stream_allow(vsk, remote_addr->svm_cid,
1724 					     remote_addr->svm_port)) {
1725 			err = -ENETUNREACH;
1726 			goto out;
1727 		}
1728 
1729 		if (vsock_msgzerocopy_allow(transport)) {
1730 			set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1731 		} else if (sock_flag(sk, SOCK_ZEROCOPY)) {
1732 			/* If this option was set before 'connect()',
1733 			 * when transport was unknown, check that this
1734 			 * feature is supported here.
1735 			 */
1736 			err = -EOPNOTSUPP;
1737 			goto out;
1738 		}
1739 
1740 		err = vsock_auto_bind(vsk);
1741 		if (err)
1742 			goto out;
1743 
1744 		sk->sk_state = TCP_SYN_SENT;
1745 
1746 		err = transport->connect(vsk);
1747 		if (err < 0)
1748 			goto out;
1749 
1750 		/* sk_err might have been set as a result of an earlier
1751 		 * (failed) connect attempt.
1752 		 */
1753 		sk->sk_err = 0;
1754 
1755 		/* Mark sock as connecting and set the error code to in
1756 		 * progress in case this is a non-blocking connect.
1757 		 */
1758 		sock->state = SS_CONNECTING;
1759 		err = -EINPROGRESS;
1760 	}
1761 
1762 	/* The receive path will handle all communication until we are able to
1763 	 * enter the connected state.  Here we wait for the connection to be
1764 	 * completed or a notification of an error.
1765 	 */
1766 	timeout = vsk->connect_timeout;
1767 	prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1768 
1769 	/* If the socket is already closing or it is in an error state, there
1770 	 * is no point in waiting.
1771 	 */
1772 	while (sk->sk_state != TCP_ESTABLISHED &&
1773 	       sk->sk_state != TCP_CLOSING && sk->sk_err == 0) {
1774 		if (flags & O_NONBLOCK) {
1775 			/* If we're not going to block, we schedule a timeout
1776 			 * function to generate a timeout on the connection
1777 			 * attempt, in case the peer doesn't respond in a
1778 			 * timely manner. We hold on to the socket until the
1779 			 * timeout fires.
1780 			 */
1781 			sock_hold(sk);
1782 
1783 			/* If the timeout function is already scheduled,
1784 			 * reschedule it, then ungrab the socket refcount to
1785 			 * keep it balanced.
1786 			 */
1787 			if (mod_delayed_work(system_percpu_wq, &vsk->connect_work,
1788 					     timeout))
1789 				sock_put(sk);
1790 
1791 			/* Skip ahead to preserve error code set above. */
1792 			goto out_wait;
1793 		}
1794 
1795 		release_sock(sk);
1796 		timeout = schedule_timeout(timeout);
1797 		lock_sock(sk);
1798 
1799 		/* Connection established. Whatever happens to socket once we
1800 		 * release it, that's not connect()'s concern. No need to go
1801 		 * into signal and timeout handling. Call it a day.
1802 		 *
1803 		 * Note that allowing to "reset" an already established socket
1804 		 * here is racy and insecure.
1805 		 */
1806 		if (sk->sk_state == TCP_ESTABLISHED)
1807 			break;
1808 
1809 		/* If connection was _not_ established and a signal/timeout came
1810 		 * to be, we want the socket's state reset. User space may want
1811 		 * to retry.
1812 		 *
1813 		 * sk_state != TCP_ESTABLISHED implies that socket is not on
1814 		 * vsock_connected_table. We keep the binding and the transport
1815 		 * assigned.
1816 		 */
1817 		if (signal_pending(current) || timeout == 0) {
1818 			err = timeout == 0 ? -ETIMEDOUT : sock_intr_errno(timeout);
1819 
1820 			/* Listener might have already responded with
1821 			 * VIRTIO_VSOCK_OP_RESPONSE. Its handling expects our
1822 			 * sk_state == TCP_SYN_SENT, which hereby we break.
1823 			 * In such case VIRTIO_VSOCK_OP_RST will follow.
1824 			 */
1825 			sk->sk_state = TCP_CLOSE;
1826 			sock->state = SS_UNCONNECTED;
1827 
1828 			/* Try to cancel VIRTIO_VSOCK_OP_REQUEST skb sent out by
1829 			 * transport->connect().
1830 			 */
1831 			vsock_transport_cancel_pkt(vsk);
1832 
1833 			goto out_wait;
1834 		}
1835 
1836 		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1837 	}
1838 
1839 	if (sk->sk_err) {
1840 		err = -sk->sk_err;
1841 		sk->sk_state = TCP_CLOSE;
1842 		sock->state = SS_UNCONNECTED;
1843 	} else {
1844 		err = 0;
1845 	}
1846 
1847 out_wait:
1848 	finish_wait(sk_sleep(sk), &wait);
1849 out:
1850 	release_sock(sk);
1851 	return err;
1852 }
1853 
1854 static int vsock_accept(struct socket *sock, struct socket *newsock,
1855 			struct proto_accept_arg *arg)
1856 {
1857 	struct sock *listener;
1858 	int err;
1859 	struct sock *connected;
1860 	struct vsock_sock *vconnected;
1861 	long timeout;
1862 	DEFINE_WAIT(wait);
1863 
1864 	err = 0;
1865 	listener = sock->sk;
1866 
1867 	lock_sock(listener);
1868 
1869 	if (!sock_type_connectible(sock->type)) {
1870 		err = -EOPNOTSUPP;
1871 		goto out;
1872 	}
1873 
1874 	if (listener->sk_state != TCP_LISTEN) {
1875 		err = -EINVAL;
1876 		goto out;
1877 	}
1878 
1879 	/* Wait for children sockets to appear; these are the new sockets
1880 	 * created upon connection establishment.
1881 	 */
1882 	timeout = sock_rcvtimeo(listener, arg->flags & O_NONBLOCK);
1883 
1884 	while ((connected = vsock_dequeue_accept(listener)) == NULL &&
1885 	       listener->sk_err == 0 && timeout != 0) {
1886 		prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1887 		release_sock(listener);
1888 		timeout = schedule_timeout(timeout);
1889 		finish_wait(sk_sleep(listener), &wait);
1890 		lock_sock(listener);
1891 
1892 		if (signal_pending(current)) {
1893 			err = sock_intr_errno(timeout);
1894 			goto out;
1895 		}
1896 	}
1897 
1898 	if (listener->sk_err) {
1899 		err = -listener->sk_err;
1900 	} else if (!connected) {
1901 		err = -EAGAIN;
1902 	}
1903 
1904 	if (connected) {
1905 		sk_acceptq_removed(listener);
1906 
1907 		lock_sock_nested(connected, SINGLE_DEPTH_NESTING);
1908 		vconnected = vsock_sk(connected);
1909 
1910 		/* If the listener socket has received an error, then we should
1911 		 * reject this socket and return.  Note that we simply mark the
1912 		 * socket rejected, drop our reference, and let the cleanup
1913 		 * function handle the cleanup; the fact that we found it in
1914 		 * the listener's accept queue guarantees that the cleanup
1915 		 * function hasn't run yet.
1916 		 */
1917 		if (err) {
1918 			vconnected->rejected = true;
1919 		} else {
1920 			newsock->state = SS_CONNECTED;
1921 			sock_graft(connected, newsock);
1922 
1923 			set_bit(SOCK_CUSTOM_SOCKOPT,
1924 				&connected->sk_socket->flags);
1925 
1926 			if (vsock_msgzerocopy_allow(vconnected->transport))
1927 				set_bit(SOCK_SUPPORT_ZC,
1928 					&connected->sk_socket->flags);
1929 		}
1930 
1931 		release_sock(connected);
1932 		sock_put(connected);
1933 	}
1934 
1935 out:
1936 	release_sock(listener);
1937 	return err;
1938 }
1939 
1940 static int vsock_listen(struct socket *sock, int backlog)
1941 {
1942 	int err;
1943 	struct sock *sk;
1944 	struct vsock_sock *vsk;
1945 
1946 	sk = sock->sk;
1947 
1948 	lock_sock(sk);
1949 
1950 	if (!sock_type_connectible(sk->sk_type)) {
1951 		err = -EOPNOTSUPP;
1952 		goto out;
1953 	}
1954 
1955 	if (sock->state != SS_UNCONNECTED) {
1956 		err = -EINVAL;
1957 		goto out;
1958 	}
1959 
1960 	vsk = vsock_sk(sk);
1961 
1962 	if (!vsock_addr_bound(&vsk->local_addr)) {
1963 		err = -EINVAL;
1964 		goto out;
1965 	}
1966 
1967 	sk->sk_max_ack_backlog = backlog;
1968 	sk->sk_state = TCP_LISTEN;
1969 
1970 	err = 0;
1971 
1972 out:
1973 	release_sock(sk);
1974 	return err;
1975 }
1976 
1977 static void vsock_update_buffer_size(struct vsock_sock *vsk,
1978 				     const struct vsock_transport *transport,
1979 				     u64 val)
1980 {
1981 	if (val < vsk->buffer_min_size)
1982 		val = vsk->buffer_min_size;
1983 
1984 	if (val > vsk->buffer_max_size)
1985 		val = vsk->buffer_max_size;
1986 
1987 	if (val != vsk->buffer_size &&
1988 	    transport && transport->notify_buffer_size)
1989 		transport->notify_buffer_size(vsk, &val);
1990 
1991 	vsk->buffer_size = val;
1992 }
1993 
1994 static int vsock_connectible_setsockopt(struct socket *sock,
1995 					int level,
1996 					int optname,
1997 					sockptr_t optval,
1998 					unsigned int optlen)
1999 {
2000 	int err;
2001 	struct sock *sk;
2002 	struct vsock_sock *vsk;
2003 	const struct vsock_transport *transport;
2004 	u64 val;
2005 
2006 	if (level != AF_VSOCK && level != SOL_SOCKET)
2007 		return -ENOPROTOOPT;
2008 
2009 #define COPY_IN(_v)                                       \
2010 	do {						  \
2011 		if (optlen < sizeof(_v)) {		  \
2012 			err = -EINVAL;			  \
2013 			goto exit;			  \
2014 		}					  \
2015 		if (copy_from_sockptr(&_v, optval, sizeof(_v)) != 0) {	\
2016 			err = -EFAULT;					\
2017 			goto exit;					\
2018 		}							\
2019 	} while (0)
2020 
2021 	err = 0;
2022 	sk = sock->sk;
2023 	vsk = vsock_sk(sk);
2024 
2025 	lock_sock(sk);
2026 
2027 	transport = vsk->transport;
2028 
2029 	if (level == SOL_SOCKET) {
2030 		int zerocopy;
2031 
2032 		if (optname != SO_ZEROCOPY) {
2033 			release_sock(sk);
2034 			return sock_setsockopt(sock, level, optname, optval, optlen);
2035 		}
2036 
2037 		/* Use 'int' type here, because variable to
2038 		 * set this option usually has this type.
2039 		 */
2040 		COPY_IN(zerocopy);
2041 
2042 		if (zerocopy < 0 || zerocopy > 1) {
2043 			err = -EINVAL;
2044 			goto exit;
2045 		}
2046 
2047 		if (transport && !vsock_msgzerocopy_allow(transport)) {
2048 			err = -EOPNOTSUPP;
2049 			goto exit;
2050 		}
2051 
2052 		sock_valbool_flag(sk, SOCK_ZEROCOPY, zerocopy);
2053 		goto exit;
2054 	}
2055 
2056 	switch (optname) {
2057 	case SO_VM_SOCKETS_BUFFER_SIZE:
2058 		COPY_IN(val);
2059 		vsock_update_buffer_size(vsk, transport, val);
2060 		break;
2061 
2062 	case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
2063 		COPY_IN(val);
2064 		vsk->buffer_max_size = val;
2065 		vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
2066 		break;
2067 
2068 	case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
2069 		COPY_IN(val);
2070 		vsk->buffer_min_size = val;
2071 		vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
2072 		break;
2073 
2074 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
2075 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD: {
2076 		struct __kernel_sock_timeval tv;
2077 
2078 		err = sock_copy_user_timeval(&tv, optval, optlen,
2079 					     optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
2080 		if (err)
2081 			break;
2082 		if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC &&
2083 		    tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) {
2084 			vsk->connect_timeout = tv.tv_sec * HZ +
2085 				DIV_ROUND_UP((unsigned long)tv.tv_usec, (USEC_PER_SEC / HZ));
2086 			if (vsk->connect_timeout == 0)
2087 				vsk->connect_timeout =
2088 				    VSOCK_DEFAULT_CONNECT_TIMEOUT;
2089 
2090 		} else {
2091 			err = -ERANGE;
2092 		}
2093 		break;
2094 	}
2095 
2096 	default:
2097 		err = -ENOPROTOOPT;
2098 		break;
2099 	}
2100 
2101 #undef COPY_IN
2102 
2103 exit:
2104 	release_sock(sk);
2105 	return err;
2106 }
2107 
2108 static int vsock_connectible_getsockopt(struct socket *sock,
2109 					int level, int optname,
2110 					sockopt_t *opt)
2111 {
2112 	struct sock *sk = sock->sk;
2113 	struct vsock_sock *vsk = vsock_sk(sk);
2114 
2115 	union {
2116 		u64 val64;
2117 		struct old_timeval32 tm32;
2118 		struct __kernel_old_timeval tm;
2119 		struct  __kernel_sock_timeval stm;
2120 	} v;
2121 
2122 	int lv = sizeof(v.val64);
2123 	int len;
2124 
2125 	if (level != AF_VSOCK)
2126 		return -ENOPROTOOPT;
2127 
2128 	len = opt->optlen;
2129 
2130 	memset(&v, 0, sizeof(v));
2131 
2132 	switch (optname) {
2133 	case SO_VM_SOCKETS_BUFFER_SIZE:
2134 		v.val64 = vsk->buffer_size;
2135 		break;
2136 
2137 	case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
2138 		v.val64 = vsk->buffer_max_size;
2139 		break;
2140 
2141 	case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
2142 		v.val64 = vsk->buffer_min_size;
2143 		break;
2144 
2145 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
2146 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD:
2147 		lv = sock_get_timeout(vsk->connect_timeout, &v,
2148 				      optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
2149 		break;
2150 
2151 	default:
2152 		return -ENOPROTOOPT;
2153 	}
2154 
2155 	if (len < lv)
2156 		return -EINVAL;
2157 	if (len > lv)
2158 		len = lv;
2159 	if (copy_to_iter(&v, len, &opt->iter_out) != len)
2160 		return -EFAULT;
2161 
2162 	opt->optlen = len;
2163 
2164 	return 0;
2165 }
2166 
2167 static int vsock_connectible_sendmsg(struct socket *sock, struct msghdr *msg,
2168 				     size_t len)
2169 {
2170 	struct sock *sk;
2171 	struct vsock_sock *vsk;
2172 	const struct vsock_transport *transport;
2173 	ssize_t total_written;
2174 	long timeout;
2175 	int err;
2176 	struct vsock_transport_send_notify_data send_data;
2177 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
2178 
2179 	sk = sock->sk;
2180 	vsk = vsock_sk(sk);
2181 	total_written = 0;
2182 	err = 0;
2183 
2184 	if (msg->msg_flags & MSG_OOB)
2185 		return -EOPNOTSUPP;
2186 
2187 	lock_sock(sk);
2188 
2189 	transport = vsk->transport;
2190 
2191 	/* Callers should not provide a destination with connection oriented
2192 	 * sockets.
2193 	 */
2194 	if (msg->msg_namelen) {
2195 		err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
2196 		goto out;
2197 	}
2198 
2199 	/* Send data only if both sides are not shutdown in the direction. */
2200 	if (sk->sk_shutdown & SEND_SHUTDOWN ||
2201 	    vsk->peer_shutdown & RCV_SHUTDOWN) {
2202 		err = -EPIPE;
2203 		goto out;
2204 	}
2205 
2206 	if (!transport || sk->sk_state != TCP_ESTABLISHED ||
2207 	    !vsock_addr_bound(&vsk->local_addr)) {
2208 		err = -ENOTCONN;
2209 		goto out;
2210 	}
2211 
2212 	if (!vsock_addr_bound(&vsk->remote_addr)) {
2213 		err = -EDESTADDRREQ;
2214 		goto out;
2215 	}
2216 
2217 	if (msg->msg_flags & MSG_ZEROCOPY &&
2218 	    !vsock_msgzerocopy_allow(transport)) {
2219 		err = -EOPNOTSUPP;
2220 		goto out;
2221 	}
2222 
2223 	/* Wait for room in the produce queue to enqueue our user's data. */
2224 	timeout = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
2225 
2226 	err = transport->notify_send_init(vsk, &send_data);
2227 	if (err < 0)
2228 		goto out;
2229 
2230 	while (total_written < len) {
2231 		ssize_t written;
2232 
2233 		add_wait_queue(sk_sleep(sk), &wait);
2234 		while (vsock_stream_has_space(vsk) == 0 &&
2235 		       sk->sk_err == 0 &&
2236 		       !(sk->sk_shutdown & SEND_SHUTDOWN) &&
2237 		       !(vsk->peer_shutdown & RCV_SHUTDOWN)) {
2238 
2239 			/* Don't wait for non-blocking sockets. */
2240 			if (timeout == 0) {
2241 				err = -EAGAIN;
2242 				remove_wait_queue(sk_sleep(sk), &wait);
2243 				goto out_err;
2244 			}
2245 
2246 			err = transport->notify_send_pre_block(vsk, &send_data);
2247 			if (err < 0) {
2248 				remove_wait_queue(sk_sleep(sk), &wait);
2249 				goto out_err;
2250 			}
2251 
2252 			release_sock(sk);
2253 			timeout = wait_woken(&wait, TASK_INTERRUPTIBLE, timeout);
2254 			lock_sock(sk);
2255 			if (signal_pending(current)) {
2256 				err = sock_intr_errno(timeout);
2257 				remove_wait_queue(sk_sleep(sk), &wait);
2258 				goto out_err;
2259 			} else if (timeout == 0) {
2260 				err = -EAGAIN;
2261 				remove_wait_queue(sk_sleep(sk), &wait);
2262 				goto out_err;
2263 			}
2264 		}
2265 		remove_wait_queue(sk_sleep(sk), &wait);
2266 
2267 		/* These checks occur both as part of and after the loop
2268 		 * conditional since we need to check before and after
2269 		 * sleeping.
2270 		 */
2271 		if (sk->sk_err) {
2272 			err = -sk->sk_err;
2273 			goto out_err;
2274 		} else if ((sk->sk_shutdown & SEND_SHUTDOWN) ||
2275 			   (vsk->peer_shutdown & RCV_SHUTDOWN)) {
2276 			err = -EPIPE;
2277 			goto out_err;
2278 		}
2279 
2280 		err = transport->notify_send_pre_enqueue(vsk, &send_data);
2281 		if (err < 0)
2282 			goto out_err;
2283 
2284 		/* Note that enqueue will only write as many bytes as are free
2285 		 * in the produce queue, so we don't need to ensure len is
2286 		 * smaller than the queue size.  It is the caller's
2287 		 * responsibility to check how many bytes we were able to send.
2288 		 */
2289 
2290 		if (sk->sk_type == SOCK_SEQPACKET) {
2291 			written = transport->seqpacket_enqueue(vsk,
2292 						msg, len - total_written);
2293 		} else {
2294 			written = transport->stream_enqueue(vsk,
2295 					msg, len - total_written);
2296 		}
2297 
2298 		if (written < 0) {
2299 			err = written;
2300 			goto out_err;
2301 		}
2302 
2303 		total_written += written;
2304 
2305 		err = transport->notify_send_post_enqueue(
2306 				vsk, written, &send_data);
2307 		if (err < 0)
2308 			goto out_err;
2309 
2310 	}
2311 
2312 out_err:
2313 	if (total_written > 0) {
2314 		/* Return number of written bytes only if:
2315 		 * 1) SOCK_STREAM socket.
2316 		 * 2) SOCK_SEQPACKET socket when whole buffer is sent.
2317 		 */
2318 		if (sk->sk_type == SOCK_STREAM || total_written == len)
2319 			err = total_written;
2320 	}
2321 out:
2322 	if (sk->sk_type == SOCK_STREAM)
2323 		err = sk_stream_error(sk, msg->msg_flags, err);
2324 
2325 	release_sock(sk);
2326 	return err;
2327 }
2328 
2329 static int vsock_connectible_wait_data(struct sock *sk,
2330 				       struct wait_queue_entry *wait,
2331 				       long timeout,
2332 				       struct vsock_transport_recv_notify_data *recv_data,
2333 				       size_t target)
2334 {
2335 	const struct vsock_transport *transport;
2336 	struct vsock_sock *vsk;
2337 	s64 data;
2338 	int err;
2339 
2340 	vsk = vsock_sk(sk);
2341 	err = 0;
2342 	transport = vsk->transport;
2343 
2344 	while (1) {
2345 		prepare_to_wait(sk_sleep(sk), wait, TASK_INTERRUPTIBLE);
2346 		data = vsock_connectible_has_data(vsk);
2347 		if (data != 0)
2348 			break;
2349 
2350 		if (sk->sk_err != 0 ||
2351 		    (sk->sk_shutdown & RCV_SHUTDOWN) ||
2352 		    (vsk->peer_shutdown & SEND_SHUTDOWN)) {
2353 			break;
2354 		}
2355 
2356 		/* Don't wait for non-blocking sockets. */
2357 		if (timeout == 0) {
2358 			err = -EAGAIN;
2359 			break;
2360 		}
2361 
2362 		if (recv_data) {
2363 			err = transport->notify_recv_pre_block(vsk, target, recv_data);
2364 			if (err < 0)
2365 				break;
2366 		}
2367 
2368 		release_sock(sk);
2369 		timeout = schedule_timeout(timeout);
2370 		lock_sock(sk);
2371 
2372 		if (signal_pending(current)) {
2373 			err = sock_intr_errno(timeout);
2374 			break;
2375 		} else if (timeout == 0) {
2376 			err = -EAGAIN;
2377 			break;
2378 		}
2379 	}
2380 
2381 	finish_wait(sk_sleep(sk), wait);
2382 
2383 	if (err)
2384 		return err;
2385 
2386 	/* Internal transport error when checking for available
2387 	 * data. XXX This should be changed to a connection
2388 	 * reset in a later change.
2389 	 */
2390 	if (data < 0)
2391 		return -ENOMEM;
2392 
2393 	return data;
2394 }
2395 
2396 static int __vsock_stream_recvmsg(struct sock *sk, struct msghdr *msg,
2397 				  size_t len, int flags)
2398 {
2399 	struct vsock_transport_recv_notify_data recv_data;
2400 	const struct vsock_transport *transport;
2401 	struct vsock_sock *vsk;
2402 	ssize_t copied;
2403 	size_t target;
2404 	long timeout;
2405 	int err;
2406 
2407 	DEFINE_WAIT(wait);
2408 
2409 	vsk = vsock_sk(sk);
2410 	transport = vsk->transport;
2411 
2412 	/* We must not copy less than target bytes into the user's buffer
2413 	 * before returning successfully, so we wait for the consume queue to
2414 	 * have that much data to consume before dequeueing.  Note that this
2415 	 * makes it impossible to handle cases where target is greater than the
2416 	 * queue size.
2417 	 */
2418 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2419 	if (target >= transport->stream_rcvhiwat(vsk)) {
2420 		err = -ENOMEM;
2421 		goto out;
2422 	}
2423 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2424 	copied = 0;
2425 
2426 	err = transport->notify_recv_init(vsk, target, &recv_data);
2427 	if (err < 0)
2428 		goto out;
2429 
2430 
2431 	while (1) {
2432 		ssize_t read;
2433 
2434 		err = vsock_connectible_wait_data(sk, &wait, timeout,
2435 						  &recv_data, target);
2436 		if (err <= 0)
2437 			break;
2438 
2439 		err = transport->notify_recv_pre_dequeue(vsk, target,
2440 							 &recv_data);
2441 		if (err < 0)
2442 			break;
2443 
2444 		read = transport->stream_dequeue(vsk, msg, len - copied, flags);
2445 		if (read < 0) {
2446 			err = read;
2447 			break;
2448 		}
2449 
2450 		copied += read;
2451 
2452 		err = transport->notify_recv_post_dequeue(vsk, target, read,
2453 						!(flags & MSG_PEEK), &recv_data);
2454 		if (err < 0)
2455 			goto out;
2456 
2457 		if (read >= target || flags & MSG_PEEK)
2458 			break;
2459 
2460 		target -= read;
2461 	}
2462 
2463 	if (sk->sk_err)
2464 		err = -sk->sk_err;
2465 	else if (sk->sk_shutdown & RCV_SHUTDOWN)
2466 		err = 0;
2467 
2468 	if (copied > 0)
2469 		err = copied;
2470 
2471 out:
2472 	return err;
2473 }
2474 
2475 static int __vsock_seqpacket_recvmsg(struct sock *sk, struct msghdr *msg,
2476 				     size_t len, int flags)
2477 {
2478 	const struct vsock_transport *transport;
2479 	struct vsock_sock *vsk;
2480 	ssize_t msg_len;
2481 	long timeout;
2482 	int err = 0;
2483 	DEFINE_WAIT(wait);
2484 
2485 	vsk = vsock_sk(sk);
2486 	transport = vsk->transport;
2487 
2488 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2489 
2490 	err = vsock_connectible_wait_data(sk, &wait, timeout, NULL, 0);
2491 	if (err <= 0)
2492 		goto out;
2493 
2494 	msg_len = transport->seqpacket_dequeue(vsk, msg, flags);
2495 
2496 	if (msg_len < 0) {
2497 		err = msg_len;
2498 		goto out;
2499 	}
2500 
2501 	if (sk->sk_err) {
2502 		err = -sk->sk_err;
2503 	} else if (sk->sk_shutdown & RCV_SHUTDOWN) {
2504 		err = 0;
2505 	} else {
2506 		/* User sets MSG_TRUNC, so return real length of
2507 		 * packet.
2508 		 */
2509 		if (flags & MSG_TRUNC)
2510 			err = msg_len;
2511 		else
2512 			err = len - msg_data_left(msg);
2513 
2514 		/* Always set MSG_TRUNC if real length of packet is
2515 		 * bigger than user's buffer.
2516 		 */
2517 		if (msg_len > len)
2518 			msg->msg_flags |= MSG_TRUNC;
2519 	}
2520 
2521 out:
2522 	return err;
2523 }
2524 
2525 int
2526 __vsock_connectible_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
2527 			    int flags)
2528 {
2529 	struct sock *sk;
2530 	struct vsock_sock *vsk;
2531 	const struct vsock_transport *transport;
2532 	int err;
2533 
2534 	sk = sock->sk;
2535 
2536 	if (unlikely(flags & MSG_ERRQUEUE))
2537 		return sock_recv_errqueue(sk, msg, len, SOL_VSOCK, VSOCK_RECVERR);
2538 
2539 	vsk = vsock_sk(sk);
2540 	err = 0;
2541 
2542 	lock_sock(sk);
2543 
2544 	transport = vsk->transport;
2545 
2546 	if (!transport || sk->sk_state != TCP_ESTABLISHED) {
2547 		/* Recvmsg is supposed to return 0 if a peer performs an
2548 		 * orderly shutdown. Differentiate between that case and when a
2549 		 * peer has not connected or a local shutdown occurred with the
2550 		 * SOCK_DONE flag.
2551 		 */
2552 		if (sock_flag(sk, SOCK_DONE))
2553 			err = 0;
2554 		else
2555 			err = -ENOTCONN;
2556 
2557 		goto out;
2558 	}
2559 
2560 	if (flags & MSG_OOB) {
2561 		err = -EOPNOTSUPP;
2562 		goto out;
2563 	}
2564 
2565 	/* We don't check peer_shutdown flag here since peer may actually shut
2566 	 * down, but there can be data in the queue that a local socket can
2567 	 * receive.
2568 	 */
2569 	if (sk->sk_shutdown & RCV_SHUTDOWN) {
2570 		err = 0;
2571 		goto out;
2572 	}
2573 
2574 	/* It is valid on Linux to pass in a zero-length receive buffer.  This
2575 	 * is not an error.  We may as well bail out now.
2576 	 */
2577 	if (!len) {
2578 		err = 0;
2579 		goto out;
2580 	}
2581 
2582 	if (sk->sk_type == SOCK_STREAM)
2583 		err = __vsock_stream_recvmsg(sk, msg, len, flags);
2584 	else
2585 		err = __vsock_seqpacket_recvmsg(sk, msg, len, flags);
2586 
2587 out:
2588 	release_sock(sk);
2589 	return err;
2590 }
2591 
2592 int
2593 vsock_connectible_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
2594 			  int flags)
2595 {
2596 #ifdef CONFIG_BPF_SYSCALL
2597 	struct sock *sk = sock->sk;
2598 	const struct proto *prot;
2599 
2600 	prot = READ_ONCE(sk->sk_prot);
2601 	if (prot != &vsock_proto)
2602 		return prot->recvmsg(sk, msg, len, flags);
2603 #endif
2604 
2605 	return __vsock_connectible_recvmsg(sock, msg, len, flags);
2606 }
2607 EXPORT_SYMBOL_GPL(vsock_connectible_recvmsg);
2608 
2609 static int vsock_set_rcvlowat(struct sock *sk, int val)
2610 {
2611 	const struct vsock_transport *transport;
2612 	struct vsock_sock *vsk;
2613 
2614 	vsk = vsock_sk(sk);
2615 
2616 	if (val > vsk->buffer_size)
2617 		return -EINVAL;
2618 
2619 	transport = vsk->transport;
2620 
2621 	if (transport && transport->notify_set_rcvlowat) {
2622 		int err;
2623 
2624 		err = transport->notify_set_rcvlowat(vsk, val);
2625 		if (err)
2626 			return err;
2627 	}
2628 
2629 	WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
2630 	return 0;
2631 }
2632 
2633 static const struct proto_ops vsock_stream_ops = {
2634 	.family = PF_VSOCK,
2635 	.owner = THIS_MODULE,
2636 	.release = vsock_release,
2637 	.bind = vsock_bind,
2638 	.connect = vsock_connect,
2639 	.socketpair = sock_no_socketpair,
2640 	.accept = vsock_accept,
2641 	.getname = vsock_getname,
2642 	.poll = vsock_poll,
2643 	.ioctl = vsock_ioctl,
2644 	.listen = vsock_listen,
2645 	.shutdown = vsock_shutdown,
2646 	.setsockopt = vsock_connectible_setsockopt,
2647 	.getsockopt_iter = vsock_connectible_getsockopt,
2648 	.sendmsg = vsock_connectible_sendmsg,
2649 	.recvmsg = vsock_connectible_recvmsg,
2650 	.mmap = sock_no_mmap,
2651 	.set_rcvlowat = vsock_set_rcvlowat,
2652 	.read_skb = vsock_read_skb,
2653 };
2654 
2655 static const struct proto_ops vsock_seqpacket_ops = {
2656 	.family = PF_VSOCK,
2657 	.owner = THIS_MODULE,
2658 	.release = vsock_release,
2659 	.bind = vsock_bind,
2660 	.connect = vsock_connect,
2661 	.socketpair = sock_no_socketpair,
2662 	.accept = vsock_accept,
2663 	.getname = vsock_getname,
2664 	.poll = vsock_poll,
2665 	.ioctl = vsock_ioctl,
2666 	.listen = vsock_listen,
2667 	.shutdown = vsock_shutdown,
2668 	.setsockopt = vsock_connectible_setsockopt,
2669 	.getsockopt_iter = vsock_connectible_getsockopt,
2670 	.sendmsg = vsock_connectible_sendmsg,
2671 	.recvmsg = vsock_connectible_recvmsg,
2672 	.mmap = sock_no_mmap,
2673 	.read_skb = vsock_read_skb,
2674 };
2675 
2676 static int vsock_create(struct net *net, struct socket *sock,
2677 			int protocol, int kern)
2678 {
2679 	struct vsock_sock *vsk;
2680 	struct sock *sk;
2681 	int ret;
2682 
2683 	if (!sock)
2684 		return -EINVAL;
2685 
2686 	if (protocol && protocol != PF_VSOCK)
2687 		return -EPROTONOSUPPORT;
2688 
2689 	switch (sock->type) {
2690 	case SOCK_DGRAM:
2691 		sock->ops = &vsock_dgram_ops;
2692 		break;
2693 	case SOCK_STREAM:
2694 		sock->ops = &vsock_stream_ops;
2695 		break;
2696 	case SOCK_SEQPACKET:
2697 		sock->ops = &vsock_seqpacket_ops;
2698 		break;
2699 	default:
2700 		return -ESOCKTNOSUPPORT;
2701 	}
2702 
2703 	sock->state = SS_UNCONNECTED;
2704 
2705 	sk = __vsock_create(net, sock, NULL, GFP_KERNEL, 0, kern);
2706 	if (!sk)
2707 		return -ENOMEM;
2708 
2709 	vsk = vsock_sk(sk);
2710 
2711 	if (sock->type == SOCK_DGRAM) {
2712 		ret = vsock_assign_transport(vsk, NULL);
2713 		if (ret < 0) {
2714 			sock->sk = NULL;
2715 			sock_put(sk);
2716 			return ret;
2717 		}
2718 	}
2719 
2720 	/* SOCK_DGRAM doesn't have 'setsockopt' callback set in its
2721 	 * proto_ops, so there is no handler for custom logic.
2722 	 */
2723 	if (sock_type_connectible(sock->type))
2724 		set_bit(SOCK_CUSTOM_SOCKOPT, &sk->sk_socket->flags);
2725 
2726 	vsock_insert_unbound(vsk);
2727 
2728 	return 0;
2729 }
2730 
2731 static const struct net_proto_family vsock_family_ops = {
2732 	.family = AF_VSOCK,
2733 	.create = vsock_create,
2734 	.owner = THIS_MODULE,
2735 };
2736 
2737 static long vsock_dev_do_ioctl(struct file *filp,
2738 			       unsigned int cmd, void __user *ptr)
2739 {
2740 	u32 __user *p = ptr;
2741 	int retval = 0;
2742 	u32 cid;
2743 
2744 	switch (cmd) {
2745 	case IOCTL_VM_SOCKETS_GET_LOCAL_CID:
2746 		/* To be compatible with the VMCI behavior, we prioritize the
2747 		 * guest CID instead of well-know host CID (VMADDR_CID_HOST).
2748 		 */
2749 		cid = vsock_registered_transport_cid(&transport_g2h);
2750 		if (cid == VMADDR_CID_ANY)
2751 			cid = vsock_registered_transport_cid(&transport_h2g);
2752 		if (cid == VMADDR_CID_ANY)
2753 			cid = vsock_registered_transport_cid(&transport_local);
2754 
2755 		if (put_user(cid, p) != 0)
2756 			retval = -EFAULT;
2757 		break;
2758 
2759 	default:
2760 		retval = -ENOIOCTLCMD;
2761 	}
2762 
2763 	return retval;
2764 }
2765 
2766 static long vsock_dev_ioctl(struct file *filp,
2767 			    unsigned int cmd, unsigned long arg)
2768 {
2769 	return vsock_dev_do_ioctl(filp, cmd, (void __user *)arg);
2770 }
2771 
2772 #ifdef CONFIG_COMPAT
2773 static long vsock_dev_compat_ioctl(struct file *filp,
2774 				   unsigned int cmd, unsigned long arg)
2775 {
2776 	return vsock_dev_do_ioctl(filp, cmd, compat_ptr(arg));
2777 }
2778 #endif
2779 
2780 static const struct file_operations vsock_device_ops = {
2781 	.owner		= THIS_MODULE,
2782 	.unlocked_ioctl	= vsock_dev_ioctl,
2783 #ifdef CONFIG_COMPAT
2784 	.compat_ioctl	= vsock_dev_compat_ioctl,
2785 #endif
2786 	.open		= nonseekable_open,
2787 };
2788 
2789 static struct miscdevice vsock_device = {
2790 	.name		= "vsock",
2791 	.fops		= &vsock_device_ops,
2792 };
2793 
2794 static int __vsock_net_mode_string(const struct ctl_table *table, int write,
2795 				   void *buffer, size_t *lenp, loff_t *ppos,
2796 				   enum vsock_net_mode mode,
2797 				   enum vsock_net_mode *new_mode)
2798 {
2799 	char data[VSOCK_NET_MODE_STR_MAX] = {0};
2800 	struct ctl_table tmp;
2801 	int ret;
2802 
2803 	if (!table->data || !table->maxlen || !*lenp) {
2804 		*lenp = 0;
2805 		return 0;
2806 	}
2807 
2808 	tmp = *table;
2809 	tmp.data = data;
2810 
2811 	if (!write) {
2812 		const char *p;
2813 
2814 		switch (mode) {
2815 		case VSOCK_NET_MODE_GLOBAL:
2816 			p = VSOCK_NET_MODE_STR_GLOBAL;
2817 			break;
2818 		case VSOCK_NET_MODE_LOCAL:
2819 			p = VSOCK_NET_MODE_STR_LOCAL;
2820 			break;
2821 		default:
2822 			WARN_ONCE(true, "netns has invalid vsock mode");
2823 			*lenp = 0;
2824 			return 0;
2825 		}
2826 
2827 		strscpy(data, p, sizeof(data));
2828 		tmp.maxlen = strlen(p);
2829 	}
2830 
2831 	ret = proc_dostring(&tmp, write, buffer, lenp, ppos);
2832 	if (ret || !write)
2833 		return ret;
2834 
2835 	if (*lenp >= sizeof(data))
2836 		return -EINVAL;
2837 
2838 	if (!strncmp(data, VSOCK_NET_MODE_STR_GLOBAL, sizeof(data)))
2839 		*new_mode = VSOCK_NET_MODE_GLOBAL;
2840 	else if (!strncmp(data, VSOCK_NET_MODE_STR_LOCAL, sizeof(data)))
2841 		*new_mode = VSOCK_NET_MODE_LOCAL;
2842 	else
2843 		return -EINVAL;
2844 
2845 	return 0;
2846 }
2847 
2848 static int vsock_net_mode_string(const struct ctl_table *table, int write,
2849 				 void *buffer, size_t *lenp, loff_t *ppos)
2850 {
2851 	struct net *net;
2852 
2853 	if (write)
2854 		return -EPERM;
2855 
2856 	net = container_of(table->data, struct net, vsock.mode);
2857 
2858 	return __vsock_net_mode_string(table, write, buffer, lenp, ppos,
2859 				       vsock_net_mode(net), NULL);
2860 }
2861 
2862 static int vsock_net_child_mode_string(const struct ctl_table *table, int write,
2863 				       void *buffer, size_t *lenp, loff_t *ppos)
2864 {
2865 	enum vsock_net_mode new_mode;
2866 	struct net *net;
2867 	int ret;
2868 
2869 	net = container_of(table->data, struct net, vsock.child_ns_mode);
2870 
2871 	ret = __vsock_net_mode_string(table, write, buffer, lenp, ppos,
2872 				      vsock_net_child_mode(net), &new_mode);
2873 	if (ret)
2874 		return ret;
2875 
2876 	if (write) {
2877 		/* Prevent a "local" namespace from escalating to "global",
2878 		 * which would give nested namespaces access to global CIDs.
2879 		 */
2880 		if (vsock_net_mode(net) == VSOCK_NET_MODE_LOCAL &&
2881 		    new_mode == VSOCK_NET_MODE_GLOBAL)
2882 			return -EPERM;
2883 
2884 		if (!vsock_net_set_child_mode(net, new_mode))
2885 			return -EBUSY;
2886 	}
2887 
2888 	return 0;
2889 }
2890 
2891 static struct ctl_table vsock_table[] = {
2892 	{
2893 		.procname	= "ns_mode",
2894 		.data		= &init_net.vsock.mode,
2895 		.maxlen		= VSOCK_NET_MODE_STR_MAX,
2896 		.mode		= 0444,
2897 		.proc_handler	= vsock_net_mode_string
2898 	},
2899 	{
2900 		.procname	= "child_ns_mode",
2901 		.data		= &init_net.vsock.child_ns_mode,
2902 		.maxlen		= VSOCK_NET_MODE_STR_MAX,
2903 		.mode		= 0644,
2904 		.proc_handler	= vsock_net_child_mode_string
2905 	},
2906 	{
2907 		.procname	= "g2h_fallback",
2908 		.data		= &init_net.vsock.g2h_fallback,
2909 		.maxlen		= sizeof(int),
2910 		.mode		= 0644,
2911 		.proc_handler	= proc_dointvec_minmax,
2912 		.extra1		= SYSCTL_ZERO,
2913 		.extra2		= SYSCTL_ONE,
2914 	},
2915 };
2916 
2917 static int __net_init vsock_sysctl_register(struct net *net)
2918 {
2919 	struct ctl_table *table;
2920 
2921 	if (net_eq(net, &init_net)) {
2922 		table = vsock_table;
2923 	} else {
2924 		table = kmemdup(vsock_table, sizeof(vsock_table), GFP_KERNEL);
2925 		if (!table)
2926 			goto err_alloc;
2927 
2928 		table[0].data = &net->vsock.mode;
2929 		table[1].data = &net->vsock.child_ns_mode;
2930 		table[2].data = &net->vsock.g2h_fallback;
2931 	}
2932 
2933 	net->vsock.sysctl_hdr = register_net_sysctl_sz(net, "net/vsock", table,
2934 						       ARRAY_SIZE(vsock_table));
2935 	if (!net->vsock.sysctl_hdr)
2936 		goto err_reg;
2937 
2938 	return 0;
2939 
2940 err_reg:
2941 	if (!net_eq(net, &init_net))
2942 		kfree(table);
2943 err_alloc:
2944 	return -ENOMEM;
2945 }
2946 
2947 static void vsock_sysctl_unregister(struct net *net)
2948 {
2949 	const struct ctl_table *table;
2950 
2951 	table = net->vsock.sysctl_hdr->ctl_table_arg;
2952 	unregister_net_sysctl_table(net->vsock.sysctl_hdr);
2953 	if (!net_eq(net, &init_net))
2954 		kfree(table);
2955 }
2956 
2957 static void vsock_net_init(struct net *net)
2958 {
2959 	if (net_eq(net, &init_net))
2960 		net->vsock.mode = VSOCK_NET_MODE_GLOBAL;
2961 	else
2962 		net->vsock.mode = vsock_net_child_mode(current->nsproxy->net_ns);
2963 
2964 	net->vsock.child_ns_mode = net->vsock.mode;
2965 	net->vsock.child_ns_mode_locked = 0;
2966 	net->vsock.g2h_fallback = 1;
2967 }
2968 
2969 static __net_init int vsock_sysctl_init_net(struct net *net)
2970 {
2971 	vsock_net_init(net);
2972 
2973 	if (vsock_sysctl_register(net))
2974 		return -ENOMEM;
2975 
2976 	return 0;
2977 }
2978 
2979 static __net_exit void vsock_sysctl_exit_net(struct net *net)
2980 {
2981 	vsock_sysctl_unregister(net);
2982 }
2983 
2984 static struct pernet_operations vsock_sysctl_ops = {
2985 	.init = vsock_sysctl_init_net,
2986 	.exit = vsock_sysctl_exit_net,
2987 };
2988 
2989 static int __init vsock_init(void)
2990 {
2991 	int err = 0;
2992 
2993 	vsock_init_tables();
2994 
2995 	vsock_proto.owner = THIS_MODULE;
2996 	vsock_device.minor = MISC_DYNAMIC_MINOR;
2997 	err = misc_register(&vsock_device);
2998 	if (err) {
2999 		pr_err("Failed to register misc device\n");
3000 		goto err_reset_transport;
3001 	}
3002 
3003 	err = proto_register(&vsock_proto, 1);	/* we want our slab */
3004 	if (err) {
3005 		pr_err("Cannot register vsock protocol\n");
3006 		goto err_deregister_misc;
3007 	}
3008 
3009 	err = sock_register(&vsock_family_ops);
3010 	if (err) {
3011 		pr_err("could not register af_vsock (%d) address family: %d\n",
3012 		       AF_VSOCK, err);
3013 		goto err_unregister_proto;
3014 	}
3015 
3016 	if (register_pernet_subsys(&vsock_sysctl_ops)) {
3017 		err = -ENOMEM;
3018 		goto err_unregister_sock;
3019 	}
3020 
3021 	vsock_bpf_build_proto();
3022 
3023 	return 0;
3024 
3025 err_unregister_sock:
3026 	sock_unregister(AF_VSOCK);
3027 err_unregister_proto:
3028 	proto_unregister(&vsock_proto);
3029 err_deregister_misc:
3030 	misc_deregister(&vsock_device);
3031 err_reset_transport:
3032 	return err;
3033 }
3034 
3035 static void __exit vsock_exit(void)
3036 {
3037 	misc_deregister(&vsock_device);
3038 	sock_unregister(AF_VSOCK);
3039 	proto_unregister(&vsock_proto);
3040 	unregister_pernet_subsys(&vsock_sysctl_ops);
3041 }
3042 
3043 const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)
3044 {
3045 	return vsk->transport;
3046 }
3047 EXPORT_SYMBOL_GPL(vsock_core_get_transport);
3048 
3049 int vsock_core_register(const struct vsock_transport *t, int features)
3050 {
3051 	const struct vsock_transport *t_h2g, *t_g2h, *t_dgram, *t_local;
3052 	int err = mutex_lock_interruptible(&vsock_register_mutex);
3053 
3054 	if (err)
3055 		return err;
3056 
3057 	t_h2g = transport_h2g;
3058 	t_g2h = transport_g2h;
3059 	t_dgram = transport_dgram;
3060 	t_local = transport_local;
3061 
3062 	if (features & VSOCK_TRANSPORT_F_H2G) {
3063 		if (t_h2g) {
3064 			err = -EBUSY;
3065 			goto err_busy;
3066 		}
3067 		t_h2g = t;
3068 	}
3069 
3070 	if (features & VSOCK_TRANSPORT_F_G2H) {
3071 		if (t_g2h) {
3072 			err = -EBUSY;
3073 			goto err_busy;
3074 		}
3075 		t_g2h = t;
3076 	}
3077 
3078 	if (features & VSOCK_TRANSPORT_F_DGRAM) {
3079 		if (t_dgram) {
3080 			err = -EBUSY;
3081 			goto err_busy;
3082 		}
3083 		t_dgram = t;
3084 	}
3085 
3086 	if (features & VSOCK_TRANSPORT_F_LOCAL) {
3087 		if (t_local) {
3088 			err = -EBUSY;
3089 			goto err_busy;
3090 		}
3091 		t_local = t;
3092 	}
3093 
3094 	transport_h2g = t_h2g;
3095 	transport_g2h = t_g2h;
3096 	transport_dgram = t_dgram;
3097 	transport_local = t_local;
3098 
3099 err_busy:
3100 	mutex_unlock(&vsock_register_mutex);
3101 	return err;
3102 }
3103 EXPORT_SYMBOL_GPL(vsock_core_register);
3104 
3105 void vsock_core_unregister(const struct vsock_transport *t)
3106 {
3107 	mutex_lock(&vsock_register_mutex);
3108 
3109 	if (transport_h2g == t)
3110 		transport_h2g = NULL;
3111 
3112 	if (transport_g2h == t)
3113 		transport_g2h = NULL;
3114 
3115 	if (transport_dgram == t)
3116 		transport_dgram = NULL;
3117 
3118 	if (transport_local == t)
3119 		transport_local = NULL;
3120 
3121 	mutex_unlock(&vsock_register_mutex);
3122 }
3123 EXPORT_SYMBOL_GPL(vsock_core_unregister);
3124 
3125 module_init(vsock_init);
3126 module_exit(vsock_exit);
3127 
3128 MODULE_AUTHOR("VMware, Inc.");
3129 MODULE_DESCRIPTION("VMware Virtual Socket Family");
3130 MODULE_VERSION("1.0.2.0-k");
3131 MODULE_LICENSE("GPL v2");
3132