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