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