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