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