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