af_vsock.c 54.4 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
A
Andy King 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/*
 * VMware vSockets Driver
 *
 * Copyright (C) 2007-2013 VMware, Inc. All rights reserved.
 */

/* Implementation notes:
 *
 * - There are two kinds of sockets: those created by user action (such as
 * calling socket(2)) and those created by incoming connection request packets.
 *
 * - There are two "global" tables, one for bound sockets (sockets that have
 * specified an address that they are responsible for) and one for connected
 * sockets (sockets that have established a connection with another socket).
 * These tables are "global" in that all sockets on the system are placed
 * within them. - Note, though, that the bound table contains an extra entry
 * for a list of unbound sockets and SOCK_DGRAM sockets will always remain in
 * that list. The bound table is used solely for lookup of sockets when packets
 * are received and that's not necessary for SOCK_DGRAM sockets since we create
 * a datagram handle for each and need not perform a lookup.  Keeping SOCK_DGRAM
 * sockets out of the bound hash buckets will reduce the chance of collisions
 * when looking for SOCK_STREAM sockets and prevents us from having to check the
 * socket type in the hash table lookups.
 *
 * - Sockets created by user action will either be "client" sockets that
 * initiate a connection or "server" sockets that listen for connections; we do
 * not support simultaneous connects (two "client" sockets connecting).
 *
 * - "Server" sockets are referred to as listener sockets throughout this
31
 * implementation because they are in the TCP_LISTEN state.  When a
32 33 34 35 36 37 38 39 40 41 42 43 44
 * connection request is received (the second kind of socket mentioned above),
 * we create a new socket and refer to it as a pending socket.  These pending
 * sockets are placed on the pending connection list of the listener socket.
 * When future packets are received for the address the listener socket is
 * bound to, we check if the source of the packet is from one that has an
 * existing pending connection.  If it does, we process the packet for the
 * pending socket.  When that socket reaches the connected state, it is removed
 * from the listener socket's pending list and enqueued in the listener
 * socket's accept queue.  Callers of accept(2) will accept connected sockets
 * from the listener socket's accept queue.  If the socket cannot be accepted
 * for some reason then it is marked rejected.  Once the connection is
 * accepted, it is owned by the user process and the responsibility for cleanup
 * falls with that user process.
A
Andy King 已提交
45 46 47 48 49 50 51 52 53 54 55
 *
 * - It is possible that these pending sockets will never reach the connected
 * state; in fact, we may never receive another packet after the connection
 * request.  Because of this, we must schedule a cleanup function to run in the
 * future, after some amount of time passes where a connection should have been
 * established.  This function ensures that the socket is off all lists so it
 * cannot be retrieved, then drops all references to the socket so it is cleaned
 * up (sock_put() -> sk_free() -> our sk_destruct implementation).  Note this
 * function will also cleanup rejected sockets, those that reach the connected
 * state but leave it before they have been accepted.
 *
56 57 58 59 60 61 62 63
 * - Lock ordering for pending or accept queue sockets is:
 *
 *     lock_sock(listener);
 *     lock_sock_nested(pending, SINGLE_DEPTH_NESTING);
 *
 * Using explicit nested locking keeps lockdep happy since normally only one
 * lock of a given class may be taken at a time.
 *
A
Andy King 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76
 * - Sockets created by user action will be cleaned up when the user process
 * calls close(2), causing our release implementation to be called. Our release
 * implementation will perform some cleanup then drop the last reference so our
 * sk_destruct implementation is invoked.  Our sk_destruct implementation will
 * perform additional cleanup that's common for both types of sockets.
 *
 * - A socket's reference count is what ensures that the structure won't be
 * freed.  Each entry in a list (such as the "global" bound and connected tables
 * and the listener socket's pending list and connected queue) ensures a
 * reference.  When we defer work until process context and pass a socket as our
 * argument, we must ensure the reference count is increased to ensure the
 * socket isn't freed before the function is run; the deferred function will
 * then drop the reference.
77 78 79 80 81 82 83 84 85
 *
 * - sk->sk_state uses the TCP state constants because they are widely used by
 * other address families and exposed to userspace tools like ss(8):
 *
 *   TCP_CLOSE - unconnected
 *   TCP_SYN_SENT - connecting
 *   TCP_ESTABLISHED - connected
 *   TCP_CLOSING - disconnecting
 *   TCP_LISTEN - listening
A
Andy King 已提交
86 87 88 89 90 91 92 93
 */

#include <linux/types.h>
#include <linux/bitops.h>
#include <linux/cred.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/kernel.h>
94
#include <linux/sched/signal.h>
A
Andy King 已提交
95 96 97 98 99 100 101
#include <linux/kmod.h>
#include <linux/list.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/net.h>
#include <linux/poll.h>
102
#include <linux/random.h>
A
Andy King 已提交
103 104 105 106 107 108 109 110
#include <linux/skbuff.h>
#include <linux/smp.h>
#include <linux/socket.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <net/sock.h>
111
#include <net/af_vsock.h>
A
Andy King 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr);
static void vsock_sk_destruct(struct sock *sk);
static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb);

/* Protocol family. */
static struct proto vsock_proto = {
	.name = "AF_VSOCK",
	.owner = THIS_MODULE,
	.obj_size = sizeof(struct vsock_sock),
};

/* The default peer timeout indicates how long we will wait for a peer response
 * to a control message.
 */
#define VSOCK_DEFAULT_CONNECT_TIMEOUT (2 * HZ)

129 130 131 132
#define VSOCK_DEFAULT_BUFFER_SIZE     (1024 * 256)
#define VSOCK_DEFAULT_BUFFER_MAX_SIZE (1024 * 256)
#define VSOCK_DEFAULT_BUFFER_MIN_SIZE 128

133 134 135 136 137 138
/* Transport used for host->guest communication */
static const struct vsock_transport *transport_h2g;
/* Transport used for guest->host communication */
static const struct vsock_transport *transport_g2h;
/* Transport used for DGRAM communication */
static const struct vsock_transport *transport_dgram;
139 140
/* Transport used for local communication */
static const struct vsock_transport *transport_local;
A
Andy King 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
static DEFINE_MUTEX(vsock_register_mutex);

/**** UTILS ****/

/* Each bound VSocket is stored in the bind hash table and each connected
 * VSocket is stored in the connected hash table.
 *
 * Unbound sockets are all put on the same list attached to the end of the hash
 * table (vsock_unbound_sockets).  Bound sockets are added to the hash table in
 * the bucket that their local address hashes to (vsock_bound_sockets(addr)
 * represents the list that addr hashes to).
 *
 * Specifically, we initialize the vsock_bind_table array to a size of
 * VSOCK_HASH_SIZE + 1 so that vsock_bind_table[0] through
 * vsock_bind_table[VSOCK_HASH_SIZE - 1] are for bound sockets and
 * vsock_bind_table[VSOCK_HASH_SIZE] is for unbound sockets.  The hash function
157
 * mods with VSOCK_HASH_SIZE to ensure this.
A
Andy King 已提交
158 159 160
 */
#define MAX_PORT_RETRIES        24

161
#define VSOCK_HASH(addr)        ((addr)->svm_port % VSOCK_HASH_SIZE)
A
Andy King 已提交
162 163 164 165 166
#define vsock_bound_sockets(addr) (&vsock_bind_table[VSOCK_HASH(addr)])
#define vsock_unbound_sockets     (&vsock_bind_table[VSOCK_HASH_SIZE])

/* XXX This can probably be implemented in a better way. */
#define VSOCK_CONN_HASH(src, dst)				\
167
	(((src)->svm_cid ^ (dst)->svm_port) % VSOCK_HASH_SIZE)
A
Andy King 已提交
168 169 170 171 172
#define vsock_connected_sockets(src, dst)		\
	(&vsock_connected_table[VSOCK_CONN_HASH(src, dst)])
#define vsock_connected_sockets_vsk(vsk)				\
	vsock_connected_sockets(&(vsk)->remote_addr, &(vsk)->local_addr)

173 174 175 176 177 178
struct list_head vsock_bind_table[VSOCK_HASH_SIZE + 1];
EXPORT_SYMBOL_GPL(vsock_bind_table);
struct list_head vsock_connected_table[VSOCK_HASH_SIZE];
EXPORT_SYMBOL_GPL(vsock_connected_table);
DEFINE_SPINLOCK(vsock_table_lock);
EXPORT_SYMBOL_GPL(vsock_table_lock);
A
Andy King 已提交
179

180 181 182 183 184 185 186 187 188 189 190 191
/* Autobind this socket to the local address if necessary. */
static int vsock_auto_bind(struct vsock_sock *vsk)
{
	struct sock *sk = sk_vsock(vsk);
	struct sockaddr_vm local_addr;

	if (vsock_addr_bound(&vsk->local_addr))
		return 0;
	vsock_addr_init(&local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
	return __vsock_bind(sk, &local_addr);
}

192
static void vsock_init_tables(void)
A
Andy King 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
{
	int i;

	for (i = 0; i < ARRAY_SIZE(vsock_bind_table); i++)
		INIT_LIST_HEAD(&vsock_bind_table[i]);

	for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++)
		INIT_LIST_HEAD(&vsock_connected_table[i]);
}

static void __vsock_insert_bound(struct list_head *list,
				 struct vsock_sock *vsk)
{
	sock_hold(&vsk->sk);
	list_add(&vsk->bound_table, list);
}

static void __vsock_insert_connected(struct list_head *list,
				     struct vsock_sock *vsk)
{
	sock_hold(&vsk->sk);
	list_add(&vsk->connected_table, list);
}

static void __vsock_remove_bound(struct vsock_sock *vsk)
{
	list_del_init(&vsk->bound_table);
	sock_put(&vsk->sk);
}

static void __vsock_remove_connected(struct vsock_sock *vsk)
{
	list_del_init(&vsk->connected_table);
	sock_put(&vsk->sk);
}

static struct sock *__vsock_find_bound_socket(struct sockaddr_vm *addr)
{
	struct vsock_sock *vsk;

233 234
	list_for_each_entry(vsk, vsock_bound_sockets(addr), bound_table) {
		if (vsock_addr_equals_addr(addr, &vsk->local_addr))
A
Andy King 已提交
235 236
			return sk_vsock(vsk);

237 238 239 240 241 242
		if (addr->svm_port == vsk->local_addr.svm_port &&
		    (vsk->local_addr.svm_cid == VMADDR_CID_ANY ||
		     addr->svm_cid == VMADDR_CID_ANY))
			return sk_vsock(vsk);
	}

A
Andy King 已提交
243 244 245 246 247 248 249 250 251 252
	return NULL;
}

static struct sock *__vsock_find_connected_socket(struct sockaddr_vm *src,
						  struct sockaddr_vm *dst)
{
	struct vsock_sock *vsk;

	list_for_each_entry(vsk, vsock_connected_sockets(src, dst),
			    connected_table) {
253 254
		if (vsock_addr_equals_addr(src, &vsk->remote_addr) &&
		    dst->svm_port == vsk->local_addr.svm_port) {
A
Andy King 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
			return sk_vsock(vsk);
		}
	}

	return NULL;
}

static void vsock_insert_unbound(struct vsock_sock *vsk)
{
	spin_lock_bh(&vsock_table_lock);
	__vsock_insert_bound(vsock_unbound_sockets, vsk);
	spin_unlock_bh(&vsock_table_lock);
}

void vsock_insert_connected(struct vsock_sock *vsk)
{
	struct list_head *list = vsock_connected_sockets(
		&vsk->remote_addr, &vsk->local_addr);

	spin_lock_bh(&vsock_table_lock);
	__vsock_insert_connected(list, vsk);
	spin_unlock_bh(&vsock_table_lock);
}
EXPORT_SYMBOL_GPL(vsock_insert_connected);

void vsock_remove_bound(struct vsock_sock *vsk)
{
	spin_lock_bh(&vsock_table_lock);
283 284
	if (__vsock_in_bound_table(vsk))
		__vsock_remove_bound(vsk);
A
Andy King 已提交
285 286 287 288 289 290 291
	spin_unlock_bh(&vsock_table_lock);
}
EXPORT_SYMBOL_GPL(vsock_remove_bound);

void vsock_remove_connected(struct vsock_sock *vsk)
{
	spin_lock_bh(&vsock_table_lock);
292 293
	if (__vsock_in_connected_table(vsk))
		__vsock_remove_connected(vsk);
A
Andy King 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
	spin_unlock_bh(&vsock_table_lock);
}
EXPORT_SYMBOL_GPL(vsock_remove_connected);

struct sock *vsock_find_bound_socket(struct sockaddr_vm *addr)
{
	struct sock *sk;

	spin_lock_bh(&vsock_table_lock);
	sk = __vsock_find_bound_socket(addr);
	if (sk)
		sock_hold(sk);

	spin_unlock_bh(&vsock_table_lock);

	return sk;
}
EXPORT_SYMBOL_GPL(vsock_find_bound_socket);

struct sock *vsock_find_connected_socket(struct sockaddr_vm *src,
					 struct sockaddr_vm *dst)
{
	struct sock *sk;

	spin_lock_bh(&vsock_table_lock);
	sk = __vsock_find_connected_socket(src, dst);
	if (sk)
		sock_hold(sk);

	spin_unlock_bh(&vsock_table_lock);

	return sk;
}
EXPORT_SYMBOL_GPL(vsock_find_connected_socket);

329 330
void vsock_remove_sock(struct vsock_sock *vsk)
{
331 332
	vsock_remove_bound(vsk);
	vsock_remove_connected(vsk);
333 334 335
}
EXPORT_SYMBOL_GPL(vsock_remove_sock);

A
Andy King 已提交
336 337 338 339 340 341 342 343 344
void vsock_for_each_connected_socket(void (*fn)(struct sock *sk))
{
	int i;

	spin_lock_bh(&vsock_table_lock);

	for (i = 0; i < ARRAY_SIZE(vsock_connected_table); i++) {
		struct vsock_sock *vsk;
		list_for_each_entry(vsk, &vsock_connected_table[i],
345
				    connected_table)
A
Andy King 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
			fn(sk_vsock(vsk));
	}

	spin_unlock_bh(&vsock_table_lock);
}
EXPORT_SYMBOL_GPL(vsock_for_each_connected_socket);

void vsock_add_pending(struct sock *listener, struct sock *pending)
{
	struct vsock_sock *vlistener;
	struct vsock_sock *vpending;

	vlistener = vsock_sk(listener);
	vpending = vsock_sk(pending);

	sock_hold(pending);
	sock_hold(listener);
	list_add_tail(&vpending->pending_links, &vlistener->pending_links);
}
EXPORT_SYMBOL_GPL(vsock_add_pending);

void vsock_remove_pending(struct sock *listener, struct sock *pending)
{
	struct vsock_sock *vpending = vsock_sk(pending);

	list_del_init(&vpending->pending_links);
	sock_put(listener);
	sock_put(pending);
}
EXPORT_SYMBOL_GPL(vsock_remove_pending);

void vsock_enqueue_accept(struct sock *listener, struct sock *connected)
{
	struct vsock_sock *vlistener;
	struct vsock_sock *vconnected;

	vlistener = vsock_sk(listener);
	vconnected = vsock_sk(connected);

	sock_hold(connected);
	sock_hold(listener);
	list_add_tail(&vconnected->accept_queue, &vlistener->accept_queue);
}
EXPORT_SYMBOL_GPL(vsock_enqueue_accept);

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
static bool vsock_use_local_transport(unsigned int remote_cid)
{
	if (!transport_local)
		return false;

	if (remote_cid == VMADDR_CID_LOCAL)
		return true;

	if (transport_g2h) {
		return remote_cid == transport_g2h->get_local_cid();
	} else {
		return remote_cid == VMADDR_CID_HOST;
	}
}

406 407 408 409 410 411 412 413 414 415
static void vsock_deassign_transport(struct vsock_sock *vsk)
{
	if (!vsk->transport)
		return;

	vsk->transport->destruct(vsk);
	module_put(vsk->transport->module);
	vsk->transport = NULL;
}

416 417 418 419 420 421
/* Assign a transport to a socket and call the .init transport callback.
 *
 * Note: for stream socket this must be called when vsk->remote_addr is set
 * (e.g. during the connect() or when a connection request on a listener
 * socket is received).
 * The vsk->remote_addr is used to decide which transport to use:
422 423
 *  - remote CID == VMADDR_CID_LOCAL or g2h->local_cid or VMADDR_CID_HOST if
 *    g2h is not loaded, will use local transport;
424 425
 *  - remote CID <= VMADDR_CID_HOST or h2g is not loaded or remote flags field
 *    includes VMADDR_FLAG_TO_HOST flag value, will use guest->host transport;
426 427 428 429 430 431 432
 *  - remote CID > VMADDR_CID_HOST will use host->guest transport;
 */
int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)
{
	const struct vsock_transport *new_transport;
	struct sock *sk = sk_vsock(vsk);
	unsigned int remote_cid = vsk->remote_addr.svm_cid;
433
	__u8 remote_flags;
434
	int ret;
435

436 437 438 439 440 441 442 443 444 445 446 447
	/* If the packet is coming with the source and destination CIDs higher
	 * than VMADDR_CID_HOST, then a vsock channel where all the packets are
	 * forwarded to the host should be established. Then the host will
	 * need to forward the packets to the guest.
	 *
	 * The flag is set on the (listen) receive path (psk is not NULL). On
	 * the connect path the flag can be set by the user space application.
	 */
	if (psk && vsk->local_addr.svm_cid > VMADDR_CID_HOST &&
	    vsk->remote_addr.svm_cid > VMADDR_CID_HOST)
		vsk->remote_addr.svm_flags |= VMADDR_FLAG_TO_HOST;

448 449
	remote_flags = vsk->remote_addr.svm_flags;

450 451 452 453 454
	switch (sk->sk_type) {
	case SOCK_DGRAM:
		new_transport = transport_dgram;
		break;
	case SOCK_STREAM:
455 456
		if (vsock_use_local_transport(remote_cid))
			new_transport = transport_local;
457 458
		else if (remote_cid <= VMADDR_CID_HOST || !transport_h2g ||
			 (remote_flags & VMADDR_FLAG_TO_HOST))
459 460 461 462 463 464 465 466 467 468 469 470
			new_transport = transport_g2h;
		else
			new_transport = transport_h2g;
		break;
	default:
		return -ESOCKTNOSUPPORT;
	}

	if (vsk->transport) {
		if (vsk->transport == new_transport)
			return 0;

471 472 473 474 475 476
		/* transport->release() must be called with sock lock acquired.
		 * This path can only be taken during vsock_stream_connect(),
		 * where we have already held the sock lock.
		 * In the other cases, this function is called on a new socket
		 * which is not assigned to any transport.
		 */
477
		vsk->transport->release(vsk);
478
		vsock_deassign_transport(vsk);
479 480
	}

481 482 483 484
	/* We increase the module refcnt to prevent the transport unloading
	 * while there are open sockets assigned to it.
	 */
	if (!new_transport || !try_module_get(new_transport->module))
485 486
		return -ENODEV;

487 488 489 490 491 492
	ret = new_transport->init(vsk, psk);
	if (ret) {
		module_put(new_transport->module);
		return ret;
	}

493 494
	vsk->transport = new_transport;

495
	return 0;
496 497 498 499 500 501 502 503 504 505 506
}
EXPORT_SYMBOL_GPL(vsock_assign_transport);

bool vsock_find_cid(unsigned int cid)
{
	if (transport_g2h && cid == transport_g2h->get_local_cid())
		return true;

	if (transport_h2g && cid == VMADDR_CID_HOST)
		return true;

507 508 509
	if (transport_local && cid == VMADDR_CID_LOCAL)
		return true;

510 511 512 513
	return false;
}
EXPORT_SYMBOL_GPL(vsock_find_cid);

A
Andy King 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
static struct sock *vsock_dequeue_accept(struct sock *listener)
{
	struct vsock_sock *vlistener;
	struct vsock_sock *vconnected;

	vlistener = vsock_sk(listener);

	if (list_empty(&vlistener->accept_queue))
		return NULL;

	vconnected = list_entry(vlistener->accept_queue.next,
				struct vsock_sock, accept_queue);

	list_del_init(&vconnected->accept_queue);
	sock_put(listener);
	/* The caller will need a reference on the connected socket so we let
	 * it call sock_put().
	 */

	return sk_vsock(vconnected);
}

static bool vsock_is_accept_queue_empty(struct sock *sk)
{
	struct vsock_sock *vsk = vsock_sk(sk);
	return list_empty(&vsk->accept_queue);
}

static bool vsock_is_pending(struct sock *sk)
{
	struct vsock_sock *vsk = vsock_sk(sk);
	return !list_empty(&vsk->pending_links);
}

static int vsock_send_shutdown(struct sock *sk, int mode)
{
550 551
	struct vsock_sock *vsk = vsock_sk(sk);

552 553 554
	if (!vsk->transport)
		return -ENODEV;

555
	return vsk->transport->shutdown(vsk, mode);
A
Andy King 已提交
556 557
}

558
static void vsock_pending_work(struct work_struct *work)
A
Andy King 已提交
559 560 561 562 563 564
{
	struct sock *sk;
	struct sock *listener;
	struct vsock_sock *vsk;
	bool cleanup;

565
	vsk = container_of(work, struct vsock_sock, pending_work.work);
A
Andy King 已提交
566 567 568 569 570
	sk = sk_vsock(vsk);
	listener = vsk->listener;
	cleanup = true;

	lock_sock(listener);
571
	lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
A
Andy King 已提交
572 573 574

	if (vsock_is_pending(sk)) {
		vsock_remove_pending(listener, sk);
575

576
		sk_acceptq_removed(listener);
A
Andy King 已提交
577 578 579 580 581 582 583 584 585 586 587 588 589 590
	} else if (!vsk->rejected) {
		/* We are not on the pending list and accept() did not reject
		 * us, so we must have been accepted by our user process.  We
		 * just need to drop our references to the sockets and be on
		 * our way.
		 */
		cleanup = false;
		goto out;
	}

	/* We need to remove ourself from the global connected sockets list so
	 * incoming packets can't find this socket, and to reduce the reference
	 * count.
	 */
591
	vsock_remove_connected(vsk);
A
Andy King 已提交
592

593
	sk->sk_state = TCP_CLOSE;
A
Andy King 已提交
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

out:
	release_sock(sk);
	release_sock(listener);
	if (cleanup)
		sock_put(sk);

	sock_put(sk);
	sock_put(listener);
}

/**** SOCKET OPERATIONS ****/

static int __vsock_bind_stream(struct vsock_sock *vsk,
			       struct sockaddr_vm *addr)
{
610
	static u32 port;
A
Andy King 已提交
611 612
	struct sockaddr_vm new_addr;

613 614 615 616
	if (!port)
		port = LAST_RESERVED_PORT + 1 +
			prandom_u32_max(U32_MAX - LAST_RESERVED_PORT);

A
Andy King 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
	vsock_addr_init(&new_addr, addr->svm_cid, addr->svm_port);

	if (addr->svm_port == VMADDR_PORT_ANY) {
		bool found = false;
		unsigned int i;

		for (i = 0; i < MAX_PORT_RETRIES; i++) {
			if (port <= LAST_RESERVED_PORT)
				port = LAST_RESERVED_PORT + 1;

			new_addr.svm_port = port++;

			if (!__vsock_find_bound_socket(&new_addr)) {
				found = true;
				break;
			}
		}

		if (!found)
			return -EADDRNOTAVAIL;
	} else {
		/* If port is in reserved range, ensure caller
		 * has necessary privileges.
		 */
		if (addr->svm_port <= LAST_RESERVED_PORT &&
		    !capable(CAP_NET_BIND_SERVICE)) {
			return -EACCES;
		}

		if (__vsock_find_bound_socket(&new_addr))
			return -EADDRINUSE;
	}

	vsock_addr_init(&vsk->local_addr, new_addr.svm_cid, new_addr.svm_port);

	/* Remove stream sockets from the unbound list and add them to the hash
	 * table for easy lookup by its address.  The unbound list is simply an
	 * extra entry at the end of the hash table, a trick used by AF_UNIX.
	 */
	__vsock_remove_bound(vsk);
	__vsock_insert_bound(vsock_bound_sockets(&vsk->local_addr), vsk);

	return 0;
}

static int __vsock_bind_dgram(struct vsock_sock *vsk,
			      struct sockaddr_vm *addr)
{
665
	return vsk->transport->dgram_bind(vsk, addr);
A
Andy King 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679
}

static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr)
{
	struct vsock_sock *vsk = vsock_sk(sk);
	int retval;

	/* First ensure this socket isn't already bound. */
	if (vsock_addr_bound(&vsk->local_addr))
		return -EINVAL;

	/* Now bind to the provided address or select appropriate values if
	 * none are provided (VMADDR_CID_ANY and VMADDR_PORT_ANY).  Note that
	 * like AF_INET prevents binding to a non-local IP address (in most
680
	 * cases), we only allow binding to a local CID.
A
Andy King 已提交
681
	 */
682
	if (addr->svm_cid != VMADDR_CID_ANY && !vsock_find_cid(addr->svm_cid))
A
Andy King 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
		return -EADDRNOTAVAIL;

	switch (sk->sk_socket->type) {
	case SOCK_STREAM:
		spin_lock_bh(&vsock_table_lock);
		retval = __vsock_bind_stream(vsk, addr);
		spin_unlock_bh(&vsock_table_lock);
		break;

	case SOCK_DGRAM:
		retval = __vsock_bind_dgram(vsk, addr);
		break;

	default:
		retval = -EINVAL;
		break;
	}

	return retval;
}

704 705
static void vsock_connect_timeout(struct work_struct *work);

706 707 708 709 710 711
static struct sock *__vsock_create(struct net *net,
				   struct socket *sock,
				   struct sock *parent,
				   gfp_t priority,
				   unsigned short type,
				   int kern)
A
Andy King 已提交
712 713 714 715 716
{
	struct sock *sk;
	struct vsock_sock *psk;
	struct vsock_sock *vsk;

717
	sk = sk_alloc(net, AF_VSOCK, priority, &vsock_proto, kern);
A
Andy King 已提交
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
	if (!sk)
		return NULL;

	sock_init_data(sock, sk);

	/* sk->sk_type is normally set in sock_init_data, but only if sock is
	 * non-NULL. We make sure that our sockets always have a type by
	 * setting it here if needed.
	 */
	if (!sock)
		sk->sk_type = type;

	vsk = vsock_sk(sk);
	vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
	vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);

	sk->sk_destruct = vsock_sk_destruct;
	sk->sk_backlog_rcv = vsock_queue_rcv_skb;
	sock_reset_flag(sk, SOCK_DONE);

	INIT_LIST_HEAD(&vsk->bound_table);
	INIT_LIST_HEAD(&vsk->connected_table);
	vsk->listener = NULL;
	INIT_LIST_HEAD(&vsk->pending_links);
	INIT_LIST_HEAD(&vsk->accept_queue);
	vsk->rejected = false;
	vsk->sent_request = false;
	vsk->ignore_connecting_rst = false;
	vsk->peer_shutdown = 0;
747 748
	INIT_DELAYED_WORK(&vsk->connect_work, vsock_connect_timeout);
	INIT_DELAYED_WORK(&vsk->pending_work, vsock_pending_work);
A
Andy King 已提交
749 750 751 752 753 754

	psk = parent ? vsock_sk(parent) : NULL;
	if (parent) {
		vsk->trusted = psk->trusted;
		vsk->owner = get_cred(psk->owner);
		vsk->connect_timeout = psk->connect_timeout;
755 756 757
		vsk->buffer_size = psk->buffer_size;
		vsk->buffer_min_size = psk->buffer_min_size;
		vsk->buffer_max_size = psk->buffer_max_size;
758
		security_sk_clone(parent, sk);
A
Andy King 已提交
759
	} else {
760
		vsk->trusted = ns_capable_noaudit(&init_user_ns, CAP_NET_ADMIN);
A
Andy King 已提交
761 762
		vsk->owner = get_current_cred();
		vsk->connect_timeout = VSOCK_DEFAULT_CONNECT_TIMEOUT;
763 764 765
		vsk->buffer_size = VSOCK_DEFAULT_BUFFER_SIZE;
		vsk->buffer_min_size = VSOCK_DEFAULT_BUFFER_MIN_SIZE;
		vsk->buffer_max_size = VSOCK_DEFAULT_BUFFER_MAX_SIZE;
A
Andy King 已提交
766 767 768 769 770
	}

	return sk;
}

771
static void __vsock_release(struct sock *sk, int level)
A
Andy King 已提交
772 773 774 775 776 777 778 779
{
	if (sk) {
		struct sock *pending;
		struct vsock_sock *vsk;

		vsk = vsock_sk(sk);
		pending = NULL;	/* Compiler warning. */

780 781 782 783 784 785
		/* When "level" is SINGLE_DEPTH_NESTING, use the nested
		 * version to avoid the warning "possible recursive locking
		 * detected". When "level" is 0, lock_sock_nested(sk, level)
		 * is the same as lock_sock(sk).
		 */
		lock_sock_nested(sk, level);
786 787 788 789 790 791

		if (vsk->transport)
			vsk->transport->release(vsk);
		else if (sk->sk_type == SOCK_STREAM)
			vsock_remove_sock(vsk);

A
Andy King 已提交
792 793 794
		sock_orphan(sk);
		sk->sk_shutdown = SHUTDOWN_MASK;

795
		skb_queue_purge(&sk->sk_receive_queue);
A
Andy King 已提交
796 797 798

		/* Clean up any sockets that never were accepted. */
		while ((pending = vsock_dequeue_accept(sk)) != NULL) {
799
			__vsock_release(pending, SINGLE_DEPTH_NESTING);
A
Andy King 已提交
800 801 802 803 804 805 806 807 808 809 810 811
			sock_put(pending);
		}

		release_sock(sk);
		sock_put(sk);
	}
}

static void vsock_sk_destruct(struct sock *sk)
{
	struct vsock_sock *vsk = vsock_sk(sk);

812
	vsock_deassign_transport(vsk);
A
Andy King 已提交
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833

	/* When clearing these addresses, there's no need to set the family and
	 * possibly register the address family with the kernel.
	 */
	vsock_addr_init(&vsk->local_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);
	vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY, VMADDR_PORT_ANY);

	put_cred(vsk->owner);
}

static int vsock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
	int err;

	err = sock_queue_rcv_skb(sk, skb);
	if (err)
		kfree_skb(skb);

	return err;
}

834 835 836 837 838 839 840
struct sock *vsock_create_connected(struct sock *parent)
{
	return __vsock_create(sock_net(parent), NULL, parent, GFP_KERNEL,
			      parent->sk_type, 0);
}
EXPORT_SYMBOL_GPL(vsock_create_connected);

A
Andy King 已提交
841 842
s64 vsock_stream_has_data(struct vsock_sock *vsk)
{
843
	return vsk->transport->stream_has_data(vsk);
A
Andy King 已提交
844 845 846 847 848
}
EXPORT_SYMBOL_GPL(vsock_stream_has_data);

s64 vsock_stream_has_space(struct vsock_sock *vsk)
{
849
	return vsk->transport->stream_has_space(vsk);
A
Andy King 已提交
850 851 852 853 854
}
EXPORT_SYMBOL_GPL(vsock_stream_has_space);

static int vsock_release(struct socket *sock)
{
855
	__vsock_release(sock->sk, 0);
A
Andy King 已提交
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
	sock->sk = NULL;
	sock->state = SS_FREE;

	return 0;
}

static int
vsock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
	int err;
	struct sock *sk;
	struct sockaddr_vm *vm_addr;

	sk = sock->sk;

	if (vsock_addr_cast(addr, addr_len, &vm_addr) != 0)
		return -EINVAL;

	lock_sock(sk);
	err = __vsock_bind(sk, vm_addr);
	release_sock(sk);

	return err;
}

static int vsock_getname(struct socket *sock,
882
			 struct sockaddr *addr, int peer)
A
Andy King 已提交
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
{
	int err;
	struct sock *sk;
	struct vsock_sock *vsk;
	struct sockaddr_vm *vm_addr;

	sk = sock->sk;
	vsk = vsock_sk(sk);
	err = 0;

	lock_sock(sk);

	if (peer) {
		if (sock->state != SS_CONNECTED) {
			err = -ENOTCONN;
			goto out;
		}
		vm_addr = &vsk->remote_addr;
	} else {
		vm_addr = &vsk->local_addr;
	}

	if (!vm_addr) {
		err = -EINVAL;
		goto out;
	}

	/* sys_getsockname() and sys_getpeername() pass us a
	 * MAX_SOCK_ADDR-sized buffer and don't set addr_len.  Unfortunately
	 * that macro is defined in socket.c instead of .h, so we hardcode its
	 * value here.
	 */
	BUILD_BUG_ON(sizeof(*vm_addr) > 128);
	memcpy(addr, vm_addr, sizeof(*vm_addr));
917
	err = sizeof(*vm_addr);
A
Andy King 已提交
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946

out:
	release_sock(sk);
	return err;
}

static int vsock_shutdown(struct socket *sock, int mode)
{
	int err;
	struct sock *sk;

	/* User level uses SHUT_RD (0) and SHUT_WR (1), but the kernel uses
	 * RCV_SHUTDOWN (1) and SEND_SHUTDOWN (2), so we must increment mode
	 * here like the other address families do.  Note also that the
	 * increment makes SHUT_RDWR (2) into RCV_SHUTDOWN | SEND_SHUTDOWN (3),
	 * which is what we want.
	 */
	mode++;

	if ((mode & ~SHUTDOWN_MASK) || !mode)
		return -EINVAL;

	/* If this is a STREAM socket and it is not connected then bail out
	 * immediately.  If it is a DGRAM socket then we must first kick the
	 * socket so that it wakes up from any sleeping calls, for example
	 * recv(), and then afterwards return the error.
	 */

	sk = sock->sk;
947 948

	lock_sock(sk);
A
Andy King 已提交
949 950 951
	if (sock->state == SS_UNCONNECTED) {
		err = -ENOTCONN;
		if (sk->sk_type == SOCK_STREAM)
952
			goto out;
A
Andy King 已提交
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
	} else {
		sock->state = SS_DISCONNECTING;
		err = 0;
	}

	/* Receive and send shutdowns are treated alike. */
	mode = mode & (RCV_SHUTDOWN | SEND_SHUTDOWN);
	if (mode) {
		sk->sk_shutdown |= mode;
		sk->sk_state_change(sk);

		if (sk->sk_type == SOCK_STREAM) {
			sock_reset_flag(sk, SOCK_DONE);
			vsock_send_shutdown(sk, mode);
		}
	}

970 971
out:
	release_sock(sk);
A
Andy King 已提交
972 973 974
	return err;
}

975 976
static __poll_t vsock_poll(struct file *file, struct socket *sock,
			       poll_table *wait)
A
Andy King 已提交
977
{
978 979 980 981 982 983 984 985 986
	struct sock *sk;
	__poll_t mask;
	struct vsock_sock *vsk;

	sk = sock->sk;
	vsk = vsock_sk(sk);

	poll_wait(file, sk_sleep(sk), wait);
	mask = 0;
A
Andy King 已提交
987 988 989

	if (sk->sk_err)
		/* Signify that there has been an error on this socket. */
990
		mask |= EPOLLERR;
A
Andy King 已提交
991 992

	/* INET sockets treat local write shutdown and peer write shutdown as a
993
	 * case of EPOLLHUP set.
A
Andy King 已提交
994 995 996 997
	 */
	if ((sk->sk_shutdown == SHUTDOWN_MASK) ||
	    ((sk->sk_shutdown & SEND_SHUTDOWN) &&
	     (vsk->peer_shutdown & SEND_SHUTDOWN))) {
998
		mask |= EPOLLHUP;
A
Andy King 已提交
999 1000 1001 1002
	}

	if (sk->sk_shutdown & RCV_SHUTDOWN ||
	    vsk->peer_shutdown & SEND_SHUTDOWN) {
1003
		mask |= EPOLLRDHUP;
A
Andy King 已提交
1004 1005 1006 1007 1008 1009 1010
	}

	if (sock->type == SOCK_DGRAM) {
		/* For datagram sockets we can read if there is something in
		 * the queue and write as long as the socket isn't shutdown for
		 * sending.
		 */
1011
		if (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
A
Andy King 已提交
1012
		    (sk->sk_shutdown & RCV_SHUTDOWN)) {
1013
			mask |= EPOLLIN | EPOLLRDNORM;
A
Andy King 已提交
1014 1015 1016
		}

		if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1017
			mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
A
Andy King 已提交
1018 1019

	} else if (sock->type == SOCK_STREAM) {
1020 1021
		const struct vsock_transport *transport;

A
Andy King 已提交
1022 1023
		lock_sock(sk);

1024 1025
		transport = vsk->transport;

A
Andy King 已提交
1026 1027 1028
		/* Listening sockets that have connections in their accept
		 * queue can be read.
		 */
1029
		if (sk->sk_state == TCP_LISTEN
A
Andy King 已提交
1030
		    && !vsock_is_accept_queue_empty(sk))
1031
			mask |= EPOLLIN | EPOLLRDNORM;
A
Andy King 已提交
1032 1033

		/* If there is something in the queue then we can read. */
1034
		if (transport && transport->stream_is_active(vsk) &&
A
Andy King 已提交
1035 1036 1037 1038 1039
		    !(sk->sk_shutdown & RCV_SHUTDOWN)) {
			bool data_ready_now = false;
			int ret = transport->notify_poll_in(
					vsk, 1, &data_ready_now);
			if (ret < 0) {
1040
				mask |= EPOLLERR;
A
Andy King 已提交
1041 1042
			} else {
				if (data_ready_now)
1043
					mask |= EPOLLIN | EPOLLRDNORM;
A
Andy King 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053

			}
		}

		/* Sockets whose connections have been closed, reset, or
		 * terminated should also be considered read, and we check the
		 * shutdown flag for that.
		 */
		if (sk->sk_shutdown & RCV_SHUTDOWN ||
		    vsk->peer_shutdown & SEND_SHUTDOWN) {
1054
			mask |= EPOLLIN | EPOLLRDNORM;
A
Andy King 已提交
1055 1056 1057
		}

		/* Connected sockets that can produce data can be written. */
1058
		if (transport && sk->sk_state == TCP_ESTABLISHED) {
A
Andy King 已提交
1059 1060 1061 1062 1063
			if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
				bool space_avail_now = false;
				int ret = transport->notify_poll_out(
						vsk, 1, &space_avail_now);
				if (ret < 0) {
1064
					mask |= EPOLLERR;
A
Andy King 已提交
1065 1066
				} else {
					if (space_avail_now)
1067
						/* Remove EPOLLWRBAND since INET
A
Andy King 已提交
1068 1069
						 * sockets are not setting it.
						 */
1070
						mask |= EPOLLOUT | EPOLLWRNORM;
A
Andy King 已提交
1071 1072 1073 1074 1075 1076

				}
			}
		}

		/* Simulate INET socket poll behaviors, which sets
1077
		 * EPOLLOUT|EPOLLWRNORM when peer is closed and nothing to read,
A
Andy King 已提交
1078 1079
		 * but local send is not shutdown.
		 */
1080
		if (sk->sk_state == TCP_CLOSE || sk->sk_state == TCP_CLOSING) {
A
Andy King 已提交
1081
			if (!(sk->sk_shutdown & SEND_SHUTDOWN))
1082
				mask |= EPOLLOUT | EPOLLWRNORM;
A
Andy King 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091

		}

		release_sock(sk);
	}

	return mask;
}

1092 1093
static int vsock_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
			       size_t len)
A
Andy King 已提交
1094 1095 1096 1097 1098
{
	int err;
	struct sock *sk;
	struct vsock_sock *vsk;
	struct sockaddr_vm *remote_addr;
1099
	const struct vsock_transport *transport;
A
Andy King 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110

	if (msg->msg_flags & MSG_OOB)
		return -EOPNOTSUPP;

	/* For now, MSG_DONTWAIT is always assumed... */
	err = 0;
	sk = sock->sk;
	vsk = vsock_sk(sk);

	lock_sock(sk);

1111 1112
	transport = vsk->transport;

1113 1114 1115
	err = vsock_auto_bind(vsk);
	if (err)
		goto out;
A
Andy King 已提交
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158


	/* If the provided message contains an address, use that.  Otherwise
	 * fall back on the socket's remote handle (if it has been connected).
	 */
	if (msg->msg_name &&
	    vsock_addr_cast(msg->msg_name, msg->msg_namelen,
			    &remote_addr) == 0) {
		/* Ensure this address is of the right type and is a valid
		 * destination.
		 */

		if (remote_addr->svm_cid == VMADDR_CID_ANY)
			remote_addr->svm_cid = transport->get_local_cid();

		if (!vsock_addr_bound(remote_addr)) {
			err = -EINVAL;
			goto out;
		}
	} else if (sock->state == SS_CONNECTED) {
		remote_addr = &vsk->remote_addr;

		if (remote_addr->svm_cid == VMADDR_CID_ANY)
			remote_addr->svm_cid = transport->get_local_cid();

		/* XXX Should connect() or this function ensure remote_addr is
		 * bound?
		 */
		if (!vsock_addr_bound(&vsk->remote_addr)) {
			err = -EINVAL;
			goto out;
		}
	} else {
		err = -EINVAL;
		goto out;
	}

	if (!transport->dgram_allow(remote_addr->svm_cid,
				    remote_addr->svm_port)) {
		err = -EINVAL;
		goto out;
	}

1159
	err = transport->dgram_enqueue(vsk, remote_addr, msg, len);
A
Andy King 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189

out:
	release_sock(sk);
	return err;
}

static int vsock_dgram_connect(struct socket *sock,
			       struct sockaddr *addr, int addr_len, int flags)
{
	int err;
	struct sock *sk;
	struct vsock_sock *vsk;
	struct sockaddr_vm *remote_addr;

	sk = sock->sk;
	vsk = vsock_sk(sk);

	err = vsock_addr_cast(addr, addr_len, &remote_addr);
	if (err == -EAFNOSUPPORT && remote_addr->svm_family == AF_UNSPEC) {
		lock_sock(sk);
		vsock_addr_init(&vsk->remote_addr, VMADDR_CID_ANY,
				VMADDR_PORT_ANY);
		sock->state = SS_UNCONNECTED;
		release_sock(sk);
		return 0;
	} else if (err != 0)
		return -EINVAL;

	lock_sock(sk);

1190 1191 1192
	err = vsock_auto_bind(vsk);
	if (err)
		goto out;
A
Andy King 已提交
1193

1194 1195
	if (!vsk->transport->dgram_allow(remote_addr->svm_cid,
					 remote_addr->svm_port)) {
A
Andy King 已提交
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
		err = -EINVAL;
		goto out;
	}

	memcpy(&vsk->remote_addr, remote_addr, sizeof(vsk->remote_addr));
	sock->state = SS_CONNECTED;

out:
	release_sock(sk);
	return err;
}

1208 1209
static int vsock_dgram_recvmsg(struct socket *sock, struct msghdr *msg,
			       size_t len, int flags)
A
Andy King 已提交
1210
{
1211 1212 1213
	struct vsock_sock *vsk = vsock_sk(sock->sk);

	return vsk->transport->dgram_dequeue(vsk, msg, len, flags);
A
Andy King 已提交
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
}

static const struct proto_ops vsock_dgram_ops = {
	.family = PF_VSOCK,
	.owner = THIS_MODULE,
	.release = vsock_release,
	.bind = vsock_bind,
	.connect = vsock_dgram_connect,
	.socketpair = sock_no_socketpair,
	.accept = sock_no_accept,
	.getname = vsock_getname,
1225
	.poll = vsock_poll,
A
Andy King 已提交
1226 1227 1228 1229 1230 1231 1232 1233 1234
	.ioctl = sock_no_ioctl,
	.listen = sock_no_listen,
	.shutdown = vsock_shutdown,
	.sendmsg = vsock_dgram_sendmsg,
	.recvmsg = vsock_dgram_recvmsg,
	.mmap = sock_no_mmap,
	.sendpage = sock_no_sendpage,
};

1235 1236
static int vsock_transport_cancel_pkt(struct vsock_sock *vsk)
{
1237 1238
	const struct vsock_transport *transport = vsk->transport;

1239
	if (!transport || !transport->cancel_pkt)
1240 1241 1242 1243 1244
		return -EOPNOTSUPP;

	return transport->cancel_pkt(vsk);
}

A
Andy King 已提交
1245 1246 1247 1248 1249
static void vsock_connect_timeout(struct work_struct *work)
{
	struct sock *sk;
	struct vsock_sock *vsk;

1250
	vsk = container_of(work, struct vsock_sock, connect_work.work);
A
Andy King 已提交
1251 1252 1253
	sk = sk_vsock(vsk);

	lock_sock(sk);
1254
	if (sk->sk_state == TCP_SYN_SENT &&
A
Andy King 已提交
1255
	    (sk->sk_shutdown != SHUTDOWN_MASK)) {
1256
		sk->sk_state = TCP_CLOSE;
A
Andy King 已提交
1257 1258
		sk->sk_err = ETIMEDOUT;
		sk->sk_error_report(sk);
1259
		vsock_transport_cancel_pkt(vsk);
A
Andy King 已提交
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
	}
	release_sock(sk);

	sock_put(sk);
}

static int vsock_stream_connect(struct socket *sock, struct sockaddr *addr,
				int addr_len, int flags)
{
	int err;
	struct sock *sk;
	struct vsock_sock *vsk;
1272
	const struct vsock_transport *transport;
A
Andy King 已提交
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
	struct sockaddr_vm *remote_addr;
	long timeout;
	DEFINE_WAIT(wait);

	err = 0;
	sk = sock->sk;
	vsk = vsock_sk(sk);

	lock_sock(sk);

	/* XXX AF_UNSPEC should make us disconnect like AF_INET. */
	switch (sock->state) {
	case SS_CONNECTED:
		err = -EISCONN;
		goto out;
	case SS_DISCONNECTING:
		err = -EINVAL;
		goto out;
	case SS_CONNECTING:
		/* This continues on so we can move sock into the SS_CONNECTED
		 * state once the connection has completed (at which point err
		 * will be set to zero also).  Otherwise, we will either wait
		 * for the connection or return -EALREADY should this be a
		 * non-blocking call.
		 */
		err = -EALREADY;
		break;
	default:
1301
		if ((sk->sk_state == TCP_LISTEN) ||
A
Andy King 已提交
1302 1303 1304 1305 1306
		    vsock_addr_cast(addr, addr_len, &remote_addr) != 0) {
			err = -EINVAL;
			goto out;
		}

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
		/* Set the remote address that we are connecting to. */
		memcpy(&vsk->remote_addr, remote_addr,
		       sizeof(vsk->remote_addr));

		err = vsock_assign_transport(vsk, NULL);
		if (err)
			goto out;

		transport = vsk->transport;

A
Andy King 已提交
1317 1318 1319
		/* The hypervisor and well-known contexts do not have socket
		 * endpoints.
		 */
1320 1321
		if (!transport ||
		    !transport->stream_allow(remote_addr->svm_cid,
A
Andy King 已提交
1322 1323 1324 1325 1326
					     remote_addr->svm_port)) {
			err = -ENETUNREACH;
			goto out;
		}

1327 1328 1329
		err = vsock_auto_bind(vsk);
		if (err)
			goto out;
A
Andy King 已提交
1330

1331
		sk->sk_state = TCP_SYN_SENT;
A
Andy King 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350

		err = transport->connect(vsk);
		if (err < 0)
			goto out;

		/* Mark sock as connecting and set the error code to in
		 * progress in case this is a non-blocking connect.
		 */
		sock->state = SS_CONNECTING;
		err = -EINPROGRESS;
	}

	/* The receive path will handle all communication until we are able to
	 * enter the connected state.  Here we wait for the connection to be
	 * completed or a notification of an error.
	 */
	timeout = vsk->connect_timeout;
	prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);

1351
	while (sk->sk_state != TCP_ESTABLISHED && sk->sk_err == 0) {
A
Andy King 已提交
1352 1353 1354 1355 1356 1357 1358 1359
		if (flags & O_NONBLOCK) {
			/* If we're not going to block, we schedule a timeout
			 * function to generate a timeout on the connection
			 * attempt, in case the peer doesn't respond in a
			 * timely manner. We hold on to the socket until the
			 * timeout fires.
			 */
			sock_hold(sk);
1360
			schedule_delayed_work(&vsk->connect_work, timeout);
A
Andy King 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371

			/* Skip ahead to preserve error code set above. */
			goto out_wait;
		}

		release_sock(sk);
		timeout = schedule_timeout(timeout);
		lock_sock(sk);

		if (signal_pending(current)) {
			err = sock_intr_errno(timeout);
1372
			sk->sk_state = TCP_CLOSE;
1373
			sock->state = SS_UNCONNECTED;
1374
			vsock_transport_cancel_pkt(vsk);
1375
			goto out_wait;
A
Andy King 已提交
1376 1377
		} else if (timeout == 0) {
			err = -ETIMEDOUT;
1378
			sk->sk_state = TCP_CLOSE;
1379
			sock->state = SS_UNCONNECTED;
1380
			vsock_transport_cancel_pkt(vsk);
1381
			goto out_wait;
A
Andy King 已提交
1382 1383 1384 1385 1386 1387 1388
		}

		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
	}

	if (sk->sk_err) {
		err = -sk->sk_err;
1389
		sk->sk_state = TCP_CLOSE;
1390 1391
		sock->state = SS_UNCONNECTED;
	} else {
A
Andy King 已提交
1392
		err = 0;
1393
	}
A
Andy King 已提交
1394 1395 1396 1397 1398 1399 1400 1401

out_wait:
	finish_wait(sk_sleep(sk), &wait);
out:
	release_sock(sk);
	return err;
}

1402 1403
static int vsock_accept(struct socket *sock, struct socket *newsock, int flags,
			bool kern)
A
Andy King 已提交
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
{
	struct sock *listener;
	int err;
	struct sock *connected;
	struct vsock_sock *vconnected;
	long timeout;
	DEFINE_WAIT(wait);

	err = 0;
	listener = sock->sk;

	lock_sock(listener);

	if (sock->type != SOCK_STREAM) {
		err = -EOPNOTSUPP;
		goto out;
	}

1422
	if (listener->sk_state != TCP_LISTEN) {
A
Andy King 已提交
1423 1424 1425 1426 1427 1428 1429
		err = -EINVAL;
		goto out;
	}

	/* Wait for children sockets to appear; these are the new sockets
	 * created upon connection establishment.
	 */
1430
	timeout = sock_rcvtimeo(listener, flags & O_NONBLOCK);
A
Andy King 已提交
1431 1432 1433 1434 1435 1436
	prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);

	while ((connected = vsock_dequeue_accept(listener)) == NULL &&
	       listener->sk_err == 0) {
		release_sock(listener);
		timeout = schedule_timeout(timeout);
1437
		finish_wait(sk_sleep(listener), &wait);
A
Andy King 已提交
1438 1439 1440 1441
		lock_sock(listener);

		if (signal_pending(current)) {
			err = sock_intr_errno(timeout);
1442
			goto out;
A
Andy King 已提交
1443 1444
		} else if (timeout == 0) {
			err = -EAGAIN;
1445
			goto out;
A
Andy King 已提交
1446 1447 1448 1449
		}

		prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
	}
1450
	finish_wait(sk_sleep(listener), &wait);
A
Andy King 已提交
1451 1452 1453 1454 1455

	if (listener->sk_err)
		err = -listener->sk_err;

	if (connected) {
1456
		sk_acceptq_removed(listener);
A
Andy King 已提交
1457

1458
		lock_sock_nested(connected, SINGLE_DEPTH_NESTING);
A
Andy King 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
		vconnected = vsock_sk(connected);

		/* If the listener socket has received an error, then we should
		 * reject this socket and return.  Note that we simply mark the
		 * socket rejected, drop our reference, and let the cleanup
		 * function handle the cleanup; the fact that we found it in
		 * the listener's accept queue guarantees that the cleanup
		 * function hasn't run yet.
		 */
		if (err) {
			vconnected->rejected = true;
1470 1471 1472
		} else {
			newsock->state = SS_CONNECTED;
			sock_graft(connected, newsock);
A
Andy King 已提交
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
		}

		release_sock(connected);
		sock_put(connected);
	}

out:
	release_sock(listener);
	return err;
}

static int vsock_listen(struct socket *sock, int backlog)
{
	int err;
	struct sock *sk;
	struct vsock_sock *vsk;

	sk = sock->sk;

	lock_sock(sk);

	if (sock->type != SOCK_STREAM) {
		err = -EOPNOTSUPP;
		goto out;
	}

	if (sock->state != SS_UNCONNECTED) {
		err = -EINVAL;
		goto out;
	}

	vsk = vsock_sk(sk);

	if (!vsock_addr_bound(&vsk->local_addr)) {
		err = -EINVAL;
		goto out;
	}

	sk->sk_max_ack_backlog = backlog;
1512
	sk->sk_state = TCP_LISTEN;
A
Andy King 已提交
1513 1514 1515 1516 1517 1518 1519 1520

	err = 0;

out:
	release_sock(sk);
	return err;
}

1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
static void vsock_update_buffer_size(struct vsock_sock *vsk,
				     const struct vsock_transport *transport,
				     u64 val)
{
	if (val > vsk->buffer_max_size)
		val = vsk->buffer_max_size;

	if (val < vsk->buffer_min_size)
		val = vsk->buffer_min_size;

	if (val != vsk->buffer_size &&
	    transport && transport->notify_buffer_size)
		transport->notify_buffer_size(vsk, &val);

	vsk->buffer_size = val;
}

A
Andy King 已提交
1538 1539 1540
static int vsock_stream_setsockopt(struct socket *sock,
				   int level,
				   int optname,
1541
				   sockptr_t optval,
A
Andy King 已提交
1542 1543 1544 1545 1546
				   unsigned int optlen)
{
	int err;
	struct sock *sk;
	struct vsock_sock *vsk;
1547
	const struct vsock_transport *transport;
A
Andy King 已提交
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
	u64 val;

	if (level != AF_VSOCK)
		return -ENOPROTOOPT;

#define COPY_IN(_v)                                       \
	do {						  \
		if (optlen < sizeof(_v)) {		  \
			err = -EINVAL;			  \
			goto exit;			  \
		}					  \
1559
		if (copy_from_sockptr(&_v, optval, sizeof(_v)) != 0) {	\
A
Andy King 已提交
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
			err = -EFAULT;					\
			goto exit;					\
		}							\
	} while (0)

	err = 0;
	sk = sock->sk;
	vsk = vsock_sk(sk);

	lock_sock(sk);

1571 1572
	transport = vsk->transport;

A
Andy King 已提交
1573 1574 1575
	switch (optname) {
	case SO_VM_SOCKETS_BUFFER_SIZE:
		COPY_IN(val);
1576
		vsock_update_buffer_size(vsk, transport, val);
A
Andy King 已提交
1577 1578 1579 1580
		break;

	case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
		COPY_IN(val);
1581 1582
		vsk->buffer_max_size = val;
		vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
A
Andy King 已提交
1583 1584 1585 1586
		break;

	case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
		COPY_IN(val);
1587 1588
		vsk->buffer_min_size = val;
		vsock_update_buffer_size(vsk, transport, vsk->buffer_size);
A
Andy King 已提交
1589 1590 1591
		break;

	case SO_VM_SOCKETS_CONNECT_TIMEOUT: {
1592
		struct __kernel_old_timeval tv;
A
Andy King 已提交
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
		COPY_IN(tv);
		if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC &&
		    tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) {
			vsk->connect_timeout = tv.tv_sec * HZ +
			    DIV_ROUND_UP(tv.tv_usec, (1000000 / HZ));
			if (vsk->connect_timeout == 0)
				vsk->connect_timeout =
				    VSOCK_DEFAULT_CONNECT_TIMEOUT;

		} else {
			err = -ERANGE;
		}
		break;
	}

	default:
		err = -ENOPROTOOPT;
		break;
	}

#undef COPY_IN

exit:
	release_sock(sk);
	return err;
}

static int vsock_stream_getsockopt(struct socket *sock,
				   int level, int optname,
				   char __user *optval,
				   int __user *optlen)
{
	int err;
	int len;
	struct sock *sk;
	struct vsock_sock *vsk;
	u64 val;

	if (level != AF_VSOCK)
		return -ENOPROTOOPT;

	err = get_user(len, optlen);
	if (err != 0)
		return err;

#define COPY_OUT(_v)                            \
	do {					\
		if (len < sizeof(_v))		\
			return -EINVAL;		\
						\
		len = sizeof(_v);		\
		if (copy_to_user(optval, &_v, len) != 0)	\
			return -EFAULT;				\
								\
	} while (0)

	err = 0;
	sk = sock->sk;
	vsk = vsock_sk(sk);

	switch (optname) {
	case SO_VM_SOCKETS_BUFFER_SIZE:
1655
		val = vsk->buffer_size;
A
Andy King 已提交
1656 1657 1658 1659
		COPY_OUT(val);
		break;

	case SO_VM_SOCKETS_BUFFER_MAX_SIZE:
1660
		val = vsk->buffer_max_size;
A
Andy King 已提交
1661 1662 1663 1664
		COPY_OUT(val);
		break;

	case SO_VM_SOCKETS_BUFFER_MIN_SIZE:
1665
		val = vsk->buffer_min_size;
A
Andy King 已提交
1666 1667 1668 1669
		COPY_OUT(val);
		break;

	case SO_VM_SOCKETS_CONNECT_TIMEOUT: {
1670
		struct __kernel_old_timeval tv;
A
Andy King 已提交
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
		tv.tv_sec = vsk->connect_timeout / HZ;
		tv.tv_usec =
		    (vsk->connect_timeout -
		     tv.tv_sec * HZ) * (1000000 / HZ);
		COPY_OUT(tv);
		break;
	}
	default:
		return -ENOPROTOOPT;
	}

	err = put_user(len, optlen);
	if (err != 0)
		return -EFAULT;

#undef COPY_OUT

	return 0;
}

1691 1692
static int vsock_stream_sendmsg(struct socket *sock, struct msghdr *msg,
				size_t len)
A
Andy King 已提交
1693 1694 1695
{
	struct sock *sk;
	struct vsock_sock *vsk;
1696
	const struct vsock_transport *transport;
A
Andy King 已提交
1697 1698 1699 1700
	ssize_t total_written;
	long timeout;
	int err;
	struct vsock_transport_send_notify_data send_data;
1701
	DEFINE_WAIT_FUNC(wait, woken_wake_function);
A
Andy King 已提交
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712

	sk = sock->sk;
	vsk = vsock_sk(sk);
	total_written = 0;
	err = 0;

	if (msg->msg_flags & MSG_OOB)
		return -EOPNOTSUPP;

	lock_sock(sk);

1713 1714
	transport = vsk->transport;

A
Andy King 已提交
1715 1716
	/* Callers should not provide a destination with stream sockets. */
	if (msg->msg_namelen) {
1717
		err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
A
Andy King 已提交
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
		goto out;
	}

	/* Send data only if both sides are not shutdown in the direction. */
	if (sk->sk_shutdown & SEND_SHUTDOWN ||
	    vsk->peer_shutdown & RCV_SHUTDOWN) {
		err = -EPIPE;
		goto out;
	}

1728
	if (!transport || sk->sk_state != TCP_ESTABLISHED ||
A
Andy King 已提交
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
	    !vsock_addr_bound(&vsk->local_addr)) {
		err = -ENOTCONN;
		goto out;
	}

	if (!vsock_addr_bound(&vsk->remote_addr)) {
		err = -EDESTADDRREQ;
		goto out;
	}

	/* Wait for room in the produce queue to enqueue our user's data. */
	timeout = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);

	err = transport->notify_send_init(vsk, &send_data);
	if (err < 0)
		goto out;

	while (total_written < len) {
		ssize_t written;

1749
		add_wait_queue(sk_sleep(sk), &wait);
A
Andy King 已提交
1750 1751 1752 1753 1754 1755 1756 1757
		while (vsock_stream_has_space(vsk) == 0 &&
		       sk->sk_err == 0 &&
		       !(sk->sk_shutdown & SEND_SHUTDOWN) &&
		       !(vsk->peer_shutdown & RCV_SHUTDOWN)) {

			/* Don't wait for non-blocking sockets. */
			if (timeout == 0) {
				err = -EAGAIN;
1758
				remove_wait_queue(sk_sleep(sk), &wait);
1759
				goto out_err;
A
Andy King 已提交
1760 1761 1762
			}

			err = transport->notify_send_pre_block(vsk, &send_data);
1763
			if (err < 0) {
1764
				remove_wait_queue(sk_sleep(sk), &wait);
1765 1766
				goto out_err;
			}
A
Andy King 已提交
1767 1768

			release_sock(sk);
1769
			timeout = wait_woken(&wait, TASK_INTERRUPTIBLE, timeout);
A
Andy King 已提交
1770 1771 1772
			lock_sock(sk);
			if (signal_pending(current)) {
				err = sock_intr_errno(timeout);
1773
				remove_wait_queue(sk_sleep(sk), &wait);
1774
				goto out_err;
A
Andy King 已提交
1775 1776
			} else if (timeout == 0) {
				err = -EAGAIN;
1777
				remove_wait_queue(sk_sleep(sk), &wait);
1778
				goto out_err;
A
Andy King 已提交
1779 1780
			}
		}
1781
		remove_wait_queue(sk_sleep(sk), &wait);
A
Andy King 已提交
1782 1783 1784 1785 1786 1787 1788

		/* These checks occur both as part of and after the loop
		 * conditional since we need to check before and after
		 * sleeping.
		 */
		if (sk->sk_err) {
			err = -sk->sk_err;
1789
			goto out_err;
A
Andy King 已提交
1790 1791 1792
		} else if ((sk->sk_shutdown & SEND_SHUTDOWN) ||
			   (vsk->peer_shutdown & RCV_SHUTDOWN)) {
			err = -EPIPE;
1793
			goto out_err;
A
Andy King 已提交
1794 1795 1796 1797
		}

		err = transport->notify_send_pre_enqueue(vsk, &send_data);
		if (err < 0)
1798
			goto out_err;
A
Andy King 已提交
1799 1800 1801 1802 1803 1804 1805 1806

		/* Note that enqueue will only write as many bytes as are free
		 * in the produce queue, so we don't need to ensure len is
		 * smaller than the queue size.  It is the caller's
		 * responsibility to check how many bytes we were able to send.
		 */

		written = transport->stream_enqueue(
1807
				vsk, msg,
A
Andy King 已提交
1808 1809 1810
				len - total_written);
		if (written < 0) {
			err = -ENOMEM;
1811
			goto out_err;
A
Andy King 已提交
1812 1813 1814 1815 1816 1817 1818
		}

		total_written += written;

		err = transport->notify_send_post_enqueue(
				vsk, written, &send_data);
		if (err < 0)
1819
			goto out_err;
A
Andy King 已提交
1820 1821 1822

	}

1823
out_err:
A
Andy King 已提交
1824 1825 1826 1827 1828 1829 1830 1831 1832
	if (total_written > 0)
		err = total_written;
out:
	release_sock(sk);
	return err;
}


static int
1833 1834
vsock_stream_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
		     int flags)
A
Andy King 已提交
1835 1836 1837
{
	struct sock *sk;
	struct vsock_sock *vsk;
1838
	const struct vsock_transport *transport;
A
Andy King 已提交
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
	int err;
	size_t target;
	ssize_t copied;
	long timeout;
	struct vsock_transport_recv_notify_data recv_data;

	DEFINE_WAIT(wait);

	sk = sock->sk;
	vsk = vsock_sk(sk);
	err = 0;

	lock_sock(sk);

1853 1854
	transport = vsk->transport;

1855
	if (!transport || sk->sk_state != TCP_ESTABLISHED) {
A
Andy King 已提交
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
		/* Recvmsg is supposed to return 0 if a peer performs an
		 * orderly shutdown. Differentiate between that case and when a
		 * peer has not connected or a local shutdown occured with the
		 * SOCK_DONE flag.
		 */
		if (sock_flag(sk, SOCK_DONE))
			err = 0;
		else
			err = -ENOTCONN;

		goto out;
	}

	if (flags & MSG_OOB) {
		err = -EOPNOTSUPP;
		goto out;
	}

	/* We don't check peer_shutdown flag here since peer may actually shut
	 * down, but there can be data in the queue that a local socket can
	 * receive.
	 */
	if (sk->sk_shutdown & RCV_SHUTDOWN) {
		err = 0;
		goto out;
	}

	/* It is valid on Linux to pass in a zero-length receive buffer.  This
	 * is not an error.  We may as well bail out now.
	 */
	if (!len) {
		err = 0;
		goto out;
	}

	/* We must not copy less than target bytes into the user's buffer
	 * before returning successfully, so we wait for the consume queue to
	 * have that much data to consume before dequeueing.  Note that this
	 * makes it impossible to handle cases where target is greater than the
	 * queue size.
	 */
	target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
	if (target >= transport->stream_rcvhiwat(vsk)) {
		err = -ENOMEM;
		goto out;
	}
	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
	copied = 0;

	err = transport->notify_recv_init(vsk, target, &recv_data);
	if (err < 0)
		goto out;


	while (1) {
1911
		s64 ready;
A
Andy King 已提交
1912

1913 1914
		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
		ready = vsock_stream_has_data(vsk);
A
Andy King 已提交
1915

1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
		if (ready == 0) {
			if (sk->sk_err != 0 ||
			    (sk->sk_shutdown & RCV_SHUTDOWN) ||
			    (vsk->peer_shutdown & SEND_SHUTDOWN)) {
				finish_wait(sk_sleep(sk), &wait);
				break;
			}
			/* Don't wait for non-blocking sockets. */
			if (timeout == 0) {
				err = -EAGAIN;
				finish_wait(sk_sleep(sk), &wait);
				break;
			}

			err = transport->notify_recv_pre_block(
					vsk, target, &recv_data);
			if (err < 0) {
				finish_wait(sk_sleep(sk), &wait);
				break;
			}
			release_sock(sk);
			timeout = schedule_timeout(timeout);
			lock_sock(sk);

			if (signal_pending(current)) {
				err = sock_intr_errno(timeout);
				finish_wait(sk_sleep(sk), &wait);
				break;
			} else if (timeout == 0) {
				err = -EAGAIN;
				finish_wait(sk_sleep(sk), &wait);
				break;
			}
		} else {
A
Andy King 已提交
1950 1951
			ssize_t read;

1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
			finish_wait(sk_sleep(sk), &wait);

			if (ready < 0) {
				/* Invalid queue pair content. XXX This should
				* be changed to a connection reset in a later
				* change.
				*/

				err = -ENOMEM;
				goto out;
			}

A
Andy King 已提交
1964 1965 1966 1967 1968 1969
			err = transport->notify_recv_pre_dequeue(
					vsk, target, &recv_data);
			if (err < 0)
				break;

			read = transport->stream_dequeue(
1970
					vsk, msg,
A
Andy King 已提交
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
					len - copied, flags);
			if (read < 0) {
				err = -ENOMEM;
				break;
			}

			copied += read;

			err = transport->notify_recv_post_dequeue(
					vsk, target, read,
					!(flags & MSG_PEEK), &recv_data);
			if (err < 0)
1983
				goto out;
A
Andy King 已提交
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996

			if (read >= target || flags & MSG_PEEK)
				break;

			target -= read;
		}
	}

	if (sk->sk_err)
		err = -sk->sk_err;
	else if (sk->sk_shutdown & RCV_SHUTDOWN)
		err = 0;

1997
	if (copied > 0)
A
Andy King 已提交
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
		err = copied;

out:
	release_sock(sk);
	return err;
}

static const struct proto_ops vsock_stream_ops = {
	.family = PF_VSOCK,
	.owner = THIS_MODULE,
	.release = vsock_release,
	.bind = vsock_bind,
	.connect = vsock_stream_connect,
	.socketpair = sock_no_socketpair,
	.accept = vsock_accept,
	.getname = vsock_getname,
2014
	.poll = vsock_poll,
A
Andy King 已提交
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
	.ioctl = sock_no_ioctl,
	.listen = vsock_listen,
	.shutdown = vsock_shutdown,
	.setsockopt = vsock_stream_setsockopt,
	.getsockopt = vsock_stream_getsockopt,
	.sendmsg = vsock_stream_sendmsg,
	.recvmsg = vsock_stream_recvmsg,
	.mmap = sock_no_mmap,
	.sendpage = sock_no_sendpage,
};

static int vsock_create(struct net *net, struct socket *sock,
			int protocol, int kern)
{
2029
	struct vsock_sock *vsk;
2030
	struct sock *sk;
2031
	int ret;
2032

A
Andy King 已提交
2033 2034 2035
	if (!sock)
		return -EINVAL;

2036
	if (protocol && protocol != PF_VSOCK)
A
Andy King 已提交
2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
		return -EPROTONOSUPPORT;

	switch (sock->type) {
	case SOCK_DGRAM:
		sock->ops = &vsock_dgram_ops;
		break;
	case SOCK_STREAM:
		sock->ops = &vsock_stream_ops;
		break;
	default:
		return -ESOCKTNOSUPPORT;
	}

	sock->state = SS_UNCONNECTED;

2052 2053 2054 2055
	sk = __vsock_create(net, sock, NULL, GFP_KERNEL, 0, kern);
	if (!sk)
		return -ENOMEM;

2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
	vsk = vsock_sk(sk);

	if (sock->type == SOCK_DGRAM) {
		ret = vsock_assign_transport(vsk, NULL);
		if (ret < 0) {
			sock_put(sk);
			return ret;
		}
	}

	vsock_insert_unbound(vsk);
2067 2068

	return 0;
A
Andy King 已提交
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
}

static const struct net_proto_family vsock_family_ops = {
	.family = AF_VSOCK,
	.create = vsock_create,
	.owner = THIS_MODULE,
};

static long vsock_dev_do_ioctl(struct file *filp,
			       unsigned int cmd, void __user *ptr)
{
	u32 __user *p = ptr;
2081
	u32 cid = VMADDR_CID_ANY;
A
Andy King 已提交
2082 2083 2084 2085
	int retval = 0;

	switch (cmd) {
	case IOCTL_VM_SOCKETS_GET_LOCAL_CID:
2086 2087 2088 2089 2090 2091 2092 2093 2094
		/* To be compatible with the VMCI behavior, we prioritize the
		 * guest CID instead of well-know host CID (VMADDR_CID_HOST).
		 */
		if (transport_g2h)
			cid = transport_g2h->get_local_cid();
		else if (transport_h2g)
			cid = transport_h2g->get_local_cid();

		if (put_user(cid, p) != 0)
A
Andy King 已提交
2095 2096 2097 2098
			retval = -EFAULT;
		break;

	default:
2099
		retval = -ENOIOCTLCMD;
A
Andy King 已提交
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
	}

	return retval;
}

static long vsock_dev_ioctl(struct file *filp,
			    unsigned int cmd, unsigned long arg)
{
	return vsock_dev_do_ioctl(filp, cmd, (void __user *)arg);
}

#ifdef CONFIG_COMPAT
static long vsock_dev_compat_ioctl(struct file *filp,
				   unsigned int cmd, unsigned long arg)
{
	return vsock_dev_do_ioctl(filp, cmd, compat_ptr(arg));
}
#endif

static const struct file_operations vsock_device_ops = {
	.owner		= THIS_MODULE,
	.unlocked_ioctl	= vsock_dev_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl	= vsock_dev_compat_ioctl,
#endif
	.open		= nonseekable_open,
};

static struct miscdevice vsock_device = {
	.name		= "vsock",
	.fops		= &vsock_device_ops,
};

2133
static int __init vsock_init(void)
A
Andy King 已提交
2134
{
2135
	int err = 0;
2136

2137
	vsock_init_tables();
A
Andy King 已提交
2138

2139
	vsock_proto.owner = THIS_MODULE;
A
Asias He 已提交
2140
	vsock_device.minor = MISC_DYNAMIC_MINOR;
A
Andy King 已提交
2141 2142 2143
	err = misc_register(&vsock_device);
	if (err) {
		pr_err("Failed to register misc device\n");
2144
		goto err_reset_transport;
A
Andy King 已提交
2145 2146 2147 2148 2149
	}

	err = proto_register(&vsock_proto, 1);	/* we want our slab */
	if (err) {
		pr_err("Cannot register vsock protocol\n");
2150
		goto err_deregister_misc;
A
Andy King 已提交
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163
	}

	err = sock_register(&vsock_family_ops);
	if (err) {
		pr_err("could not register af_vsock (%d) address family: %d\n",
		       AF_VSOCK, err);
		goto err_unregister_proto;
	}

	return 0;

err_unregister_proto:
	proto_unregister(&vsock_proto);
2164
err_deregister_misc:
A
Andy King 已提交
2165
	misc_deregister(&vsock_device);
2166
err_reset_transport:
2167
	return err;
A
Andy King 已提交
2168 2169
}

2170
static void __exit vsock_exit(void)
A
Andy King 已提交
2171 2172 2173 2174 2175 2176
{
	misc_deregister(&vsock_device);
	sock_unregister(AF_VSOCK);
	proto_unregister(&vsock_proto);
}

2177
const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)
2178
{
2179
	return vsk->transport;
2180 2181 2182
}
EXPORT_SYMBOL_GPL(vsock_core_get_transport);

2183 2184
int vsock_core_register(const struct vsock_transport *t, int features)
{
2185
	const struct vsock_transport *t_h2g, *t_g2h, *t_dgram, *t_local;
2186 2187 2188 2189 2190 2191 2192 2193
	int err = mutex_lock_interruptible(&vsock_register_mutex);

	if (err)
		return err;

	t_h2g = transport_h2g;
	t_g2h = transport_g2h;
	t_dgram = transport_dgram;
2194
	t_local = transport_local;
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219

	if (features & VSOCK_TRANSPORT_F_H2G) {
		if (t_h2g) {
			err = -EBUSY;
			goto err_busy;
		}
		t_h2g = t;
	}

	if (features & VSOCK_TRANSPORT_F_G2H) {
		if (t_g2h) {
			err = -EBUSY;
			goto err_busy;
		}
		t_g2h = t;
	}

	if (features & VSOCK_TRANSPORT_F_DGRAM) {
		if (t_dgram) {
			err = -EBUSY;
			goto err_busy;
		}
		t_dgram = t;
	}

2220 2221 2222 2223 2224 2225 2226 2227
	if (features & VSOCK_TRANSPORT_F_LOCAL) {
		if (t_local) {
			err = -EBUSY;
			goto err_busy;
		}
		t_local = t;
	}

2228 2229 2230
	transport_h2g = t_h2g;
	transport_g2h = t_g2h;
	transport_dgram = t_dgram;
2231
	transport_local = t_local;
2232 2233 2234 2235 2236 2237 2238 2239

err_busy:
	mutex_unlock(&vsock_register_mutex);
	return err;
}
EXPORT_SYMBOL_GPL(vsock_core_register);

void vsock_core_unregister(const struct vsock_transport *t)
2240
{
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
	mutex_lock(&vsock_register_mutex);

	if (transport_h2g == t)
		transport_h2g = NULL;

	if (transport_g2h == t)
		transport_g2h = NULL;

	if (transport_dgram == t)
		transport_dgram = NULL;

2252 2253 2254
	if (transport_local == t)
		transport_local = NULL;

2255
	mutex_unlock(&vsock_register_mutex);
2256
}
2257
EXPORT_SYMBOL_GPL(vsock_core_unregister);
2258

2259
module_init(vsock_init);
2260
module_exit(vsock_exit);
C
Cong Wang 已提交
2261

A
Andy King 已提交
2262 2263
MODULE_AUTHOR("VMware, Inc.");
MODULE_DESCRIPTION("VMware Virtual Socket Family");
2264
MODULE_VERSION("1.0.2.0-k");
A
Andy King 已提交
2265
MODULE_LICENSE("GPL v2");