1 // SPDX-License-Identifier: GPL-2.0-only
3 * VMware vSockets Driver
5 * Copyright (C) 2007-2013 VMware, Inc. All rights reserved.
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/init.h>
94 #include <linux/kernel.h>
95 #include <linux/sched/signal.h>
96 #include <linux/kmod.h>
97 #include <linux/list.h>
98 #include <linux/miscdevice.h>
99 #include <linux/module.h>
100 #include <linux/mutex.h>
101 #include <linux/net.h>
102 #include <linux/poll.h>
103 #include <linux/random.h>
104 #include <linux/skbuff.h>
105 #include <linux/smp.h>
106 #include <linux/socket.h>
107 #include <linux/stddef.h>
108 #include <linux/unistd.h>
109 #include <linux/wait.h>
110 #include <linux/workqueue.h>
111 #include <net/sock.h>
112 #include <net/af_vsock.h>
114 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr);
115 static void vsock_sk_destruct(struct sock *sk);
116 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb);
118 /* Protocol family. */
119 struct proto vsock_proto = {
121 .owner = THIS_MODULE,
122 .obj_size = sizeof(struct vsock_sock),
123 #ifdef CONFIG_BPF_SYSCALL
124 .psock_update_sk_prot = vsock_bpf_update_proto,
128 /* The default peer timeout indicates how long we will wait for a peer response
129 * to a control message.
131 #define VSOCK_DEFAULT_CONNECT_TIMEOUT (2 * HZ)
133 #define VSOCK_DEFAULT_BUFFER_SIZE (1024 * 256)
134 #define VSOCK_DEFAULT_BUFFER_MAX_SIZE (1024 * 256)
135 #define VSOCK_DEFAULT_BUFFER_MIN_SIZE 128
137 /* Transport used for host->guest communication */
138 static const struct vsock_transport *transport_h2g;
139 /* Transport used for guest->host communication */
140 static const struct vsock_transport *transport_g2h;
141 /* Transport used for DGRAM communication */
142 static const struct vsock_transport *transport_dgram;
143 /* Transport used for local communication */
144 static const struct vsock_transport *transport_local;
145 static DEFINE_MUTEX(vsock_register_mutex);
149 /* Each bound VSocket is stored in the bind hash table and each connected
150 * VSocket is stored in the connected hash table.
152 * Unbound sockets are all put on the same list attached to the end of the hash
153 * table (vsock_unbound_sockets). Bound sockets are added to the hash table in
154 * the bucket that their local address hashes to (vsock_bound_sockets(addr)
155 * represents the list that addr hashes to).
157 * Specifically, we initialize the vsock_bind_table array to a size of
158 * VSOCK_HASH_SIZE + 1 so that vsock_bind_table[0] through
159 * vsock_bind_table[VSOCK_HASH_SIZE - 1] are for bound sockets and
160 * vsock_bind_table[VSOCK_HASH_SIZE] is for unbound sockets. The hash function
161 * mods with VSOCK_HASH_SIZE to ensure this.
163 #define MAX_PORT_RETRIES 24
165 #define VSOCK_HASH(addr) ((addr)->svm_port % VSOCK_HASH_SIZE)
166 #define vsock_bound_sockets(addr) (&vsock_bind_table[VSOCK_HASH(addr)])
167 #define vsock_unbound_sockets (&vsock_bind_table[VSOCK_HASH_SIZE])
169 /* XXX This can probably be implemented in a better way. */
170 #define VSOCK_CONN_HASH(src, dst) \
171 (((src)->svm_cid ^ (dst)->svm_port) % VSOCK_HASH_SIZE)
172 #define vsock_connected_sockets(src, dst) \
173 (&vsock_connected_table[VSOCK_CONN_HASH(src, dst)])
174 #define vsock_connected_sockets_vsk(vsk) \
175 vsock_connected_sockets(&(vsk)->remote_addr, &(vsk)->local_addr)
177 struct list_head vsock_bind_table[VSOCK_HASH_SIZE + 1];
178 EXPORT_SYMBOL_GPL(vsock_bind_table);
179 struct list_head vsock_connected_table[VSOCK_HASH_SIZE];
180 EXPORT_SYMBOL_GPL(vsock_connected_table);
181 DEFINE_SPINLOCK(vsock_table_lock);
182 EXPORT_SYMBOL_GPL(vsock_table_lock);
184 /* Autobind this socket to the local address if necessary. */
185 static int vsock_auto_bind(struct vsock_sock *vsk)
187 struct sock *sk = sk_vsock(vsk);
188 struct sockaddr_vm local_addr;
190 if (vsock_addr_bound(&vsk->local_addr))
192 vsock_addr_init(&local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
193 return __vsock_bind(sk, &local_addr);
196 static void vsock_init_tables(void)
200 for (i = 0; i < ARRAY_SIZE(vsock_bind_table); i++)
201 INIT_LIST_HEAD(&vsock_bind_table[i]);
203 for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++)
204 INIT_LIST_HEAD(&vsock_connected_table[i]);
207 static void __vsock_insert_bound(struct list_head *list,
208 struct vsock_sock *vsk)
211 list_add(&vsk->bound_table, list);
214 static void __vsock_insert_connected(struct list_head *list,
215 struct vsock_sock *vsk)
218 list_add(&vsk->connected_table, list);
221 static void __vsock_remove_bound(struct vsock_sock *vsk)
223 list_del_init(&vsk->bound_table);
227 static void __vsock_remove_connected(struct vsock_sock *vsk)
229 list_del_init(&vsk->connected_table);
233 static struct sock *__vsock_find_bound_socket(struct sockaddr_vm *addr)
235 struct vsock_sock *vsk;
237 list_for_each_entry(vsk, vsock_bound_sockets(addr), bound_table) {
238 if (vsock_addr_equals_addr(addr, &vsk->local_addr))
239 return sk_vsock(vsk);
241 if (addr->svm_port == vsk->local_addr.svm_port &&
242 (vsk->local_addr.svm_cid == VMADDR_CID_ANY ||
243 addr->svm_cid == VMADDR_CID_ANY))
244 return sk_vsock(vsk);
250 static struct sock *__vsock_find_connected_socket(struct sockaddr_vm *src,
251 struct sockaddr_vm *dst)
253 struct vsock_sock *vsk;
255 list_for_each_entry(vsk, vsock_connected_sockets(src, dst),
257 if (vsock_addr_equals_addr(src, &vsk->remote_addr) &&
258 dst->svm_port == vsk->local_addr.svm_port) {
259 return sk_vsock(vsk);
266 static void vsock_insert_unbound(struct vsock_sock *vsk)
268 spin_lock_bh(&vsock_table_lock);
269 __vsock_insert_bound(vsock_unbound_sockets, vsk);
270 spin_unlock_bh(&vsock_table_lock);
273 void vsock_insert_connected(struct vsock_sock *vsk)
275 struct list_head *list = vsock_connected_sockets(
276 &vsk->remote_addr, &vsk->local_addr);
278 spin_lock_bh(&vsock_table_lock);
279 __vsock_insert_connected(list, vsk);
280 spin_unlock_bh(&vsock_table_lock);
282 EXPORT_SYMBOL_GPL(vsock_insert_connected);
284 void vsock_remove_bound(struct vsock_sock *vsk)
286 spin_lock_bh(&vsock_table_lock);
287 if (__vsock_in_bound_table(vsk))
288 __vsock_remove_bound(vsk);
289 spin_unlock_bh(&vsock_table_lock);
291 EXPORT_SYMBOL_GPL(vsock_remove_bound);
293 void vsock_remove_connected(struct vsock_sock *vsk)
295 spin_lock_bh(&vsock_table_lock);
296 if (__vsock_in_connected_table(vsk))
297 __vsock_remove_connected(vsk);
298 spin_unlock_bh(&vsock_table_lock);
300 EXPORT_SYMBOL_GPL(vsock_remove_connected);
302 struct sock *vsock_find_bound_socket(struct sockaddr_vm *addr)
306 spin_lock_bh(&vsock_table_lock);
307 sk = __vsock_find_bound_socket(addr);
311 spin_unlock_bh(&vsock_table_lock);
315 EXPORT_SYMBOL_GPL(vsock_find_bound_socket);
317 struct sock *vsock_find_connected_socket(struct sockaddr_vm *src,
318 struct sockaddr_vm *dst)
322 spin_lock_bh(&vsock_table_lock);
323 sk = __vsock_find_connected_socket(src, dst);
327 spin_unlock_bh(&vsock_table_lock);
331 EXPORT_SYMBOL_GPL(vsock_find_connected_socket);
333 void vsock_remove_sock(struct vsock_sock *vsk)
335 vsock_remove_bound(vsk);
336 vsock_remove_connected(vsk);
338 EXPORT_SYMBOL_GPL(vsock_remove_sock);
340 void vsock_for_each_connected_socket(struct vsock_transport *transport,
341 void (*fn)(struct sock *sk))
345 spin_lock_bh(&vsock_table_lock);
347 for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++) {
348 struct vsock_sock *vsk;
349 list_for_each_entry(vsk, &vsock_connected_table[i],
351 if (vsk->transport != transport)
358 spin_unlock_bh(&vsock_table_lock);
360 EXPORT_SYMBOL_GPL(vsock_for_each_connected_socket);
362 void vsock_add_pending(struct sock *listener, struct sock *pending)
364 struct vsock_sock *vlistener;
365 struct vsock_sock *vpending;
367 vlistener = vsock_sk(listener);
368 vpending = vsock_sk(pending);
372 list_add_tail(&vpending->pending_links, &vlistener->pending_links);
374 EXPORT_SYMBOL_GPL(vsock_add_pending);
376 void vsock_remove_pending(struct sock *listener, struct sock *pending)
378 struct vsock_sock *vpending = vsock_sk(pending);
380 list_del_init(&vpending->pending_links);
384 EXPORT_SYMBOL_GPL(vsock_remove_pending);
386 void vsock_enqueue_accept(struct sock *listener, struct sock *connected)
388 struct vsock_sock *vlistener;
389 struct vsock_sock *vconnected;
391 vlistener = vsock_sk(listener);
392 vconnected = vsock_sk(connected);
394 sock_hold(connected);
396 list_add_tail(&vconnected->accept_queue, &vlistener->accept_queue);
398 EXPORT_SYMBOL_GPL(vsock_enqueue_accept);
400 static bool vsock_use_local_transport(unsigned int remote_cid)
402 if (!transport_local)
405 if (remote_cid == VMADDR_CID_LOCAL)
409 return remote_cid == transport_g2h->get_local_cid();
411 return remote_cid == VMADDR_CID_HOST;
415 static void vsock_deassign_transport(struct vsock_sock *vsk)
420 vsk->transport->destruct(vsk);
421 module_put(vsk->transport->module);
422 vsk->transport = NULL;
425 /* Assign a transport to a socket and call the .init transport callback.
427 * Note: for connection oriented socket this must be called when vsk->remote_addr
428 * is set (e.g. during the connect() or when a connection request on a listener
429 * socket is received).
430 * The vsk->remote_addr is used to decide which transport to use:
431 * - remote CID == VMADDR_CID_LOCAL or g2h->local_cid or VMADDR_CID_HOST if
432 * g2h is not loaded, will use local transport;
433 * - remote CID <= VMADDR_CID_HOST or h2g is not loaded or remote flags field
434 * includes VMADDR_FLAG_TO_HOST flag value, will use guest->host transport;
435 * - remote CID > VMADDR_CID_HOST will use host->guest transport;
437 int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)
439 const struct vsock_transport *new_transport;
440 struct sock *sk = sk_vsock(vsk);
441 unsigned int remote_cid = vsk->remote_addr.svm_cid;
445 /* If the packet is coming with the source and destination CIDs higher
446 * than VMADDR_CID_HOST, then a vsock channel where all the packets are
447 * forwarded to the host should be established. Then the host will
448 * need to forward the packets to the guest.
450 * The flag is set on the (listen) receive path (psk is not NULL). On
451 * the connect path the flag can be set by the user space application.
453 if (psk && vsk->local_addr.svm_cid > VMADDR_CID_HOST &&
454 vsk->remote_addr.svm_cid > VMADDR_CID_HOST)
455 vsk->remote_addr.svm_flags |= VMADDR_FLAG_TO_HOST;
457 remote_flags = vsk->remote_addr.svm_flags;
459 switch (sk->sk_type) {
461 new_transport = transport_dgram;
465 if (vsock_use_local_transport(remote_cid))
466 new_transport = transport_local;
467 else if (remote_cid <= VMADDR_CID_HOST || !transport_h2g ||
468 (remote_flags & VMADDR_FLAG_TO_HOST))
469 new_transport = transport_g2h;
471 new_transport = transport_h2g;
474 return -ESOCKTNOSUPPORT;
477 if (vsk->transport) {
478 if (vsk->transport == new_transport)
481 /* transport->release() must be called with sock lock acquired.
482 * This path can only be taken during vsock_connect(), where we
483 * have already held the sock lock. In the other cases, this
484 * function is called on a new socket which is not assigned to
487 vsk->transport->release(vsk);
488 vsock_deassign_transport(vsk);
491 /* We increase the module refcnt to prevent the transport unloading
492 * while there are open sockets assigned to it.
494 if (!new_transport || !try_module_get(new_transport->module))
497 if (sk->sk_type == SOCK_SEQPACKET) {
498 if (!new_transport->seqpacket_allow ||
499 !new_transport->seqpacket_allow(remote_cid)) {
500 module_put(new_transport->module);
501 return -ESOCKTNOSUPPORT;
505 ret = new_transport->init(vsk, psk);
507 module_put(new_transport->module);
511 vsk->transport = new_transport;
515 EXPORT_SYMBOL_GPL(vsock_assign_transport);
517 bool vsock_find_cid(unsigned int cid)
519 if (transport_g2h && cid == transport_g2h->get_local_cid())
522 if (transport_h2g && cid == VMADDR_CID_HOST)
525 if (transport_local && cid == VMADDR_CID_LOCAL)
530 EXPORT_SYMBOL_GPL(vsock_find_cid);
532 static struct sock *vsock_dequeue_accept(struct sock *listener)
534 struct vsock_sock *vlistener;
535 struct vsock_sock *vconnected;
537 vlistener = vsock_sk(listener);
539 if (list_empty(&vlistener->accept_queue))
542 vconnected = list_entry(vlistener->accept_queue.next,
543 struct vsock_sock, accept_queue);
545 list_del_init(&vconnected->accept_queue);
547 /* The caller will need a reference on the connected socket so we let
548 * it call sock_put().
551 return sk_vsock(vconnected);
554 static bool vsock_is_accept_queue_empty(struct sock *sk)
556 struct vsock_sock *vsk = vsock_sk(sk);
557 return list_empty(&vsk->accept_queue);
560 static bool vsock_is_pending(struct sock *sk)
562 struct vsock_sock *vsk = vsock_sk(sk);
563 return !list_empty(&vsk->pending_links);
566 static int vsock_send_shutdown(struct sock *sk, int mode)
568 struct vsock_sock *vsk = vsock_sk(sk);
573 return vsk->transport->shutdown(vsk, mode);
576 static void vsock_pending_work(struct work_struct *work)
579 struct sock *listener;
580 struct vsock_sock *vsk;
583 vsk = container_of(work, struct vsock_sock, pending_work.work);
585 listener = vsk->listener;
589 lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
591 if (vsock_is_pending(sk)) {
592 vsock_remove_pending(listener, sk);
594 sk_acceptq_removed(listener);
595 } else if (!vsk->rejected) {
596 /* We are not on the pending list and accept() did not reject
597 * us, so we must have been accepted by our user process. We
598 * just need to drop our references to the sockets and be on
605 /* We need to remove ourself from the global connected sockets list so
606 * incoming packets can't find this socket, and to reduce the reference
609 vsock_remove_connected(vsk);
611 sk->sk_state = TCP_CLOSE;
615 release_sock(listener);
623 /**** SOCKET OPERATIONS ****/
625 static int __vsock_bind_connectible(struct vsock_sock *vsk,
626 struct sockaddr_vm *addr)
629 struct sockaddr_vm new_addr;
632 port = get_random_u32_above(LAST_RESERVED_PORT);
634 vsock_addr_init(&new_addr, addr->svm_cid, addr->svm_port);
636 if (addr->svm_port == VMADDR_PORT_ANY) {
640 for (i = 0; i < MAX_PORT_RETRIES; i++) {
641 if (port <= LAST_RESERVED_PORT)
642 port = LAST_RESERVED_PORT + 1;
644 new_addr.svm_port = port++;
646 if (!__vsock_find_bound_socket(&new_addr)) {
653 return -EADDRNOTAVAIL;
655 /* If port is in reserved range, ensure caller
656 * has necessary privileges.
658 if (addr->svm_port <= LAST_RESERVED_PORT &&
659 !capable(CAP_NET_BIND_SERVICE)) {
663 if (__vsock_find_bound_socket(&new_addr))
667 vsock_addr_init(&vsk->local_addr, new_addr.svm_cid, new_addr.svm_port);
669 /* Remove connection oriented sockets from the unbound list and add them
670 * to the hash table for easy lookup by its address. The unbound list
671 * is simply an extra entry at the end of the hash table, a trick used
674 __vsock_remove_bound(vsk);
675 __vsock_insert_bound(vsock_bound_sockets(&vsk->local_addr), vsk);
680 static int __vsock_bind_dgram(struct vsock_sock *vsk,
681 struct sockaddr_vm *addr)
683 return vsk->transport->dgram_bind(vsk, addr);
686 static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr)
688 struct vsock_sock *vsk = vsock_sk(sk);
691 /* First ensure this socket isn't already bound. */
692 if (vsock_addr_bound(&vsk->local_addr))
695 /* Now bind to the provided address or select appropriate values if
696 * none are provided (VMADDR_CID_ANY and VMADDR_PORT_ANY). Note that
697 * like AF_INET prevents binding to a non-local IP address (in most
698 * cases), we only allow binding to a local CID.
700 if (addr->svm_cid != VMADDR_CID_ANY && !vsock_find_cid(addr->svm_cid))
701 return -EADDRNOTAVAIL;
703 switch (sk->sk_socket->type) {
706 spin_lock_bh(&vsock_table_lock);
707 retval = __vsock_bind_connectible(vsk, addr);
708 spin_unlock_bh(&vsock_table_lock);
712 retval = __vsock_bind_dgram(vsk, addr);
723 static void vsock_connect_timeout(struct work_struct *work);
725 static struct sock *__vsock_create(struct net *net,
733 struct vsock_sock *psk;
734 struct vsock_sock *vsk;
736 sk = sk_alloc(net, AF_VSOCK, priority, &vsock_proto, kern);
740 sock_init_data(sock, sk);
742 /* sk->sk_type is normally set in sock_init_data, but only if sock is
743 * non-NULL. We make sure that our sockets always have a type by
744 * setting it here if needed.
750 vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
751 vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
753 sk->sk_destruct = vsock_sk_destruct;
754 sk->sk_backlog_rcv = vsock_queue_rcv_skb;
755 sock_reset_flag(sk, SOCK_DONE);
757 INIT_LIST_HEAD(&vsk->bound_table);
758 INIT_LIST_HEAD(&vsk->connected_table);
759 vsk->listener = NULL;
760 INIT_LIST_HEAD(&vsk->pending_links);
761 INIT_LIST_HEAD(&vsk->accept_queue);
762 vsk->rejected = false;
763 vsk->sent_request = false;
764 vsk->ignore_connecting_rst = false;
765 vsk->peer_shutdown = 0;
766 INIT_DELAYED_WORK(&vsk->connect_work, vsock_connect_timeout);
767 INIT_DELAYED_WORK(&vsk->pending_work, vsock_pending_work);
769 psk = parent ? vsock_sk(parent) : NULL;
771 vsk->trusted = psk->trusted;
772 vsk->owner = get_cred(psk->owner);
773 vsk->connect_timeout = psk->connect_timeout;
774 vsk->buffer_size = psk->buffer_size;
775 vsk->buffer_min_size = psk->buffer_min_size;
776 vsk->buffer_max_size = psk->buffer_max_size;
777 security_sk_clone(parent, sk);
779 vsk->trusted = ns_capable_noaudit(&init_user_ns, CAP_NET_ADMIN);
780 vsk->owner = get_current_cred();
781 vsk->connect_timeout = VSOCK_DEFAULT_CONNECT_TIMEOUT;
782 vsk->buffer_size = VSOCK_DEFAULT_BUFFER_SIZE;
783 vsk->buffer_min_size = VSOCK_DEFAULT_BUFFER_MIN_SIZE;
784 vsk->buffer_max_size = VSOCK_DEFAULT_BUFFER_MAX_SIZE;
790 static bool sock_type_connectible(u16 type)
792 return (type == SOCK_STREAM) || (type == SOCK_SEQPACKET);
795 static void __vsock_release(struct sock *sk, int level)
798 struct sock *pending;
799 struct vsock_sock *vsk;
802 pending = NULL; /* Compiler warning. */
804 /* When "level" is SINGLE_DEPTH_NESTING, use the nested
805 * version to avoid the warning "possible recursive locking
806 * detected". When "level" is 0, lock_sock_nested(sk, level)
807 * is the same as lock_sock(sk).
809 lock_sock_nested(sk, level);
812 vsk->transport->release(vsk);
813 else if (sock_type_connectible(sk->sk_type))
814 vsock_remove_sock(vsk);
817 sk->sk_shutdown = SHUTDOWN_MASK;
819 skb_queue_purge(&sk->sk_receive_queue);
821 /* Clean up any sockets that never were accepted. */
822 while ((pending = vsock_dequeue_accept(sk)) != NULL) {
823 __vsock_release(pending, SINGLE_DEPTH_NESTING);
832 static void vsock_sk_destruct(struct sock *sk)
834 struct vsock_sock *vsk = vsock_sk(sk);
836 vsock_deassign_transport(vsk);
838 /* When clearing these addresses, there's no need to set the family and
839 * possibly register the address family with the kernel.
841 vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
842 vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
844 put_cred(vsk->owner);
847 static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
851 err = sock_queue_rcv_skb(sk, skb);
858 struct sock *vsock_create_connected(struct sock *parent)
860 return __vsock_create(sock_net(parent), NULL, parent, GFP_KERNEL,
863 EXPORT_SYMBOL_GPL(vsock_create_connected);
865 s64 vsock_stream_has_data(struct vsock_sock *vsk)
867 return vsk->transport->stream_has_data(vsk);
869 EXPORT_SYMBOL_GPL(vsock_stream_has_data);
871 s64 vsock_connectible_has_data(struct vsock_sock *vsk)
873 struct sock *sk = sk_vsock(vsk);
875 if (sk->sk_type == SOCK_SEQPACKET)
876 return vsk->transport->seqpacket_has_data(vsk);
878 return vsock_stream_has_data(vsk);
880 EXPORT_SYMBOL_GPL(vsock_connectible_has_data);
882 s64 vsock_stream_has_space(struct vsock_sock *vsk)
884 return vsk->transport->stream_has_space(vsk);
886 EXPORT_SYMBOL_GPL(vsock_stream_has_space);
888 void vsock_data_ready(struct sock *sk)
890 struct vsock_sock *vsk = vsock_sk(sk);
892 if (vsock_stream_has_data(vsk) >= sk->sk_rcvlowat ||
893 sock_flag(sk, SOCK_DONE))
894 sk->sk_data_ready(sk);
896 EXPORT_SYMBOL_GPL(vsock_data_ready);
898 static int vsock_release(struct socket *sock)
900 __vsock_release(sock->sk, 0);
902 sock->state = SS_FREE;
908 vsock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
912 struct sockaddr_vm *vm_addr;
916 if (vsock_addr_cast(addr, addr_len, &vm_addr) != 0)
920 err = __vsock_bind(sk, vm_addr);
926 static int vsock_getname(struct socket *sock,
927 struct sockaddr *addr, int peer)
931 struct vsock_sock *vsk;
932 struct sockaddr_vm *vm_addr;
941 if (sock->state != SS_CONNECTED) {
945 vm_addr = &vsk->remote_addr;
947 vm_addr = &vsk->local_addr;
955 /* sys_getsockname() and sys_getpeername() pass us a
956 * MAX_SOCK_ADDR-sized buffer and don't set addr_len. Unfortunately
957 * that macro is defined in socket.c instead of .h, so we hardcode its
960 BUILD_BUG_ON(sizeof(*vm_addr) > 128);
961 memcpy(addr, vm_addr, sizeof(*vm_addr));
962 err = sizeof(*vm_addr);
969 static int vsock_shutdown(struct socket *sock, int mode)
974 /* User level uses SHUT_RD (0) and SHUT_WR (1), but the kernel uses
975 * RCV_SHUTDOWN (1) and SEND_SHUTDOWN (2), so we must increment mode
976 * here like the other address families do. Note also that the
977 * increment makes SHUT_RDWR (2) into RCV_SHUTDOWN | SEND_SHUTDOWN (3),
978 * which is what we want.
982 if ((mode & ~SHUTDOWN_MASK) || !mode)
985 /* If this is a connection oriented socket and it is not connected then
986 * bail out immediately. If it is a DGRAM socket then we must first
987 * kick the socket so that it wakes up from any sleeping calls, for
988 * example recv(), and then afterwards return the error.
994 if (sock->state == SS_UNCONNECTED) {
996 if (sock_type_connectible(sk->sk_type))
999 sock->state = SS_DISCONNECTING;
1003 /* Receive and send shutdowns are treated alike. */
1004 mode = mode & (RCV_SHUTDOWN | SEND_SHUTDOWN);
1006 sk->sk_shutdown |= mode;
1007 sk->sk_state_change(sk);
1009 if (sock_type_connectible(sk->sk_type)) {
1010 sock_reset_flag(sk, SOCK_DONE);
1011 vsock_send_shutdown(sk, mode);
1020 static __poll_t vsock_poll(struct file *file, struct socket *sock,
1025 struct vsock_sock *vsk;
1030 poll_wait(file, sk_sleep(sk), wait);
1034 /* Signify that there has been an error on this socket. */
1037 /* INET sockets treat local write shutdown and peer write shutdown as a
1038 * case of EPOLLHUP set.
1040 if ((sk->sk_shutdown == SHUTDOWN_MASK) ||
1041 ((sk->sk_shutdown & SEND_SHUTDOWN) &&
1042 (vsk->peer_shutdown & SEND_SHUTDOWN))) {
1046 if (sk->sk_shutdown & RCV_SHUTDOWN ||
1047 vsk->peer_shutdown & SEND_SHUTDOWN) {
1051 if (sock->type == SOCK_DGRAM) {
1052 /* For datagram sockets we can read if there is something in
1053 * the queue and write as long as the socket isn't shutdown for
1056 if (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
1057 (sk->sk_shutdown & RCV_SHUTDOWN)) {
1058 mask |= EPOLLIN | EPOLLRDNORM;
1061 if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1062 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
1064 } else if (sock_type_connectible(sk->sk_type)) {
1065 const struct vsock_transport *transport;
1069 transport = vsk->transport;
1071 /* Listening sockets that have connections in their accept
1072 * queue can be read.
1074 if (sk->sk_state == TCP_LISTEN
1075 && !vsock_is_accept_queue_empty(sk))
1076 mask |= EPOLLIN | EPOLLRDNORM;
1078 /* If there is something in the queue then we can read. */
1079 if (transport && transport->stream_is_active(vsk) &&
1080 !(sk->sk_shutdown & RCV_SHUTDOWN)) {
1081 bool data_ready_now = false;
1082 int target = sock_rcvlowat(sk, 0, INT_MAX);
1083 int ret = transport->notify_poll_in(
1084 vsk, target, &data_ready_now);
1089 mask |= EPOLLIN | EPOLLRDNORM;
1094 /* Sockets whose connections have been closed, reset, or
1095 * terminated should also be considered read, and we check the
1096 * shutdown flag for that.
1098 if (sk->sk_shutdown & RCV_SHUTDOWN ||
1099 vsk->peer_shutdown & SEND_SHUTDOWN) {
1100 mask |= EPOLLIN | EPOLLRDNORM;
1103 /* Connected sockets that can produce data can be written. */
1104 if (transport && sk->sk_state == TCP_ESTABLISHED) {
1105 if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
1106 bool space_avail_now = false;
1107 int ret = transport->notify_poll_out(
1108 vsk, 1, &space_avail_now);
1112 if (space_avail_now)
1113 /* Remove EPOLLWRBAND since INET
1114 * sockets are not setting it.
1116 mask |= EPOLLOUT | EPOLLWRNORM;
1122 /* Simulate INET socket poll behaviors, which sets
1123 * EPOLLOUT|EPOLLWRNORM when peer is closed and nothing to read,
1124 * but local send is not shutdown.
1126 if (sk->sk_state == TCP_CLOSE || sk->sk_state == TCP_CLOSING) {
1127 if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1128 mask |= EPOLLOUT | EPOLLWRNORM;
1138 static int vsock_read_skb(struct sock *sk, skb_read_actor_t read_actor)
1140 struct vsock_sock *vsk = vsock_sk(sk);
1142 return vsk->transport->read_skb(vsk, read_actor);
1145 static int vsock_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
1150 struct vsock_sock *vsk;
1151 struct sockaddr_vm *remote_addr;
1152 const struct vsock_transport *transport;
1154 if (msg->msg_flags & MSG_OOB)
1157 /* For now, MSG_DONTWAIT is always assumed... */
1164 transport = vsk->transport;
1166 err = vsock_auto_bind(vsk);
1171 /* If the provided message contains an address, use that. Otherwise
1172 * fall back on the socket's remote handle (if it has been connected).
1174 if (msg->msg_name &&
1175 vsock_addr_cast(msg->msg_name, msg->msg_namelen,
1176 &remote_addr) == 0) {
1177 /* Ensure this address is of the right type and is a valid
1181 if (remote_addr->svm_cid == VMADDR_CID_ANY)
1182 remote_addr->svm_cid = transport->get_local_cid();
1184 if (!vsock_addr_bound(remote_addr)) {
1188 } else if (sock->state == SS_CONNECTED) {
1189 remote_addr = &vsk->remote_addr;
1191 if (remote_addr->svm_cid == VMADDR_CID_ANY)
1192 remote_addr->svm_cid = transport->get_local_cid();
1194 /* XXX Should connect() or this function ensure remote_addr is
1197 if (!vsock_addr_bound(&vsk->remote_addr)) {
1206 if (!transport->dgram_allow(remote_addr->svm_cid,
1207 remote_addr->svm_port)) {
1212 err = transport->dgram_enqueue(vsk, remote_addr, msg, len);
1219 static int vsock_dgram_connect(struct socket *sock,
1220 struct sockaddr *addr, int addr_len, int flags)
1224 struct vsock_sock *vsk;
1225 struct sockaddr_vm *remote_addr;
1230 err = vsock_addr_cast(addr, addr_len, &remote_addr);
1231 if (err == -EAFNOSUPPORT && remote_addr->svm_family == AF_UNSPEC) {
1233 vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY,
1235 sock->state = SS_UNCONNECTED;
1238 } else if (err != 0)
1243 err = vsock_auto_bind(vsk);
1247 if (!vsk->transport->dgram_allow(remote_addr->svm_cid,
1248 remote_addr->svm_port)) {
1253 memcpy(&vsk->remote_addr, remote_addr, sizeof(vsk->remote_addr));
1254 sock->state = SS_CONNECTED;
1256 /* sock map disallows redirection of non-TCP sockets with sk_state !=
1257 * TCP_ESTABLISHED (see sock_map_redirect_allowed()), so we set
1258 * TCP_ESTABLISHED here to allow redirection of connected vsock dgrams.
1260 * This doesn't seem to be abnormal state for datagram sockets, as the
1261 * same approach can be see in other datagram socket types as well
1262 * (such as unix sockets).
1264 sk->sk_state = TCP_ESTABLISHED;
1271 int vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
1272 size_t len, int flags)
1274 #ifdef CONFIG_BPF_SYSCALL
1275 const struct proto *prot;
1277 struct vsock_sock *vsk;
1283 #ifdef CONFIG_BPF_SYSCALL
1284 prot = READ_ONCE(sk->sk_prot);
1285 if (prot != &vsock_proto)
1286 return prot->recvmsg(sk, msg, len, flags, NULL);
1289 return vsk->transport->dgram_dequeue(vsk, msg, len, flags);
1291 EXPORT_SYMBOL_GPL(vsock_dgram_recvmsg);
1293 static const struct proto_ops vsock_dgram_ops = {
1295 .owner = THIS_MODULE,
1296 .release = vsock_release,
1298 .connect = vsock_dgram_connect,
1299 .socketpair = sock_no_socketpair,
1300 .accept = sock_no_accept,
1301 .getname = vsock_getname,
1303 .ioctl = sock_no_ioctl,
1304 .listen = sock_no_listen,
1305 .shutdown = vsock_shutdown,
1306 .sendmsg = vsock_dgram_sendmsg,
1307 .recvmsg = vsock_dgram_recvmsg,
1308 .mmap = sock_no_mmap,
1309 .read_skb = vsock_read_skb,
1312 static int vsock_transport_cancel_pkt(struct vsock_sock *vsk)
1314 const struct vsock_transport *transport = vsk->transport;
1316 if (!transport || !transport->cancel_pkt)
1319 return transport->cancel_pkt(vsk);
1322 static void vsock_connect_timeout(struct work_struct *work)
1325 struct vsock_sock *vsk;
1327 vsk = container_of(work, struct vsock_sock, connect_work.work);
1331 if (sk->sk_state == TCP_SYN_SENT &&
1332 (sk->sk_shutdown != SHUTDOWN_MASK)) {
1333 sk->sk_state = TCP_CLOSE;
1334 sk->sk_socket->state = SS_UNCONNECTED;
1335 sk->sk_err = ETIMEDOUT;
1336 sk_error_report(sk);
1337 vsock_transport_cancel_pkt(vsk);
1344 static int vsock_connect(struct socket *sock, struct sockaddr *addr,
1345 int addr_len, int flags)
1349 struct vsock_sock *vsk;
1350 const struct vsock_transport *transport;
1351 struct sockaddr_vm *remote_addr;
1361 /* XXX AF_UNSPEC should make us disconnect like AF_INET. */
1362 switch (sock->state) {
1366 case SS_DISCONNECTING:
1370 /* This continues on so we can move sock into the SS_CONNECTED
1371 * state once the connection has completed (at which point err
1372 * will be set to zero also). Otherwise, we will either wait
1373 * for the connection or return -EALREADY should this be a
1374 * non-blocking call.
1377 if (flags & O_NONBLOCK)
1381 if ((sk->sk_state == TCP_LISTEN) ||
1382 vsock_addr_cast(addr, addr_len, &remote_addr) != 0) {
1387 /* Set the remote address that we are connecting to. */
1388 memcpy(&vsk->remote_addr, remote_addr,
1389 sizeof(vsk->remote_addr));
1391 err = vsock_assign_transport(vsk, NULL);
1395 transport = vsk->transport;
1397 /* The hypervisor and well-known contexts do not have socket
1401 !transport->stream_allow(remote_addr->svm_cid,
1402 remote_addr->svm_port)) {
1407 err = vsock_auto_bind(vsk);
1411 sk->sk_state = TCP_SYN_SENT;
1413 err = transport->connect(vsk);
1417 /* Mark sock as connecting and set the error code to in
1418 * progress in case this is a non-blocking connect.
1420 sock->state = SS_CONNECTING;
1424 /* The receive path will handle all communication until we are able to
1425 * enter the connected state. Here we wait for the connection to be
1426 * completed or a notification of an error.
1428 timeout = vsk->connect_timeout;
1429 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1431 while (sk->sk_state != TCP_ESTABLISHED && sk->sk_err == 0) {
1432 if (flags & O_NONBLOCK) {
1433 /* If we're not going to block, we schedule a timeout
1434 * function to generate a timeout on the connection
1435 * attempt, in case the peer doesn't respond in a
1436 * timely manner. We hold on to the socket until the
1441 /* If the timeout function is already scheduled,
1442 * reschedule it, then ungrab the socket refcount to
1445 if (mod_delayed_work(system_wq, &vsk->connect_work,
1449 /* Skip ahead to preserve error code set above. */
1454 timeout = schedule_timeout(timeout);
1457 if (signal_pending(current)) {
1458 err = sock_intr_errno(timeout);
1459 sk->sk_state = sk->sk_state == TCP_ESTABLISHED ? TCP_CLOSING : TCP_CLOSE;
1460 sock->state = SS_UNCONNECTED;
1461 vsock_transport_cancel_pkt(vsk);
1462 vsock_remove_connected(vsk);
1464 } else if ((sk->sk_state != TCP_ESTABLISHED) && (timeout == 0)) {
1466 sk->sk_state = TCP_CLOSE;
1467 sock->state = SS_UNCONNECTED;
1468 vsock_transport_cancel_pkt(vsk);
1472 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1477 sk->sk_state = TCP_CLOSE;
1478 sock->state = SS_UNCONNECTED;
1484 finish_wait(sk_sleep(sk), &wait);
1490 static int vsock_accept(struct socket *sock, struct socket *newsock, int flags,
1493 struct sock *listener;
1495 struct sock *connected;
1496 struct vsock_sock *vconnected;
1501 listener = sock->sk;
1503 lock_sock(listener);
1505 if (!sock_type_connectible(sock->type)) {
1510 if (listener->sk_state != TCP_LISTEN) {
1515 /* Wait for children sockets to appear; these are the new sockets
1516 * created upon connection establishment.
1518 timeout = sock_rcvtimeo(listener, flags & O_NONBLOCK);
1519 prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1521 while ((connected = vsock_dequeue_accept(listener)) == NULL &&
1522 listener->sk_err == 0) {
1523 release_sock(listener);
1524 timeout = schedule_timeout(timeout);
1525 finish_wait(sk_sleep(listener), &wait);
1526 lock_sock(listener);
1528 if (signal_pending(current)) {
1529 err = sock_intr_errno(timeout);
1531 } else if (timeout == 0) {
1536 prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
1538 finish_wait(sk_sleep(listener), &wait);
1540 if (listener->sk_err)
1541 err = -listener->sk_err;
1544 sk_acceptq_removed(listener);
1546 lock_sock_nested(connected, SINGLE_DEPTH_NESTING);
1547 vconnected = vsock_sk(connected);
1549 /* If the listener socket has received an error, then we should
1550 * reject this socket and return. Note that we simply mark the
1551 * socket rejected, drop our reference, and let the cleanup
1552 * function handle the cleanup; the fact that we found it in
1553 * the listener's accept queue guarantees that the cleanup
1554 * function hasn't run yet.
1557 vconnected->rejected = true;
1559 newsock->state = SS_CONNECTED;
1560 sock_graft(connected, newsock);
1563 release_sock(connected);
1564 sock_put(connected);
1568 release_sock(listener);
1572 static int vsock_listen(struct socket *sock, int backlog)
1576 struct vsock_sock *vsk;
1582 if (!sock_type_connectible(sk->sk_type)) {
1587 if (sock->state != SS_UNCONNECTED) {
1594 if (!vsock_addr_bound(&vsk->local_addr)) {
1599 sk->sk_max_ack_backlog = backlog;
1600 sk->sk_state = TCP_LISTEN;
1609 static void vsock_update_buffer_size(struct vsock_sock *vsk,
1610 const struct vsock_transport *transport,
1613 if (val > vsk->buffer_max_size)
1614 val = vsk->buffer_max_size;
1616 if (val < vsk->buffer_min_size)
1617 val = vsk->buffer_min_size;
1619 if (val != vsk->buffer_size &&
1620 transport && transport->notify_buffer_size)
1621 transport->notify_buffer_size(vsk, &val);
1623 vsk->buffer_size = val;
1626 static int vsock_connectible_setsockopt(struct socket *sock,
1630 unsigned int optlen)
1634 struct vsock_sock *vsk;
1635 const struct vsock_transport *transport;
1638 if (level != AF_VSOCK)
1639 return -ENOPROTOOPT;
1641 #define COPY_IN(_v) \
1643 if (optlen < sizeof(_v)) { \
1647 if (copy_from_sockptr(&_v, optval, sizeof(_v)) != 0) { \
1659 transport = vsk->transport;
1662 case SO_VM_SOCKETS_BUFFER_SIZE:
1664 vsock_update_buffer_size(vsk, transport, val);
1667 case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1669 vsk->buffer_max_size = val;
1670 vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
1673 case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1675 vsk->buffer_min_size = val;
1676 vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
1679 case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
1680 case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD: {
1681 struct __kernel_sock_timeval tv;
1683 err = sock_copy_user_timeval(&tv, optval, optlen,
1684 optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
1687 if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC &&
1688 tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) {
1689 vsk->connect_timeout = tv.tv_sec * HZ +
1690 DIV_ROUND_UP((unsigned long)tv.tv_usec, (USEC_PER_SEC / HZ));
1691 if (vsk->connect_timeout == 0)
1692 vsk->connect_timeout =
1693 VSOCK_DEFAULT_CONNECT_TIMEOUT;
1713 static int vsock_connectible_getsockopt(struct socket *sock,
1714 int level, int optname,
1715 char __user *optval,
1718 struct sock *sk = sock->sk;
1719 struct vsock_sock *vsk = vsock_sk(sk);
1723 struct old_timeval32 tm32;
1724 struct __kernel_old_timeval tm;
1725 struct __kernel_sock_timeval stm;
1728 int lv = sizeof(v.val64);
1731 if (level != AF_VSOCK)
1732 return -ENOPROTOOPT;
1734 if (get_user(len, optlen))
1737 memset(&v, 0, sizeof(v));
1740 case SO_VM_SOCKETS_BUFFER_SIZE:
1741 v.val64 = vsk->buffer_size;
1744 case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1745 v.val64 = vsk->buffer_max_size;
1748 case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1749 v.val64 = vsk->buffer_min_size;
1752 case SO_VM_SOCKETS_CONNECT_TIMEOUT_NEW:
1753 case SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD:
1754 lv = sock_get_timeout(vsk->connect_timeout, &v,
1755 optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
1759 return -ENOPROTOOPT;
1766 if (copy_to_user(optval, &v, len))
1769 if (put_user(len, optlen))
1775 static int vsock_connectible_sendmsg(struct socket *sock, struct msghdr *msg,
1779 struct vsock_sock *vsk;
1780 const struct vsock_transport *transport;
1781 ssize_t total_written;
1784 struct vsock_transport_send_notify_data send_data;
1785 DEFINE_WAIT_FUNC(wait, woken_wake_function);
1792 if (msg->msg_flags & MSG_OOB)
1797 transport = vsk->transport;
1799 /* Callers should not provide a destination with connection oriented
1802 if (msg->msg_namelen) {
1803 err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
1807 /* Send data only if both sides are not shutdown in the direction. */
1808 if (sk->sk_shutdown & SEND_SHUTDOWN ||
1809 vsk->peer_shutdown & RCV_SHUTDOWN) {
1814 if (!transport || sk->sk_state != TCP_ESTABLISHED ||
1815 !vsock_addr_bound(&vsk->local_addr)) {
1820 if (!vsock_addr_bound(&vsk->remote_addr)) {
1821 err = -EDESTADDRREQ;
1825 /* Wait for room in the produce queue to enqueue our user's data. */
1826 timeout = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1828 err = transport->notify_send_init(vsk, &send_data);
1832 while (total_written < len) {
1835 add_wait_queue(sk_sleep(sk), &wait);
1836 while (vsock_stream_has_space(vsk) == 0 &&
1838 !(sk->sk_shutdown & SEND_SHUTDOWN) &&
1839 !(vsk->peer_shutdown & RCV_SHUTDOWN)) {
1841 /* Don't wait for non-blocking sockets. */
1844 remove_wait_queue(sk_sleep(sk), &wait);
1848 err = transport->notify_send_pre_block(vsk, &send_data);
1850 remove_wait_queue(sk_sleep(sk), &wait);
1855 timeout = wait_woken(&wait, TASK_INTERRUPTIBLE, timeout);
1857 if (signal_pending(current)) {
1858 err = sock_intr_errno(timeout);
1859 remove_wait_queue(sk_sleep(sk), &wait);
1861 } else if (timeout == 0) {
1863 remove_wait_queue(sk_sleep(sk), &wait);
1867 remove_wait_queue(sk_sleep(sk), &wait);
1869 /* These checks occur both as part of and after the loop
1870 * conditional since we need to check before and after
1876 } else if ((sk->sk_shutdown & SEND_SHUTDOWN) ||
1877 (vsk->peer_shutdown & RCV_SHUTDOWN)) {
1882 err = transport->notify_send_pre_enqueue(vsk, &send_data);
1886 /* Note that enqueue will only write as many bytes as are free
1887 * in the produce queue, so we don't need to ensure len is
1888 * smaller than the queue size. It is the caller's
1889 * responsibility to check how many bytes we were able to send.
1892 if (sk->sk_type == SOCK_SEQPACKET) {
1893 written = transport->seqpacket_enqueue(vsk,
1894 msg, len - total_written);
1896 written = transport->stream_enqueue(vsk,
1897 msg, len - total_written);
1905 total_written += written;
1907 err = transport->notify_send_post_enqueue(
1908 vsk, written, &send_data);
1915 if (total_written > 0) {
1916 /* Return number of written bytes only if:
1917 * 1) SOCK_STREAM socket.
1918 * 2) SOCK_SEQPACKET socket when whole buffer is sent.
1920 if (sk->sk_type == SOCK_STREAM || total_written == len)
1921 err = total_written;
1928 static int vsock_connectible_wait_data(struct sock *sk,
1929 struct wait_queue_entry *wait,
1931 struct vsock_transport_recv_notify_data *recv_data,
1934 const struct vsock_transport *transport;
1935 struct vsock_sock *vsk;
1941 transport = vsk->transport;
1944 prepare_to_wait(sk_sleep(sk), wait, TASK_INTERRUPTIBLE);
1945 data = vsock_connectible_has_data(vsk);
1949 if (sk->sk_err != 0 ||
1950 (sk->sk_shutdown & RCV_SHUTDOWN) ||
1951 (vsk->peer_shutdown & SEND_SHUTDOWN)) {
1955 /* Don't wait for non-blocking sockets. */
1962 err = transport->notify_recv_pre_block(vsk, target, recv_data);
1968 timeout = schedule_timeout(timeout);
1971 if (signal_pending(current)) {
1972 err = sock_intr_errno(timeout);
1974 } else if (timeout == 0) {
1980 finish_wait(sk_sleep(sk), wait);
1985 /* Internal transport error when checking for available
1986 * data. XXX This should be changed to a connection
1987 * reset in a later change.
1995 static int __vsock_stream_recvmsg(struct sock *sk, struct msghdr *msg,
1996 size_t len, int flags)
1998 struct vsock_transport_recv_notify_data recv_data;
1999 const struct vsock_transport *transport;
2000 struct vsock_sock *vsk;
2009 transport = vsk->transport;
2011 /* We must not copy less than target bytes into the user's buffer
2012 * before returning successfully, so we wait for the consume queue to
2013 * have that much data to consume before dequeueing. Note that this
2014 * makes it impossible to handle cases where target is greater than the
2017 target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
2018 if (target >= transport->stream_rcvhiwat(vsk)) {
2022 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2025 err = transport->notify_recv_init(vsk, target, &recv_data);
2033 err = vsock_connectible_wait_data(sk, &wait, timeout,
2034 &recv_data, target);
2038 err = transport->notify_recv_pre_dequeue(vsk, target,
2043 read = transport->stream_dequeue(vsk, msg, len - copied, flags);
2051 err = transport->notify_recv_post_dequeue(vsk, target, read,
2052 !(flags & MSG_PEEK), &recv_data);
2056 if (read >= target || flags & MSG_PEEK)
2064 else if (sk->sk_shutdown & RCV_SHUTDOWN)
2074 static int __vsock_seqpacket_recvmsg(struct sock *sk, struct msghdr *msg,
2075 size_t len, int flags)
2077 const struct vsock_transport *transport;
2078 struct vsock_sock *vsk;
2085 transport = vsk->transport;
2087 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2089 err = vsock_connectible_wait_data(sk, &wait, timeout, NULL, 0);
2093 msg_len = transport->seqpacket_dequeue(vsk, msg, flags);
2102 } else if (sk->sk_shutdown & RCV_SHUTDOWN) {
2105 /* User sets MSG_TRUNC, so return real length of
2108 if (flags & MSG_TRUNC)
2111 err = len - msg_data_left(msg);
2113 /* Always set MSG_TRUNC if real length of packet is
2114 * bigger than user's buffer.
2117 msg->msg_flags |= MSG_TRUNC;
2125 vsock_connectible_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
2129 struct vsock_sock *vsk;
2130 const struct vsock_transport *transport;
2131 #ifdef CONFIG_BPF_SYSCALL
2132 const struct proto *prot;
2142 transport = vsk->transport;
2144 if (!transport || sk->sk_state != TCP_ESTABLISHED) {
2145 /* Recvmsg is supposed to return 0 if a peer performs an
2146 * orderly shutdown. Differentiate between that case and when a
2147 * peer has not connected or a local shutdown occurred with the
2150 if (sock_flag(sk, SOCK_DONE))
2158 if (flags & MSG_OOB) {
2163 /* We don't check peer_shutdown flag here since peer may actually shut
2164 * down, but there can be data in the queue that a local socket can
2167 if (sk->sk_shutdown & RCV_SHUTDOWN) {
2172 /* It is valid on Linux to pass in a zero-length receive buffer. This
2173 * is not an error. We may as well bail out now.
2180 #ifdef CONFIG_BPF_SYSCALL
2181 prot = READ_ONCE(sk->sk_prot);
2182 if (prot != &vsock_proto) {
2184 return prot->recvmsg(sk, msg, len, flags, NULL);
2188 if (sk->sk_type == SOCK_STREAM)
2189 err = __vsock_stream_recvmsg(sk, msg, len, flags);
2191 err = __vsock_seqpacket_recvmsg(sk, msg, len, flags);
2197 EXPORT_SYMBOL_GPL(vsock_connectible_recvmsg);
2199 static int vsock_set_rcvlowat(struct sock *sk, int val)
2201 const struct vsock_transport *transport;
2202 struct vsock_sock *vsk;
2206 if (val > vsk->buffer_size)
2209 transport = vsk->transport;
2211 if (transport && transport->set_rcvlowat)
2212 return transport->set_rcvlowat(vsk, val);
2214 WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
2218 static const struct proto_ops vsock_stream_ops = {
2220 .owner = THIS_MODULE,
2221 .release = vsock_release,
2223 .connect = vsock_connect,
2224 .socketpair = sock_no_socketpair,
2225 .accept = vsock_accept,
2226 .getname = vsock_getname,
2228 .ioctl = sock_no_ioctl,
2229 .listen = vsock_listen,
2230 .shutdown = vsock_shutdown,
2231 .setsockopt = vsock_connectible_setsockopt,
2232 .getsockopt = vsock_connectible_getsockopt,
2233 .sendmsg = vsock_connectible_sendmsg,
2234 .recvmsg = vsock_connectible_recvmsg,
2235 .mmap = sock_no_mmap,
2236 .set_rcvlowat = vsock_set_rcvlowat,
2237 .read_skb = vsock_read_skb,
2240 static const struct proto_ops vsock_seqpacket_ops = {
2242 .owner = THIS_MODULE,
2243 .release = vsock_release,
2245 .connect = vsock_connect,
2246 .socketpair = sock_no_socketpair,
2247 .accept = vsock_accept,
2248 .getname = vsock_getname,
2250 .ioctl = sock_no_ioctl,
2251 .listen = vsock_listen,
2252 .shutdown = vsock_shutdown,
2253 .setsockopt = vsock_connectible_setsockopt,
2254 .getsockopt = vsock_connectible_getsockopt,
2255 .sendmsg = vsock_connectible_sendmsg,
2256 .recvmsg = vsock_connectible_recvmsg,
2257 .mmap = sock_no_mmap,
2258 .read_skb = vsock_read_skb,
2261 static int vsock_create(struct net *net, struct socket *sock,
2262 int protocol, int kern)
2264 struct vsock_sock *vsk;
2271 if (protocol && protocol != PF_VSOCK)
2272 return -EPROTONOSUPPORT;
2274 switch (sock->type) {
2276 sock->ops = &vsock_dgram_ops;
2279 sock->ops = &vsock_stream_ops;
2281 case SOCK_SEQPACKET:
2282 sock->ops = &vsock_seqpacket_ops;
2285 return -ESOCKTNOSUPPORT;
2288 sock->state = SS_UNCONNECTED;
2290 sk = __vsock_create(net, sock, NULL, GFP_KERNEL, 0, kern);
2296 if (sock->type == SOCK_DGRAM) {
2297 ret = vsock_assign_transport(vsk, NULL);
2304 vsock_insert_unbound(vsk);
2309 static const struct net_proto_family vsock_family_ops = {
2311 .create = vsock_create,
2312 .owner = THIS_MODULE,
2315 static long vsock_dev_do_ioctl(struct file *filp,
2316 unsigned int cmd, void __user *ptr)
2318 u32 __user *p = ptr;
2319 u32 cid = VMADDR_CID_ANY;
2323 case IOCTL_VM_SOCKETS_GET_LOCAL_CID:
2324 /* To be compatible with the VMCI behavior, we prioritize the
2325 * guest CID instead of well-know host CID (VMADDR_CID_HOST).
2328 cid = transport_g2h->get_local_cid();
2329 else if (transport_h2g)
2330 cid = transport_h2g->get_local_cid();
2332 if (put_user(cid, p) != 0)
2337 retval = -ENOIOCTLCMD;
2343 static long vsock_dev_ioctl(struct file *filp,
2344 unsigned int cmd, unsigned long arg)
2346 return vsock_dev_do_ioctl(filp, cmd, (void __user *)arg);
2349 #ifdef CONFIG_COMPAT
2350 static long vsock_dev_compat_ioctl(struct file *filp,
2351 unsigned int cmd, unsigned long arg)
2353 return vsock_dev_do_ioctl(filp, cmd, compat_ptr(arg));
2357 static const struct file_operations vsock_device_ops = {
2358 .owner = THIS_MODULE,
2359 .unlocked_ioctl = vsock_dev_ioctl,
2360 #ifdef CONFIG_COMPAT
2361 .compat_ioctl = vsock_dev_compat_ioctl,
2363 .open = nonseekable_open,
2366 static struct miscdevice vsock_device = {
2368 .fops = &vsock_device_ops,
2371 static int __init vsock_init(void)
2375 vsock_init_tables();
2377 vsock_proto.owner = THIS_MODULE;
2378 vsock_device.minor = MISC_DYNAMIC_MINOR;
2379 err = misc_register(&vsock_device);
2381 pr_err("Failed to register misc device\n");
2382 goto err_reset_transport;
2385 err = proto_register(&vsock_proto, 1); /* we want our slab */
2387 pr_err("Cannot register vsock protocol\n");
2388 goto err_deregister_misc;
2391 err = sock_register(&vsock_family_ops);
2393 pr_err("could not register af_vsock (%d) address family: %d\n",
2395 goto err_unregister_proto;
2398 vsock_bpf_build_proto();
2402 err_unregister_proto:
2403 proto_unregister(&vsock_proto);
2404 err_deregister_misc:
2405 misc_deregister(&vsock_device);
2406 err_reset_transport:
2410 static void __exit vsock_exit(void)
2412 misc_deregister(&vsock_device);
2413 sock_unregister(AF_VSOCK);
2414 proto_unregister(&vsock_proto);
2417 const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)
2419 return vsk->transport;
2421 EXPORT_SYMBOL_GPL(vsock_core_get_transport);
2423 int vsock_core_register(const struct vsock_transport *t, int features)
2425 const struct vsock_transport *t_h2g, *t_g2h, *t_dgram, *t_local;
2426 int err = mutex_lock_interruptible(&vsock_register_mutex);
2431 t_h2g = transport_h2g;
2432 t_g2h = transport_g2h;
2433 t_dgram = transport_dgram;
2434 t_local = transport_local;
2436 if (features & VSOCK_TRANSPORT_F_H2G) {
2444 if (features & VSOCK_TRANSPORT_F_G2H) {
2452 if (features & VSOCK_TRANSPORT_F_DGRAM) {
2460 if (features & VSOCK_TRANSPORT_F_LOCAL) {
2468 transport_h2g = t_h2g;
2469 transport_g2h = t_g2h;
2470 transport_dgram = t_dgram;
2471 transport_local = t_local;
2474 mutex_unlock(&vsock_register_mutex);
2477 EXPORT_SYMBOL_GPL(vsock_core_register);
2479 void vsock_core_unregister(const struct vsock_transport *t)
2481 mutex_lock(&vsock_register_mutex);
2483 if (transport_h2g == t)
2484 transport_h2g = NULL;
2486 if (transport_g2h == t)
2487 transport_g2h = NULL;
2489 if (transport_dgram == t)
2490 transport_dgram = NULL;
2492 if (transport_local == t)
2493 transport_local = NULL;
2495 mutex_unlock(&vsock_register_mutex);
2497 EXPORT_SYMBOL_GPL(vsock_core_unregister);
2499 module_init(vsock_init);
2500 module_exit(vsock_exit);
2502 MODULE_AUTHOR("VMware, Inc.");
2503 MODULE_DESCRIPTION("VMware Virtual Socket Family");
2504 MODULE_VERSION("1.0.2.0-k");
2505 MODULE_LICENSE("GPL v2");