xref: /linux/net/vmw_vsock/af_vsock.c (revision eb3ab13d997a2f12ec9d557b6ae2aea4e28e2bc3)
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. */
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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  */
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
793 static bool sock_type_connectible(u16 type)
794 {
795 	return (type == SOCK_STREAM) || (type == SOCK_SEQPACKET);
796 }
797 
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 
835 static void vsock_sk_destruct(struct sock *sk)
836 {
837 	struct vsock_sock *vsk = vsock_sk(sk);
838 
839 	vsock_deassign_transport(vsk);
840 
841 	/* When clearing these addresses, there's no need to set the family and
842 	 * possibly register the address family with the kernel.
843 	 */
844 	vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
845 	vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
846 
847 	put_cred(vsk->owner);
848 }
849 
850 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
851 {
852 	int err;
853 
854 	err = sock_queue_rcv_skb(sk, skb);
855 	if (err)
856 		kfree_skb(skb);
857 
858 	return err;
859 }
860 
861 struct sock *vsock_create_connected(struct sock *parent)
862 {
863 	return __vsock_create(sock_net(parent), NULL, parent, GFP_KERNEL,
864 			      parent->sk_type, 0);
865 }
866 EXPORT_SYMBOL_GPL(vsock_create_connected);
867 
868 s64 vsock_stream_has_data(struct vsock_sock *vsk)
869 {
870 	return vsk->transport->stream_has_data(vsk);
871 }
872 EXPORT_SYMBOL_GPL(vsock_stream_has_data);
873 
874 s64 vsock_connectible_has_data(struct vsock_sock *vsk)
875 {
876 	struct sock *sk = sk_vsock(vsk);
877 
878 	if (sk->sk_type == SOCK_SEQPACKET)
879 		return vsk->transport->seqpacket_has_data(vsk);
880 	else
881 		return vsock_stream_has_data(vsk);
882 }
883 EXPORT_SYMBOL_GPL(vsock_connectible_has_data);
884 
885 s64 vsock_stream_has_space(struct vsock_sock *vsk)
886 {
887 	return vsk->transport->stream_has_space(vsk);
888 }
889 EXPORT_SYMBOL_GPL(vsock_stream_has_space);
890 
891 void vsock_data_ready(struct sock *sk)
892 {
893 	struct vsock_sock *vsk = vsock_sk(sk);
894 
895 	if (vsock_stream_has_data(vsk) >= sk->sk_rcvlowat ||
896 	    sock_flag(sk, SOCK_DONE))
897 		sk->sk_data_ready(sk);
898 }
899 EXPORT_SYMBOL_GPL(vsock_data_ready);
900 
901 static int vsock_release(struct socket *sock)
902 {
903 	__vsock_release(sock->sk, 0);
904 	sock->sk = NULL;
905 	sock->state = SS_FREE;
906 
907 	return 0;
908 }
909 
910 static int
911 vsock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
912 {
913 	int err;
914 	struct sock *sk;
915 	struct sockaddr_vm *vm_addr;
916 
917 	sk = sock->sk;
918 
919 	if (vsock_addr_cast(addr, addr_len, &vm_addr) != 0)
920 		return -EINVAL;
921 
922 	lock_sock(sk);
923 	err = __vsock_bind(sk, vm_addr);
924 	release_sock(sk);
925 
926 	return err;
927 }
928 
929 static int vsock_getname(struct socket *sock,
930 			 struct sockaddr *addr, int peer)
931 {
932 	int err;
933 	struct sock *sk;
934 	struct vsock_sock *vsk;
935 	struct sockaddr_vm *vm_addr;
936 
937 	sk = sock->sk;
938 	vsk = vsock_sk(sk);
939 	err = 0;
940 
941 	lock_sock(sk);
942 
943 	if (peer) {
944 		if (sock->state != SS_CONNECTED) {
945 			err = -ENOTCONN;
946 			goto out;
947 		}
948 		vm_addr = &vsk->remote_addr;
949 	} else {
950 		vm_addr = &vsk->local_addr;
951 	}
952 
953 	if (!vm_addr) {
954 		err = -EINVAL;
955 		goto out;
956 	}
957 
958 	/* sys_getsockname() and sys_getpeername() pass us a
959 	 * MAX_SOCK_ADDR-sized buffer and don't set addr_len.  Unfortunately
960 	 * that macro is defined in socket.c instead of .h, so we hardcode its
961 	 * value here.
962 	 */
963 	BUILD_BUG_ON(sizeof(*vm_addr) > 128);
964 	memcpy(addr, vm_addr, sizeof(*vm_addr));
965 	err = sizeof(*vm_addr);
966 
967 out:
968 	release_sock(sk);
969 	return err;
970 }
971 
972 static int vsock_shutdown(struct socket *sock, int mode)
973 {
974 	int err;
975 	struct sock *sk;
976 
977 	/* User level uses SHUT_RD (0) and SHUT_WR (1), but the kernel uses
978 	 * RCV_SHUTDOWN (1) and SEND_SHUTDOWN (2), so we must increment mode
979 	 * here like the other address families do.  Note also that the
980 	 * increment makes SHUT_RDWR (2) into RCV_SHUTDOWN | SEND_SHUTDOWN (3),
981 	 * which is what we want.
982 	 */
983 	mode++;
984 
985 	if ((mode & ~SHUTDOWN_MASK) || !mode)
986 		return -EINVAL;
987 
988 	/* If this is a connection oriented socket and it is not connected then
989 	 * bail out immediately.  If it is a DGRAM socket then we must first
990 	 * kick the socket so that it wakes up from any sleeping calls, for
991 	 * example recv(), and then afterwards return the error.
992 	 */
993 
994 	sk = sock->sk;
995 
996 	lock_sock(sk);
997 	if (sock->state == SS_UNCONNECTED) {
998 		err = -ENOTCONN;
999 		if (sock_type_connectible(sk->sk_type))
1000 			goto out;
1001 	} else {
1002 		sock->state = SS_DISCONNECTING;
1003 		err = 0;
1004 	}
1005 
1006 	/* Receive and send shutdowns are treated alike. */
1007 	mode = mode & (RCV_SHUTDOWN | SEND_SHUTDOWN);
1008 	if (mode) {
1009 		sk->sk_shutdown |= mode;
1010 		sk->sk_state_change(sk);
1011 
1012 		if (sock_type_connectible(sk->sk_type)) {
1013 			sock_reset_flag(sk, SOCK_DONE);
1014 			vsock_send_shutdown(sk, mode);
1015 		}
1016 	}
1017 
1018 out:
1019 	release_sock(sk);
1020 	return err;
1021 }
1022 
1023 static __poll_t vsock_poll(struct file *file, struct socket *sock,
1024 			       poll_table *wait)
1025 {
1026 	struct sock *sk;
1027 	__poll_t mask;
1028 	struct vsock_sock *vsk;
1029 
1030 	sk = sock->sk;
1031 	vsk = vsock_sk(sk);
1032 
1033 	poll_wait(file, sk_sleep(sk), wait);
1034 	mask = 0;
1035 
1036 	if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
1037 		/* Signify that there has been an error on this socket. */
1038 		mask |= EPOLLERR;
1039 
1040 	/* INET sockets treat local write shutdown and peer write shutdown as a
1041 	 * case of EPOLLHUP set.
1042 	 */
1043 	if ((sk->sk_shutdown == SHUTDOWN_MASK) ||
1044 	    ((sk->sk_shutdown & SEND_SHUTDOWN) &&
1045 	     (vsk->peer_shutdown & SEND_SHUTDOWN))) {
1046 		mask |= EPOLLHUP;
1047 	}
1048 
1049 	if (sk->sk_shutdown & RCV_SHUTDOWN ||
1050 	    vsk->peer_shutdown & SEND_SHUTDOWN) {
1051 		mask |= EPOLLRDHUP;
1052 	}
1053 
1054 	if (sock->type == SOCK_DGRAM) {
1055 		/* For datagram sockets we can read if there is something in
1056 		 * the queue and write as long as the socket isn't shutdown for
1057 		 * sending.
1058 		 */
1059 		if (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
1060 		    (sk->sk_shutdown & RCV_SHUTDOWN)) {
1061 			mask |= EPOLLIN | EPOLLRDNORM;
1062 		}
1063 
1064 		if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1065 			mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
1066 
1067 	} else if (sock_type_connectible(sk->sk_type)) {
1068 		const struct vsock_transport *transport;
1069 
1070 		lock_sock(sk);
1071 
1072 		transport = vsk->transport;
1073 
1074 		/* Listening sockets that have connections in their accept
1075 		 * queue can be read.
1076 		 */
1077 		if (sk->sk_state == TCP_LISTEN
1078 		    && !vsock_is_accept_queue_empty(sk))
1079 			mask |= EPOLLIN | EPOLLRDNORM;
1080 
1081 		/* If there is something in the queue then we can read. */
1082 		if (transport && transport->stream_is_active(vsk) &&
1083 		    !(sk->sk_shutdown & RCV_SHUTDOWN)) {
1084 			bool data_ready_now = false;
1085 			int target = sock_rcvlowat(sk, 0, INT_MAX);
1086 			int ret = transport->notify_poll_in(
1087 					vsk, target, &data_ready_now);
1088 			if (ret < 0) {
1089 				mask |= EPOLLERR;
1090 			} else {
1091 				if (data_ready_now)
1092 					mask |= EPOLLIN | EPOLLRDNORM;
1093 
1094 			}
1095 		}
1096 
1097 		/* Sockets whose connections have been closed, reset, or
1098 		 * terminated should also be considered read, and we check the
1099 		 * shutdown flag for that.
1100 		 */
1101 		if (sk->sk_shutdown & RCV_SHUTDOWN ||
1102 		    vsk->peer_shutdown & SEND_SHUTDOWN) {
1103 			mask |= EPOLLIN | EPOLLRDNORM;
1104 		}
1105 
1106 		/* Connected sockets that can produce data can be written. */
1107 		if (transport && sk->sk_state == TCP_ESTABLISHED) {
1108 			if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
1109 				bool space_avail_now = false;
1110 				int ret = transport->notify_poll_out(
1111 						vsk, 1, &space_avail_now);
1112 				if (ret < 0) {
1113 					mask |= EPOLLERR;
1114 				} else {
1115 					if (space_avail_now)
1116 						/* Remove EPOLLWRBAND since INET
1117 						 * sockets are not setting it.
1118 						 */
1119 						mask |= EPOLLOUT | EPOLLWRNORM;
1120 
1121 				}
1122 			}
1123 		}
1124 
1125 		/* Simulate INET socket poll behaviors, which sets
1126 		 * EPOLLOUT|EPOLLWRNORM when peer is closed and nothing to read,
1127 		 * but local send is not shutdown.
1128 		 */
1129 		if (sk->sk_state == TCP_CLOSE || sk->sk_state == TCP_CLOSING) {
1130 			if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1131 				mask |= EPOLLOUT | EPOLLWRNORM;
1132 
1133 		}
1134 
1135 		release_sock(sk);
1136 	}
1137 
1138 	return mask;
1139 }
1140 
1141 static int vsock_read_skb(struct sock *sk, skb_read_actor_t read_actor)
1142 {
1143 	struct vsock_sock *vsk = vsock_sk(sk);
1144 
1145 	return vsk->transport->read_skb(vsk, read_actor);
1146 }
1147 
1148 static int vsock_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
1149 			       size_t len)
1150 {
1151 	int err;
1152 	struct sock *sk;
1153 	struct vsock_sock *vsk;
1154 	struct sockaddr_vm *remote_addr;
1155 	const struct vsock_transport *transport;
1156 
1157 	if (msg->msg_flags & MSG_OOB)
1158 		return -EOPNOTSUPP;
1159 
1160 	/* For now, MSG_DONTWAIT is always assumed... */
1161 	err = 0;
1162 	sk = sock->sk;
1163 	vsk = vsock_sk(sk);
1164 
1165 	lock_sock(sk);
1166 
1167 	transport = vsk->transport;
1168 
1169 	err = vsock_auto_bind(vsk);
1170 	if (err)
1171 		goto out;
1172 
1173 
1174 	/* If the provided message contains an address, use that.  Otherwise
1175 	 * fall back on the socket's remote handle (if it has been connected).
1176 	 */
1177 	if (msg->msg_name &&
1178 	    vsock_addr_cast(msg->msg_name, msg->msg_namelen,
1179 			    &remote_addr) == 0) {
1180 		/* Ensure this address is of the right type and is a valid
1181 		 * destination.
1182 		 */
1183 
1184 		if (remote_addr->svm_cid == VMADDR_CID_ANY)
1185 			remote_addr->svm_cid = transport->get_local_cid();
1186 
1187 		if (!vsock_addr_bound(remote_addr)) {
1188 			err = -EINVAL;
1189 			goto out;
1190 		}
1191 	} else if (sock->state == SS_CONNECTED) {
1192 		remote_addr = &vsk->remote_addr;
1193 
1194 		if (remote_addr->svm_cid == VMADDR_CID_ANY)
1195 			remote_addr->svm_cid = transport->get_local_cid();
1196 
1197 		/* XXX Should connect() or this function ensure remote_addr is
1198 		 * bound?
1199 		 */
1200 		if (!vsock_addr_bound(&vsk->remote_addr)) {
1201 			err = -EINVAL;
1202 			goto out;
1203 		}
1204 	} else {
1205 		err = -EINVAL;
1206 		goto out;
1207 	}
1208 
1209 	if (!transport->dgram_allow(remote_addr->svm_cid,
1210 				    remote_addr->svm_port)) {
1211 		err = -EINVAL;
1212 		goto out;
1213 	}
1214 
1215 	err = transport->dgram_enqueue(vsk, remote_addr, msg, len);
1216 
1217 out:
1218 	release_sock(sk);
1219 	return err;
1220 }
1221 
1222 static int vsock_dgram_connect(struct socket *sock,
1223 			       struct sockaddr *addr, int addr_len, int flags)
1224 {
1225 	int err;
1226 	struct sock *sk;
1227 	struct vsock_sock *vsk;
1228 	struct sockaddr_vm *remote_addr;
1229 
1230 	sk = sock->sk;
1231 	vsk = vsock_sk(sk);
1232 
1233 	err = vsock_addr_cast(addr, addr_len, &remote_addr);
1234 	if (err == -EAFNOSUPPORT && remote_addr->svm_family == AF_UNSPEC) {
1235 		lock_sock(sk);
1236 		vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY,
1237 				VMADDR_PORT_ANY);
1238 		sock->state = SS_UNCONNECTED;
1239 		release_sock(sk);
1240 		return 0;
1241 	} else if (err != 0)
1242 		return -EINVAL;
1243 
1244 	lock_sock(sk);
1245 
1246 	err = vsock_auto_bind(vsk);
1247 	if (err)
1248 		goto out;
1249 
1250 	if (!vsk->transport->dgram_allow(remote_addr->svm_cid,
1251 					 remote_addr->svm_port)) {
1252 		err = -EINVAL;
1253 		goto out;
1254 	}
1255 
1256 	memcpy(&vsk->remote_addr, remote_addr, sizeof(vsk->remote_addr));
1257 	sock->state = SS_CONNECTED;
1258 
1259 	/* sock map disallows redirection of non-TCP sockets with sk_state !=
1260 	 * TCP_ESTABLISHED (see sock_map_redirect_allowed()), so we set
1261 	 * TCP_ESTABLISHED here to allow redirection of connected vsock dgrams.
1262 	 *
1263 	 * This doesn't seem to be abnormal state for datagram sockets, as the
1264 	 * same approach can be see in other datagram socket types as well
1265 	 * (such as unix sockets).
1266 	 */
1267 	sk->sk_state = TCP_ESTABLISHED;
1268 
1269 out:
1270 	release_sock(sk);
1271 	return err;
1272 }
1273 
1274 int vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
1275 			size_t len, int flags)
1276 {
1277 #ifdef CONFIG_BPF_SYSCALL
1278 	const struct proto *prot;
1279 #endif
1280 	struct vsock_sock *vsk;
1281 	struct sock *sk;
1282 
1283 	sk = sock->sk;
1284 	vsk = vsock_sk(sk);
1285 
1286 #ifdef CONFIG_BPF_SYSCALL
1287 	prot = READ_ONCE(sk->sk_prot);
1288 	if (prot != &vsock_proto)
1289 		return prot->recvmsg(sk, msg, len, flags, NULL);
1290 #endif
1291 
1292 	return vsk->transport->dgram_dequeue(vsk, msg, len, flags);
1293 }
1294 EXPORT_SYMBOL_GPL(vsock_dgram_recvmsg);
1295 
1296 static int vsock_do_ioctl(struct socket *sock, unsigned int cmd,
1297 			  int __user *arg)
1298 {
1299 	struct sock *sk = sock->sk;
1300 	struct vsock_sock *vsk;
1301 	int ret;
1302 
1303 	vsk = vsock_sk(sk);
1304 
1305 	switch (cmd) {
1306 	case SIOCOUTQ: {
1307 		ssize_t n_bytes;
1308 
1309 		if (!vsk->transport || !vsk->transport->unsent_bytes) {
1310 			ret = -EOPNOTSUPP;
1311 			break;
1312 		}
1313 
1314 		if (sock_type_connectible(sk->sk_type) && sk->sk_state == TCP_LISTEN) {
1315 			ret = -EINVAL;
1316 			break;
1317 		}
1318 
1319 		n_bytes = vsk->transport->unsent_bytes(vsk);
1320 		if (n_bytes < 0) {
1321 			ret = n_bytes;
1322 			break;
1323 		}
1324 
1325 		ret = put_user(n_bytes, arg);
1326 		break;
1327 	}
1328 	default:
1329 		ret = -ENOIOCTLCMD;
1330 	}
1331 
1332 	return ret;
1333 }
1334 
1335 static int vsock_ioctl(struct socket *sock, unsigned int cmd,
1336 		       unsigned long arg)
1337 {
1338 	int ret;
1339 
1340 	lock_sock(sock->sk);
1341 	ret = vsock_do_ioctl(sock, cmd, (int __user *)arg);
1342 	release_sock(sock->sk);
1343 
1344 	return ret;
1345 }
1346 
1347 static const struct proto_ops vsock_dgram_ops = {
1348 	.family = PF_VSOCK,
1349 	.owner = THIS_MODULE,
1350 	.release = vsock_release,
1351 	.bind = vsock_bind,
1352 	.connect = vsock_dgram_connect,
1353 	.socketpair = sock_no_socketpair,
1354 	.accept = sock_no_accept,
1355 	.getname = vsock_getname,
1356 	.poll = vsock_poll,
1357 	.ioctl = vsock_ioctl,
1358 	.listen = sock_no_listen,
1359 	.shutdown = vsock_shutdown,
1360 	.sendmsg = vsock_dgram_sendmsg,
1361 	.recvmsg = vsock_dgram_recvmsg,
1362 	.mmap = sock_no_mmap,
1363 	.read_skb = vsock_read_skb,
1364 };
1365 
1366 static int vsock_transport_cancel_pkt(struct vsock_sock *vsk)
1367 {
1368 	const struct vsock_transport *transport = vsk->transport;
1369 
1370 	if (!transport || !transport->cancel_pkt)
1371 		return -EOPNOTSUPP;
1372 
1373 	return transport->cancel_pkt(vsk);
1374 }
1375 
1376 static void vsock_connect_timeout(struct work_struct *work)
1377 {
1378 	struct sock *sk;
1379 	struct vsock_sock *vsk;
1380 
1381 	vsk = container_of(work, struct vsock_sock, connect_work.work);
1382 	sk = sk_vsock(vsk);
1383 
1384 	lock_sock(sk);
1385 	if (sk->sk_state == TCP_SYN_SENT &&
1386 	    (sk->sk_shutdown != SHUTDOWN_MASK)) {
1387 		sk->sk_state = TCP_CLOSE;
1388 		sk->sk_socket->state = SS_UNCONNECTED;
1389 		sk->sk_err = ETIMEDOUT;
1390 		sk_error_report(sk);
1391 		vsock_transport_cancel_pkt(vsk);
1392 	}
1393 	release_sock(sk);
1394 
1395 	sock_put(sk);
1396 }
1397 
1398 static int vsock_connect(struct socket *sock, struct sockaddr *addr,
1399 			 int addr_len, int flags)
1400 {
1401 	int err;
1402 	struct sock *sk;
1403 	struct vsock_sock *vsk;
1404 	const struct vsock_transport *transport;
1405 	struct sockaddr_vm *remote_addr;
1406 	long timeout;
1407 	DEFINE_WAIT(wait);
1408 
1409 	err = 0;
1410 	sk = sock->sk;
1411 	vsk = vsock_sk(sk);
1412 
1413 	lock_sock(sk);
1414 
1415 	/* XXX AF_UNSPEC should make us disconnect like AF_INET. */
1416 	switch (sock->state) {
1417 	case SS_CONNECTED:
1418 		err = -EISCONN;
1419 		goto out;
1420 	case SS_DISCONNECTING:
1421 		err = -EINVAL;
1422 		goto out;
1423 	case SS_CONNECTING:
1424 		/* This continues on so we can move sock into the SS_CONNECTED
1425 		 * state once the connection has completed (at which point err
1426 		 * will be set to zero also).  Otherwise, we will either wait
1427 		 * for the connection or return -EALREADY should this be a
1428 		 * non-blocking call.
1429 		 */
1430 		err = -EALREADY;
1431 		if (flags & O_NONBLOCK)
1432 			goto out;
1433 		break;
1434 	default:
1435 		if ((sk->sk_state == TCP_LISTEN) ||
1436 		    vsock_addr_cast(addr, addr_len, &remote_addr) != 0) {
1437 			err = -EINVAL;
1438 			goto out;
1439 		}
1440 
1441 		/* Set the remote address that we are connecting to. */
1442 		memcpy(&vsk->remote_addr, remote_addr,
1443 		       sizeof(vsk->remote_addr));
1444 
1445 		err = vsock_assign_transport(vsk, NULL);
1446 		if (err)
1447 			goto out;
1448 
1449 		transport = vsk->transport;
1450 
1451 		/* The hypervisor and well-known contexts do not have socket
1452 		 * endpoints.
1453 		 */
1454 		if (!transport ||
1455 		    !transport->stream_allow(remote_addr->svm_cid,
1456 					     remote_addr->svm_port)) {
1457 			err = -ENETUNREACH;
1458 			goto out;
1459 		}
1460 
1461 		if (vsock_msgzerocopy_allow(transport)) {
1462 			set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1463 		} else if (sock_flag(sk, SOCK_ZEROCOPY)) {
1464 			/* If this option was set before 'connect()',
1465 			 * when transport was unknown, check that this
1466 			 * feature is supported here.
1467 			 */
1468 			err = -EOPNOTSUPP;
1469 			goto out;
1470 		}
1471 
1472 		err = vsock_auto_bind(vsk);
1473 		if (err)
1474 			goto out;
1475 
1476 		sk->sk_state = TCP_SYN_SENT;
1477 
1478 		err = transport->connect(vsk);
1479 		if (err < 0)
1480 			goto out;
1481 
1482 		/* Mark sock as connecting and set the error code to in
1483 		 * progress in case this is a non-blocking connect.
1484 		 */
1485 		sock->state = SS_CONNECTING;
1486 		err = -EINPROGRESS;
1487 	}
1488 
1489 	/* The receive path will handle all communication until we are able to
1490 	 * enter the connected state.  Here we wait for the connection to be
1491 	 * completed or a notification of an error.
1492 	 */
1493 	timeout = vsk->connect_timeout;
1494 	prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1495 
1496 	while (sk->sk_state != TCP_ESTABLISHED && sk->sk_err == 0) {
1497 		if (flags & O_NONBLOCK) {
1498 			/* If we're not going to block, we schedule a timeout
1499 			 * function to generate a timeout on the connection
1500 			 * attempt, in case the peer doesn't respond in a
1501 			 * timely manner. We hold on to the socket until the
1502 			 * timeout fires.
1503 			 */
1504 			sock_hold(sk);
1505 
1506 			/* If the timeout function is already scheduled,
1507 			 * reschedule it, then ungrab the socket refcount to
1508 			 * keep it balanced.
1509 			 */
1510 			if (mod_delayed_work(system_wq, &vsk->connect_work,
1511 					     timeout))
1512 				sock_put(sk);
1513 
1514 			/* Skip ahead to preserve error code set above. */
1515 			goto out_wait;
1516 		}
1517 
1518 		release_sock(sk);
1519 		timeout = schedule_timeout(timeout);
1520 		lock_sock(sk);
1521 
1522 		if (signal_pending(current)) {
1523 			err = sock_intr_errno(timeout);
1524 			sk->sk_state = sk->sk_state == TCP_ESTABLISHED ? TCP_CLOSING : TCP_CLOSE;
1525 			sock->state = SS_UNCONNECTED;
1526 			vsock_transport_cancel_pkt(vsk);
1527 			vsock_remove_connected(vsk);
1528 			goto out_wait;
1529 		} else if ((sk->sk_state != TCP_ESTABLISHED) && (timeout == 0)) {
1530 			err = -ETIMEDOUT;
1531 			sk->sk_state = TCP_CLOSE;
1532 			sock->state = SS_UNCONNECTED;
1533 			vsock_transport_cancel_pkt(vsk);
1534 			goto out_wait;
1535 		}
1536 
1537 		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1538 	}
1539 
1540 	if (sk->sk_err) {
1541 		err = -sk->sk_err;
1542 		sk->sk_state = TCP_CLOSE;
1543 		sock->state = SS_UNCONNECTED;
1544 	} else {
1545 		err = 0;
1546 	}
1547 
1548 out_wait:
1549 	finish_wait(sk_sleep(sk), &wait);
1550 out:
1551 	release_sock(sk);
1552 	return err;
1553 }
1554 
1555 static int vsock_accept(struct socket *sock, struct socket *newsock,
1556 			struct proto_accept_arg *arg)
1557 {
1558 	struct sock *listener;
1559 	int err;
1560 	struct sock *connected;
1561 	struct vsock_sock *vconnected;
1562 	long timeout;
1563 	DEFINE_WAIT(wait);
1564 
1565 	err = 0;
1566 	listener = sock->sk;
1567 
1568 	lock_sock(listener);
1569 
1570 	if (!sock_type_connectible(sock->type)) {
1571 		err = -EOPNOTSUPP;
1572 		goto out;
1573 	}
1574 
1575 	if (listener->sk_state != TCP_LISTEN) {
1576 		err = -EINVAL;
1577 		goto out;
1578 	}
1579 
1580 	/* Wait for children sockets to appear; these are the new sockets
1581 	 * created upon connection establishment.
1582 	 */
1583 	timeout = sock_rcvtimeo(listener, arg->flags & O_NONBLOCK);
1584 	prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1585 
1586 	while ((connected = vsock_dequeue_accept(listener)) == NULL &&
1587 	       listener->sk_err == 0) {
1588 		release_sock(listener);
1589 		timeout = schedule_timeout(timeout);
1590 		finish_wait(sk_sleep(listener), &wait);
1591 		lock_sock(listener);
1592 
1593 		if (signal_pending(current)) {
1594 			err = sock_intr_errno(timeout);
1595 			goto out;
1596 		} else if (timeout == 0) {
1597 			err = -EAGAIN;
1598 			goto out;
1599 		}
1600 
1601 		prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1602 	}
1603 	finish_wait(sk_sleep(listener), &wait);
1604 
1605 	if (listener->sk_err)
1606 		err = -listener->sk_err;
1607 
1608 	if (connected) {
1609 		sk_acceptq_removed(listener);
1610 
1611 		lock_sock_nested(connected, SINGLE_DEPTH_NESTING);
1612 		vconnected = vsock_sk(connected);
1613 
1614 		/* If the listener socket has received an error, then we should
1615 		 * reject this socket and return.  Note that we simply mark the
1616 		 * socket rejected, drop our reference, and let the cleanup
1617 		 * function handle the cleanup; the fact that we found it in
1618 		 * the listener's accept queue guarantees that the cleanup
1619 		 * function hasn't run yet.
1620 		 */
1621 		if (err) {
1622 			vconnected->rejected = true;
1623 		} else {
1624 			newsock->state = SS_CONNECTED;
1625 			sock_graft(connected, newsock);
1626 			if (vsock_msgzerocopy_allow(vconnected->transport))
1627 				set_bit(SOCK_SUPPORT_ZC,
1628 					&connected->sk_socket->flags);
1629 		}
1630 
1631 		release_sock(connected);
1632 		sock_put(connected);
1633 	}
1634 
1635 out:
1636 	release_sock(listener);
1637 	return err;
1638 }
1639 
1640 static int vsock_listen(struct socket *sock, int backlog)
1641 {
1642 	int err;
1643 	struct sock *sk;
1644 	struct vsock_sock *vsk;
1645 
1646 	sk = sock->sk;
1647 
1648 	lock_sock(sk);
1649 
1650 	if (!sock_type_connectible(sk->sk_type)) {
1651 		err = -EOPNOTSUPP;
1652 		goto out;
1653 	}
1654 
1655 	if (sock->state != SS_UNCONNECTED) {
1656 		err = -EINVAL;
1657 		goto out;
1658 	}
1659 
1660 	vsk = vsock_sk(sk);
1661 
1662 	if (!vsock_addr_bound(&vsk->local_addr)) {
1663 		err = -EINVAL;
1664 		goto out;
1665 	}
1666 
1667 	sk->sk_max_ack_backlog = backlog;
1668 	sk->sk_state = TCP_LISTEN;
1669 
1670 	err = 0;
1671 
1672 out:
1673 	release_sock(sk);
1674 	return err;
1675 }
1676 
1677 static void vsock_update_buffer_size(struct vsock_sock *vsk,
1678 				     const struct vsock_transport *transport,
1679 				     u64 val)
1680 {
1681 	if (val > vsk->buffer_max_size)
1682 		val = vsk->buffer_max_size;
1683 
1684 	if (val < vsk->buffer_min_size)
1685 		val = vsk->buffer_min_size;
1686 
1687 	if (val != vsk->buffer_size &&
1688 	    transport && transport->notify_buffer_size)
1689 		transport->notify_buffer_size(vsk, &val);
1690 
1691 	vsk->buffer_size = val;
1692 }
1693 
1694 static int vsock_connectible_setsockopt(struct socket *sock,
1695 					int level,
1696 					int optname,
1697 					sockptr_t optval,
1698 					unsigned int optlen)
1699 {
1700 	int err;
1701 	struct sock *sk;
1702 	struct vsock_sock *vsk;
1703 	const struct vsock_transport *transport;
1704 	u64 val;
1705 
1706 	if (level != AF_VSOCK && level != SOL_SOCKET)
1707 		return -ENOPROTOOPT;
1708 
1709 #define COPY_IN(_v)                                       \
1710 	do {						  \
1711 		if (optlen < sizeof(_v)) {		  \
1712 			err = -EINVAL;			  \
1713 			goto exit;			  \
1714 		}					  \
1715 		if (copy_from_sockptr(&_v, optval, sizeof(_v)) != 0) {	\
1716 			err = -EFAULT;					\
1717 			goto exit;					\
1718 		}							\
1719 	} while (0)
1720 
1721 	err = 0;
1722 	sk = sock->sk;
1723 	vsk = vsock_sk(sk);
1724 
1725 	lock_sock(sk);
1726 
1727 	transport = vsk->transport;
1728 
1729 	if (level == SOL_SOCKET) {
1730 		int zerocopy;
1731 
1732 		if (optname != SO_ZEROCOPY) {
1733 			release_sock(sk);
1734 			return sock_setsockopt(sock, level, optname, optval, optlen);
1735 		}
1736 
1737 		/* Use 'int' type here, because variable to
1738 		 * set this option usually has this type.
1739 		 */
1740 		COPY_IN(zerocopy);
1741 
1742 		if (zerocopy < 0 || zerocopy > 1) {
1743 			err = -EINVAL;
1744 			goto exit;
1745 		}
1746 
1747 		if (transport && !vsock_msgzerocopy_allow(transport)) {
1748 			err = -EOPNOTSUPP;
1749 			goto exit;
1750 		}
1751 
1752 		sock_valbool_flag(sk, SOCK_ZEROCOPY, zerocopy);
1753 		goto exit;
1754 	}
1755 
1756 	switch (optname) {
1757 	case SO_VM_SOCKETS_BUFFER_SIZE:
1758 		COPY_IN(val);
1759 		vsock_update_buffer_size(vsk, transport, val);
1760 		break;
1761 
1762 	case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1763 		COPY_IN(val);
1764 		vsk->buffer_max_size = val;
1765 		vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
1766 		break;
1767 
1768 	case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1769 		COPY_IN(val);
1770 		vsk->buffer_min_size = val;
1771 		vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
1772 		break;
1773 
1774 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
1775 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD: {
1776 		struct __kernel_sock_timeval tv;
1777 
1778 		err = sock_copy_user_timeval(&tv, optval, optlen,
1779 					     optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
1780 		if (err)
1781 			break;
1782 		if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC &&
1783 		    tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) {
1784 			vsk->connect_timeout = tv.tv_sec * HZ +
1785 				DIV_ROUND_UP((unsigned long)tv.tv_usec, (USEC_PER_SEC / HZ));
1786 			if (vsk->connect_timeout == 0)
1787 				vsk->connect_timeout =
1788 				    VSOCK_DEFAULT_CONNECT_TIMEOUT;
1789 
1790 		} else {
1791 			err = -ERANGE;
1792 		}
1793 		break;
1794 	}
1795 
1796 	default:
1797 		err = -ENOPROTOOPT;
1798 		break;
1799 	}
1800 
1801 #undef COPY_IN
1802 
1803 exit:
1804 	release_sock(sk);
1805 	return err;
1806 }
1807 
1808 static int vsock_connectible_getsockopt(struct socket *sock,
1809 					int level, int optname,
1810 					char __user *optval,
1811 					int __user *optlen)
1812 {
1813 	struct sock *sk = sock->sk;
1814 	struct vsock_sock *vsk = vsock_sk(sk);
1815 
1816 	union {
1817 		u64 val64;
1818 		struct old_timeval32 tm32;
1819 		struct __kernel_old_timeval tm;
1820 		struct  __kernel_sock_timeval stm;
1821 	} v;
1822 
1823 	int lv = sizeof(v.val64);
1824 	int len;
1825 
1826 	if (level != AF_VSOCK)
1827 		return -ENOPROTOOPT;
1828 
1829 	if (get_user(len, optlen))
1830 		return -EFAULT;
1831 
1832 	memset(&v, 0, sizeof(v));
1833 
1834 	switch (optname) {
1835 	case SO_VM_SOCKETS_BUFFER_SIZE:
1836 		v.val64 = vsk->buffer_size;
1837 		break;
1838 
1839 	case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1840 		v.val64 = vsk->buffer_max_size;
1841 		break;
1842 
1843 	case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1844 		v.val64 = vsk->buffer_min_size;
1845 		break;
1846 
1847 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
1848 	case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD:
1849 		lv = sock_get_timeout(vsk->connect_timeout, &v,
1850 				      optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
1851 		break;
1852 
1853 	default:
1854 		return -ENOPROTOOPT;
1855 	}
1856 
1857 	if (len < lv)
1858 		return -EINVAL;
1859 	if (len > lv)
1860 		len = lv;
1861 	if (copy_to_user(optval, &v, len))
1862 		return -EFAULT;
1863 
1864 	if (put_user(len, optlen))
1865 		return -EFAULT;
1866 
1867 	return 0;
1868 }
1869 
1870 static int vsock_connectible_sendmsg(struct socket *sock, struct msghdr *msg,
1871 				     size_t len)
1872 {
1873 	struct sock *sk;
1874 	struct vsock_sock *vsk;
1875 	const struct vsock_transport *transport;
1876 	ssize_t total_written;
1877 	long timeout;
1878 	int err;
1879 	struct vsock_transport_send_notify_data send_data;
1880 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1881 
1882 	sk = sock->sk;
1883 	vsk = vsock_sk(sk);
1884 	total_written = 0;
1885 	err = 0;
1886 
1887 	if (msg->msg_flags & MSG_OOB)
1888 		return -EOPNOTSUPP;
1889 
1890 	lock_sock(sk);
1891 
1892 	transport = vsk->transport;
1893 
1894 	/* Callers should not provide a destination with connection oriented
1895 	 * sockets.
1896 	 */
1897 	if (msg->msg_namelen) {
1898 		err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
1899 		goto out;
1900 	}
1901 
1902 	/* Send data only if both sides are not shutdown in the direction. */
1903 	if (sk->sk_shutdown & SEND_SHUTDOWN ||
1904 	    vsk->peer_shutdown & RCV_SHUTDOWN) {
1905 		err = -EPIPE;
1906 		goto out;
1907 	}
1908 
1909 	if (!transport || sk->sk_state != TCP_ESTABLISHED ||
1910 	    !vsock_addr_bound(&vsk->local_addr)) {
1911 		err = -ENOTCONN;
1912 		goto out;
1913 	}
1914 
1915 	if (!vsock_addr_bound(&vsk->remote_addr)) {
1916 		err = -EDESTADDRREQ;
1917 		goto out;
1918 	}
1919 
1920 	if (msg->msg_flags & MSG_ZEROCOPY &&
1921 	    !vsock_msgzerocopy_allow(transport)) {
1922 		err = -EOPNOTSUPP;
1923 		goto out;
1924 	}
1925 
1926 	/* Wait for room in the produce queue to enqueue our user's data. */
1927 	timeout = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1928 
1929 	err = transport->notify_send_init(vsk, &send_data);
1930 	if (err < 0)
1931 		goto out;
1932 
1933 	while (total_written < len) {
1934 		ssize_t written;
1935 
1936 		add_wait_queue(sk_sleep(sk), &wait);
1937 		while (vsock_stream_has_space(vsk) == 0 &&
1938 		       sk->sk_err == 0 &&
1939 		       !(sk->sk_shutdown & SEND_SHUTDOWN) &&
1940 		       !(vsk->peer_shutdown & RCV_SHUTDOWN)) {
1941 
1942 			/* Don't wait for non-blocking sockets. */
1943 			if (timeout == 0) {
1944 				err = -EAGAIN;
1945 				remove_wait_queue(sk_sleep(sk), &wait);
1946 				goto out_err;
1947 			}
1948 
1949 			err = transport->notify_send_pre_block(vsk, &send_data);
1950 			if (err < 0) {
1951 				remove_wait_queue(sk_sleep(sk), &wait);
1952 				goto out_err;
1953 			}
1954 
1955 			release_sock(sk);
1956 			timeout = wait_woken(&wait, TASK_INTERRUPTIBLE, timeout);
1957 			lock_sock(sk);
1958 			if (signal_pending(current)) {
1959 				err = sock_intr_errno(timeout);
1960 				remove_wait_queue(sk_sleep(sk), &wait);
1961 				goto out_err;
1962 			} else if (timeout == 0) {
1963 				err = -EAGAIN;
1964 				remove_wait_queue(sk_sleep(sk), &wait);
1965 				goto out_err;
1966 			}
1967 		}
1968 		remove_wait_queue(sk_sleep(sk), &wait);
1969 
1970 		/* These checks occur both as part of and after the loop
1971 		 * conditional since we need to check before and after
1972 		 * sleeping.
1973 		 */
1974 		if (sk->sk_err) {
1975 			err = -sk->sk_err;
1976 			goto out_err;
1977 		} else if ((sk->sk_shutdown & SEND_SHUTDOWN) ||
1978 			   (vsk->peer_shutdown & RCV_SHUTDOWN)) {
1979 			err = -EPIPE;
1980 			goto out_err;
1981 		}
1982 
1983 		err = transport->notify_send_pre_enqueue(vsk, &send_data);
1984 		if (err < 0)
1985 			goto out_err;
1986 
1987 		/* Note that enqueue will only write as many bytes as are free
1988 		 * in the produce queue, so we don't need to ensure len is
1989 		 * smaller than the queue size.  It is the caller's
1990 		 * responsibility to check how many bytes we were able to send.
1991 		 */
1992 
1993 		if (sk->sk_type == SOCK_SEQPACKET) {
1994 			written = transport->seqpacket_enqueue(vsk,
1995 						msg, len - total_written);
1996 		} else {
1997 			written = transport->stream_enqueue(vsk,
1998 					msg, len - total_written);
1999 		}
2000 
2001 		if (written < 0) {
2002 			err = written;
2003 			goto out_err;
2004 		}
2005 
2006 		total_written += written;
2007 
2008 		err = transport->notify_send_post_enqueue(
2009 				vsk, written, &send_data);
2010 		if (err < 0)
2011 			goto out_err;
2012 
2013 	}
2014 
2015 out_err:
2016 	if (total_written > 0) {
2017 		/* Return number of written bytes only if:
2018 		 * 1) SOCK_STREAM socket.
2019 		 * 2) SOCK_SEQPACKET socket when whole buffer is sent.
2020 		 */
2021 		if (sk->sk_type == SOCK_STREAM || total_written == len)
2022 			err = total_written;
2023 	}
2024 out:
2025 	if (sk->sk_type == SOCK_STREAM)
2026 		err = sk_stream_error(sk, msg->msg_flags, err);
2027 
2028 	release_sock(sk);
2029 	return err;
2030 }
2031 
2032 static int vsock_connectible_wait_data(struct sock *sk,
2033 				       struct wait_queue_entry *wait,
2034 				       long timeout,
2035 				       struct vsock_transport_recv_notify_data *recv_data,
2036 				       size_t target)
2037 {
2038 	const struct vsock_transport *transport;
2039 	struct vsock_sock *vsk;
2040 	s64 data;
2041 	int err;
2042 
2043 	vsk = vsock_sk(sk);
2044 	err = 0;
2045 	transport = vsk->transport;
2046 
2047 	while (1) {
2048 		prepare_to_wait(sk_sleep(sk), wait, TASK_INTERRUPTIBLE);
2049 		data = vsock_connectible_has_data(vsk);
2050 		if (data != 0)
2051 			break;
2052 
2053 		if (sk->sk_err != 0 ||
2054 		    (sk->sk_shutdown & RCV_SHUTDOWN) ||
2055 		    (vsk->peer_shutdown & SEND_SHUTDOWN)) {
2056 			break;
2057 		}
2058 
2059 		/* Don't wait for non-blocking sockets. */
2060 		if (timeout == 0) {
2061 			err = -EAGAIN;
2062 			break;
2063 		}
2064 
2065 		if (recv_data) {
2066 			err = transport->notify_recv_pre_block(vsk, target, recv_data);
2067 			if (err < 0)
2068 				break;
2069 		}
2070 
2071 		release_sock(sk);
2072 		timeout = schedule_timeout(timeout);
2073 		lock_sock(sk);
2074 
2075 		if (signal_pending(current)) {
2076 			err = sock_intr_errno(timeout);
2077 			break;
2078 		} else if (timeout == 0) {
2079 			err = -EAGAIN;
2080 			break;
2081 		}
2082 	}
2083 
2084 	finish_wait(sk_sleep(sk), wait);
2085 
2086 	if (err)
2087 		return err;
2088 
2089 	/* Internal transport error when checking for available
2090 	 * data. XXX This should be changed to a connection
2091 	 * reset in a later change.
2092 	 */
2093 	if (data < 0)
2094 		return -ENOMEM;
2095 
2096 	return data;
2097 }
2098 
2099 static int __vsock_stream_recvmsg(struct sock *sk, struct msghdr *msg,
2100 				  size_t len, int flags)
2101 {
2102 	struct vsock_transport_recv_notify_data recv_data;
2103 	const struct vsock_transport *transport;
2104 	struct vsock_sock *vsk;
2105 	ssize_t copied;
2106 	size_t target;
2107 	long timeout;
2108 	int err;
2109 
2110 	DEFINE_WAIT(wait);
2111 
2112 	vsk = vsock_sk(sk);
2113 	transport = vsk->transport;
2114 
2115 	/* We must not copy less than target bytes into the user's buffer
2116 	 * before returning successfully, so we wait for the consume queue to
2117 	 * have that much data to consume before dequeueing.  Note that this
2118 	 * makes it impossible to handle cases where target is greater than the
2119 	 * queue size.
2120 	 */
2121 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2122 	if (target >= transport->stream_rcvhiwat(vsk)) {
2123 		err = -ENOMEM;
2124 		goto out;
2125 	}
2126 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2127 	copied = 0;
2128 
2129 	err = transport->notify_recv_init(vsk, target, &recv_data);
2130 	if (err < 0)
2131 		goto out;
2132 
2133 
2134 	while (1) {
2135 		ssize_t read;
2136 
2137 		err = vsock_connectible_wait_data(sk, &wait, timeout,
2138 						  &recv_data, target);
2139 		if (err <= 0)
2140 			break;
2141 
2142 		err = transport->notify_recv_pre_dequeue(vsk, target,
2143 							 &recv_data);
2144 		if (err < 0)
2145 			break;
2146 
2147 		read = transport->stream_dequeue(vsk, msg, len - copied, flags);
2148 		if (read < 0) {
2149 			err = read;
2150 			break;
2151 		}
2152 
2153 		copied += read;
2154 
2155 		err = transport->notify_recv_post_dequeue(vsk, target, read,
2156 						!(flags & MSG_PEEK), &recv_data);
2157 		if (err < 0)
2158 			goto out;
2159 
2160 		if (read >= target || flags & MSG_PEEK)
2161 			break;
2162 
2163 		target -= read;
2164 	}
2165 
2166 	if (sk->sk_err)
2167 		err = -sk->sk_err;
2168 	else if (sk->sk_shutdown & RCV_SHUTDOWN)
2169 		err = 0;
2170 
2171 	if (copied > 0)
2172 		err = copied;
2173 
2174 out:
2175 	return err;
2176 }
2177 
2178 static int __vsock_seqpacket_recvmsg(struct sock *sk, struct msghdr *msg,
2179 				     size_t len, int flags)
2180 {
2181 	const struct vsock_transport *transport;
2182 	struct vsock_sock *vsk;
2183 	ssize_t msg_len;
2184 	long timeout;
2185 	int err = 0;
2186 	DEFINE_WAIT(wait);
2187 
2188 	vsk = vsock_sk(sk);
2189 	transport = vsk->transport;
2190 
2191 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2192 
2193 	err = vsock_connectible_wait_data(sk, &wait, timeout, NULL, 0);
2194 	if (err <= 0)
2195 		goto out;
2196 
2197 	msg_len = transport->seqpacket_dequeue(vsk, msg, flags);
2198 
2199 	if (msg_len < 0) {
2200 		err = msg_len;
2201 		goto out;
2202 	}
2203 
2204 	if (sk->sk_err) {
2205 		err = -sk->sk_err;
2206 	} else if (sk->sk_shutdown & RCV_SHUTDOWN) {
2207 		err = 0;
2208 	} else {
2209 		/* User sets MSG_TRUNC, so return real length of
2210 		 * packet.
2211 		 */
2212 		if (flags & MSG_TRUNC)
2213 			err = msg_len;
2214 		else
2215 			err = len - msg_data_left(msg);
2216 
2217 		/* Always set MSG_TRUNC if real length of packet is
2218 		 * bigger than user's buffer.
2219 		 */
2220 		if (msg_len > len)
2221 			msg->msg_flags |= MSG_TRUNC;
2222 	}
2223 
2224 out:
2225 	return err;
2226 }
2227 
2228 int
2229 vsock_connectible_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
2230 			  int flags)
2231 {
2232 	struct sock *sk;
2233 	struct vsock_sock *vsk;
2234 	const struct vsock_transport *transport;
2235 #ifdef CONFIG_BPF_SYSCALL
2236 	const struct proto *prot;
2237 #endif
2238 	int err;
2239 
2240 	sk = sock->sk;
2241 
2242 	if (unlikely(flags & MSG_ERRQUEUE))
2243 		return sock_recv_errqueue(sk, msg, len, SOL_VSOCK, VSOCK_RECVERR);
2244 
2245 	vsk = vsock_sk(sk);
2246 	err = 0;
2247 
2248 	lock_sock(sk);
2249 
2250 	transport = vsk->transport;
2251 
2252 	if (!transport || sk->sk_state != TCP_ESTABLISHED) {
2253 		/* Recvmsg is supposed to return 0 if a peer performs an
2254 		 * orderly shutdown. Differentiate between that case and when a
2255 		 * peer has not connected or a local shutdown occurred with the
2256 		 * SOCK_DONE flag.
2257 		 */
2258 		if (sock_flag(sk, SOCK_DONE))
2259 			err = 0;
2260 		else
2261 			err = -ENOTCONN;
2262 
2263 		goto out;
2264 	}
2265 
2266 	if (flags & MSG_OOB) {
2267 		err = -EOPNOTSUPP;
2268 		goto out;
2269 	}
2270 
2271 	/* We don't check peer_shutdown flag here since peer may actually shut
2272 	 * down, but there can be data in the queue that a local socket can
2273 	 * receive.
2274 	 */
2275 	if (sk->sk_shutdown & RCV_SHUTDOWN) {
2276 		err = 0;
2277 		goto out;
2278 	}
2279 
2280 	/* It is valid on Linux to pass in a zero-length receive buffer.  This
2281 	 * is not an error.  We may as well bail out now.
2282 	 */
2283 	if (!len) {
2284 		err = 0;
2285 		goto out;
2286 	}
2287 
2288 #ifdef CONFIG_BPF_SYSCALL
2289 	prot = READ_ONCE(sk->sk_prot);
2290 	if (prot != &vsock_proto) {
2291 		release_sock(sk);
2292 		return prot->recvmsg(sk, msg, len, flags, NULL);
2293 	}
2294 #endif
2295 
2296 	if (sk->sk_type == SOCK_STREAM)
2297 		err = __vsock_stream_recvmsg(sk, msg, len, flags);
2298 	else
2299 		err = __vsock_seqpacket_recvmsg(sk, msg, len, flags);
2300 
2301 out:
2302 	release_sock(sk);
2303 	return err;
2304 }
2305 EXPORT_SYMBOL_GPL(vsock_connectible_recvmsg);
2306 
2307 static int vsock_set_rcvlowat(struct sock *sk, int val)
2308 {
2309 	const struct vsock_transport *transport;
2310 	struct vsock_sock *vsk;
2311 
2312 	vsk = vsock_sk(sk);
2313 
2314 	if (val > vsk->buffer_size)
2315 		return -EINVAL;
2316 
2317 	transport = vsk->transport;
2318 
2319 	if (transport && transport->notify_set_rcvlowat) {
2320 		int err;
2321 
2322 		err = transport->notify_set_rcvlowat(vsk, val);
2323 		if (err)
2324 			return err;
2325 	}
2326 
2327 	WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
2328 	return 0;
2329 }
2330 
2331 static const struct proto_ops vsock_stream_ops = {
2332 	.family = PF_VSOCK,
2333 	.owner = THIS_MODULE,
2334 	.release = vsock_release,
2335 	.bind = vsock_bind,
2336 	.connect = vsock_connect,
2337 	.socketpair = sock_no_socketpair,
2338 	.accept = vsock_accept,
2339 	.getname = vsock_getname,
2340 	.poll = vsock_poll,
2341 	.ioctl = vsock_ioctl,
2342 	.listen = vsock_listen,
2343 	.shutdown = vsock_shutdown,
2344 	.setsockopt = vsock_connectible_setsockopt,
2345 	.getsockopt = vsock_connectible_getsockopt,
2346 	.sendmsg = vsock_connectible_sendmsg,
2347 	.recvmsg = vsock_connectible_recvmsg,
2348 	.mmap = sock_no_mmap,
2349 	.set_rcvlowat = vsock_set_rcvlowat,
2350 	.read_skb = vsock_read_skb,
2351 };
2352 
2353 static const struct proto_ops vsock_seqpacket_ops = {
2354 	.family = PF_VSOCK,
2355 	.owner = THIS_MODULE,
2356 	.release = vsock_release,
2357 	.bind = vsock_bind,
2358 	.connect = vsock_connect,
2359 	.socketpair = sock_no_socketpair,
2360 	.accept = vsock_accept,
2361 	.getname = vsock_getname,
2362 	.poll = vsock_poll,
2363 	.ioctl = vsock_ioctl,
2364 	.listen = vsock_listen,
2365 	.shutdown = vsock_shutdown,
2366 	.setsockopt = vsock_connectible_setsockopt,
2367 	.getsockopt = vsock_connectible_getsockopt,
2368 	.sendmsg = vsock_connectible_sendmsg,
2369 	.recvmsg = vsock_connectible_recvmsg,
2370 	.mmap = sock_no_mmap,
2371 	.read_skb = vsock_read_skb,
2372 };
2373 
2374 static int vsock_create(struct net *net, struct socket *sock,
2375 			int protocol, int kern)
2376 {
2377 	struct vsock_sock *vsk;
2378 	struct sock *sk;
2379 	int ret;
2380 
2381 	if (!sock)
2382 		return -EINVAL;
2383 
2384 	if (protocol && protocol != PF_VSOCK)
2385 		return -EPROTONOSUPPORT;
2386 
2387 	switch (sock->type) {
2388 	case SOCK_DGRAM:
2389 		sock->ops = &vsock_dgram_ops;
2390 		break;
2391 	case SOCK_STREAM:
2392 		sock->ops = &vsock_stream_ops;
2393 		break;
2394 	case SOCK_SEQPACKET:
2395 		sock->ops = &vsock_seqpacket_ops;
2396 		break;
2397 	default:
2398 		return -ESOCKTNOSUPPORT;
2399 	}
2400 
2401 	sock->state = SS_UNCONNECTED;
2402 
2403 	sk = __vsock_create(net, sock, NULL, GFP_KERNEL, 0, kern);
2404 	if (!sk)
2405 		return -ENOMEM;
2406 
2407 	vsk = vsock_sk(sk);
2408 
2409 	if (sock->type == SOCK_DGRAM) {
2410 		ret = vsock_assign_transport(vsk, NULL);
2411 		if (ret < 0) {
2412 			sock_put(sk);
2413 			return ret;
2414 		}
2415 	}
2416 
2417 	/* SOCK_DGRAM doesn't have 'setsockopt' callback set in its
2418 	 * proto_ops, so there is no handler for custom logic.
2419 	 */
2420 	if (sock_type_connectible(sock->type))
2421 		set_bit(SOCK_CUSTOM_SOCKOPT, &sk->sk_socket->flags);
2422 
2423 	vsock_insert_unbound(vsk);
2424 
2425 	return 0;
2426 }
2427 
2428 static const struct net_proto_family vsock_family_ops = {
2429 	.family = AF_VSOCK,
2430 	.create = vsock_create,
2431 	.owner = THIS_MODULE,
2432 };
2433 
2434 static long vsock_dev_do_ioctl(struct file *filp,
2435 			       unsigned int cmd, void __user *ptr)
2436 {
2437 	u32 __user *p = ptr;
2438 	u32 cid = VMADDR_CID_ANY;
2439 	int retval = 0;
2440 
2441 	switch (cmd) {
2442 	case IOCTL_VM_SOCKETS_GET_LOCAL_CID:
2443 		/* To be compatible with the VMCI behavior, we prioritize the
2444 		 * guest CID instead of well-know host CID (VMADDR_CID_HOST).
2445 		 */
2446 		if (transport_g2h)
2447 			cid = transport_g2h->get_local_cid();
2448 		else if (transport_h2g)
2449 			cid = transport_h2g->get_local_cid();
2450 
2451 		if (put_user(cid, p) != 0)
2452 			retval = -EFAULT;
2453 		break;
2454 
2455 	default:
2456 		retval = -ENOIOCTLCMD;
2457 	}
2458 
2459 	return retval;
2460 }
2461 
2462 static long vsock_dev_ioctl(struct file *filp,
2463 			    unsigned int cmd, unsigned long arg)
2464 {
2465 	return vsock_dev_do_ioctl(filp, cmd, (void __user *)arg);
2466 }
2467 
2468 #ifdef CONFIG_COMPAT
2469 static long vsock_dev_compat_ioctl(struct file *filp,
2470 				   unsigned int cmd, unsigned long arg)
2471 {
2472 	return vsock_dev_do_ioctl(filp, cmd, compat_ptr(arg));
2473 }
2474 #endif
2475 
2476 static const struct file_operations vsock_device_ops = {
2477 	.owner		= THIS_MODULE,
2478 	.unlocked_ioctl	= vsock_dev_ioctl,
2479 #ifdef CONFIG_COMPAT
2480 	.compat_ioctl	= vsock_dev_compat_ioctl,
2481 #endif
2482 	.open		= nonseekable_open,
2483 };
2484 
2485 static struct miscdevice vsock_device = {
2486 	.name		= "vsock",
2487 	.fops		= &vsock_device_ops,
2488 };
2489 
2490 static int __init vsock_init(void)
2491 {
2492 	int err = 0;
2493 
2494 	vsock_init_tables();
2495 
2496 	vsock_proto.owner = THIS_MODULE;
2497 	vsock_device.minor = MISC_DYNAMIC_MINOR;
2498 	err = misc_register(&vsock_device);
2499 	if (err) {
2500 		pr_err("Failed to register misc device\n");
2501 		goto err_reset_transport;
2502 	}
2503 
2504 	err = proto_register(&vsock_proto, 1);	/* we want our slab */
2505 	if (err) {
2506 		pr_err("Cannot register vsock protocol\n");
2507 		goto err_deregister_misc;
2508 	}
2509 
2510 	err = sock_register(&vsock_family_ops);
2511 	if (err) {
2512 		pr_err("could not register af_vsock (%d) address family: %d\n",
2513 		       AF_VSOCK, err);
2514 		goto err_unregister_proto;
2515 	}
2516 
2517 	vsock_bpf_build_proto();
2518 
2519 	return 0;
2520 
2521 err_unregister_proto:
2522 	proto_unregister(&vsock_proto);
2523 err_deregister_misc:
2524 	misc_deregister(&vsock_device);
2525 err_reset_transport:
2526 	return err;
2527 }
2528 
2529 static void __exit vsock_exit(void)
2530 {
2531 	misc_deregister(&vsock_device);
2532 	sock_unregister(AF_VSOCK);
2533 	proto_unregister(&vsock_proto);
2534 }
2535 
2536 const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)
2537 {
2538 	return vsk->transport;
2539 }
2540 EXPORT_SYMBOL_GPL(vsock_core_get_transport);
2541 
2542 int vsock_core_register(const struct vsock_transport *t, int features)
2543 {
2544 	const struct vsock_transport *t_h2g, *t_g2h, *t_dgram, *t_local;
2545 	int err = mutex_lock_interruptible(&vsock_register_mutex);
2546 
2547 	if (err)
2548 		return err;
2549 
2550 	t_h2g = transport_h2g;
2551 	t_g2h = transport_g2h;
2552 	t_dgram = transport_dgram;
2553 	t_local = transport_local;
2554 
2555 	if (features & VSOCK_TRANSPORT_F_H2G) {
2556 		if (t_h2g) {
2557 			err = -EBUSY;
2558 			goto err_busy;
2559 		}
2560 		t_h2g = t;
2561 	}
2562 
2563 	if (features & VSOCK_TRANSPORT_F_G2H) {
2564 		if (t_g2h) {
2565 			err = -EBUSY;
2566 			goto err_busy;
2567 		}
2568 		t_g2h = t;
2569 	}
2570 
2571 	if (features & VSOCK_TRANSPORT_F_DGRAM) {
2572 		if (t_dgram) {
2573 			err = -EBUSY;
2574 			goto err_busy;
2575 		}
2576 		t_dgram = t;
2577 	}
2578 
2579 	if (features & VSOCK_TRANSPORT_F_LOCAL) {
2580 		if (t_local) {
2581 			err = -EBUSY;
2582 			goto err_busy;
2583 		}
2584 		t_local = t;
2585 	}
2586 
2587 	transport_h2g = t_h2g;
2588 	transport_g2h = t_g2h;
2589 	transport_dgram = t_dgram;
2590 	transport_local = t_local;
2591 
2592 err_busy:
2593 	mutex_unlock(&vsock_register_mutex);
2594 	return err;
2595 }
2596 EXPORT_SYMBOL_GPL(vsock_core_register);
2597 
2598 void vsock_core_unregister(const struct vsock_transport *t)
2599 {
2600 	mutex_lock(&vsock_register_mutex);
2601 
2602 	if (transport_h2g == t)
2603 		transport_h2g = NULL;
2604 
2605 	if (transport_g2h == t)
2606 		transport_g2h = NULL;
2607 
2608 	if (transport_dgram == t)
2609 		transport_dgram = NULL;
2610 
2611 	if (transport_local == t)
2612 		transport_local = NULL;
2613 
2614 	mutex_unlock(&vsock_register_mutex);
2615 }
2616 EXPORT_SYMBOL_GPL(vsock_core_unregister);
2617 
2618 module_init(vsock_init);
2619 module_exit(vsock_exit);
2620 
2621 MODULE_AUTHOR("VMware, Inc.");
2622 MODULE_DESCRIPTION("VMware Virtual Socket Family");
2623 MODULE_VERSION("1.0.2.0-k");
2624 MODULE_LICENSE("GPL v2");
2625