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