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