drm/tests: hdmi: Fix memory leaks in drm_display_mode_from_cea_vic()
[drm/drm-misc.git] / net / vmw_vsock / af_vsock.c
blob35681adedd9aaec3565495158f5342b8aa76c9bc
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * VMware vSockets Driver
5 * Copyright (C) 2007-2013 VMware, Inc. All rights reserved.
6 */
8 /* Implementation notes:
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.
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.
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).
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.
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.
56 * - Lock ordering for pending or accept queue sockets is:
58 * lock_sock(listener);
59 * lock_sock_nested(pending, SINGLE_DEPTH_NESTING);
61 * Using explicit nested locking keeps lockdep happy since normally only one
62 * lock of a given class may be taken at a time.
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.
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.
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):
81 * TCP_CLOSE - unconnected
82 * TCP_SYN_SENT - connecting
83 * TCP_ESTABLISHED - connected
84 * TCP_CLOSING - disconnecting
85 * TCP_LISTEN - listening
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>
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);
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
131 /* The default peer timeout indicates how long we will wait for a peer response
132 * to a control message.
134 #define VSOCK_DEFAULT_CONNECT_TIMEOUT (2 * HZ)
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
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);
150 /**** UTILS ****/
152 /* Each bound VSocket is stored in the bind hash table and each connected
153 * VSocket is stored in the connected hash table.
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).
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.
166 #define MAX_PORT_RETRIES 24
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])
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)
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);
187 /* Autobind this socket to the local address if necessary. */
188 static int vsock_auto_bind(struct vsock_sock *vsk)
190 struct sock *sk = sk_vsock(vsk);
191 struct sockaddr_vm local_addr;
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);
199 static void vsock_init_tables(void)
201 int i;
203 for (i = 0; i < ARRAY_SIZE(vsock_bind_table); i++)
204 INIT_LIST_HEAD(&vsock_bind_table[i]);
206 for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++)
207 INIT_LIST_HEAD(&vsock_connected_table[i]);
210 static void __vsock_insert_bound(struct list_head *list,
211 struct vsock_sock *vsk)
213 sock_hold(&vsk->sk);
214 list_add(&vsk->bound_table, list);
217 static void __vsock_insert_connected(struct list_head *list,
218 struct vsock_sock *vsk)
220 sock_hold(&vsk->sk);
221 list_add(&vsk->connected_table, list);
224 static void __vsock_remove_bound(struct vsock_sock *vsk)
226 list_del_init(&vsk->bound_table);
227 sock_put(&vsk->sk);
230 static void __vsock_remove_connected(struct vsock_sock *vsk)
232 list_del_init(&vsk->connected_table);
233 sock_put(&vsk->sk);
236 static struct sock *__vsock_find_bound_socket(struct sockaddr_vm *addr)
238 struct vsock_sock *vsk;
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);
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);
250 return NULL;
253 static struct sock *__vsock_find_connected_socket(struct sockaddr_vm *src,
254 struct sockaddr_vm *dst)
256 struct vsock_sock *vsk;
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);
266 return NULL;
269 static void vsock_insert_unbound(struct vsock_sock *vsk)
271 spin_lock_bh(&vsock_table_lock);
272 __vsock_insert_bound(vsock_unbound_sockets, vsk);
273 spin_unlock_bh(&vsock_table_lock);
276 void vsock_insert_connected(struct vsock_sock *vsk)
278 struct list_head *list = vsock_connected_sockets(
279 &vsk->remote_addr, &vsk->local_addr);
281 spin_lock_bh(&vsock_table_lock);
282 __vsock_insert_connected(list, vsk);
283 spin_unlock_bh(&vsock_table_lock);
285 EXPORT_SYMBOL_GPL(vsock_insert_connected);
287 void vsock_remove_bound(struct vsock_sock *vsk)
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);
294 EXPORT_SYMBOL_GPL(vsock_remove_bound);
296 void vsock_remove_connected(struct vsock_sock *vsk)
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);
303 EXPORT_SYMBOL_GPL(vsock_remove_connected);
305 struct sock *vsock_find_bound_socket(struct sockaddr_vm *addr)
307 struct sock *sk;
309 spin_lock_bh(&vsock_table_lock);
310 sk = __vsock_find_bound_socket(addr);
311 if (sk)
312 sock_hold(sk);
314 spin_unlock_bh(&vsock_table_lock);
316 return sk;
318 EXPORT_SYMBOL_GPL(vsock_find_bound_socket);
320 struct sock *vsock_find_connected_socket(struct sockaddr_vm *src,
321 struct sockaddr_vm *dst)
323 struct sock *sk;
325 spin_lock_bh(&vsock_table_lock);
326 sk = __vsock_find_connected_socket(src, dst);
327 if (sk)
328 sock_hold(sk);
330 spin_unlock_bh(&vsock_table_lock);
332 return sk;
334 EXPORT_SYMBOL_GPL(vsock_find_connected_socket);
336 void vsock_remove_sock(struct vsock_sock *vsk)
338 vsock_remove_bound(vsk);
339 vsock_remove_connected(vsk);
341 EXPORT_SYMBOL_GPL(vsock_remove_sock);
343 void vsock_for_each_connected_socket(struct vsock_transport *transport,
344 void (*fn)(struct sock *sk))
346 int i;
348 spin_lock_bh(&vsock_table_lock);
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;
357 fn(sk_vsock(vsk));
361 spin_unlock_bh(&vsock_table_lock);
363 EXPORT_SYMBOL_GPL(vsock_for_each_connected_socket);
365 void vsock_add_pending(struct sock *listener, struct sock *pending)
367 struct vsock_sock *vlistener;
368 struct vsock_sock *vpending;
370 vlistener = vsock_sk(listener);
371 vpending = vsock_sk(pending);
373 sock_hold(pending);
374 sock_hold(listener);
375 list_add_tail(&vpending->pending_links, &vlistener->pending_links);
377 EXPORT_SYMBOL_GPL(vsock_add_pending);
379 void vsock_remove_pending(struct sock *listener, struct sock *pending)
381 struct vsock_sock *vpending = vsock_sk(pending);
383 list_del_init(&vpending->pending_links);
384 sock_put(listener);
385 sock_put(pending);
387 EXPORT_SYMBOL_GPL(vsock_remove_pending);
389 void vsock_enqueue_accept(struct sock *listener, struct sock *connected)
391 struct vsock_sock *vlistener;
392 struct vsock_sock *vconnected;
394 vlistener = vsock_sk(listener);
395 vconnected = vsock_sk(connected);
397 sock_hold(connected);
398 sock_hold(listener);
399 list_add_tail(&vconnected->accept_queue, &vlistener->accept_queue);
401 EXPORT_SYMBOL_GPL(vsock_enqueue_accept);
403 static bool vsock_use_local_transport(unsigned int remote_cid)
405 if (!transport_local)
406 return false;
408 if (remote_cid == VMADDR_CID_LOCAL)
409 return true;
411 if (transport_g2h) {
412 return remote_cid == transport_g2h->get_local_cid();
413 } else {
414 return remote_cid == VMADDR_CID_HOST;
418 static void vsock_deassign_transport(struct vsock_sock *vsk)
420 if (!vsk->transport)
421 return;
423 vsk->transport->destruct(vsk);
424 module_put(vsk->transport->module);
425 vsk->transport = NULL;
428 /* Assign a transport to a socket and call the .init transport callback.
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;
440 int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)
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;
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.
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.
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;
460 remote_flags = vsk->remote_addr.svm_flags;
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;
480 if (vsk->transport) {
481 if (vsk->transport == new_transport)
482 return 0;
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.
490 vsk->transport->release(vsk);
491 vsock_deassign_transport(vsk);
494 /* We increase the module refcnt to prevent the transport unloading
495 * while there are open sockets assigned to it.
497 if (!new_transport || !try_module_get(new_transport->module))
498 return -ENODEV;
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;
508 ret = new_transport->init(vsk, psk);
509 if (ret) {
510 module_put(new_transport->module);
511 return ret;
514 vsk->transport = new_transport;
516 return 0;
518 EXPORT_SYMBOL_GPL(vsock_assign_transport);
520 bool vsock_find_cid(unsigned int cid)
522 if (transport_g2h && cid == transport_g2h->get_local_cid())
523 return true;
525 if (transport_h2g && cid == VMADDR_CID_HOST)
526 return true;
528 if (transport_local && cid == VMADDR_CID_LOCAL)
529 return true;
531 return false;
533 EXPORT_SYMBOL_GPL(vsock_find_cid);
535 static struct sock *vsock_dequeue_accept(struct sock *listener)
537 struct vsock_sock *vlistener;
538 struct vsock_sock *vconnected;
540 vlistener = vsock_sk(listener);
542 if (list_empty(&vlistener->accept_queue))
543 return NULL;
545 vconnected = list_entry(vlistener->accept_queue.next,
546 struct vsock_sock, accept_queue);
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().
554 return sk_vsock(vconnected);
557 static bool vsock_is_accept_queue_empty(struct sock *sk)
559 struct vsock_sock *vsk = vsock_sk(sk);
560 return list_empty(&vsk->accept_queue);
563 static bool vsock_is_pending(struct sock *sk)
565 struct vsock_sock *vsk = vsock_sk(sk);
566 return !list_empty(&vsk->pending_links);
569 static int vsock_send_shutdown(struct sock *sk, int mode)
571 struct vsock_sock *vsk = vsock_sk(sk);
573 if (!vsk->transport)
574 return -ENODEV;
576 return vsk->transport->shutdown(vsk, mode);
579 static void vsock_pending_work(struct work_struct *work)
581 struct sock *sk;
582 struct sock *listener;
583 struct vsock_sock *vsk;
584 bool cleanup;
586 vsk = container_of(work, struct vsock_sock, pending_work.work);
587 sk = sk_vsock(vsk);
588 listener = vsk->listener;
589 cleanup = true;
591 lock_sock(listener);
592 lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
594 if (vsock_is_pending(sk)) {
595 vsock_remove_pending(listener, sk);
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.
604 cleanup = false;
605 goto out;
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.
612 vsock_remove_connected(vsk);
614 sk->sk_state = TCP_CLOSE;
616 out:
617 release_sock(sk);
618 release_sock(listener);
619 if (cleanup)
620 sock_put(sk);
622 sock_put(sk);
623 sock_put(listener);
626 /**** SOCKET OPERATIONS ****/
628 static int __vsock_bind_connectible(struct vsock_sock *vsk,
629 struct sockaddr_vm *addr)
631 static u32 port;
632 struct sockaddr_vm new_addr;
634 if (!port)
635 port = get_random_u32_above(LAST_RESERVED_PORT);
637 vsock_addr_init(&new_addr, addr->svm_cid, addr->svm_port);
639 if (addr->svm_port == VMADDR_PORT_ANY) {
640 bool found = false;
641 unsigned int i;
643 for (i = 0; i < MAX_PORT_RETRIES; i++) {
644 if (port <= LAST_RESERVED_PORT)
645 port = LAST_RESERVED_PORT + 1;
647 new_addr.svm_port = port++;
649 if (!__vsock_find_bound_socket(&new_addr)) {
650 found = true;
651 break;
655 if (!found)
656 return -EADDRNOTAVAIL;
657 } else {
658 /* If port is in reserved range, ensure caller
659 * has necessary privileges.
661 if (addr->svm_port <= LAST_RESERVED_PORT &&
662 !capable(CAP_NET_BIND_SERVICE)) {
663 return -EACCES;
666 if (__vsock_find_bound_socket(&new_addr))
667 return -EADDRINUSE;
670 vsock_addr_init(&vsk->local_addr, new_addr.svm_cid, new_addr.svm_port);
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.
677 __vsock_remove_bound(vsk);
678 __vsock_insert_bound(vsock_bound_sockets(&vsk->local_addr), vsk);
680 return 0;
683 static int __vsock_bind_dgram(struct vsock_sock *vsk,
684 struct sockaddr_vm *addr)
686 return vsk->transport->dgram_bind(vsk, addr);
689 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr)
691 struct vsock_sock *vsk = vsock_sk(sk);
692 int retval;
694 /* First ensure this socket isn't already bound. */
695 if (vsock_addr_bound(&vsk->local_addr))
696 return -EINVAL;
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.
703 if (addr->svm_cid != VMADDR_CID_ANY && !vsock_find_cid(addr->svm_cid))
704 return -EADDRNOTAVAIL;
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;
714 case SOCK_DGRAM:
715 retval = __vsock_bind_dgram(vsk, addr);
716 break;
718 default:
719 retval = -EINVAL;
720 break;
723 return retval;
726 static void vsock_connect_timeout(struct work_struct *work);
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)
735 struct sock *sk;
736 struct vsock_sock *psk;
737 struct vsock_sock *vsk;
739 sk = sk_alloc(net, AF_VSOCK, priority, &vsock_proto, kern);
740 if (!sk)
741 return NULL;
743 sock_init_data(sock, sk);
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.
749 if (!sock)
750 sk->sk_type = type;
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);
756 sk->sk_destruct = vsock_sk_destruct;
757 sk->sk_backlog_rcv = vsock_queue_rcv_skb;
758 sock_reset_flag(sk, SOCK_DONE);
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);
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;
790 return sk;
793 static bool sock_type_connectible(u16 type)
795 return (type == SOCK_STREAM) || (type == SOCK_SEQPACKET);
798 static void __vsock_release(struct sock *sk, int level)
800 if (sk) {
801 struct sock *pending;
802 struct vsock_sock *vsk;
804 vsk = vsock_sk(sk);
805 pending = NULL; /* Compiler warning. */
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).
812 lock_sock_nested(sk, level);
814 if (vsk->transport)
815 vsk->transport->release(vsk);
816 else if (sock_type_connectible(sk->sk_type))
817 vsock_remove_sock(vsk);
819 sock_orphan(sk);
820 sk->sk_shutdown = SHUTDOWN_MASK;
822 skb_queue_purge(&sk->sk_receive_queue);
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);
830 release_sock(sk);
831 sock_put(sk);
835 static void vsock_sk_destruct(struct sock *sk)
837 struct vsock_sock *vsk = vsock_sk(sk);
839 vsock_deassign_transport(vsk);
841 /* When clearing these addresses, there's no need to set the family and
842 * possibly register the address family with the kernel.
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);
847 put_cred(vsk->owner);
850 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
852 int err;
854 err = sock_queue_rcv_skb(sk, skb);
855 if (err)
856 kfree_skb(skb);
858 return err;
861 struct sock *vsock_create_connected(struct sock *parent)
863 return __vsock_create(sock_net(parent), NULL, parent, GFP_KERNEL,
864 parent->sk_type, 0);
866 EXPORT_SYMBOL_GPL(vsock_create_connected);
868 s64 vsock_stream_has_data(struct vsock_sock *vsk)
870 return vsk->transport->stream_has_data(vsk);
872 EXPORT_SYMBOL_GPL(vsock_stream_has_data);
874 s64 vsock_connectible_has_data(struct vsock_sock *vsk)
876 struct sock *sk = sk_vsock(vsk);
878 if (sk->sk_type == SOCK_SEQPACKET)
879 return vsk->transport->seqpacket_has_data(vsk);
880 else
881 return vsock_stream_has_data(vsk);
883 EXPORT_SYMBOL_GPL(vsock_connectible_has_data);
885 s64 vsock_stream_has_space(struct vsock_sock *vsk)
887 return vsk->transport->stream_has_space(vsk);
889 EXPORT_SYMBOL_GPL(vsock_stream_has_space);
891 void vsock_data_ready(struct sock *sk)
893 struct vsock_sock *vsk = vsock_sk(sk);
895 if (vsock_stream_has_data(vsk) >= sk->sk_rcvlowat ||
896 sock_flag(sk, SOCK_DONE))
897 sk->sk_data_ready(sk);
899 EXPORT_SYMBOL_GPL(vsock_data_ready);
901 static int vsock_release(struct socket *sock)
903 __vsock_release(sock->sk, 0);
904 sock->sk = NULL;
905 sock->state = SS_FREE;
907 return 0;
910 static int
911 vsock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
913 int err;
914 struct sock *sk;
915 struct sockaddr_vm *vm_addr;
917 sk = sock->sk;
919 if (vsock_addr_cast(addr, addr_len, &vm_addr) != 0)
920 return -EINVAL;
922 lock_sock(sk);
923 err = __vsock_bind(sk, vm_addr);
924 release_sock(sk);
926 return err;
929 static int vsock_getname(struct socket *sock,
930 struct sockaddr *addr, int peer)
932 int err;
933 struct sock *sk;
934 struct vsock_sock *vsk;
935 struct sockaddr_vm *vm_addr;
937 sk = sock->sk;
938 vsk = vsock_sk(sk);
939 err = 0;
941 lock_sock(sk);
943 if (peer) {
944 if (sock->state != SS_CONNECTED) {
945 err = -ENOTCONN;
946 goto out;
948 vm_addr = &vsk->remote_addr;
949 } else {
950 vm_addr = &vsk->local_addr;
953 if (!vm_addr) {
954 err = -EINVAL;
955 goto out;
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.
963 BUILD_BUG_ON(sizeof(*vm_addr) > 128);
964 memcpy(addr, vm_addr, sizeof(*vm_addr));
965 err = sizeof(*vm_addr);
967 out:
968 release_sock(sk);
969 return err;
972 static int vsock_shutdown(struct socket *sock, int mode)
974 int err;
975 struct sock *sk;
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.
983 mode++;
985 if ((mode & ~SHUTDOWN_MASK) || !mode)
986 return -EINVAL;
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.
994 sk = sock->sk;
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;
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);
1012 if (sock_type_connectible(sk->sk_type)) {
1013 sock_reset_flag(sk, SOCK_DONE);
1014 vsock_send_shutdown(sk, mode);
1018 out:
1019 release_sock(sk);
1020 return err;
1023 static __poll_t vsock_poll(struct file *file, struct socket *sock,
1024 poll_table *wait)
1026 struct sock *sk;
1027 __poll_t mask;
1028 struct vsock_sock *vsk;
1030 sk = sock->sk;
1031 vsk = vsock_sk(sk);
1033 poll_wait(file, sk_sleep(sk), wait);
1034 mask = 0;
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;
1040 /* INET sockets treat local write shutdown and peer write shutdown as a
1041 * case of EPOLLHUP set.
1043 if ((sk->sk_shutdown == SHUTDOWN_MASK) ||
1044 ((sk->sk_shutdown & SEND_SHUTDOWN) &&
1045 (vsk->peer_shutdown & SEND_SHUTDOWN))) {
1046 mask |= EPOLLHUP;
1049 if (sk->sk_shutdown & RCV_SHUTDOWN ||
1050 vsk->peer_shutdown & SEND_SHUTDOWN) {
1051 mask |= EPOLLRDHUP;
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.
1059 if (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
1060 (sk->sk_shutdown & RCV_SHUTDOWN)) {
1061 mask |= EPOLLIN | EPOLLRDNORM;
1064 if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1065 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
1067 } else if (sock_type_connectible(sk->sk_type)) {
1068 const struct vsock_transport *transport;
1070 lock_sock(sk);
1072 transport = vsk->transport;
1074 /* Listening sockets that have connections in their accept
1075 * queue can be read.
1077 if (sk->sk_state == TCP_LISTEN
1078 && !vsock_is_accept_queue_empty(sk))
1079 mask |= EPOLLIN | EPOLLRDNORM;
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;
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.
1101 if (sk->sk_shutdown & RCV_SHUTDOWN ||
1102 vsk->peer_shutdown & SEND_SHUTDOWN) {
1103 mask |= EPOLLIN | EPOLLRDNORM;
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.
1119 mask |= EPOLLOUT | EPOLLWRNORM;
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.
1129 if (sk->sk_state == TCP_CLOSE || sk->sk_state == TCP_CLOSING) {
1130 if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1131 mask |= EPOLLOUT | EPOLLWRNORM;
1135 release_sock(sk);
1138 return mask;
1141 static int vsock_read_skb(struct sock *sk, skb_read_actor_t read_actor)
1143 struct vsock_sock *vsk = vsock_sk(sk);
1145 return vsk->transport->read_skb(vsk, read_actor);
1148 static int vsock_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
1149 size_t len)
1151 int err;
1152 struct sock *sk;
1153 struct vsock_sock *vsk;
1154 struct sockaddr_vm *remote_addr;
1155 const struct vsock_transport *transport;
1157 if (msg->msg_flags & MSG_OOB)
1158 return -EOPNOTSUPP;
1160 /* For now, MSG_DONTWAIT is always assumed... */
1161 err = 0;
1162 sk = sock->sk;
1163 vsk = vsock_sk(sk);
1165 lock_sock(sk);
1167 transport = vsk->transport;
1169 err = vsock_auto_bind(vsk);
1170 if (err)
1171 goto out;
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).
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.
1184 if (remote_addr->svm_cid == VMADDR_CID_ANY)
1185 remote_addr->svm_cid = transport->get_local_cid();
1187 if (!vsock_addr_bound(remote_addr)) {
1188 err = -EINVAL;
1189 goto out;
1191 } else if (sock->state == SS_CONNECTED) {
1192 remote_addr = &vsk->remote_addr;
1194 if (remote_addr->svm_cid == VMADDR_CID_ANY)
1195 remote_addr->svm_cid = transport->get_local_cid();
1197 /* XXX Should connect() or this function ensure remote_addr is
1198 * bound?
1200 if (!vsock_addr_bound(&vsk->remote_addr)) {
1201 err = -EINVAL;
1202 goto out;
1204 } else {
1205 err = -EINVAL;
1206 goto out;
1209 if (!transport->dgram_allow(remote_addr->svm_cid,
1210 remote_addr->svm_port)) {
1211 err = -EINVAL;
1212 goto out;
1215 err = transport->dgram_enqueue(vsk, remote_addr, msg, len);
1217 out:
1218 release_sock(sk);
1219 return err;
1222 static int vsock_dgram_connect(struct socket *sock,
1223 struct sockaddr *addr, int addr_len, int flags)
1225 int err;
1226 struct sock *sk;
1227 struct vsock_sock *vsk;
1228 struct sockaddr_vm *remote_addr;
1230 sk = sock->sk;
1231 vsk = vsock_sk(sk);
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;
1244 lock_sock(sk);
1246 err = vsock_auto_bind(vsk);
1247 if (err)
1248 goto out;
1250 if (!vsk->transport->dgram_allow(remote_addr->svm_cid,
1251 remote_addr->svm_port)) {
1252 err = -EINVAL;
1253 goto out;
1256 memcpy(&vsk->remote_addr, remote_addr, sizeof(vsk->remote_addr));
1257 sock->state = SS_CONNECTED;
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.
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).
1267 sk->sk_state = TCP_ESTABLISHED;
1269 out:
1270 release_sock(sk);
1271 return err;
1274 int __vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
1275 size_t len, int flags)
1277 struct sock *sk = sock->sk;
1278 struct vsock_sock *vsk = vsock_sk(sk);
1280 return vsk->transport->dgram_dequeue(vsk, msg, len, flags);
1283 int vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
1284 size_t len, int flags)
1286 #ifdef CONFIG_BPF_SYSCALL
1287 struct sock *sk = sock->sk;
1288 const struct proto *prot;
1290 prot = READ_ONCE(sk->sk_prot);
1291 if (prot != &vsock_proto)
1292 return prot->recvmsg(sk, msg, len, flags, NULL);
1293 #endif
1295 return __vsock_dgram_recvmsg(sock, msg, len, flags);
1297 EXPORT_SYMBOL_GPL(vsock_dgram_recvmsg);
1299 static int vsock_do_ioctl(struct socket *sock, unsigned int cmd,
1300 int __user *arg)
1302 struct sock *sk = sock->sk;
1303 struct vsock_sock *vsk;
1304 int ret;
1306 vsk = vsock_sk(sk);
1308 switch (cmd) {
1309 case SIOCOUTQ: {
1310 ssize_t n_bytes;
1312 if (!vsk->transport || !vsk->transport->unsent_bytes) {
1313 ret = -EOPNOTSUPP;
1314 break;
1317 if (sock_type_connectible(sk->sk_type) && sk->sk_state == TCP_LISTEN) {
1318 ret = -EINVAL;
1319 break;
1322 n_bytes = vsk->transport->unsent_bytes(vsk);
1323 if (n_bytes < 0) {
1324 ret = n_bytes;
1325 break;
1328 ret = put_user(n_bytes, arg);
1329 break;
1331 default:
1332 ret = -ENOIOCTLCMD;
1335 return ret;
1338 static int vsock_ioctl(struct socket *sock, unsigned int cmd,
1339 unsigned long arg)
1341 int ret;
1343 lock_sock(sock->sk);
1344 ret = vsock_do_ioctl(sock, cmd, (int __user *)arg);
1345 release_sock(sock->sk);
1347 return ret;
1350 static const struct proto_ops vsock_dgram_ops = {
1351 .family = PF_VSOCK,
1352 .owner = THIS_MODULE,
1353 .release = vsock_release,
1354 .bind = vsock_bind,
1355 .connect = vsock_dgram_connect,
1356 .socketpair = sock_no_socketpair,
1357 .accept = sock_no_accept,
1358 .getname = vsock_getname,
1359 .poll = vsock_poll,
1360 .ioctl = vsock_ioctl,
1361 .listen = sock_no_listen,
1362 .shutdown = vsock_shutdown,
1363 .sendmsg = vsock_dgram_sendmsg,
1364 .recvmsg = vsock_dgram_recvmsg,
1365 .mmap = sock_no_mmap,
1366 .read_skb = vsock_read_skb,
1369 static int vsock_transport_cancel_pkt(struct vsock_sock *vsk)
1371 const struct vsock_transport *transport = vsk->transport;
1373 if (!transport || !transport->cancel_pkt)
1374 return -EOPNOTSUPP;
1376 return transport->cancel_pkt(vsk);
1379 static void vsock_connect_timeout(struct work_struct *work)
1381 struct sock *sk;
1382 struct vsock_sock *vsk;
1384 vsk = container_of(work, struct vsock_sock, connect_work.work);
1385 sk = sk_vsock(vsk);
1387 lock_sock(sk);
1388 if (sk->sk_state == TCP_SYN_SENT &&
1389 (sk->sk_shutdown != SHUTDOWN_MASK)) {
1390 sk->sk_state = TCP_CLOSE;
1391 sk->sk_socket->state = SS_UNCONNECTED;
1392 sk->sk_err = ETIMEDOUT;
1393 sk_error_report(sk);
1394 vsock_transport_cancel_pkt(vsk);
1396 release_sock(sk);
1398 sock_put(sk);
1401 static int vsock_connect(struct socket *sock, struct sockaddr *addr,
1402 int addr_len, int flags)
1404 int err;
1405 struct sock *sk;
1406 struct vsock_sock *vsk;
1407 const struct vsock_transport *transport;
1408 struct sockaddr_vm *remote_addr;
1409 long timeout;
1410 DEFINE_WAIT(wait);
1412 err = 0;
1413 sk = sock->sk;
1414 vsk = vsock_sk(sk);
1416 lock_sock(sk);
1418 /* XXX AF_UNSPEC should make us disconnect like AF_INET. */
1419 switch (sock->state) {
1420 case SS_CONNECTED:
1421 err = -EISCONN;
1422 goto out;
1423 case SS_DISCONNECTING:
1424 err = -EINVAL;
1425 goto out;
1426 case SS_CONNECTING:
1427 /* This continues on so we can move sock into the SS_CONNECTED
1428 * state once the connection has completed (at which point err
1429 * will be set to zero also). Otherwise, we will either wait
1430 * for the connection or return -EALREADY should this be a
1431 * non-blocking call.
1433 err = -EALREADY;
1434 if (flags & O_NONBLOCK)
1435 goto out;
1436 break;
1437 default:
1438 if ((sk->sk_state == TCP_LISTEN) ||
1439 vsock_addr_cast(addr, addr_len, &remote_addr) != 0) {
1440 err = -EINVAL;
1441 goto out;
1444 /* Set the remote address that we are connecting to. */
1445 memcpy(&vsk->remote_addr, remote_addr,
1446 sizeof(vsk->remote_addr));
1448 err = vsock_assign_transport(vsk, NULL);
1449 if (err)
1450 goto out;
1452 transport = vsk->transport;
1454 /* The hypervisor and well-known contexts do not have socket
1455 * endpoints.
1457 if (!transport ||
1458 !transport->stream_allow(remote_addr->svm_cid,
1459 remote_addr->svm_port)) {
1460 err = -ENETUNREACH;
1461 goto out;
1464 if (vsock_msgzerocopy_allow(transport)) {
1465 set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1466 } else if (sock_flag(sk, SOCK_ZEROCOPY)) {
1467 /* If this option was set before 'connect()',
1468 * when transport was unknown, check that this
1469 * feature is supported here.
1471 err = -EOPNOTSUPP;
1472 goto out;
1475 err = vsock_auto_bind(vsk);
1476 if (err)
1477 goto out;
1479 sk->sk_state = TCP_SYN_SENT;
1481 err = transport->connect(vsk);
1482 if (err < 0)
1483 goto out;
1485 /* Mark sock as connecting and set the error code to in
1486 * progress in case this is a non-blocking connect.
1488 sock->state = SS_CONNECTING;
1489 err = -EINPROGRESS;
1492 /* The receive path will handle all communication until we are able to
1493 * enter the connected state. Here we wait for the connection to be
1494 * completed or a notification of an error.
1496 timeout = vsk->connect_timeout;
1497 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1499 while (sk->sk_state != TCP_ESTABLISHED && sk->sk_err == 0) {
1500 if (flags & O_NONBLOCK) {
1501 /* If we're not going to block, we schedule a timeout
1502 * function to generate a timeout on the connection
1503 * attempt, in case the peer doesn't respond in a
1504 * timely manner. We hold on to the socket until the
1505 * timeout fires.
1507 sock_hold(sk);
1509 /* If the timeout function is already scheduled,
1510 * reschedule it, then ungrab the socket refcount to
1511 * keep it balanced.
1513 if (mod_delayed_work(system_wq, &vsk->connect_work,
1514 timeout))
1515 sock_put(sk);
1517 /* Skip ahead to preserve error code set above. */
1518 goto out_wait;
1521 release_sock(sk);
1522 timeout = schedule_timeout(timeout);
1523 lock_sock(sk);
1525 if (signal_pending(current)) {
1526 err = sock_intr_errno(timeout);
1527 sk->sk_state = sk->sk_state == TCP_ESTABLISHED ? TCP_CLOSING : TCP_CLOSE;
1528 sock->state = SS_UNCONNECTED;
1529 vsock_transport_cancel_pkt(vsk);
1530 vsock_remove_connected(vsk);
1531 goto out_wait;
1532 } else if ((sk->sk_state != TCP_ESTABLISHED) && (timeout == 0)) {
1533 err = -ETIMEDOUT;
1534 sk->sk_state = TCP_CLOSE;
1535 sock->state = SS_UNCONNECTED;
1536 vsock_transport_cancel_pkt(vsk);
1537 goto out_wait;
1540 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1543 if (sk->sk_err) {
1544 err = -sk->sk_err;
1545 sk->sk_state = TCP_CLOSE;
1546 sock->state = SS_UNCONNECTED;
1547 } else {
1548 err = 0;
1551 out_wait:
1552 finish_wait(sk_sleep(sk), &wait);
1553 out:
1554 release_sock(sk);
1555 return err;
1558 static int vsock_accept(struct socket *sock, struct socket *newsock,
1559 struct proto_accept_arg *arg)
1561 struct sock *listener;
1562 int err;
1563 struct sock *connected;
1564 struct vsock_sock *vconnected;
1565 long timeout;
1566 DEFINE_WAIT(wait);
1568 err = 0;
1569 listener = sock->sk;
1571 lock_sock(listener);
1573 if (!sock_type_connectible(sock->type)) {
1574 err = -EOPNOTSUPP;
1575 goto out;
1578 if (listener->sk_state != TCP_LISTEN) {
1579 err = -EINVAL;
1580 goto out;
1583 /* Wait for children sockets to appear; these are the new sockets
1584 * created upon connection establishment.
1586 timeout = sock_rcvtimeo(listener, arg->flags & O_NONBLOCK);
1587 prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1589 while ((connected = vsock_dequeue_accept(listener)) == NULL &&
1590 listener->sk_err == 0) {
1591 release_sock(listener);
1592 timeout = schedule_timeout(timeout);
1593 finish_wait(sk_sleep(listener), &wait);
1594 lock_sock(listener);
1596 if (signal_pending(current)) {
1597 err = sock_intr_errno(timeout);
1598 goto out;
1599 } else if (timeout == 0) {
1600 err = -EAGAIN;
1601 goto out;
1604 prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1606 finish_wait(sk_sleep(listener), &wait);
1608 if (listener->sk_err)
1609 err = -listener->sk_err;
1611 if (connected) {
1612 sk_acceptq_removed(listener);
1614 lock_sock_nested(connected, SINGLE_DEPTH_NESTING);
1615 vconnected = vsock_sk(connected);
1617 /* If the listener socket has received an error, then we should
1618 * reject this socket and return. Note that we simply mark the
1619 * socket rejected, drop our reference, and let the cleanup
1620 * function handle the cleanup; the fact that we found it in
1621 * the listener's accept queue guarantees that the cleanup
1622 * function hasn't run yet.
1624 if (err) {
1625 vconnected->rejected = true;
1626 } else {
1627 newsock->state = SS_CONNECTED;
1628 sock_graft(connected, newsock);
1629 if (vsock_msgzerocopy_allow(vconnected->transport))
1630 set_bit(SOCK_SUPPORT_ZC,
1631 &connected->sk_socket->flags);
1634 release_sock(connected);
1635 sock_put(connected);
1638 out:
1639 release_sock(listener);
1640 return err;
1643 static int vsock_listen(struct socket *sock, int backlog)
1645 int err;
1646 struct sock *sk;
1647 struct vsock_sock *vsk;
1649 sk = sock->sk;
1651 lock_sock(sk);
1653 if (!sock_type_connectible(sk->sk_type)) {
1654 err = -EOPNOTSUPP;
1655 goto out;
1658 if (sock->state != SS_UNCONNECTED) {
1659 err = -EINVAL;
1660 goto out;
1663 vsk = vsock_sk(sk);
1665 if (!vsock_addr_bound(&vsk->local_addr)) {
1666 err = -EINVAL;
1667 goto out;
1670 sk->sk_max_ack_backlog = backlog;
1671 sk->sk_state = TCP_LISTEN;
1673 err = 0;
1675 out:
1676 release_sock(sk);
1677 return err;
1680 static void vsock_update_buffer_size(struct vsock_sock *vsk,
1681 const struct vsock_transport *transport,
1682 u64 val)
1684 if (val > vsk->buffer_max_size)
1685 val = vsk->buffer_max_size;
1687 if (val < vsk->buffer_min_size)
1688 val = vsk->buffer_min_size;
1690 if (val != vsk->buffer_size &&
1691 transport && transport->notify_buffer_size)
1692 transport->notify_buffer_size(vsk, &val);
1694 vsk->buffer_size = val;
1697 static int vsock_connectible_setsockopt(struct socket *sock,
1698 int level,
1699 int optname,
1700 sockptr_t optval,
1701 unsigned int optlen)
1703 int err;
1704 struct sock *sk;
1705 struct vsock_sock *vsk;
1706 const struct vsock_transport *transport;
1707 u64 val;
1709 if (level != AF_VSOCK && level != SOL_SOCKET)
1710 return -ENOPROTOOPT;
1712 #define COPY_IN(_v) \
1713 do { \
1714 if (optlen < sizeof(_v)) { \
1715 err = -EINVAL; \
1716 goto exit; \
1718 if (copy_from_sockptr(&_v, optval, sizeof(_v)) != 0) { \
1719 err = -EFAULT; \
1720 goto exit; \
1722 } while (0)
1724 err = 0;
1725 sk = sock->sk;
1726 vsk = vsock_sk(sk);
1728 lock_sock(sk);
1730 transport = vsk->transport;
1732 if (level == SOL_SOCKET) {
1733 int zerocopy;
1735 if (optname != SO_ZEROCOPY) {
1736 release_sock(sk);
1737 return sock_setsockopt(sock, level, optname, optval, optlen);
1740 /* Use 'int' type here, because variable to
1741 * set this option usually has this type.
1743 COPY_IN(zerocopy);
1745 if (zerocopy < 0 || zerocopy > 1) {
1746 err = -EINVAL;
1747 goto exit;
1750 if (transport && !vsock_msgzerocopy_allow(transport)) {
1751 err = -EOPNOTSUPP;
1752 goto exit;
1755 sock_valbool_flag(sk, SOCK_ZEROCOPY, zerocopy);
1756 goto exit;
1759 switch (optname) {
1760 case SO_VM_SOCKETS_BUFFER_SIZE:
1761 COPY_IN(val);
1762 vsock_update_buffer_size(vsk, transport, val);
1763 break;
1765 case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1766 COPY_IN(val);
1767 vsk->buffer_max_size = val;
1768 vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
1769 break;
1771 case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1772 COPY_IN(val);
1773 vsk->buffer_min_size = val;
1774 vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
1775 break;
1777 case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
1778 case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD: {
1779 struct __kernel_sock_timeval tv;
1781 err = sock_copy_user_timeval(&tv, optval, optlen,
1782 optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
1783 if (err)
1784 break;
1785 if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC &&
1786 tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) {
1787 vsk->connect_timeout = tv.tv_sec * HZ +
1788 DIV_ROUND_UP((unsigned long)tv.tv_usec, (USEC_PER_SEC / HZ));
1789 if (vsk->connect_timeout == 0)
1790 vsk->connect_timeout =
1791 VSOCK_DEFAULT_CONNECT_TIMEOUT;
1793 } else {
1794 err = -ERANGE;
1796 break;
1799 default:
1800 err = -ENOPROTOOPT;
1801 break;
1804 #undef COPY_IN
1806 exit:
1807 release_sock(sk);
1808 return err;
1811 static int vsock_connectible_getsockopt(struct socket *sock,
1812 int level, int optname,
1813 char __user *optval,
1814 int __user *optlen)
1816 struct sock *sk = sock->sk;
1817 struct vsock_sock *vsk = vsock_sk(sk);
1819 union {
1820 u64 val64;
1821 struct old_timeval32 tm32;
1822 struct __kernel_old_timeval tm;
1823 struct __kernel_sock_timeval stm;
1824 } v;
1826 int lv = sizeof(v.val64);
1827 int len;
1829 if (level != AF_VSOCK)
1830 return -ENOPROTOOPT;
1832 if (get_user(len, optlen))
1833 return -EFAULT;
1835 memset(&v, 0, sizeof(v));
1837 switch (optname) {
1838 case SO_VM_SOCKETS_BUFFER_SIZE:
1839 v.val64 = vsk->buffer_size;
1840 break;
1842 case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1843 v.val64 = vsk->buffer_max_size;
1844 break;
1846 case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1847 v.val64 = vsk->buffer_min_size;
1848 break;
1850 case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
1851 case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD:
1852 lv = sock_get_timeout(vsk->connect_timeout, &v,
1853 optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
1854 break;
1856 default:
1857 return -ENOPROTOOPT;
1860 if (len < lv)
1861 return -EINVAL;
1862 if (len > lv)
1863 len = lv;
1864 if (copy_to_user(optval, &v, len))
1865 return -EFAULT;
1867 if (put_user(len, optlen))
1868 return -EFAULT;
1870 return 0;
1873 static int vsock_connectible_sendmsg(struct socket *sock, struct msghdr *msg,
1874 size_t len)
1876 struct sock *sk;
1877 struct vsock_sock *vsk;
1878 const struct vsock_transport *transport;
1879 ssize_t total_written;
1880 long timeout;
1881 int err;
1882 struct vsock_transport_send_notify_data send_data;
1883 DEFINE_WAIT_FUNC(wait, woken_wake_function);
1885 sk = sock->sk;
1886 vsk = vsock_sk(sk);
1887 total_written = 0;
1888 err = 0;
1890 if (msg->msg_flags & MSG_OOB)
1891 return -EOPNOTSUPP;
1893 lock_sock(sk);
1895 transport = vsk->transport;
1897 /* Callers should not provide a destination with connection oriented
1898 * sockets.
1900 if (msg->msg_namelen) {
1901 err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
1902 goto out;
1905 /* Send data only if both sides are not shutdown in the direction. */
1906 if (sk->sk_shutdown & SEND_SHUTDOWN ||
1907 vsk->peer_shutdown & RCV_SHUTDOWN) {
1908 err = -EPIPE;
1909 goto out;
1912 if (!transport || sk->sk_state != TCP_ESTABLISHED ||
1913 !vsock_addr_bound(&vsk->local_addr)) {
1914 err = -ENOTCONN;
1915 goto out;
1918 if (!vsock_addr_bound(&vsk->remote_addr)) {
1919 err = -EDESTADDRREQ;
1920 goto out;
1923 if (msg->msg_flags & MSG_ZEROCOPY &&
1924 !vsock_msgzerocopy_allow(transport)) {
1925 err = -EOPNOTSUPP;
1926 goto out;
1929 /* Wait for room in the produce queue to enqueue our user's data. */
1930 timeout = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1932 err = transport->notify_send_init(vsk, &send_data);
1933 if (err < 0)
1934 goto out;
1936 while (total_written < len) {
1937 ssize_t written;
1939 add_wait_queue(sk_sleep(sk), &wait);
1940 while (vsock_stream_has_space(vsk) == 0 &&
1941 sk->sk_err == 0 &&
1942 !(sk->sk_shutdown & SEND_SHUTDOWN) &&
1943 !(vsk->peer_shutdown & RCV_SHUTDOWN)) {
1945 /* Don't wait for non-blocking sockets. */
1946 if (timeout == 0) {
1947 err = -EAGAIN;
1948 remove_wait_queue(sk_sleep(sk), &wait);
1949 goto out_err;
1952 err = transport->notify_send_pre_block(vsk, &send_data);
1953 if (err < 0) {
1954 remove_wait_queue(sk_sleep(sk), &wait);
1955 goto out_err;
1958 release_sock(sk);
1959 timeout = wait_woken(&wait, TASK_INTERRUPTIBLE, timeout);
1960 lock_sock(sk);
1961 if (signal_pending(current)) {
1962 err = sock_intr_errno(timeout);
1963 remove_wait_queue(sk_sleep(sk), &wait);
1964 goto out_err;
1965 } else if (timeout == 0) {
1966 err = -EAGAIN;
1967 remove_wait_queue(sk_sleep(sk), &wait);
1968 goto out_err;
1971 remove_wait_queue(sk_sleep(sk), &wait);
1973 /* These checks occur both as part of and after the loop
1974 * conditional since we need to check before and after
1975 * sleeping.
1977 if (sk->sk_err) {
1978 err = -sk->sk_err;
1979 goto out_err;
1980 } else if ((sk->sk_shutdown & SEND_SHUTDOWN) ||
1981 (vsk->peer_shutdown & RCV_SHUTDOWN)) {
1982 err = -EPIPE;
1983 goto out_err;
1986 err = transport->notify_send_pre_enqueue(vsk, &send_data);
1987 if (err < 0)
1988 goto out_err;
1990 /* Note that enqueue will only write as many bytes as are free
1991 * in the produce queue, so we don't need to ensure len is
1992 * smaller than the queue size. It is the caller's
1993 * responsibility to check how many bytes we were able to send.
1996 if (sk->sk_type == SOCK_SEQPACKET) {
1997 written = transport->seqpacket_enqueue(vsk,
1998 msg, len - total_written);
1999 } else {
2000 written = transport->stream_enqueue(vsk,
2001 msg, len - total_written);
2004 if (written < 0) {
2005 err = written;
2006 goto out_err;
2009 total_written += written;
2011 err = transport->notify_send_post_enqueue(
2012 vsk, written, &send_data);
2013 if (err < 0)
2014 goto out_err;
2018 out_err:
2019 if (total_written > 0) {
2020 /* Return number of written bytes only if:
2021 * 1) SOCK_STREAM socket.
2022 * 2) SOCK_SEQPACKET socket when whole buffer is sent.
2024 if (sk->sk_type == SOCK_STREAM || total_written == len)
2025 err = total_written;
2027 out:
2028 if (sk->sk_type == SOCK_STREAM)
2029 err = sk_stream_error(sk, msg->msg_flags, err);
2031 release_sock(sk);
2032 return err;
2035 static int vsock_connectible_wait_data(struct sock *sk,
2036 struct wait_queue_entry *wait,
2037 long timeout,
2038 struct vsock_transport_recv_notify_data *recv_data,
2039 size_t target)
2041 const struct vsock_transport *transport;
2042 struct vsock_sock *vsk;
2043 s64 data;
2044 int err;
2046 vsk = vsock_sk(sk);
2047 err = 0;
2048 transport = vsk->transport;
2050 while (1) {
2051 prepare_to_wait(sk_sleep(sk), wait, TASK_INTERRUPTIBLE);
2052 data = vsock_connectible_has_data(vsk);
2053 if (data != 0)
2054 break;
2056 if (sk->sk_err != 0 ||
2057 (sk->sk_shutdown & RCV_SHUTDOWN) ||
2058 (vsk->peer_shutdown & SEND_SHUTDOWN)) {
2059 break;
2062 /* Don't wait for non-blocking sockets. */
2063 if (timeout == 0) {
2064 err = -EAGAIN;
2065 break;
2068 if (recv_data) {
2069 err = transport->notify_recv_pre_block(vsk, target, recv_data);
2070 if (err < 0)
2071 break;
2074 release_sock(sk);
2075 timeout = schedule_timeout(timeout);
2076 lock_sock(sk);
2078 if (signal_pending(current)) {
2079 err = sock_intr_errno(timeout);
2080 break;
2081 } else if (timeout == 0) {
2082 err = -EAGAIN;
2083 break;
2087 finish_wait(sk_sleep(sk), wait);
2089 if (err)
2090 return err;
2092 /* Internal transport error when checking for available
2093 * data. XXX This should be changed to a connection
2094 * reset in a later change.
2096 if (data < 0)
2097 return -ENOMEM;
2099 return data;
2102 static int __vsock_stream_recvmsg(struct sock *sk, struct msghdr *msg,
2103 size_t len, int flags)
2105 struct vsock_transport_recv_notify_data recv_data;
2106 const struct vsock_transport *transport;
2107 struct vsock_sock *vsk;
2108 ssize_t copied;
2109 size_t target;
2110 long timeout;
2111 int err;
2113 DEFINE_WAIT(wait);
2115 vsk = vsock_sk(sk);
2116 transport = vsk->transport;
2118 /* We must not copy less than target bytes into the user's buffer
2119 * before returning successfully, so we wait for the consume queue to
2120 * have that much data to consume before dequeueing. Note that this
2121 * makes it impossible to handle cases where target is greater than the
2122 * queue size.
2124 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2125 if (target >= transport->stream_rcvhiwat(vsk)) {
2126 err = -ENOMEM;
2127 goto out;
2129 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2130 copied = 0;
2132 err = transport->notify_recv_init(vsk, target, &recv_data);
2133 if (err < 0)
2134 goto out;
2137 while (1) {
2138 ssize_t read;
2140 err = vsock_connectible_wait_data(sk, &wait, timeout,
2141 &recv_data, target);
2142 if (err <= 0)
2143 break;
2145 err = transport->notify_recv_pre_dequeue(vsk, target,
2146 &recv_data);
2147 if (err < 0)
2148 break;
2150 read = transport->stream_dequeue(vsk, msg, len - copied, flags);
2151 if (read < 0) {
2152 err = read;
2153 break;
2156 copied += read;
2158 err = transport->notify_recv_post_dequeue(vsk, target, read,
2159 !(flags & MSG_PEEK), &recv_data);
2160 if (err < 0)
2161 goto out;
2163 if (read >= target || flags & MSG_PEEK)
2164 break;
2166 target -= read;
2169 if (sk->sk_err)
2170 err = -sk->sk_err;
2171 else if (sk->sk_shutdown & RCV_SHUTDOWN)
2172 err = 0;
2174 if (copied > 0)
2175 err = copied;
2177 out:
2178 return err;
2181 static int __vsock_seqpacket_recvmsg(struct sock *sk, struct msghdr *msg,
2182 size_t len, int flags)
2184 const struct vsock_transport *transport;
2185 struct vsock_sock *vsk;
2186 ssize_t msg_len;
2187 long timeout;
2188 int err = 0;
2189 DEFINE_WAIT(wait);
2191 vsk = vsock_sk(sk);
2192 transport = vsk->transport;
2194 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2196 err = vsock_connectible_wait_data(sk, &wait, timeout, NULL, 0);
2197 if (err <= 0)
2198 goto out;
2200 msg_len = transport->seqpacket_dequeue(vsk, msg, flags);
2202 if (msg_len < 0) {
2203 err = msg_len;
2204 goto out;
2207 if (sk->sk_err) {
2208 err = -sk->sk_err;
2209 } else if (sk->sk_shutdown & RCV_SHUTDOWN) {
2210 err = 0;
2211 } else {
2212 /* User sets MSG_TRUNC, so return real length of
2213 * packet.
2215 if (flags & MSG_TRUNC)
2216 err = msg_len;
2217 else
2218 err = len - msg_data_left(msg);
2220 /* Always set MSG_TRUNC if real length of packet is
2221 * bigger than user's buffer.
2223 if (msg_len > len)
2224 msg->msg_flags |= MSG_TRUNC;
2227 out:
2228 return err;
2232 __vsock_connectible_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
2233 int flags)
2235 struct sock *sk;
2236 struct vsock_sock *vsk;
2237 const struct vsock_transport *transport;
2238 int err;
2240 sk = sock->sk;
2242 if (unlikely(flags & MSG_ERRQUEUE))
2243 return sock_recv_errqueue(sk, msg, len, SOL_VSOCK, VSOCK_RECVERR);
2245 vsk = vsock_sk(sk);
2246 err = 0;
2248 lock_sock(sk);
2250 transport = vsk->transport;
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.
2258 if (sock_flag(sk, SOCK_DONE))
2259 err = 0;
2260 else
2261 err = -ENOTCONN;
2263 goto out;
2266 if (flags & MSG_OOB) {
2267 err = -EOPNOTSUPP;
2268 goto out;
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.
2275 if (sk->sk_shutdown & RCV_SHUTDOWN) {
2276 err = 0;
2277 goto out;
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.
2283 if (!len) {
2284 err = 0;
2285 goto out;
2288 if (sk->sk_type == SOCK_STREAM)
2289 err = __vsock_stream_recvmsg(sk, msg, len, flags);
2290 else
2291 err = __vsock_seqpacket_recvmsg(sk, msg, len, flags);
2293 out:
2294 release_sock(sk);
2295 return err;
2299 vsock_connectible_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
2300 int flags)
2302 #ifdef CONFIG_BPF_SYSCALL
2303 struct sock *sk = sock->sk;
2304 const struct proto *prot;
2306 prot = READ_ONCE(sk->sk_prot);
2307 if (prot != &vsock_proto)
2308 return prot->recvmsg(sk, msg, len, flags, NULL);
2309 #endif
2311 return __vsock_connectible_recvmsg(sock, msg, len, flags);
2313 EXPORT_SYMBOL_GPL(vsock_connectible_recvmsg);
2315 static int vsock_set_rcvlowat(struct sock *sk, int val)
2317 const struct vsock_transport *transport;
2318 struct vsock_sock *vsk;
2320 vsk = vsock_sk(sk);
2322 if (val > vsk->buffer_size)
2323 return -EINVAL;
2325 transport = vsk->transport;
2327 if (transport && transport->notify_set_rcvlowat) {
2328 int err;
2330 err = transport->notify_set_rcvlowat(vsk, val);
2331 if (err)
2332 return err;
2335 WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
2336 return 0;
2339 static const struct proto_ops vsock_stream_ops = {
2340 .family = PF_VSOCK,
2341 .owner = THIS_MODULE,
2342 .release = vsock_release,
2343 .bind = vsock_bind,
2344 .connect = vsock_connect,
2345 .socketpair = sock_no_socketpair,
2346 .accept = vsock_accept,
2347 .getname = vsock_getname,
2348 .poll = vsock_poll,
2349 .ioctl = vsock_ioctl,
2350 .listen = vsock_listen,
2351 .shutdown = vsock_shutdown,
2352 .setsockopt = vsock_connectible_setsockopt,
2353 .getsockopt = vsock_connectible_getsockopt,
2354 .sendmsg = vsock_connectible_sendmsg,
2355 .recvmsg = vsock_connectible_recvmsg,
2356 .mmap = sock_no_mmap,
2357 .set_rcvlowat = vsock_set_rcvlowat,
2358 .read_skb = vsock_read_skb,
2361 static const struct proto_ops vsock_seqpacket_ops = {
2362 .family = PF_VSOCK,
2363 .owner = THIS_MODULE,
2364 .release = vsock_release,
2365 .bind = vsock_bind,
2366 .connect = vsock_connect,
2367 .socketpair = sock_no_socketpair,
2368 .accept = vsock_accept,
2369 .getname = vsock_getname,
2370 .poll = vsock_poll,
2371 .ioctl = vsock_ioctl,
2372 .listen = vsock_listen,
2373 .shutdown = vsock_shutdown,
2374 .setsockopt = vsock_connectible_setsockopt,
2375 .getsockopt = vsock_connectible_getsockopt,
2376 .sendmsg = vsock_connectible_sendmsg,
2377 .recvmsg = vsock_connectible_recvmsg,
2378 .mmap = sock_no_mmap,
2379 .read_skb = vsock_read_skb,
2382 static int vsock_create(struct net *net, struct socket *sock,
2383 int protocol, int kern)
2385 struct vsock_sock *vsk;
2386 struct sock *sk;
2387 int ret;
2389 if (!sock)
2390 return -EINVAL;
2392 if (protocol && protocol != PF_VSOCK)
2393 return -EPROTONOSUPPORT;
2395 switch (sock->type) {
2396 case SOCK_DGRAM:
2397 sock->ops = &vsock_dgram_ops;
2398 break;
2399 case SOCK_STREAM:
2400 sock->ops = &vsock_stream_ops;
2401 break;
2402 case SOCK_SEQPACKET:
2403 sock->ops = &vsock_seqpacket_ops;
2404 break;
2405 default:
2406 return -ESOCKTNOSUPPORT;
2409 sock->state = SS_UNCONNECTED;
2411 sk = __vsock_create(net, sock, NULL, GFP_KERNEL, 0, kern);
2412 if (!sk)
2413 return -ENOMEM;
2415 vsk = vsock_sk(sk);
2417 if (sock->type == SOCK_DGRAM) {
2418 ret = vsock_assign_transport(vsk, NULL);
2419 if (ret < 0) {
2420 sock_put(sk);
2421 return ret;
2425 /* SOCK_DGRAM doesn't have 'setsockopt' callback set in its
2426 * proto_ops, so there is no handler for custom logic.
2428 if (sock_type_connectible(sock->type))
2429 set_bit(SOCK_CUSTOM_SOCKOPT, &sk->sk_socket->flags);
2431 vsock_insert_unbound(vsk);
2433 return 0;
2436 static const struct net_proto_family vsock_family_ops = {
2437 .family = AF_VSOCK,
2438 .create = vsock_create,
2439 .owner = THIS_MODULE,
2442 static long vsock_dev_do_ioctl(struct file *filp,
2443 unsigned int cmd, void __user *ptr)
2445 u32 __user *p = ptr;
2446 u32 cid = VMADDR_CID_ANY;
2447 int retval = 0;
2449 switch (cmd) {
2450 case IOCTL_VM_SOCKETS_GET_LOCAL_CID:
2451 /* To be compatible with the VMCI behavior, we prioritize the
2452 * guest CID instead of well-know host CID (VMADDR_CID_HOST).
2454 if (transport_g2h)
2455 cid = transport_g2h->get_local_cid();
2456 else if (transport_h2g)
2457 cid = transport_h2g->get_local_cid();
2459 if (put_user(cid, p) != 0)
2460 retval = -EFAULT;
2461 break;
2463 default:
2464 retval = -ENOIOCTLCMD;
2467 return retval;
2470 static long vsock_dev_ioctl(struct file *filp,
2471 unsigned int cmd, unsigned long arg)
2473 return vsock_dev_do_ioctl(filp, cmd, (void __user *)arg);
2476 #ifdef CONFIG_COMPAT
2477 static long vsock_dev_compat_ioctl(struct file *filp,
2478 unsigned int cmd, unsigned long arg)
2480 return vsock_dev_do_ioctl(filp, cmd, compat_ptr(arg));
2482 #endif
2484 static const struct file_operations vsock_device_ops = {
2485 .owner = THIS_MODULE,
2486 .unlocked_ioctl = vsock_dev_ioctl,
2487 #ifdef CONFIG_COMPAT
2488 .compat_ioctl = vsock_dev_compat_ioctl,
2489 #endif
2490 .open = nonseekable_open,
2493 static struct miscdevice vsock_device = {
2494 .name = "vsock",
2495 .fops = &vsock_device_ops,
2498 static int __init vsock_init(void)
2500 int err = 0;
2502 vsock_init_tables();
2504 vsock_proto.owner = THIS_MODULE;
2505 vsock_device.minor = MISC_DYNAMIC_MINOR;
2506 err = misc_register(&vsock_device);
2507 if (err) {
2508 pr_err("Failed to register misc device\n");
2509 goto err_reset_transport;
2512 err = proto_register(&vsock_proto, 1); /* we want our slab */
2513 if (err) {
2514 pr_err("Cannot register vsock protocol\n");
2515 goto err_deregister_misc;
2518 err = sock_register(&vsock_family_ops);
2519 if (err) {
2520 pr_err("could not register af_vsock (%d) address family: %d\n",
2521 AF_VSOCK, err);
2522 goto err_unregister_proto;
2525 vsock_bpf_build_proto();
2527 return 0;
2529 err_unregister_proto:
2530 proto_unregister(&vsock_proto);
2531 err_deregister_misc:
2532 misc_deregister(&vsock_device);
2533 err_reset_transport:
2534 return err;
2537 static void __exit vsock_exit(void)
2539 misc_deregister(&vsock_device);
2540 sock_unregister(AF_VSOCK);
2541 proto_unregister(&vsock_proto);
2544 const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)
2546 return vsk->transport;
2548 EXPORT_SYMBOL_GPL(vsock_core_get_transport);
2550 int vsock_core_register(const struct vsock_transport *t, int features)
2552 const struct vsock_transport *t_h2g, *t_g2h, *t_dgram, *t_local;
2553 int err = mutex_lock_interruptible(&vsock_register_mutex);
2555 if (err)
2556 return err;
2558 t_h2g = transport_h2g;
2559 t_g2h = transport_g2h;
2560 t_dgram = transport_dgram;
2561 t_local = transport_local;
2563 if (features & VSOCK_TRANSPORT_F_H2G) {
2564 if (t_h2g) {
2565 err = -EBUSY;
2566 goto err_busy;
2568 t_h2g = t;
2571 if (features & VSOCK_TRANSPORT_F_G2H) {
2572 if (t_g2h) {
2573 err = -EBUSY;
2574 goto err_busy;
2576 t_g2h = t;
2579 if (features & VSOCK_TRANSPORT_F_DGRAM) {
2580 if (t_dgram) {
2581 err = -EBUSY;
2582 goto err_busy;
2584 t_dgram = t;
2587 if (features & VSOCK_TRANSPORT_F_LOCAL) {
2588 if (t_local) {
2589 err = -EBUSY;
2590 goto err_busy;
2592 t_local = t;
2595 transport_h2g = t_h2g;
2596 transport_g2h = t_g2h;
2597 transport_dgram = t_dgram;
2598 transport_local = t_local;
2600 err_busy:
2601 mutex_unlock(&vsock_register_mutex);
2602 return err;
2604 EXPORT_SYMBOL_GPL(vsock_core_register);
2606 void vsock_core_unregister(const struct vsock_transport *t)
2608 mutex_lock(&vsock_register_mutex);
2610 if (transport_h2g == t)
2611 transport_h2g = NULL;
2613 if (transport_g2h == t)
2614 transport_g2h = NULL;
2616 if (transport_dgram == t)
2617 transport_dgram = NULL;
2619 if (transport_local == t)
2620 transport_local = NULL;
2622 mutex_unlock(&vsock_register_mutex);
2624 EXPORT_SYMBOL_GPL(vsock_core_unregister);
2626 module_init(vsock_init);
2627 module_exit(vsock_exit);
2629 MODULE_AUTHOR("VMware, Inc.");
2630 MODULE_DESCRIPTION("VMware Virtual Socket Family");
2631 MODULE_VERSION("1.0.2.0-k");
2632 MODULE_LICENSE("GPL v2");