Skip to contentSkip to conversation

VMCI for Linux

RFC Superseded Andrew Stiegmann (stieg) 6 participants 39 messages May 15, 2012 – Jun 14, 2012 Page 2 of 2

Subsystems (4)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#20 lore raw

RFC 8/11 Apply VMCI queue pairs

In reply to Andrew Stiegmann (stieg)

VMCI queue pairs allow for bi-directional ordered communication between host and guests.

---
 drivers/misc/vmw_vmci/vmci_queue_pair.c | 4517 +++++++++++++++++++++++++++++++
 drivers/misc/vmw_vmci/vmci_queue_pair.h |  258 ++
 2 files changed, 4775 insertions(+), 0 deletions(-)
 create mode 100644 drivers/misc/vmw_vmci/vmci_queue_pair.c
 create mode 100644 drivers/misc/vmw_vmci/vmci_queue_pair.h
drivers/misc/vmw_vmci/vmci_queue_pair.c new file +4517 -0
new file mode 100644
index 0000000..b5b1b8e
@@ -0,0 +1,4517 @@
+/*
+ * VMware VMCI Driver
+ *
+ * Copyright (C) 2012 VMware, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation version 2 and no later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ */
+
+#include <linux/device-mapper.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/sched.h>
+#include <linux/semaphore.h>
+#include <linux/socket.h>
+#include <linux/vmw_vmci_api.h>
+#include <linux/vmw_vmci_defs.h>
+
+#include "vmci_common_int.h"
+#include "vmci_context.h"
+#include "vmci_datagram.h"
+#include "vmci_driver.h"
+#include "vmci_event.h"
+#include "vmci_handle_array.h"
+#include "vmci_hash_table.h"
+#include "vmci_queue_pair.h"
+#include "vmci_resource.h"
+#include "vmci_route.h"
+
+#define INVALID_VMCI_GUEST_MEM_ID  0
+
+/*
+ * In the following, we will distinguish between two kinds of VMX processes -
+ * the ones with versions lower than VMCI_VERSION_NOVMVM that use specialized
+ * VMCI page files in the VMX and supporting VM to VM communication and the
+ * newer ones that use the guest memory directly. We will in the following refer
+ * to the older VMX versions as old-style VMX'en, and the newer ones as new-style
+ * VMX'en.
+ *
+ * The state transition datagram is as follows (the VMCIQPB_ prefix has been
+ * removed for readability) - see below for more details on the transtions:
+ *
+ *            --------------  NEW  -------------
+ *            |                                |
+ *           \_/                              \_/
+ *     CREATED_NO_MEM <-----------------> CREATED_MEM
+ *            |    |                           |
+ *            |    o-----------------------o   |
+ *            |                            |   |
+ *           \_/                          \_/ \_/
+ *     ATTACHED_NO_MEM <----------------> ATTACHED_MEM
+ *            |                            |   |
+ *            |     o----------------------o   |
+ *            |     |                          |
+ *           \_/   \_/                        \_/
+ *     SHUTDOWN_NO_MEM <----------------> SHUTDOWN_MEM
+ *            |                                |
+ *            |                                |
+ *            -------------> gone <-------------
+ *
+ * In more detail. When a VMCI queue pair is first created, it will be in the
+ * VMCIQPB_NEW state. It will then move into one of the following states:
+ * - VMCIQPB_CREATED_NO_MEM: this state indicates that either:
+ *     - the created was performed by a host endpoint, in which case there is no
+ *       backing memory yet.
+ *     - the create was initiated by an old-style VMX, that uses
+ *       vmci_qp_broker_set_page_store to specify the UVAs of the queue pair at a
+ *       later point in time. This state can be distinguished from the one above
+ *       by the context ID of the creator. A host side is not allowed to attach
+ *       until the page store has been set.
+ * - VMCIQPB_CREATED_MEM: this state is the result when the queue pair is created
+ *     by a VMX using the queue pair device backend that sets the UVAs of the
+ *     queue pair immediately and stores the information for later attachers. At
+ *     this point, it is ready for the host side to attach to it.
+ * Once the queue pair is in one of the created states (with the exception of the
+ * case mentioned for older VMX'en above), it is possible to attach to the queue
+ * pair. Again we have two new states possible:
+ * - VMCIQPB_ATTACHED_MEM: this state can be reached through the following paths:
+ *     - from VMCIQPB_CREATED_NO_MEM when a new-style VMX allocates a queue pair,
+ *       and attaches to a queue pair previously created by the host side.
+ *     - from VMCIQPB_CREATED_MEM when the host side attaches to a queue pair
+ *       already created by a guest.
+ *     - from VMCIQPB_ATTACHED_NO_MEM, when an old-style VMX calls
+ *       vmci_qp_broker_set_page_store (see below).
+ * - VMCIQPB_ATTACHED_NO_MEM: If the queue pair already was in the
+ *     VMCIQPB_CREATED_NO_MEM due to a host side create, an old-style VMX will
+ *     bring the queue pair into this state. Once vmci_qp_broker_set_page_store is
+ *     called to register the user memory, the VMCIQPB_ATTACH_MEM state will be
+ *     entered.
+ * From the attached queue pair, the queue pair can enter the shutdown states
+ * when either side of the queue pair detaches. If the guest side detaches first,
+ * the queue pair will enter the VMCIQPB_SHUTDOWN_NO_MEM state, where the content
+ * of the queue pair will no longer be available. If the host side detaches first,
+ * the queue pair will either enter the VMCIQPB_SHUTDOWN_MEM, if the guest memory
+ * is currently mapped, or VMCIQPB_SHUTDOWN_NO_MEM, if the guest memory is not
+ * mapped (e.g., the host detaches while a guest is stunned).
+ *
+ * New-style VMX'en will also unmap guest memory, if the guest is quiesced, e.g.,
+ * during a snapshot operation. In that case, the guest memory will no longer be
+ * available, and the queue pair will transition from *_MEM state to a *_NO_MEM
+ * state. The VMX may later map the memory once more, in which case the queue
+ * pair will transition from the *_NO_MEM state at that point back to the *_MEM
+ * state. Note that the *_NO_MEM state may have changed, since the peer may have
+ * either attached or detached in the meantime. The values are laid out such that
+ * ++ on a state will move from a *_NO_MEM to a *_MEM state, and vice versa.
+ */
+
+/* The Kernel specific component of the struct vmci_queue structure. */
+struct vmci_queue_kern_if {
+	struct page **page;
+	struct page **headerPage;
+	void *va;
+	struct semaphore __mutex;
+	struct semaphore *mutex;
+	bool host;
+	size_t numPages;
+	bool mapped;
+};
+
+/*
+ * This structure is opaque to the clients.
+ */
+struct vmci_qp {
+	struct vmci_handle handle;
+	struct vmci_queue *produceQ;
+	struct vmci_queue *consumeQ;
+	uint64_t produceQSize;
+	uint64_t consumeQSize;
+	uint32_t peer;
+	uint32_t flags;
+	uint32_t privFlags;
+	bool guestEndpoint;
+	uint32_t blocked;
+	wait_queue_head_t event;
+};
+
+enum qp_broker_state {
+	VMCIQPB_NEW,
+	VMCIQPB_CREATED_NO_MEM,
+	VMCIQPB_CREATED_MEM,
+	VMCIQPB_ATTACHED_NO_MEM,
+	VMCIQPB_ATTACHED_MEM,
+	VMCIQPB_SHUTDOWN_NO_MEM,
+	VMCIQPB_SHUTDOWN_MEM,
+	VMCIQPB_GONE
+};
+
+#define QPBROKERSTATE_HAS_MEM(_qpb) (_qpb->state == VMCIQPB_CREATED_MEM || \
+                                     _qpb->state == VMCIQPB_ATTACHED_MEM || \
+                                     _qpb->state == VMCIQPB_SHUTDOWN_MEM)
+
+/*
+ * In the queue pair broker, we always use the guest point of view for
+ * the produce and consume queue values and references, e.g., the
+ * produce queue size stored is the guests produce queue size. The
+ * host endpoint will need to swap these around. The only exception is
+ * the local queue pairs on the host, in which case the host endpoint
+ * that creates the queue pair will have the right orientation, and
+ * the attaching host endpoint will need to swap.
+ */
+
+struct qp_entry {
+	struct list_head listItem;
+	struct vmci_handle handle;
+	uint32_t peer;
+	uint32_t flags;
+	uint64_t produceSize;
+	uint64_t consumeSize;
+	uint32_t refCount;
+};
+
+struct qp_broker_entry {
+	struct qp_entry qp;
+	uint32_t createId;
+	uint32_t attachId;
+	enum qp_broker_state state;
+	bool requireTrustedAttach;
+	bool createdByTrusted;
+	bool vmciPageFiles;	// Created by VMX using VMCI page files
+	struct vmci_queue *produceQ;
+	struct vmci_queue *consumeQ;
+	struct vmci_queue_header savedProduceQ;
+	struct vmci_queue_header savedConsumeQ;
+	VMCIEventReleaseCB wakeupCB;
+	void *clientData;
+	void *localMem;		// Kernel memory for local queue pair
+};
+
+struct qp_guest_endpoint {
+	struct qp_entry qp;
+	uint64_t numPPNs;
+	void *produceQ;
+	void *consumeQ;
+	struct PPNSet ppnSet;
+};
+
+struct qp_list {
+	struct list_head head;
+	struct semaphore mutex;
+};
+
+static struct qp_list qpBrokerList;
+
+#define QPE_NUM_PAGES(_QPE) ((uint32_t)(dm_div_up(_QPE.produceSize, PAGE_SIZE) + \
+					dm_div_up(_QPE.consumeSize, PAGE_SIZE) + 2))
+
+static struct qp_list qpGuestEndpoints;
+
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_free_queue --
+ *
+ *      Frees kernel VA space for a given queue and its queue header, and
+ *      frees physical data pages.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      Memory is freed.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_free_queue(void *q,	// IN:
+			  uint64_t size)	// IN: size of queue (not including header)
+{
+	struct vmci_queue *queue = q;
+
+	if (queue) {
+		uint64_t i = dm_div_up(size, PAGE_SIZE);
+
+		if (queue->kernelIf->mapped) {
+			ASSERT(queue->kernelIf->va);
+			vunmap(queue->kernelIf->va);
+			queue->kernelIf->va = NULL;
+		}
+
+		while (i)
+			__free_page(queue->kernelIf->page[--i]);
+
+		vfree(queue->qHeader);
+	}
+}
+
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_alloc_queue --
+ *
+ *      Allocates kernel VA space of specified size, plus space for the
+ *      queue structure/kernel interface and the queue header.  Allocates
+ *      physical pages for the queue data pages.
+ *
+ *      PAGE m:      struct vmci_queue_header (struct vmci_queue->qHeader)
+ *      PAGE m+1:    struct vmci_queue
+ *      PAGE m+1+q:  struct vmci_queue_kern_if (struct vmci_queue->kernelIf)
+ *      PAGE n-size: Data pages (struct vmci_queue->kernelIf->page[])
+ *
+ * Results:
+ *      Pointer to the queue on success, NULL otherwise.
+ *
+ * Side effects:
+ *      Memory is allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void *qp_alloc_queue(uint64_t size,	// IN: size of queue (not including header)
+			    uint32_t flags)
+{
+	uint64_t i;
+	struct vmci_queue *queue;
+	struct vmci_queue_header *qHeader;
+	const uint64_t numDataPages = dm_div_up(size, PAGE_SIZE);
+	const uint queueSize =
+		PAGE_SIZE +
+		sizeof(*queue) + sizeof(*(queue->kernelIf)) +
+		numDataPages * sizeof(*(queue->kernelIf->page));
+
+	ASSERT(size <= VMCI_MAX_GUEST_QP_MEMORY);
+	ASSERT(!QP_PINNED(flags) || size <= VMCI_MAX_PINNED_QP_MEMORY);
+
+	qHeader = vmalloc(queueSize);
+	if (!qHeader)
+		return NULL;
+
+	queue = (struct vmci_queue *)((uint8_t *) qHeader + PAGE_SIZE);
+	queue->qHeader = qHeader;
+	queue->savedHeader = NULL;
+	queue->kernelIf =
+		(struct vmci_queue_kern_if *)((uint8_t *) queue + sizeof(*queue));
+	queue->kernelIf->headerPage = NULL;	/* Unused in guest. */
+	queue->kernelIf->page =
+		(struct page **)((uint8_t *) queue->kernelIf +
+				 sizeof(*(queue->kernelIf)));
+	queue->kernelIf->host = false;
+	queue->kernelIf->va = NULL;
+	queue->kernelIf->mapped = false;
+
+	for (i = 0; i < numDataPages; i++) {
+		queue->kernelIf->page[i] = alloc_pages(GFP_KERNEL, 0);
+		if (!queue->kernelIf->page[i])
+			goto fail;
+	}
+
+	if (QP_PINNED(flags)) {
+		queue->kernelIf->va = vmap(queue->kernelIf->page, numDataPages,
+					   VM_MAP, PAGE_KERNEL);
+		if (!queue->kernelIf->va)
+			goto fail;
+
+		queue->kernelIf->mapped = true;
+	}
+
+	return (void *)queue;
+
+fail:
+	qp_free_queue(queue, i * PAGE_SIZE);
+	return NULL;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * __qp_memcpy_to_queue --
+ *
+ *      Copies from a given buffer or iovector to a VMCI Queue.  Uses
+ *      kmap()/kunmap() to dynamically map/unmap required portions of the queue
+ *      by traversing the offset -> page translation structure for the queue.
+ *      Assumes that offset + size does not wrap around in the queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int __qp_memcpy_to_queue(struct vmci_queue *queue,	// OUT:
+				uint64_t queueOffset,	// IN:
+				const void *src,	// IN:
+				size_t size,	// IN:
+				bool isIovec)	// IN: if src is a struct iovec *
+{
+	struct vmci_queue_kern_if *kernelIf = queue->kernelIf;
+	size_t bytesCopied = 0;
+
+	while (bytesCopied < size) {
+		uint64_t pageIndex = (queueOffset + bytesCopied) / PAGE_SIZE;
+		size_t pageOffset =
+			(queueOffset + bytesCopied) & (PAGE_SIZE - 1);
+		void *va;
+		size_t toCopy;
+
+		if (!kernelIf->mapped)
+			va = kmap(kernelIf->page[pageIndex]);
+		else
+			va = (void *)((uint8_t *)kernelIf->va + (pageIndex * PAGE_SIZE));
+
+		if (size - bytesCopied > PAGE_SIZE - pageOffset) {
+			/* Enough payload to fill up from this page. */
+			toCopy = PAGE_SIZE - pageOffset;
+		} else {
+			toCopy = size - bytesCopied;
+		}
+
+		if (isIovec) {
+			struct iovec *iov = (struct iovec *)src;
+			int err;
+
+			/* The iovec will track bytesCopied internally. */
+			err = memcpy_fromiovec((uint8_t *) va + pageOffset,
+					       iov, toCopy);
+			if (err != 0) {
+				kunmap(kernelIf->page[pageIndex]);
+				return VMCI_ERROR_INVALID_ARGS;
+			}
+		} else {
+			memcpy((uint8_t *) va + pageOffset,
+			       (uint8_t *) src + bytesCopied, toCopy);
+		}
+
+		bytesCopied += toCopy;
+		if (!kernelIf->mapped)
+			kunmap(kernelIf->page[pageIndex]);
+	}
+
+	return VMCI_SUCCESS;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * __qp_memcpy_from_queue --
+ *
+ *      Copies to a given buffer or iovector from a VMCI Queue.  Uses
+ *      kmap()/kunmap() to dynamically map/unmap required portions of the queue
+ *      by traversing the offset -> page translation structure for the queue.
+ *      Assumes that offset + size does not wrap around in the queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int __qp_memcpy_from_queue(void *dest,	// OUT:
+				  const struct vmci_queue *queue,	// IN:
+				  uint64_t queueOffset,	// IN:
+				  size_t size,	// IN:
+				  bool isIovec)	// IN: if dest is a struct iovec *
+{
+	struct vmci_queue_kern_if *kernelIf = queue->kernelIf;
+	size_t bytesCopied = 0;
+
+	while (bytesCopied < size) {
+		uint64_t pageIndex = (queueOffset + bytesCopied) / PAGE_SIZE;
+		size_t pageOffset =
+			(queueOffset + bytesCopied) & (PAGE_SIZE - 1);
+		void *va;
+		size_t toCopy;
+
+		if (!kernelIf->mapped)
+			va = kmap(kernelIf->page[pageIndex]);
+		else
+			va = (void *)((uint8_t *)kernelIf->va + (pageIndex * PAGE_SIZE));
+
+		if (size - bytesCopied > PAGE_SIZE - pageOffset) {
+			/* Enough payload to fill up this page. */
+			toCopy = PAGE_SIZE - pageOffset;
+		} else {
+			toCopy = size - bytesCopied;
+		}
+
+		if (isIovec) {
+			struct iovec *iov = (struct iovec *)dest;
+			int err;
+
+			/* The iovec will track bytesCopied internally. */
+			err = memcpy_toiovec(iov, (uint8_t *) va + pageOffset,
+					     toCopy);
+			if (err != 0) {
+				kunmap(kernelIf->page[pageIndex]);
+				return VMCI_ERROR_INVALID_ARGS;
+			}
+		} else {
+			memcpy((uint8_t *) dest + bytesCopied,
+			       (uint8_t *) va + pageOffset, toCopy);
+		}
+
+		bytesCopied += toCopy;
+		if (!kernelIf->mapped)
+			kunmap(kernelIf->page[pageIndex]);
+	}
+
+	return VMCI_SUCCESS;
+}
+
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_alloc_ppn_set --
+ *
+ *      Allocates two list of PPNs --- one for the pages in the produce queue,
+ *      and the other for the pages in the consume queue. Intializes the list
+ *      of PPNs with the page frame numbers of the KVA for the two queues (and
+ *      the queue headers).
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory may be allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_alloc_ppn_set(void *prodQ,	// IN:
+			    uint64_t numProducePages,	// IN: for queue plus header
+			    void *consQ,	// IN:
+			    uint64_t numConsumePages,	// IN: for queue plus header
+			    struct PPNSet *ppnSet)	// OUT:
+{
+	uint32_t *producePPNs;
+	uint32_t *consumePPNs;
+	struct vmci_queue *produceQ = prodQ;
+	struct vmci_queue *consumeQ = consQ;
+	uint64_t i;
+
+	if (!produceQ || !numProducePages || !consumeQ ||
+	    !numConsumePages || !ppnSet)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	if (ppnSet->initialized)
+		return VMCI_ERROR_ALREADY_EXISTS;
+
+	producePPNs =
+		kmalloc(numProducePages * sizeof *producePPNs, GFP_KERNEL);
+	if (!producePPNs)
+		return VMCI_ERROR_NO_MEM;
+
+	consumePPNs =
+		kmalloc(numConsumePages * sizeof *consumePPNs, GFP_KERNEL);
+	if (!consumePPNs) {
+		kfree(producePPNs);
+		return VMCI_ERROR_NO_MEM;
+	}
+
+	producePPNs[0] = page_to_pfn(vmalloc_to_page(produceQ->qHeader));
+	for (i = 1; i < numProducePages; i++) {
+		unsigned long pfn;
+
+		producePPNs[i] = pfn =
+			page_to_pfn(produceQ->kernelIf->page[i - 1]);
+
+		/* Fail allocation if PFN isn't supported by hypervisor. */
+		if (sizeof pfn > sizeof *producePPNs && pfn != producePPNs[i])
+			goto ppnError;
+	}
+	consumePPNs[0] = page_to_pfn(vmalloc_to_page(consumeQ->qHeader));
+	for (i = 1; i < numConsumePages; i++) {
+		unsigned long pfn;
+
+		consumePPNs[i] = pfn =
+			page_to_pfn(consumeQ->kernelIf->page[i - 1]);
+
+		/* Fail allocation if PFN isn't supported by hypervisor. */
+		if (sizeof pfn > sizeof *consumePPNs && pfn != consumePPNs[i])
+			goto ppnError;
+	}
+
+	ppnSet->numProducePages = numProducePages;
+	ppnSet->numConsumePages = numConsumePages;
+	ppnSet->producePPNs = producePPNs;
+	ppnSet->consumePPNs = consumePPNs;
+	ppnSet->initialized = true;
+	return VMCI_SUCCESS;
+
+ppnError:
+	kfree(producePPNs);
+	kfree(consumePPNs);
+	return VMCI_ERROR_INVALID_ARGS;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_free_ppn_set --
+ *
+ *      Frees the two list of PPNs for a queue pair.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_free_ppn_set(struct PPNSet *ppnSet)	// IN:
+{
+	ASSERT(ppnSet);
+	if (ppnSet->initialized) {
+		/* Do not call these functions on NULL inputs. */
+		ASSERT(ppnSet->producePPNs && ppnSet->consumePPNs);
+		kfree(ppnSet->producePPNs);
+		kfree(ppnSet->consumePPNs);
+	}
+	memset(ppnSet, 0, sizeof *ppnSet);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_populate_ppn_set --
+ *
+ *      Populates the list of PPNs in the hypercall structure with the PPNS
+ *      of the produce queue and the consume queue.
+ *
+ * Results:
+ *      VMCI_SUCCESS.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_populate_ppn_set(uint8_t * callBuf,	// OUT:
+			       const struct PPNSet *ppnSet)	// IN:
+{
+	ASSERT(callBuf && ppnSet && ppnSet->initialized);
+	memcpy(callBuf, ppnSet->producePPNs,
+	       ppnSet->numProducePages * sizeof *ppnSet->producePPNs);
+	memcpy(callBuf +
+	       ppnSet->numProducePages * sizeof *ppnSet->producePPNs,
+	       ppnSet->consumePPNs,
+	       ppnSet->numConsumePages * sizeof *ppnSet->consumePPNs);
+
+	return VMCI_SUCCESS;
+}
+
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_memcpy_to_queue --
+ *
+ *      Copies from a given buffer to a VMCI Queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_memcpy_to_queue(struct vmci_queue *queue,	// OUT:
+				     uint64_t queueOffset,	// IN:
+				     const void *src,	// IN:
+				     size_t srcOffset,	// IN:
+				     size_t size,	// IN:
+				     int bufType)	// IN: Unused
+{
+	return __qp_memcpy_to_queue(queue, queueOffset,
+				    (uint8_t *) src + srcOffset, size, false);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_memcpy_from_queue --
+ *
+ *      Copies to a given buffer from a VMCI Queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_memcpy_from_queue(void *dest,	// OUT:
+				       size_t destOffset,	// IN:
+				       const struct vmci_queue *queue,	// IN:
+				       uint64_t queueOffset,	// IN:
+				       size_t size,	// IN:
+				       int bufType)	// IN: Unused
+{
+	return __qp_memcpy_from_queue((uint8_t *) dest + destOffset,
+				      queue, queueOffset, size, false);
+}
+
+/*
+ *----------------------------------------------------------------------------
+ *
+ * qp_memcpy_to_queue_iov --
+ *
+ *      Copies from a given iovec from a VMCI Queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+static int qp_memcpy_to_queue_iov(struct vmci_queue *queue,	// OUT:
+					 uint64_t queueOffset,	// IN:
+					 const void *src,	// IN: iovec
+					 size_t srcOffset,	// IN: ignored
+					 size_t size,	// IN:
+					 int bufType)	// IN: ignored
+{
+
+	/*
+	 * We ignore srcOffset because src is really a struct iovec * and will
+	 * maintain offset internally.
+	 */
+	return __qp_memcpy_to_queue(queue, queueOffset, src, size, true);
+}
+
+/*
+ *----------------------------------------------------------------------------
+ *
+ * qp_memcpy_from_queue_iov --
+ *
+ *      Copies to a given iovec from a VMCI Queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+static int qp_memcpy_from_queue_iov(void *dest,	// OUT: iovec
+					   size_t destOffset,	// IN: ignored
+					   const struct vmci_queue *queue,	// IN:
+					   uint64_t queueOffset,	// IN:
+					   size_t size,	// IN:
+					   int bufType)	// IN: ignored
+{
+	/*
+	 * We ignore destOffset because dest is really a struct iovec * and will
+	 * maintain offset internally.
+	 */
+	return __qp_memcpy_from_queue(dest, queue, queueOffset, size, true);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_AllocQueue --
+ *
+ *      Allocates kernel VA space of specified size plus space for the queue
+ *      and kernel interface.  This is different from the guest queue allocator,
+ *      because we do not allocate our own queue header/data pages here but
+ *      share those of the guest.
+ *
+ * Results:
+ *      A pointer to an allocated and initialized struct vmci_queue structure or NULL.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+struct vmci_queue *VMCIHost_AllocQueue(uint64_t size)	// IN:
+{
+	struct vmci_queue *queue;
+	const size_t numPages = dm_div_up(size, PAGE_SIZE) + 1;
+	const size_t queueSize = sizeof(*queue) + sizeof(*(queue->kernelIf));
+	const size_t queuePageSize = numPages * sizeof(*queue->kernelIf->page);
+
+	queue = kzalloc(queueSize + queuePageSize, GFP_KERNEL);
+	if (queue) {
+		queue->qHeader = NULL;
+		queue->savedHeader = NULL;
+		queue->kernelIf =
+			(struct vmci_queue_kern_if *)((uint8_t *) queue +
+						      sizeof(*queue));
+		queue->kernelIf->host = true;
+		queue->kernelIf->mutex = NULL;
+		queue->kernelIf->numPages = numPages;
+		queue->kernelIf->headerPage =
+			(struct page **)((uint8_t *) queue + queueSize);
+		queue->kernelIf->page = &queue->kernelIf->headerPage[1];
+		queue->kernelIf->va = NULL;
+		queue->kernelIf->mapped = false;
+	}
+
+	return queue;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_FreeQueue --
+ *
+ *      Frees kernel memory for a given queue (header plus translation
+ *      structure).
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      Memory is freed.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+void VMCIHost_FreeQueue(struct vmci_queue *queue,	// IN:
+			uint64_t queueSize)	// IN:
+{
+	if (queue)
+		kfree(queue);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCI_InitQueueMutex()
+ *
+ *       Initialize the mutex for the pair of queues.  This mutex is used to
+ *       protect the qHeader and the buffer from changing out from under any
+ *       users of either queue.  Of course, it's only any good if the mutexes
+ *       are actually acquired.  Queue structure must lie on non-paged memory
+ *       or we cannot guarantee access to the mutex.
+ *
+ * Results:
+ *       None.
+ *
+ * Side Effects:
+ *       None.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+void VMCI_InitQueueMutex(struct vmci_queue *produceQ,	// IN/OUT
+			 struct vmci_queue *consumeQ)	// IN/OUT
+{
+	ASSERT(produceQ);
+	ASSERT(consumeQ);
+	ASSERT(produceQ->kernelIf);
+	ASSERT(consumeQ->kernelIf);
+
+	/*
+	 * Only the host queue has shared state - the guest queues do not
+	 * need to synchronize access using a queue mutex.
+	 */
+
+	if (produceQ->kernelIf->host) {
+		produceQ->kernelIf->mutex = &produceQ->kernelIf->__mutex;
+		consumeQ->kernelIf->mutex = &produceQ->kernelIf->__mutex;
+		sema_init(produceQ->kernelIf->mutex, 1);
+	}
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCI_CleanupQueueMutex()
+ *
+ *       Cleans up the mutex for the pair of queues.
+ *
+ * Results:
+ *       None.
+ *
+ * Side Effects:
+ *       None.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+void VMCI_CleanupQueueMutex(struct vmci_queue *produceQ,	// IN/OUT
+			    struct vmci_queue *consumeQ)	// IN/OUT
+{
+	ASSERT(produceQ);
+	ASSERT(consumeQ);
+	ASSERT(produceQ->kernelIf);
+	ASSERT(consumeQ->kernelIf);
+
+	if (produceQ->kernelIf->host) {
+		produceQ->kernelIf->mutex = NULL;
+		consumeQ->kernelIf->mutex = NULL;
+	}
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCI_AcquireQueueMutex()
+ *
+ *       Acquire the mutex for the queue.  Note that the produceQ and
+ *       the consumeQ share a mutex.  So, only one of the two need to
+ *       be passed in to this routine.  Either will work just fine.
+ *
+ * Results:
+ *       None.
+ *
+ * Side Effects:
+ *       May block the caller.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+void VMCI_AcquireQueueMutex(struct vmci_queue *queue)	// IN
+{
+	ASSERT(queue);
+	ASSERT(queue->kernelIf);
+
+	if (queue->kernelIf->host) {
+		ASSERT(queue->kernelIf->mutex);
+		down(queue->kernelIf->mutex);
+	}
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCI_ReleaseQueueMutex()
+ *
+ *       Release the mutex for the queue.  Note that the produceQ and
+ *       the consumeQ share a mutex.  So, only one of the two need to
+ *       be passed in to this routine.  Either will work just fine.
+ *
+ * Results:
+ *       None.
+ *
+ * Side Effects:
+ *       May block the caller.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+void VMCI_ReleaseQueueMutex(struct vmci_queue *queue)	// IN
+{
+	ASSERT(queue);
+	ASSERT(queue->kernelIf);
+
+	if (queue->kernelIf->host) {
+		ASSERT(queue->kernelIf->mutex);
+		up(queue->kernelIf->mutex);
+	}
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIReleasePageStorePages --
+ *
+ *       Helper function to release pages in the PageStoreAttachInfo
+ *       previously obtained using get_user_pages.
+ *
+ * Results:
+ *       None.
+ *
+ * Side Effects:
+ *       None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void VMCIReleasePages(struct page **pages,	// IN
+			     uint64_t numPages,	// IN
+			     bool dirty)	// IN
+{
+	int i;
+
+	for (i = 0; i < numPages; i++) {
+		ASSERT(pages[i]);
+
+		if (dirty)
+			set_page_dirty(pages[i]);
+
+		page_cache_release(pages[i]);
+		pages[i] = NULL;
+	}
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_GetUserMemory --
+ *
+ *
+ *       Lock the user pages referenced by the {produce,consume}Buffer
+ *       struct into memory and populate the {produce,consume}Pages
+ *       arrays in the attach structure with them.
+ *
+ * Results:
+ *       VMCI_SUCCESS on sucess, negative error code on failure.
+ *
+ * Side Effects:
+ *       None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int VMCIHost_GetUserMemory(uint64_t produceUVA,	// IN
+			   uint64_t consumeUVA,	// IN
+			   struct vmci_queue *produceQ,	// OUT
+			   struct vmci_queue *consumeQ)	// OUT
+{
+	int retval;
+	int err = VMCI_SUCCESS;
+
+	down_write(&current->mm->mmap_sem);
+	retval = get_user_pages(current,
+				current->mm,
+				(uintptr_t) produceUVA,
+				produceQ->kernelIf->numPages,
+				1, 0, produceQ->kernelIf->headerPage, NULL);
+	if (retval < produceQ->kernelIf->numPages) {
+		pr_warn("get_user_pages(produce) failed (retval=%d)",
+			retval);
+		VMCIReleasePages(produceQ->kernelIf->headerPage, retval, false);
+		err = VMCI_ERROR_NO_MEM;
+		goto out;
+	}
+
+	retval = get_user_pages(current,
+				current->mm,
+				(uintptr_t) consumeUVA,
+				consumeQ->kernelIf->numPages,
+				1, 0, consumeQ->kernelIf->headerPage, NULL);
+	if (retval < consumeQ->kernelIf->numPages) {
+		pr_warn("get_user_pages(consume) failed (retval=%d)",
+			retval);
+		VMCIReleasePages(consumeQ->kernelIf->headerPage, retval, false);
+		VMCIReleasePages(produceQ->kernelIf->headerPage,
+				 produceQ->kernelIf->numPages, false);
+		err = VMCI_ERROR_NO_MEM;
+	}
+
+out:
+	up_write(&current->mm->mmap_sem);
+
+	return err;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_RegisterUserMemory --
+ *
+ *       Registers the specification of the user pages used for backing a queue
+ *       pair. Enough information to map in pages is stored in the OS specific
+ *       part of the struct vmci_queue structure.
+ *
+ * Results:
+ *       VMCI_SUCCESS on sucess, negative error code on failure.
+ *
+ * Side Effects:
+ *       None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int VMCIHost_RegisterUserMemory(QueuePairPageStore * pageStore,	// IN
+				struct vmci_queue *produceQ,	// OUT
+				struct vmci_queue *consumeQ)	// OUT
+{
+	uint64_t produceUVA;
+	uint64_t consumeUVA;
+
+	ASSERT(produceQ->kernelIf->headerPage
+	       && consumeQ->kernelIf->headerPage);
+
+	/*
+	 * The new style and the old style mapping only differs in that we either
+	 * get a single or two UVAs, so we split the single UVA range at the
+	 * appropriate spot.
+	 */
+
+	produceUVA = pageStore->pages;
+	consumeUVA =
+		pageStore->pages + produceQ->kernelIf->numPages * PAGE_SIZE;
+	return VMCIHost_GetUserMemory(produceUVA, consumeUVA, produceQ,
+				      consumeQ);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_UnregisterUserMemory --
+ *
+ *       Releases and removes the references to user pages stored in the attach
+ *       struct.
+ *
+ * Results:
+ *       None
+ *
+ * Side Effects:
+ *       Pages are released from the page cache and may become
+ *       swappable again.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+void VMCIHost_UnregisterUserMemory(struct vmci_queue *produceQ,	// IN/OUT
+				   struct vmci_queue *consumeQ)	// IN/OUT
+{
+	ASSERT(produceQ->kernelIf);
+	ASSERT(consumeQ->kernelIf);
+	ASSERT(!produceQ->qHeader && !consumeQ->qHeader);
+
+	VMCIReleasePages(produceQ->kernelIf->headerPage,
+			 produceQ->kernelIf->numPages, true);
+	memset(produceQ->kernelIf->headerPage, 0,
+	       sizeof *produceQ->kernelIf->headerPage *
+	       produceQ->kernelIf->numPages);
+	VMCIReleasePages(consumeQ->kernelIf->headerPage,
+			 consumeQ->kernelIf->numPages, true);
+	memset(consumeQ->kernelIf->headerPage, 0,
+	       sizeof *consumeQ->kernelIf->headerPage *
+	       consumeQ->kernelIf->numPages);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_MapQueues --
+ *
+ *       Once VMCIHost_RegisterUserMemory has been performed on a
+ *       queue, the queue pair headers can be mapped into the
+ *       kernel. Once mapped, they must be unmapped with
+ *       VMCIHost_UnmapQueues prior to calling
+ *       VMCIHost_UnregisterUserMemory.
+ *
+ * Results:
+ *       VMCI_SUCCESS if pages are mapped, appropriate error code otherwise.
+ *
+ * Side Effects:
+ *       Pages are pinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int VMCIHost_MapQueues(struct vmci_queue *produceQ,	// IN/OUT
+		       struct vmci_queue *consumeQ)	// IN/OUT
+{
+	int result;
+
+	if (!produceQ->qHeader || !consumeQ->qHeader) {
+		struct page *headers[2];
+
+		if (produceQ->qHeader != consumeQ->qHeader)
+			return VMCI_ERROR_QUEUEPAIR_MISMATCH;
+
+		if (produceQ->kernelIf->headerPage == NULL ||
+		    *produceQ->kernelIf->headerPage == NULL)
+			return VMCI_ERROR_UNAVAILABLE;
+
+		ASSERT(*produceQ->kernelIf->headerPage
+		       && *consumeQ->kernelIf->headerPage);
+
+		headers[0] = *produceQ->kernelIf->headerPage;
+		headers[1] = *consumeQ->kernelIf->headerPage;
+
+		produceQ->qHeader = vmap(headers, 2, VM_MAP, PAGE_KERNEL);
+		if (produceQ->qHeader != NULL) {
+			consumeQ->qHeader =
+				(struct vmci_queue_header *)((uint8_t *)
+							     produceQ->qHeader +
+							     PAGE_SIZE);
+			result = VMCI_SUCCESS;
+		} else {
+			pr_warn("vmap failed.");
+			result = VMCI_ERROR_NO_MEM;
+		}
+	} else {
+		result = VMCI_SUCCESS;
+	}
+
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_UnmapQueues --
+ *
+ *       Unmaps previously mapped queue pair headers from the kernel.
+ *
+ * Results:
+ *       VMCI_SUCCESS always.
+ *
+ * Side Effects:
+ *       Pages are unpinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int VMCIHost_UnmapQueues(uint32_t gid,	// IN
+			 struct vmci_queue *produceQ,	// IN/OUT
+			 struct vmci_queue *consumeQ)	// IN/OUT
+{
+	if (produceQ->qHeader) {
+		ASSERT(consumeQ->qHeader);
+
+		if (produceQ->qHeader < consumeQ->qHeader)
+			vunmap(produceQ->qHeader);
+		else
+			vunmap(consumeQ->qHeader);
+
+		produceQ->qHeader = NULL;
+		consumeQ->qHeader = NULL;
+	}
+
+	return VMCI_SUCCESS;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_ReleaseUserMemory --
+ *       Release the reference to user pages stored in the attach
+ *       struct
+ *
+ * Results:
+ *       None
+ *
+ * Side Effects:
+ *       Pages are released from the page cache and may become
+ *       swappable again.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+void VMCIHost_ReleaseUserMemory(struct vmci_queue *produceQ,	// IN/OUT
+				struct vmci_queue *consumeQ)	// IN/OUT
+{
+	ASSERT(produceQ->kernelIf->headerPage);
+
+	VMCIHost_UnregisterUserMemory(produceQ, consumeQ);
+}
+
+
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_list_find --
+ *
+ *      Finds the entry in the list corresponding to a given handle. Assumes
+ *      that the list is locked.
+ *
+ * Results:
+ *      Pointer to entry.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static struct qp_entry *qp_list_find(struct qp_list *qpList,	// IN
+				     struct vmci_handle handle)	// IN
+{
+	struct qp_entry *entry;
+
+	if (VMCI_HANDLE_INVALID(handle))
+		return NULL;
+
+	list_for_each_entry(entry, &qpList->head, listItem) {
+		if (VMCI_HANDLE_EQUAL(entry->handle, handle))
+			return entry;
+	}
+
+	return NULL;
+}
+
+/*
+ *----------------------------------------------------------------------------
+ *
+ * qp_notify_peer_local --
+ *
+ *      Dispatches a queue pair event message directly into the local event
+ *      queue.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, error code otherwise
+ *
+ * Side effects:
+ *      None.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+static int qp_notify_peer_local(bool attach,	// IN: attach or detach?
+				struct vmci_handle handle)	// IN: queue pair handle
+{
+	struct vmci_event_msg *eMsg;
+	struct vmci_event_payld_qp *ePayload;
+	/* buf is only 48 bytes. */
+	char buf[sizeof *eMsg + sizeof *ePayload];
+	uint32_t contextId;
+
+	contextId = VMCI_GetContextID();
+
+	eMsg = (struct vmci_event_msg *)buf;
+	ePayload = vmci_event_data_payload(&eMsg->eventData);
+
+	eMsg->hdr.dst = vmci_make_handle(contextId, VMCI_EVENT_HANDLER);
+	eMsg->hdr.src = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
+					 VMCI_CONTEXT_RESOURCE_ID);
+	eMsg->hdr.payloadSize =
+		sizeof *eMsg + sizeof *ePayload - sizeof eMsg->hdr;
+	eMsg->eventData.event =
+		attach ? VMCI_EVENT_QP_PEER_ATTACH : VMCI_EVENT_QP_PEER_DETACH;
+	ePayload->peerId = contextId;
+	ePayload->handle = handle;
+
+	return vmci_event_dispatch((struct vmci_dg *)eMsg);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_guest_endpoint_create --
+ *
+ *      Allocates and initializes a qp_guest_endpoint structure.
+ *      Allocates a QueuePair rid (and handle) iff the given entry has
+ *      an invalid handle.  0 through VMCI_RESERVED_RESOURCE_ID_MAX
+ *      are reserved handles.  Assumes that the QP list mutex is held
+ *      by the caller.
+ *
+ * Results:
+ *      Pointer to structure intialized.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static struct qp_guest_endpoint *qp_guest_endpoint_create(struct vmci_handle handle,	// IN
+							  uint32_t peer,	// IN
+							  uint32_t flags,	// IN
+							  uint64_t produceSize,	// IN
+							  uint64_t consumeSize,	// IN
+							  void *produceQ,	// IN
+							  void *consumeQ)	// IN
+{
+	static uint32_t queuePairRID = VMCI_RESERVED_RESOURCE_ID_MAX + 1;
+	struct qp_guest_endpoint *entry;
+	const uint64_t numPPNs = dm_div_up(produceSize, PAGE_SIZE) + dm_div_up(consumeSize, PAGE_SIZE) + 2;	/* One page each for the queue headers. */
+
+	ASSERT((produceSize || consumeSize) && produceQ && consumeQ);
+
+	if (VMCI_HANDLE_INVALID(handle)) {
+		uint32_t contextID = VMCI_GetContextID();
+		uint32_t oldRID = queuePairRID;
+
+		/*
+		 * Generate a unique QueuePair rid.  Keep on trying until we wrap around
+		 * in the RID space.
+		 */
+		ASSERT(oldRID > VMCI_RESERVED_RESOURCE_ID_MAX);
+		do {
+			handle = vmci_make_handle(contextID, queuePairRID);
+			entry = (struct qp_guest_endpoint *)
+				qp_list_find(&qpGuestEndpoints, handle);
+			queuePairRID++;
+
+			if (unlikely(!queuePairRID))
+				/* Skip the reserved rids. */
+				queuePairRID = 
+				  VMCI_RESERVED_RESOURCE_ID_MAX + 1;
+
+		} while (entry && queuePairRID != oldRID);
+
+		if (unlikely(entry != NULL)) {
+			ASSERT(queuePairRID == oldRID);
+			/*
+			 * We wrapped around --- no rids were free.
+			 */
+			return NULL;
+		}
+	}
+
+	ASSERT(!VMCI_HANDLE_INVALID(handle) &&
+	       qp_list_find(&qpGuestEndpoints, handle) == NULL);
+	entry = kzalloc(sizeof *entry, GFP_KERNEL);
+	if (entry) {
+		entry->qp.handle = handle;
+		entry->qp.peer = peer;
+		entry->qp.flags = flags;
+		entry->qp.produceSize = produceSize;
+		entry->qp.consumeSize = consumeSize;
+		entry->qp.refCount = 0;
+		entry->numPPNs = numPPNs;
+		entry->produceQ = produceQ;
+		entry->consumeQ = consumeQ;
+		INIT_LIST_HEAD(&entry->qp.listItem);
+	}
+	return entry;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_guest_endpoint_destroy --
+ *
+ *      Frees a QPGuestEndpoint structure.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_guest_endpoint_destroy(struct qp_guest_endpoint *entry)	// IN
+{
+	ASSERT(entry);
+	ASSERT(entry->qp.refCount == 0);
+
+	qp_free_ppn_set(&entry->ppnSet);
+	VMCI_CleanupQueueMutex(entry->produceQ, entry->consumeQ);
+	qp_free_queue(entry->produceQ, entry->qp.produceSize);
+	qp_free_queue(entry->consumeQ, entry->qp.consumeSize);
+	kfree(entry);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_alloc_hypercall --
+ *
+ *      Helper to make a QueuePairAlloc hypercall when the driver is
+ *      supporting a guest device.
+ *
+ * Results:
+ *      Result of the hypercall.
+ *
+ * Side effects:
+ *      Memory is allocated & freed.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_alloc_hypercall(const struct qp_guest_endpoint *entry)	// IN
+{
+	struct vmci_qp_alloc_msg *allocMsg;
+	size_t msgSize;
+	int result;
+
+	if (!entry || entry->numPPNs <= 2)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	ASSERT(!(entry->qp.flags & VMCI_QPFLAG_LOCAL));
+
+	msgSize = sizeof *allocMsg + (size_t) entry->numPPNs * sizeof(uint32_t);
+	allocMsg = kmalloc(msgSize, GFP_KERNEL);
+	if (!allocMsg)
+		return VMCI_ERROR_NO_MEM;
+
+	allocMsg->hdr.dst = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
+					     VMCI_QUEUEPAIR_ALLOC);
+	allocMsg->hdr.src = VMCI_ANON_SRC_HANDLE;
+	allocMsg->hdr.payloadSize = msgSize - VMCI_DG_HEADERSIZE;
+	allocMsg->handle = entry->qp.handle;
+	allocMsg->peer = entry->qp.peer;
+	allocMsg->flags = entry->qp.flags;
+	allocMsg->produceSize = entry->qp.produceSize;
+	allocMsg->consumeSize = entry->qp.consumeSize;
+	allocMsg->numPPNs = entry->numPPNs;
+
+	result =
+		qp_populate_ppn_set((uint8_t *) allocMsg + sizeof *allocMsg,
+				    &entry->ppnSet);
+	if (result == VMCI_SUCCESS)
+		result = vmci_send_dg((struct vmci_dg *)allocMsg);
+
+	kfree(allocMsg);
+
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_detatch_hypercall --
+ *
+ *      Helper to make a QueuePairDetach hypercall when the driver is
+ *      supporting a guest device.
+ *
+ * Results:
+ *      Result of the hypercall.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_detatch_hypercall(struct vmci_handle handle)	// IN
+{
+	struct vmci_qp_detach_msg detachMsg;
+
+	detachMsg.hdr.dst = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
+					     VMCI_QUEUEPAIR_DETACH);
+	detachMsg.hdr.src = VMCI_ANON_SRC_HANDLE;
+	detachMsg.hdr.payloadSize = sizeof handle;
+	detachMsg.handle = handle;
+
+	return vmci_send_dg((struct vmci_dg *)&detachMsg);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_list_add_entry --
+ *
+ *      Adds the given entry to the list. Assumes that the list is locked.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_list_add_entry(struct qp_list *qpList,	// IN
+				     struct qp_entry *entry)	// IN
+{
+	if (entry)
+		list_add(&entry->listItem, &qpList->head);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_list_remove_entry --
+ *
+ *      Removes the given entry from the list. Assumes that the list is locked.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_list_remove_entry(struct qp_list *qpList,	// IN
+					struct qp_entry *entry)	// IN
+{
+	if (entry)
+		list_del(&entry->listItem);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_detatch_guest_work --
+ *
+ *      Helper for VMCI QueuePair detach interface. Frees the physical
+ *      pages for the queue pair.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory may be freed.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_detatch_guest_work(struct vmci_handle handle)	// IN
+{
+	int result;
+	struct qp_guest_endpoint *entry;
+	uint32_t refCount = ~0;	/* To avoid compiler warning below */
+
+	ASSERT(!VMCI_HANDLE_INVALID(handle));
+
+	down(&qpGuestEndpoints.mutex);
+
+	entry = (struct qp_guest_endpoint *)
+		qp_list_find(&qpGuestEndpoints, handle);
+	if (!entry) {
+		up(&qpGuestEndpoints.mutex);
+		return VMCI_ERROR_NOT_FOUND;
+	}
+
+	ASSERT(entry->qp.refCount >= 1);
+
+	if (entry->qp.flags & VMCI_QPFLAG_LOCAL) {
+		result = VMCI_SUCCESS;
+
+		if (entry->qp.refCount > 1) {
+			result = qp_notify_peer_local(false, handle);
+			/*
+			 * We can fail to notify a local queuepair because we can't allocate.
+			 * We still want to release the entry if that happens, so don't bail
+			 * out yet.
+			 */
+		}
+	} else {
+		result = qp_detatch_hypercall(handle);
+		if (result < VMCI_SUCCESS) {
+			/*
+			 * We failed to notify a non-local queuepair.  That other queuepair
+			 * might still be accessing the shared memory, so don't release the
+			 * entry yet.  It will get cleaned up by VMCIQueuePair_Exit()
+			 * if necessary (assuming we are going away, otherwise why did this
+			 * fail?).
+			 */
+
+			up(&qpGuestEndpoints.mutex);
+			return result;
+		}
+	}
+
+	/*
+	 * If we get here then we either failed to notify a local queuepair, or
+	 * we succeeded in all cases.  Release the entry if required.
+	 */
+
+	entry->qp.refCount--;
+	if (entry->qp.refCount == 0)
+		qp_list_remove_entry(&qpGuestEndpoints, &entry->qp);
+
+	/* If we didn't remove the entry, this could change once we unlock. */
+	if (entry)
+		refCount = entry->qp.refCount;
+
+	up(&qpGuestEndpoints.mutex);
+
+	if (refCount == 0)
+		qp_guest_endpoint_destroy(entry);
+
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_alloc_guest_work --
+ *
+ *      This functions handles the actual allocation of a VMCI queue
+ *      pair guest endpoint. Allocates physical pages for the queue
+ *      pair. It makes OS dependent calls through generic wrappers.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory is allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_alloc_guest_work(struct vmci_handle *handle,	// IN/OUT
+			       struct vmci_queue **produceQ,	// OUT
+			       uint64_t produceSize,	// IN
+			       struct vmci_queue **consumeQ,	// OUT
+			       uint64_t consumeSize,	// IN
+			       uint32_t peer,	// IN
+			       uint32_t flags,	// IN
+			       uint32_t privFlags)	// IN
+{
+	const uint64_t numProducePages = dm_div_up(produceSize, PAGE_SIZE) + 1;
+	const uint64_t numConsumePages = dm_div_up(consumeSize, PAGE_SIZE) + 1;
+	void *myProduceQ = NULL;
+	void *myConsumeQ = NULL;
+	int result;
+	struct qp_guest_endpoint *queuePairEntry = NULL;
+
+	ASSERT(handle && produceQ && consumeQ && (produceSize || consumeSize));
+
+	if (privFlags != VMCI_NO_PRIVILEGE_FLAGS)
+		return VMCI_ERROR_NO_ACCESS;
+
+	down(&qpGuestEndpoints.mutex);
+
+	if ((queuePairEntry = (struct qp_guest_endpoint *)
+	     qp_list_find(&qpGuestEndpoints, *handle))) {
+		if (queuePairEntry->qp.flags & VMCI_QPFLAG_LOCAL) {
+			/* Local attach case. */
+			if (queuePairEntry->qp.refCount > 1) {
+				pr_devel("Error attempting to attach more than "
+					 "once.");
+				result = VMCI_ERROR_UNAVAILABLE;
+				goto errorKeepEntry;
+			}
+
+			if (queuePairEntry->qp.produceSize != consumeSize
+			    || queuePairEntry->qp.consumeSize !=
+			    produceSize
+			    || queuePairEntry->qp.flags !=
+			    (flags & ~VMCI_QPFLAG_ATTACH_ONLY)) {
+				pr_devel("Error mismatched queue pair in local "
+					 "attach.");
+				result = VMCI_ERROR_QUEUEPAIR_MISMATCH;
+				goto errorKeepEntry;
+			}
+
+			/*
+			 * Do a local attach.  We swap the consume and produce queues for the
+			 * attacher and deliver an attach event.
+			 */
+			result = qp_notify_peer_local(true, *handle);
+			if (result < VMCI_SUCCESS)
+				goto errorKeepEntry;
+
+			myProduceQ = queuePairEntry->consumeQ;
+			myConsumeQ = queuePairEntry->produceQ;
+			goto out;
+		}
+		result = VMCI_ERROR_ALREADY_EXISTS;
+		goto errorKeepEntry;
+	}
+
+	myProduceQ = qp_alloc_queue(produceSize, flags);
+	if (!myProduceQ) {
+		pr_warn("Error allocating pages for produce queue.");
+		result = VMCI_ERROR_NO_MEM;
+		goto error;
+	}
+
+	myConsumeQ = qp_alloc_queue(consumeSize, flags);
+	if (!myConsumeQ) {
+		pr_warn("Error allocating pages for consume queue.");
+		result = VMCI_ERROR_NO_MEM;
+		goto error;
+	}
+
+	queuePairEntry = qp_guest_endpoint_create(*handle, peer, flags,
+						  produceSize, consumeSize,
+						  myProduceQ, myConsumeQ);
+	if (!queuePairEntry) {
+		pr_warn("Error allocating memory in %s.", __FUNCTION__);
+		result = VMCI_ERROR_NO_MEM;
+		goto error;
+	}
+
+	result = qp_alloc_ppn_set(myProduceQ, numProducePages, myConsumeQ,
+				  numConsumePages, &queuePairEntry->ppnSet);
+	if (result < VMCI_SUCCESS) {
+		pr_warn("qp_alloc_ppn_set failed.");
+		goto error;
+	}
+
+	/*
+	 * It's only necessary to notify the host if this queue pair will be
+	 * attached to from another context.
+	 */
+	if (queuePairEntry->qp.flags & VMCI_QPFLAG_LOCAL) {
+		/* Local create case. */
+		uint32_t contextId = VMCI_GetContextID();
+
+		/*
+		 * Enforce similar checks on local queue pairs as we do for regular ones.
+		 * The handle's context must match the creator or attacher context id
+		 * (here they are both the current context id) and the attach-only flag
+		 * cannot exist during create.  We also ensure specified peer is this
+		 * context or an invalid one.
+		 */
+		if (queuePairEntry->qp.handle.context != contextId ||
+		    (queuePairEntry->qp.peer != VMCI_INVALID_ID &&
+		     queuePairEntry->qp.peer != contextId)) {
+			result = VMCI_ERROR_NO_ACCESS;
+			goto error;
+		}
+
+		if (queuePairEntry->qp.flags & VMCI_QPFLAG_ATTACH_ONLY) {
+			result = VMCI_ERROR_NOT_FOUND;
+			goto error;
+		}
+	} else {
+		result = qp_alloc_hypercall(queuePairEntry);
+		if (result < VMCI_SUCCESS) {
+			pr_warn("qp_alloc_hypercall result = %d.",
+				result);
+			goto error;
+		}
+	}
+
+	VMCI_InitQueueMutex((struct vmci_queue *)myProduceQ,
+			    (struct vmci_queue *)myConsumeQ);
+
+	qp_list_add_entry(&qpGuestEndpoints, &queuePairEntry->qp);
+
+out:
+	queuePairEntry->qp.refCount++;
+	*handle = queuePairEntry->qp.handle;
+	*produceQ = (struct vmci_queue *)myProduceQ;
+	*consumeQ = (struct vmci_queue *)myConsumeQ;
+
+	/*
+	 * We should initialize the queue pair header pages on a local queue pair
+	 * create.  For non-local queue pairs, the hypervisor initializes the header
+	 * pages in the create step.
+	 */
+	if ((queuePairEntry->qp.flags & VMCI_QPFLAG_LOCAL) &&
+	    queuePairEntry->qp.refCount == 1) {
+		vmci_q_header_init((*produceQ)->qHeader, *handle);
+		vmci_q_header_init((*consumeQ)->qHeader, *handle);
+	}
+
+	up(&qpGuestEndpoints.mutex);
+
+	return VMCI_SUCCESS;
+
+error:
+	up(&qpGuestEndpoints.mutex);
+	if (queuePairEntry) {
+		/* The queues will be freed inside the destroy routine. */
+		qp_guest_endpoint_destroy(queuePairEntry);
+	} else {
+		if (myProduceQ) {
+			qp_free_queue(myProduceQ, produceSize);
+		}
+		if (myConsumeQ) {
+			qp_free_queue(myConsumeQ, consumeSize);
+		}
+	}
+	return result;
+
+errorKeepEntry:
+	/* This path should only be used when an existing entry was found. */
+	ASSERT(queuePairEntry->qp.refCount > 0);
+	up(&qpGuestEndpoints.mutex);
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_broker_create --
+ *
+ *      The first endpoint issuing a queue pair allocation will create the state
+ *      of the queue pair in the queue pair broker.
+ *
+ *      If the creator is a guest, it will associate a VMX virtual address range
+ *      with the queue pair as specified by the pageStore. For compatibility with
+ *      older VMX'en, that would use a separate step to set the VMX virtual
+ *      address range, the virtual address range can be registered later using
+ *      vmci_qp_broker_set_page_store. In that case, a pageStore of NULL should be
+ *      used.
+ *
+ *      If the creator is the host, a pageStore of NULL should be used as well,
+ *      since the host is not able to supply a page store for the queue pair.
+ *
+ *      For older VMX and host callers, the queue pair will be created in the
+ *      VMCIQPB_CREATED_NO_MEM state, and for current VMX callers, it will be
+ *      created in VMCOQPB_CREATED_MEM state.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, appropriate error code otherwise.
+ *
+ * Side effects:
+ *      Memory will be allocated, and pages may be pinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_broker_create(struct vmci_handle handle,	// IN
+			    uint32_t peer,	// IN
+			    uint32_t flags,	// IN
+			    uint32_t privFlags,	// IN
+			    uint64_t produceSize,	// IN
+			    uint64_t consumeSize,	// IN
+			    QueuePairPageStore * pageStore,	// IN
+			    struct vmci_ctx *context,	// IN: Caller
+			    VMCIEventReleaseCB wakeupCB,	// IN
+			    void *clientData,	// IN
+			    struct qp_broker_entry **ent)	// OUT
+{
+	struct qp_broker_entry *entry = NULL;
+	const uint32_t contextId = vmci_ctx_get_id(context);
+	bool isLocal = flags & VMCI_QPFLAG_LOCAL;
+	int result;
+	uint64_t guestProduceSize;
+	uint64_t guestConsumeSize;
+
+	/*
+	 * Do not create if the caller asked not to.
+	 */
+
+	if (flags & VMCI_QPFLAG_ATTACH_ONLY) {
+		return VMCI_ERROR_NOT_FOUND;
+	}
+
+	/*
+	 * Creator's context ID should match handle's context ID or the creator
+	 * must allow the context in handle's context ID as the "peer".
+	 */
+
+	if (handle.context != contextId && handle.context != peer) {
+		return VMCI_ERROR_NO_ACCESS;
+	}
+
+	if (VMCI_CONTEXT_IS_VM(contextId) && VMCI_CONTEXT_IS_VM(peer)) {
+		return VMCI_ERROR_DST_UNREACHABLE;
+	}
+
+	/*
+	 * Creator's context ID for local queue pairs should match the
+	 * peer, if a peer is specified.
+	 */
+
+	if (isLocal && peer != VMCI_INVALID_ID && contextId != peer) {
+		return VMCI_ERROR_NO_ACCESS;
+	}
+
+	entry = kzalloc(sizeof *entry, GFP_ATOMIC);
+	if (!entry) {
+		return VMCI_ERROR_NO_MEM;
+	}
+
+	if (vmci_ctx_get_id(context) == VMCI_HOST_CONTEXT_ID && !isLocal) {
+		/*
+		 * The queue pair broker entry stores values from the guest
+		 * point of view, so a creating host side endpoint should swap
+		 * produce and consume values -- unless it is a local queue
+		 * pair, in which case no swapping is necessary, since the local
+		 * attacher will swap queues.
+		 */
+
+		guestProduceSize = consumeSize;
+		guestConsumeSize = produceSize;
+	} else {
+		guestProduceSize = produceSize;
+		guestConsumeSize = consumeSize;
+	}
+
+	entry->qp.handle = handle;
+	entry->qp.peer = peer;
+	entry->qp.flags = flags;
+	entry->qp.produceSize = guestProduceSize;
+	entry->qp.consumeSize = guestConsumeSize;
+	entry->qp.refCount = 1;
+	entry->createId = contextId;
+	entry->attachId = VMCI_INVALID_ID;
+	entry->state = VMCIQPB_NEW;
+	entry->requireTrustedAttach =
+		(context->privFlags & VMCI_PRIVILEGE_FLAG_RESTRICTED) ? true :
+		false;
+	entry->createdByTrusted =
+		(privFlags & VMCI_PRIVILEGE_FLAG_TRUSTED) ? true : false;
+	entry->vmciPageFiles = false;
+	entry->wakeupCB = wakeupCB;
+	entry->clientData = clientData;
+	entry->produceQ = VMCIHost_AllocQueue(guestProduceSize);
+	if (entry->produceQ == NULL) {
+		result = VMCI_ERROR_NO_MEM;
+		goto error;
+	}
+	entry->consumeQ = VMCIHost_AllocQueue(guestConsumeSize);
+	if (entry->consumeQ == NULL) {
+		result = VMCI_ERROR_NO_MEM;
+		goto error;
+	}
+
+	VMCI_InitQueueMutex(entry->produceQ, entry->consumeQ);
+
+	INIT_LIST_HEAD(&entry->qp.listItem);
+
+	if (isLocal) {
+		ASSERT(pageStore == NULL);
+
+		entry->localMem =
+			kmalloc(QPE_NUM_PAGES(entry->qp) * PAGE_SIZE, GFP_KERNEL);
+		if (entry->localMem == NULL) {
+			result = VMCI_ERROR_NO_MEM;
+			goto error;
+		}
+		entry->state = VMCIQPB_CREATED_MEM;
+		entry->produceQ->qHeader = entry->localMem;
+		entry->consumeQ->qHeader =
+			(struct vmci_queue_header *)((uint8_t *) entry->localMem +
+						     (dm_div_up
+						      (entry->qp.produceSize,
+						       PAGE_SIZE) + 1) * PAGE_SIZE);
+		vmci_q_header_init(entry->produceQ->qHeader, handle);
+		vmci_q_header_init(entry->consumeQ->qHeader, handle);
+	} else if (pageStore) {
+		ASSERT(entry->createId != VMCI_HOST_CONTEXT_ID || isLocal);
+
+		/*
+		 * The VMX already initialized the queue pair headers, so no
+		 * need for the kernel side to do that.
+		 */
+
+		result = VMCIHost_RegisterUserMemory(pageStore,
+						     entry->produceQ,
+						     entry->consumeQ);
+		if (result < VMCI_SUCCESS) {
+			goto error;
+		}
+		entry->state = VMCIQPB_CREATED_MEM;
+	} else {
+		/*
+		 * A create without a pageStore may be either a host side create (in which
+		 * case we are waiting for the guest side to supply the memory) or an old
+		 * style queue pair create (in which case we will expect a set page store
+		 * call as the next step).
+		 */
+
+		entry->state = VMCIQPB_CREATED_NO_MEM;
+	}
+
+	qp_list_add_entry(&qpBrokerList, &entry->qp);
+	if (ent != NULL)
+		*ent = entry;
+
+	vmci_ctx_qp_create(context, handle);
+
+	return VMCI_SUCCESS;
+
+error:
+	if (entry != NULL) {
+		if (entry->produceQ != NULL)
+			VMCIHost_FreeQueue(entry->produceQ, guestProduceSize);
+
+		if (entry->consumeQ != NULL)
+			VMCIHost_FreeQueue(entry->consumeQ, guestConsumeSize);
+
+		kfree(entry);
+	}
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_notify_peer --
+ *
+ *      Enqueues an event datagram to notify the peer VM attached to
+ *      the given queue pair handle about attach/detach event by the
+ *      given VM.
+ *
+ * Results:
+ *      Payload size of datagram enqueued on success, error code otherwise.
+ *
+ * Side effects:
+ *      Memory is allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_notify_peer(bool attach,	// IN: attach or detach?
+			  struct vmci_handle handle,	// IN
+			  uint32_t myId,	// IN
+			  uint32_t peerId)	// IN: CID of VM to notify
+{
+	int rv;
+	struct vmci_event_msg *eMsg;
+	struct vmci_event_payld_qp *evPayload;
+	char buf[sizeof *eMsg + sizeof *evPayload];
+
+	if (VMCI_HANDLE_INVALID(handle) || myId == VMCI_INVALID_ID ||
+	    peerId == VMCI_INVALID_ID)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	/*
+	 * Notification message contains: queue pair handle and
+	 * attaching/detaching VM's context id.
+	 */
+
+	eMsg = (struct vmci_event_msg *)buf;
+
+	/*
+	 * In vmci_ctx_enqueue_dg() we enforce the upper limit on number of
+	 * pending events from the hypervisor to a given VM otherwise a rogue VM
+	 * could do an arbitrary number of attach and detach operations causing memory
+	 * pressure in the host kernel.
+	 */
+
+	/* Clear out any garbage. */
+	memset(eMsg, 0, sizeof buf);
+
+	eMsg->hdr.dst = vmci_make_handle(peerId, VMCI_EVENT_HANDLER);
+	eMsg->hdr.src = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
+					 VMCI_CONTEXT_RESOURCE_ID);
+	eMsg->hdr.payloadSize =
+		sizeof *eMsg + sizeof *evPayload - sizeof eMsg->hdr;
+	eMsg->eventData.event =
+		attach ? VMCI_EVENT_QP_PEER_ATTACH : VMCI_EVENT_QP_PEER_DETACH;
+	evPayload = vmci_event_data_payload(&eMsg->eventData);
+	evPayload->handle = handle;
+	evPayload->peerId = myId;
+
+	rv = vmci_dg_dispatch(VMCI_HYPERVISOR_CONTEXT_ID,
+			      (struct vmci_dg *)eMsg, false);
+	if (rv < VMCI_SUCCESS)
+		pr_warn("Failed to enqueue QueuePair %s event datagram "
+			"for context (ID=0x%x).",
+			attach ? "ATTACH" : "DETACH", peerId);
+
+	return rv;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_broker_attach --
+ *
+ *      The second endpoint issuing a queue pair allocation will attach to the
+ *      queue pair registered with the queue pair broker.
+ *
+ *      If the attacher is a guest, it will associate a VMX virtual address range
+ *      with the queue pair as specified by the pageStore. At this point, the
+ *      already attach host endpoint may start using the queue pair, and an
+ *      attach event is sent to it. For compatibility with older VMX'en, that
+ *      used a separate step to set the VMX virtual address range, the virtual
+ *      address range can be registered later using vmci_qp_broker_set_page_store. In
+ *      that case, a pageStore of NULL should be used, and the attach event will
+ *      be generated once the actual page store has been set.
+ *
+ *      If the attacher is the host, a pageStore of NULL should be used as well,
+ *      since the page store information is already set by the guest.
+ *
+ *      For new VMX and host callers, the queue pair will be moved to the
+ *      VMCIQPB_ATTACHED_MEM state, and for older VMX callers, it will be
+ *      moved to the VMCOQPB_ATTACHED_NO_MEM state.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, appropriate error code otherwise.
+ *
+ * Side effects:
+ *      Memory will be allocated, and pages may be pinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_broker_attach(struct qp_broker_entry *entry,	// IN
+			    uint32_t peer,	// IN
+			    uint32_t flags,	// IN
+			    uint32_t privFlags,	// IN
+			    uint64_t produceSize,	// IN
+			    uint64_t consumeSize,	// IN
+			    QueuePairPageStore * pageStore,	// IN/OUT
+			    struct vmci_ctx *context,	// IN: Caller
+			    VMCIEventReleaseCB wakeupCB,	// IN
+			    void *clientData,	// IN
+			    struct qp_broker_entry **ent)	// OUT
+{
+	const uint32_t contextId = vmci_ctx_get_id(context);
+	bool isLocal = flags & VMCI_QPFLAG_LOCAL;
+	int result;
+
+	if (entry->state != VMCIQPB_CREATED_NO_MEM &&
+	    entry->state != VMCIQPB_CREATED_MEM)
+		return VMCI_ERROR_UNAVAILABLE;
+
+	if (isLocal) {
+		if (!(entry->qp.flags & VMCI_QPFLAG_LOCAL) ||
+		    contextId != entry->createId) {
+			return VMCI_ERROR_INVALID_ARGS;
+		}
+	} else if (contextId == entry->createId ||
+		   contextId == entry->attachId) {
+		return VMCI_ERROR_ALREADY_EXISTS;
+	}
+
+	ASSERT(entry->qp.refCount < 2);
+	ASSERT(entry->attachId == VMCI_INVALID_ID);
+
+	if (VMCI_CONTEXT_IS_VM(contextId) &&
+	    VMCI_CONTEXT_IS_VM(entry->createId))
+		return VMCI_ERROR_DST_UNREACHABLE;
+
+	/*
+	 * If we are attaching from a restricted context then the queuepair
+	 * must have been created by a trusted endpoint.
+	 */
+	if ((context->privFlags & VMCI_PRIVILEGE_FLAG_RESTRICTED) &&
+	    !entry->createdByTrusted)
+		return VMCI_ERROR_NO_ACCESS;
+
+	/*
+	 * If we are attaching to a queuepair that was created by a restricted
+	 * context then we must be trusted.
+	 */
+	if (entry->requireTrustedAttach &&
+	    (!(privFlags & VMCI_PRIVILEGE_FLAG_TRUSTED)))
+		return VMCI_ERROR_NO_ACCESS;
+
+	/*
+	 * If the creator specifies VMCI_INVALID_ID in "peer" field, access
+	 * control check is not performed.
+	 */
+
+	if (entry->qp.peer != VMCI_INVALID_ID && entry->qp.peer != contextId)
+		return VMCI_ERROR_NO_ACCESS;
+
+	if (entry->createId == VMCI_HOST_CONTEXT_ID) {
+		/*
+		 * Do not attach if the caller doesn't support Host Queue Pairs
+		 * and a host created this queue pair.
+		 */
+
+		if (!vmci_ctx_supports_host_qp(context))
+			return VMCI_ERROR_INVALID_RESOURCE;
+
+	} else if (contextId == VMCI_HOST_CONTEXT_ID) {
+		struct vmci_ctx *createContext;
+		bool supportsHostQP;
+
+		/*
+		 * Do not attach a host to a user created queue pair if that
+		 * user doesn't support host queue pair end points.
+		 */
+
+		createContext = vmci_ctx_get(entry->createId);
+		supportsHostQP = vmci_ctx_supports_host_qp(createContext);
+		vmci_ctx_release(createContext);
+
+		if (!supportsHostQP)
+			return VMCI_ERROR_INVALID_RESOURCE;
+	}
+
+	if ((entry->qp.flags & ~VMCI_QP_ASYMM) != (flags & ~VMCI_QP_ASYMM_PEER))
+		return VMCI_ERROR_QUEUEPAIR_MISMATCH;
+
+	if (contextId != VMCI_HOST_CONTEXT_ID) {
+		/*
+		 * The queue pair broker entry stores values from the guest
+		 * point of view, so an attaching guest should match the values
+		 * stored in the entry.
+		 */
+
+		if (entry->qp.produceSize != produceSize ||
+		    entry->qp.consumeSize != consumeSize) {
+			return VMCI_ERROR_QUEUEPAIR_MISMATCH;
+		}
+	} else if (entry->qp.produceSize != consumeSize ||
+		   entry->qp.consumeSize != produceSize) {
+		return VMCI_ERROR_QUEUEPAIR_MISMATCH;
+	}
+
+	if (contextId != VMCI_HOST_CONTEXT_ID) {
+		/*
+		 * If a guest attached to a queue pair, it will supply the backing memory.
+		 * If this is a pre NOVMVM vmx, the backing memory will be supplied by
+		 * calling vmci_qp_broker_set_page_store() following the return of the
+		 * vmci_qp_broker_alloc() call. If it is a vmx of version NOVMVM or later,
+		 * the page store must be supplied as part of the vmci_qp_broker_alloc call.
+		 * Under all circumstances must the initially created queue pair not have
+		 * any memory associated with it already.
+		 */
+
+		if (entry->state != VMCIQPB_CREATED_NO_MEM)
+			return VMCI_ERROR_INVALID_ARGS;
+
+		if (pageStore != NULL) {
+			/*
+			 * Patch up host state to point to guest supplied memory. The VMX
+			 * already initialized the queue pair headers, so no need for the
+			 * kernel side to do that.
+			 */
+
+			result = VMCIHost_RegisterUserMemory(pageStore,
+							     entry->produceQ,
+							     entry->consumeQ);
+			if (result < VMCI_SUCCESS)
+				return result;
+
+			/*
+			 * Preemptively load in the headers if non-blocking to
+			 * prevent blocking later.
+			 */
+			if (entry->qp.flags & VMCI_QPFLAG_NONBLOCK) {
+				result = VMCIHost_MapQueues(entry->produceQ,
+							    entry->consumeQ);
+				if (result < VMCI_SUCCESS) {
+					VMCIHost_ReleaseUserMemory(entry->
+								   produceQ,
+								   entry->
+								   consumeQ);
+					return result;
+				}
+			}
+
+			entry->state = VMCIQPB_ATTACHED_MEM;
+		} else {
+			entry->state = VMCIQPB_ATTACHED_NO_MEM;
+		}
+	} else if (entry->state == VMCIQPB_CREATED_NO_MEM) {
+		/*
+		 * The host side is attempting to attach to a queue pair that doesn't have
+		 * any memory associated with it. This must be a pre NOVMVM vmx that hasn't
+		 * set the page store information yet, or a quiesced VM.
+		 */
+
+		return VMCI_ERROR_UNAVAILABLE;
+	} else {
+		/*
+		 * For non-blocking queue pairs, we cannot rely on enqueue/dequeue to map
+		 * in the pages on the host-side, since it may block, so we make an attempt
+		 * here.
+		 */
+
+		if (flags & VMCI_QPFLAG_NONBLOCK) {
+			result =
+				VMCIHost_MapQueues(entry->produceQ,
+						   entry->consumeQ);
+			if (result < VMCI_SUCCESS)
+				return result;
+
+			entry->qp.flags |= flags &
+				(VMCI_QPFLAG_NONBLOCK | VMCI_QPFLAG_PINNED);
+		}
+
+		/* The host side has successfully attached to a queue pair. */
+		entry->state = VMCIQPB_ATTACHED_MEM;
+	}
+
+	if (entry->state == VMCIQPB_ATTACHED_MEM) {
+		result =
+			qp_notify_peer(true, entry->qp.handle, contextId,
+				       entry->createId);
+		if (result < VMCI_SUCCESS)
+			pr_warn("Failed to notify peer (ID=0x%x) of "
+				"attach to queue pair (handle=0x%x:0x%x).",
+				entry->createId, entry->qp.handle.context,
+				entry->qp.handle.resource);
+	}
+
+	entry->attachId = contextId;
+	entry->qp.refCount++;
+	if (wakeupCB) {
+		ASSERT(!entry->wakeupCB);
+		entry->wakeupCB = wakeupCB;
+		entry->clientData = clientData;
+	}
+
+	/*
+	 * When attaching to local queue pairs, the context already has
+	 * an entry tracking the queue pair, so don't add another one.
+	 */
+
+	if (!isLocal)
+		vmci_ctx_qp_create(context, entry->qp.handle);
+        else
+		ASSERT(vmci_ctx_qp_exists(context, entry->qp.handle));
+
+	if (ent != NULL)
+		*ent = entry;
+
+	return VMCI_SUCCESS;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_broker_alloc --
+ *
+ *      QueuePair_Alloc for use when setting up queue pair endpoints
+ *      on the host. Like QueuePair_Alloc, but returns a pointer to
+ *      the struct qp_broker_entry on success.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory may be allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_broker_alloc(struct vmci_handle handle,	// IN
+			   uint32_t peer,	// IN
+			   uint32_t flags,	// IN
+			   uint32_t privFlags,	// IN
+			   uint64_t produceSize,	// IN
+			   uint64_t consumeSize,	// IN
+			   QueuePairPageStore * pageStore,	// IN/OUT
+			   struct vmci_ctx *context,	// IN: Caller
+			   VMCIEventReleaseCB wakeupCB,	// IN
+			   void *clientData,	// IN
+			   struct qp_broker_entry **ent,	// OUT
+			   bool * swap)	// OUT: swap queues?
+{
+	const uint32_t contextId = vmci_ctx_get_id(context);
+	bool create;
+	struct qp_broker_entry *entry;
+	bool isLocal = flags & VMCI_QPFLAG_LOCAL;
+	int result;
+
+	if (VMCI_HANDLE_INVALID(handle) ||
+	    (flags & ~VMCI_QP_ALL_FLAGS) || isLocal ||
+	    !(produceSize || consumeSize) ||
+	    !context || contextId == VMCI_INVALID_ID ||
+	    handle.context == VMCI_INVALID_ID) {
+		return VMCI_ERROR_INVALID_ARGS;
+	}
+
+	if (pageStore && !VMCI_QP_PAGESTORE_IS_WELLFORMED(pageStore))
+		return VMCI_ERROR_INVALID_ARGS;
+
+	/*
+	 * In the initial argument check, we ensure that non-vmkernel hosts
+	 * are not allowed to create local queue pairs.
+	 */
+
+	ASSERT(!isLocal);
+
+	down(&qpBrokerList.mutex);
+
+	if (!isLocal && vmci_ctx_qp_exists(context, handle)) {
+		pr_devel("Context (ID=0x%x) already attached to queue "
+			 "pair (handle=0x%x:0x%x).", contextId,
+			 handle.context, handle.resource);
+		up(&qpBrokerList.mutex);
+		return VMCI_ERROR_ALREADY_EXISTS;
+	}
+
+	entry = (struct qp_broker_entry *)
+		qp_list_find(&qpBrokerList, handle);
+	if (!entry) {
+		create = true;
+		result =
+			qp_broker_create(handle, peer, flags, privFlags,
+					 produceSize, consumeSize, pageStore,
+					 context, wakeupCB, clientData, ent);
+	} else {
+		create = false;
+		result =
+			qp_broker_attach(entry, peer, flags, privFlags,
+					 produceSize, consumeSize, pageStore,
+					 context, wakeupCB, clientData, ent);
+	}
+
+	up(&qpBrokerList.mutex);
+
+	if (swap)
+		*swap = (contextId == VMCI_HOST_CONTEXT_ID) &&
+			!(create && isLocal);
+
+
+	return result;
+}
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * qp_alloc_host_work --
+ *
+ *    This function implements the kernel API for allocating a queue
+ *    pair.
+ *
+ * Results:
+ *     VMCI_SUCCESS on succes and appropriate failure code otherwise.
+ *
+ * Side effects:
+ *     May allocate memory.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static int qp_alloc_host_work(struct vmci_handle *handle,	// IN/OUT
+			      struct vmci_queue **produceQ,	// OUT
+			      uint64_t produceSize,	// IN
+			      struct vmci_queue **consumeQ,	// OUT
+			      uint64_t consumeSize,	// IN
+			      uint32_t peer,	// IN
+			      uint32_t flags,	// IN
+			      uint32_t privFlags,	// IN
+			      VMCIEventReleaseCB wakeupCB,	// IN
+			      void *clientData)	// IN
+{
+	struct vmci_ctx *context;
+	struct qp_broker_entry *entry;
+	int result;
+	bool swap;
+
+	if (VMCI_HANDLE_INVALID(*handle)) {
+		uint32_t resourceID = vmci_resource_get_id(VMCI_HOST_CONTEXT_ID);
+		if (resourceID == VMCI_INVALID_ID)
+			return VMCI_ERROR_NO_HANDLE;
+
+		*handle = vmci_make_handle(VMCI_HOST_CONTEXT_ID, resourceID);
+	}
+
+	context = vmci_ctx_get(VMCI_HOST_CONTEXT_ID);
+	ASSERT(context);
+
+	entry = NULL;
+	result =
+		qp_broker_alloc(*handle, peer, flags, privFlags,
+				produceSize, consumeSize, NULL, context,
+				wakeupCB, clientData, &entry, &swap);
+	if (result == VMCI_SUCCESS) {
+		if (swap) {
+			/*
+			 * If this is a local queue pair, the attacher will swap around produce
+			 * and consume queues.
+			 */
+
+			*produceQ = entry->consumeQ;
+			*consumeQ = entry->produceQ;
+		} else {
+			*produceQ = entry->produceQ;
+			*consumeQ = entry->consumeQ;
+		}
+	} else {
+		*handle = VMCI_INVALID_HANDLE;
+		pr_devel("queue pair broker failed to alloc (result=%d)"
+			 ".", result);
+	}
+	vmci_ctx_release(context);
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_alloc --
+ *
+ *      Allocates a VMCI QueuePair. Only checks validity of input
+ *      arguments. The real work is done in the host or guest
+ *      specific function.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, appropriate error code otherwise.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int vmci_qp_alloc(struct vmci_handle *handle,	// IN/OUT
+		  struct vmci_queue **produceQ,	// OUT
+		  uint64_t produceSize,	// IN
+		  struct vmci_queue **consumeQ,	// OUT
+		  uint64_t consumeSize,	// IN
+		  uint32_t peer,	// IN
+		  uint32_t flags,	// IN
+		  uint32_t privFlags,	// IN
+		  bool guestEndpoint,	// IN
+		  VMCIEventReleaseCB wakeupCB,	// IN
+		  void *clientData)	// IN
+{
+	if (!handle || !produceQ || !consumeQ || (!produceSize && !consumeSize)
+	    || (flags & ~VMCI_QP_ALL_FLAGS))
+		return VMCI_ERROR_INVALID_ARGS;
+
+	if (guestEndpoint)
+		return qp_alloc_guest_work(handle, produceQ,
+					   produceSize, consumeQ,
+					   consumeSize, peer,
+					   flags, privFlags);
+	else
+		return qp_alloc_host_work(handle, produceQ,
+					  produceSize, consumeQ,
+					  consumeSize, peer, flags,
+					  privFlags, wakeupCB,
+					  clientData);
+}
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * qp_detatch_host_work --
+ *
+ *    This function implements the host kernel API for detaching from
+ *    a queue pair.
+ *
+ * Results:
+ *     VMCI_SUCCESS on success and appropriate failure code otherwise.
+ *
+ * Side effects:
+ *     May deallocate memory.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static int qp_detatch_host_work(struct vmci_handle handle)	// IN
+{
+	int result;
+	struct vmci_ctx *context;
+
+	context = vmci_ctx_get(VMCI_HOST_CONTEXT_ID);
+
+	result = vmci_qp_broker_detach(handle, context);
+
+	vmci_ctx_release(context);
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_detatch --
+ *
+ *      Detaches from a VMCI QueuePair. Only checks validity of input argument.
+ *      Real work is done in the host or guest specific function.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory is freed.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_detatch(struct vmci_handle handle,	// IN
+		      bool guestEndpoint)	// IN
+{
+	if (VMCI_HANDLE_INVALID(handle))
+		return VMCI_ERROR_INVALID_ARGS;
+
+	if (guestEndpoint)
+		return qp_detatch_guest_work(handle);
+	else
+		return qp_detatch_host_work(handle);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_list_init --
+ *
+ *      Initializes the list of QueuePairs.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_list_init(struct qp_list *qpList)	// IN
+{
+	INIT_LIST_HEAD(&qpList->head);
+	sema_init(&qpList->mutex, 1);
+	return VMCI_SUCCESS;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_list_get_head --
+ *
+ *      Returns the entry from the head of the list. Assumes that the list is
+ *      locked.
+ *
+ * Results:
+ *      Pointer to entry.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static struct qp_entry *qp_list_get_head(struct qp_list *qpList)
+{
+	if (!list_empty(&qpList->head)) {
+		struct qp_entry *entry =
+			list_first_entry(&qpList->head, struct qp_entry,
+					 listItem);
+		return entry;
+	}
+
+	return NULL;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_broker_init --
+ *
+ *      Initalizes queue pair broker state.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int __init vmci_qp_broker_init(void)
+{
+	return qp_list_init(&qpBrokerList);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_broker_exit --
+ *
+ *      Destroys the queue pair broker state.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+void vmci_qp_broker_exit(void)
+{
+	struct qp_broker_entry *entry;
+
+	down(&qpBrokerList.mutex);
+
+	while ((entry = (struct qp_broker_entry *)
+		qp_list_get_head(&qpBrokerList))) {
+		qp_list_remove_entry(&qpBrokerList, &entry->qp);
+		kfree(entry);
+	}
+
+	up(&qpBrokerList.mutex);
+	INIT_LIST_HEAD(&(qpBrokerList.head));
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_broker_alloc --
+ *
+ *      Requests that a queue pair be allocated with the VMCI queue
+ *      pair broker. Allocates a queue pair entry if one does not
+ *      exist. Attaches to one if it exists, and retrieves the page
+ *      files backing that QueuePair.  Assumes that the queue pair
+ *      broker lock is held.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory may be allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int vmci_qp_broker_alloc(struct vmci_handle handle,	// IN
+			 uint32_t peer,	// IN
+			 uint32_t flags,	// IN
+			 uint32_t privFlags,	// IN
+			 uint64_t produceSize,	// IN
+			 uint64_t consumeSize,	// IN
+			 QueuePairPageStore * pageStore,	// IN/OUT
+			 struct vmci_ctx *context)	// IN: Caller
+{
+	return qp_broker_alloc(handle, peer, flags, privFlags,
+			       produceSize, consumeSize,
+			       pageStore, context, NULL, NULL, NULL, NULL);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_broker_set_page_store --
+ *
+ *      VMX'en with versions lower than VMCI_VERSION_NOVMVM use a separate
+ *      step to add the UVAs of the VMX mapping of the queue pair. This function
+ *      provides backwards compatibility with such VMX'en, and takes care of
+ *      registering the page store for a queue pair previously allocated by the
+ *      VMX during create or attach. This function will move the queue pair state
+ *      to either from VMCIQBP_CREATED_NO_MEM to VMCIQBP_CREATED_MEM or
+ *      VMCIQBP_ATTACHED_NO_MEM to VMCIQBP_ATTACHED_MEM. If moving to the
+ *      attached state with memory, the queue pair is ready to be used by the
+ *      host peer, and an attached event will be generated.
+ *
+ *      Assumes that the queue pair broker lock is held.
+ *
+ *      This function is only used by the hosted platform, since there is no
+ *      issue with backwards compatibility for vmkernel.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, appropriate error code otherwise.
+ *
+ * Side effects:
+ *      Pages may get pinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int vmci_qp_broker_set_page_store(struct vmci_handle handle,	// IN
+				  uint64_t produceUVA,	// IN
+				  uint64_t consumeUVA,	// IN
+				  struct vmci_ctx *context)	// IN: Caller
+{
+	struct qp_broker_entry *entry;
+	int result;
+	const uint32_t contextId = vmci_ctx_get_id(context);
+
+	if (VMCI_HANDLE_INVALID(handle) || !context
+	    || contextId == VMCI_INVALID_ID)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	/*
+	 * We only support guest to host queue pairs, so the VMX must
+	 * supply UVAs for the mapped page files.
+	 */
+
+	if (produceUVA == 0 || consumeUVA == 0)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	down(&qpBrokerList.mutex);
+
+	if (!vmci_ctx_qp_exists(context, handle)) {
+		pr_warn("Context (ID=0x%x) not attached to queue pair "
+			"(handle=0x%x:0x%x).", contextId, handle.context,
+			handle.resource);
+		result = VMCI_ERROR_NOT_FOUND;
+		goto out;
+	}
+
+	entry = (struct qp_broker_entry *)
+		qp_list_find(&qpBrokerList, handle);
+	if (!entry) {
+		result = VMCI_ERROR_NOT_FOUND;
+		goto out;
+	}
+
+	/*
+	 * If I'm the owner then I can set the page store.
+	 *
+	 * Or, if a host created the QueuePair and I'm the attached peer
+	 * then I can set the page store.
+	 */
+
+	if (entry->createId != contextId &&
+	    (entry->createId != VMCI_HOST_CONTEXT_ID ||
+	     entry->attachId != contextId)) {
+		result = VMCI_ERROR_QUEUEPAIR_NOTOWNER;
+		goto out;
+	}
+
+	if (entry->state != VMCIQPB_CREATED_NO_MEM &&
+	    entry->state != VMCIQPB_ATTACHED_NO_MEM) {
+		result = VMCI_ERROR_UNAVAILABLE;
+		goto out;
+	}
+
+	result = VMCIHost_GetUserMemory(produceUVA, consumeUVA,
+					entry->produceQ, entry->consumeQ);
+	if (result < VMCI_SUCCESS)
+		goto out;
+
+	result = VMCIHost_MapQueues(entry->produceQ, entry->consumeQ);
+	if (result < VMCI_SUCCESS) {
+		VMCIHost_ReleaseUserMemory(entry->produceQ, entry->consumeQ);
+		goto out;
+	}
+
+	if (entry->state == VMCIQPB_CREATED_NO_MEM) {
+		entry->state = VMCIQPB_CREATED_MEM;
+	} else {
+		ASSERT(entry->state == VMCIQPB_ATTACHED_NO_MEM);
+		entry->state = VMCIQPB_ATTACHED_MEM;
+	}
+	entry->vmciPageFiles = true;
+
+	if (entry->state == VMCIQPB_ATTACHED_MEM) {
+		result =
+			qp_notify_peer(true, handle, contextId,
+				       entry->createId);
+		if (result < VMCI_SUCCESS) {
+			pr_warn("Failed to notify peer (ID=0x%x) of "
+				"attach to queue pair (handle=0x%x:0x%x).",
+				entry->createId, entry->qp.handle.context,
+				entry->qp.handle.resource);
+		}
+	}
+
+	result = VMCI_SUCCESS;
+out:
+	up(&qpBrokerList.mutex);
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_reset_saved_headers --
+ *
+ *      Resets saved queue headers for the given QP broker
+ *      entry. Should be used when guest memory becomes available
+ *      again, or the guest detaches.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_reset_saved_headers(struct qp_broker_entry *entry)	// IN
+{
+	entry->produceQ->savedHeader = NULL;
+	entry->consumeQ->savedHeader = NULL;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_broker_detach --
+ *
+ *      The main entry point for detaching from a queue pair registered with the
+ *      queue pair broker. If more than one endpoint is attached to the queue
+ *      pair, the first endpoint will mainly decrement a reference count and
+ *      generate a notification to its peer. The last endpoint will clean up
+ *      the queue pair state registered with the broker.
+ *
+ *      When a guest endpoint detaches, it will unmap and unregister the guest
+ *      memory backing the queue pair. If the host is still attached, it will
+ *      no longer be able to access the queue pair content.
+ *
+ *      If the queue pair is already in a state where there is no memory
+ *      registered for the queue pair (any *_NO_MEM state), it will transition to
+ *      the VMCIQPB_SHUTDOWN_NO_MEM state. This will also happen, if a guest
+ *      endpoint is the first of two endpoints to detach. If the host endpoint is
+ *      the first out of two to detach, the queue pair will move to the
+ *      VMCIQPB_SHUTDOWN_MEM state.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, appropriate error code otherwise.
+ *
+ * Side effects:
+ *      Memory may be freed, and pages may be unpinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int vmci_qp_broker_detach(struct vmci_handle handle,	// IN
+			  struct vmci_ctx *context)	// IN
+{
+	struct qp_broker_entry *entry;
+	const uint32_t contextId = vmci_ctx_get_id(context);
+	uint32_t peerId;
+	bool isLocal = false;
+	int result;
+
+	if (VMCI_HANDLE_INVALID(handle) || !context
+	    || contextId == VMCI_INVALID_ID) {
+		return VMCI_ERROR_INVALID_ARGS;
+	}
+
+	down(&qpBrokerList.mutex);
+
+	if (!vmci_ctx_qp_exists(context, handle)) {
+		pr_devel("Context (ID=0x%x) not attached to queue pair "
+			 "(handle=0x%x:0x%x).", contextId, handle.context,
+			 handle.resource);
+		result = VMCI_ERROR_NOT_FOUND;
+		goto out;
+	}
+
+	entry = (struct qp_broker_entry *)
+		qp_list_find(&qpBrokerList, handle);
+	if (!entry) {
+		pr_devel("Context (ID=0x%x) reports being attached to "
+			 "queue pair(handle=0x%x:0x%x) that isn't present in "
+			 "broker.", contextId, handle.context,
+			 handle.resource);
+		result = VMCI_ERROR_NOT_FOUND;
+		goto out;
+	}
+
+	if (contextId != entry->createId && contextId != entry->attachId) {
+		result = VMCI_ERROR_QUEUEPAIR_NOTATTACHED;
+		goto out;
+	}
+
+	if (contextId == entry->createId) {
+		peerId = entry->attachId;
+		entry->createId = VMCI_INVALID_ID;
+	} else {
+		peerId = entry->createId;
+		entry->attachId = VMCI_INVALID_ID;
+	}
+	entry->qp.refCount--;
+
+	isLocal = entry->qp.flags & VMCI_QPFLAG_LOCAL;
+
+	if (contextId != VMCI_HOST_CONTEXT_ID) {
+		int result;
+		bool headersMapped;
+
+		ASSERT(!isLocal);
+
+		/*
+		 * Pre NOVMVM vmx'en may detach from a queue pair before setting the page
+		 * store, and in that case there is no user memory to detach from. Also,
+		 * more recent VMX'en may detach from a queue pair in the quiesced state.
+		 */
+
+		VMCI_AcquireQueueMutex(entry->produceQ);
+		headersMapped = entry->produceQ->qHeader
+			|| entry->consumeQ->qHeader;
+		if (QPBROKERSTATE_HAS_MEM(entry)) {
+			result =
+				VMCIHost_UnmapQueues
[… more lines in the raw message]

Lines of this file are not shown. View the raw message.

drivers/misc/vmw_vmci/vmci_queue_pair.h new file +258 -0

258 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
1.7.0.4

Part of the diff is not shown here. View the raw message.

#21 lore raw

RFC 8/11 Apply VMCI queue pairs

In reply to Andrew Stiegmann (stieg)

VMCI queue pairs allow for bi-directional ordered communication between host and guests.

---
 drivers/misc/vmw_vmci/vmci_queue_pair.c | 4517 +++++++++++++++++++++++++++++++
 drivers/misc/vmw_vmci/vmci_queue_pair.h |  258 ++
 2 files changed, 4775 insertions(+), 0 deletions(-)
 create mode 100644 drivers/misc/vmw_vmci/vmci_queue_pair.c
 create mode 100644 drivers/misc/vmw_vmci/vmci_queue_pair.h
drivers/misc/vmw_vmci/vmci_queue_pair.c new file +4517 -0
new file mode 100644
index 0000000..b5b1b8e
@@ -0,0 +1,4517 @@
+/*
+ * VMware VMCI Driver
+ *
+ * Copyright (C) 2012 VMware, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation version 2 and no later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ */
+
+#include <linux/device-mapper.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/sched.h>
+#include <linux/semaphore.h>
+#include <linux/socket.h>
+#include <linux/vmw_vmci_api.h>
+#include <linux/vmw_vmci_defs.h>
+
+#include "vmci_common_int.h"
+#include "vmci_context.h"
+#include "vmci_datagram.h"
+#include "vmci_driver.h"
+#include "vmci_event.h"
+#include "vmci_handle_array.h"
+#include "vmci_hash_table.h"
+#include "vmci_queue_pair.h"
+#include "vmci_resource.h"
+#include "vmci_route.h"
+
+#define INVALID_VMCI_GUEST_MEM_ID  0
+
+/*
+ * In the following, we will distinguish between two kinds of VMX processes -
+ * the ones with versions lower than VMCI_VERSION_NOVMVM that use specialized
+ * VMCI page files in the VMX and supporting VM to VM communication and the
+ * newer ones that use the guest memory directly. We will in the following refer
+ * to the older VMX versions as old-style VMX'en, and the newer ones as new-style
+ * VMX'en.
+ *
+ * The state transition datagram is as follows (the VMCIQPB_ prefix has been
+ * removed for readability) - see below for more details on the transtions:
+ *
+ *            --------------  NEW  -------------
+ *            |                                |
+ *           \_/                              \_/
+ *     CREATED_NO_MEM <-----------------> CREATED_MEM
+ *            |    |                           |
+ *            |    o-----------------------o   |
+ *            |                            |   |
+ *           \_/                          \_/ \_/
+ *     ATTACHED_NO_MEM <----------------> ATTACHED_MEM
+ *            |                            |   |
+ *            |     o----------------------o   |
+ *            |     |                          |
+ *           \_/   \_/                        \_/
+ *     SHUTDOWN_NO_MEM <----------------> SHUTDOWN_MEM
+ *            |                                |
+ *            |                                |
+ *            -------------> gone <-------------
+ *
+ * In more detail. When a VMCI queue pair is first created, it will be in the
+ * VMCIQPB_NEW state. It will then move into one of the following states:
+ * - VMCIQPB_CREATED_NO_MEM: this state indicates that either:
+ *     - the created was performed by a host endpoint, in which case there is no
+ *       backing memory yet.
+ *     - the create was initiated by an old-style VMX, that uses
+ *       vmci_qp_broker_set_page_store to specify the UVAs of the queue pair at a
+ *       later point in time. This state can be distinguished from the one above
+ *       by the context ID of the creator. A host side is not allowed to attach
+ *       until the page store has been set.
+ * - VMCIQPB_CREATED_MEM: this state is the result when the queue pair is created
+ *     by a VMX using the queue pair device backend that sets the UVAs of the
+ *     queue pair immediately and stores the information for later attachers. At
+ *     this point, it is ready for the host side to attach to it.
+ * Once the queue pair is in one of the created states (with the exception of the
+ * case mentioned for older VMX'en above), it is possible to attach to the queue
+ * pair. Again we have two new states possible:
+ * - VMCIQPB_ATTACHED_MEM: this state can be reached through the following paths:
+ *     - from VMCIQPB_CREATED_NO_MEM when a new-style VMX allocates a queue pair,
+ *       and attaches to a queue pair previously created by the host side.
+ *     - from VMCIQPB_CREATED_MEM when the host side attaches to a queue pair
+ *       already created by a guest.
+ *     - from VMCIQPB_ATTACHED_NO_MEM, when an old-style VMX calls
+ *       vmci_qp_broker_set_page_store (see below).
+ * - VMCIQPB_ATTACHED_NO_MEM: If the queue pair already was in the
+ *     VMCIQPB_CREATED_NO_MEM due to a host side create, an old-style VMX will
+ *     bring the queue pair into this state. Once vmci_qp_broker_set_page_store is
+ *     called to register the user memory, the VMCIQPB_ATTACH_MEM state will be
+ *     entered.
+ * From the attached queue pair, the queue pair can enter the shutdown states
+ * when either side of the queue pair detaches. If the guest side detaches first,
+ * the queue pair will enter the VMCIQPB_SHUTDOWN_NO_MEM state, where the content
+ * of the queue pair will no longer be available. If the host side detaches first,
+ * the queue pair will either enter the VMCIQPB_SHUTDOWN_MEM, if the guest memory
+ * is currently mapped, or VMCIQPB_SHUTDOWN_NO_MEM, if the guest memory is not
+ * mapped (e.g., the host detaches while a guest is stunned).
+ *
+ * New-style VMX'en will also unmap guest memory, if the guest is quiesced, e.g.,
+ * during a snapshot operation. In that case, the guest memory will no longer be
+ * available, and the queue pair will transition from *_MEM state to a *_NO_MEM
+ * state. The VMX may later map the memory once more, in which case the queue
+ * pair will transition from the *_NO_MEM state at that point back to the *_MEM
+ * state. Note that the *_NO_MEM state may have changed, since the peer may have
+ * either attached or detached in the meantime. The values are laid out such that
+ * ++ on a state will move from a *_NO_MEM to a *_MEM state, and vice versa.
+ */
+
+/* The Kernel specific component of the struct vmci_queue structure. */
+struct vmci_queue_kern_if {
+	struct page **page;
+	struct page **headerPage;
+	void *va;
+	struct semaphore __mutex;
+	struct semaphore *mutex;
+	bool host;
+	size_t numPages;
+	bool mapped;
+};
+
+/*
+ * This structure is opaque to the clients.
+ */
+struct vmci_qp {
+	struct vmci_handle handle;
+	struct vmci_queue *produceQ;
+	struct vmci_queue *consumeQ;
+	uint64_t produceQSize;
+	uint64_t consumeQSize;
+	uint32_t peer;
+	uint32_t flags;
+	uint32_t privFlags;
+	bool guestEndpoint;
+	uint32_t blocked;
+	wait_queue_head_t event;
+};
+
+enum qp_broker_state {
+	VMCIQPB_NEW,
+	VMCIQPB_CREATED_NO_MEM,
+	VMCIQPB_CREATED_MEM,
+	VMCIQPB_ATTACHED_NO_MEM,
+	VMCIQPB_ATTACHED_MEM,
+	VMCIQPB_SHUTDOWN_NO_MEM,
+	VMCIQPB_SHUTDOWN_MEM,
+	VMCIQPB_GONE
+};
+
+#define QPBROKERSTATE_HAS_MEM(_qpb) (_qpb->state == VMCIQPB_CREATED_MEM || \
+                                     _qpb->state == VMCIQPB_ATTACHED_MEM || \
+                                     _qpb->state == VMCIQPB_SHUTDOWN_MEM)
+
+/*
+ * In the queue pair broker, we always use the guest point of view for
+ * the produce and consume queue values and references, e.g., the
+ * produce queue size stored is the guests produce queue size. The
+ * host endpoint will need to swap these around. The only exception is
+ * the local queue pairs on the host, in which case the host endpoint
+ * that creates the queue pair will have the right orientation, and
+ * the attaching host endpoint will need to swap.
+ */
+
+struct qp_entry {
+	struct list_head listItem;
+	struct vmci_handle handle;
+	uint32_t peer;
+	uint32_t flags;
+	uint64_t produceSize;
+	uint64_t consumeSize;
+	uint32_t refCount;
+};
+
+struct qp_broker_entry {
+	struct qp_entry qp;
+	uint32_t createId;
+	uint32_t attachId;
+	enum qp_broker_state state;
+	bool requireTrustedAttach;
+	bool createdByTrusted;
+	bool vmciPageFiles;	// Created by VMX using VMCI page files
+	struct vmci_queue *produceQ;
+	struct vmci_queue *consumeQ;
+	struct vmci_queue_header savedProduceQ;
+	struct vmci_queue_header savedConsumeQ;
+	VMCIEventReleaseCB wakeupCB;
+	void *clientData;
+	void *localMem;		// Kernel memory for local queue pair
+};
+
+struct qp_guest_endpoint {
+	struct qp_entry qp;
+	uint64_t numPPNs;
+	void *produceQ;
+	void *consumeQ;
+	struct PPNSet ppnSet;
+};
+
+struct qp_list {
+	struct list_head head;
+	struct semaphore mutex;
+};
+
+static struct qp_list qpBrokerList;
+
+#define QPE_NUM_PAGES(_QPE) ((uint32_t)(dm_div_up(_QPE.produceSize, PAGE_SIZE) + \
+					dm_div_up(_QPE.consumeSize, PAGE_SIZE) + 2))
+
+static struct qp_list qpGuestEndpoints;
+
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_free_queue --
+ *
+ *      Frees kernel VA space for a given queue and its queue header, and
+ *      frees physical data pages.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      Memory is freed.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_free_queue(void *q,	// IN:
+			  uint64_t size)	// IN: size of queue (not including header)
+{
+	struct vmci_queue *queue = q;
+
+	if (queue) {
+		uint64_t i = dm_div_up(size, PAGE_SIZE);
+
+		if (queue->kernelIf->mapped) {
+			ASSERT(queue->kernelIf->va);
+			vunmap(queue->kernelIf->va);
+			queue->kernelIf->va = NULL;
+		}
+
+		while (i)
+			__free_page(queue->kernelIf->page[--i]);
+
+		vfree(queue->qHeader);
+	}
+}
+
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_alloc_queue --
+ *
+ *      Allocates kernel VA space of specified size, plus space for the
+ *      queue structure/kernel interface and the queue header.  Allocates
+ *      physical pages for the queue data pages.
+ *
+ *      PAGE m:      struct vmci_queue_header (struct vmci_queue->qHeader)
+ *      PAGE m+1:    struct vmci_queue
+ *      PAGE m+1+q:  struct vmci_queue_kern_if (struct vmci_queue->kernelIf)
+ *      PAGE n-size: Data pages (struct vmci_queue->kernelIf->page[])
+ *
+ * Results:
+ *      Pointer to the queue on success, NULL otherwise.
+ *
+ * Side effects:
+ *      Memory is allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void *qp_alloc_queue(uint64_t size,	// IN: size of queue (not including header)
+			    uint32_t flags)
+{
+	uint64_t i;
+	struct vmci_queue *queue;
+	struct vmci_queue_header *qHeader;
+	const uint64_t numDataPages = dm_div_up(size, PAGE_SIZE);
+	const uint queueSize =
+		PAGE_SIZE +
+		sizeof(*queue) + sizeof(*(queue->kernelIf)) +
+		numDataPages * sizeof(*(queue->kernelIf->page));
+
+	ASSERT(size <= VMCI_MAX_GUEST_QP_MEMORY);
+	ASSERT(!QP_PINNED(flags) || size <= VMCI_MAX_PINNED_QP_MEMORY);
+
+	qHeader = vmalloc(queueSize);
+	if (!qHeader)
+		return NULL;
+
+	queue = (struct vmci_queue *)((uint8_t *) qHeader + PAGE_SIZE);
+	queue->qHeader = qHeader;
+	queue->savedHeader = NULL;
+	queue->kernelIf =
+		(struct vmci_queue_kern_if *)((uint8_t *) queue + sizeof(*queue));
+	queue->kernelIf->headerPage = NULL;	/* Unused in guest. */
+	queue->kernelIf->page =
+		(struct page **)((uint8_t *) queue->kernelIf +
+				 sizeof(*(queue->kernelIf)));
+	queue->kernelIf->host = false;
+	queue->kernelIf->va = NULL;
+	queue->kernelIf->mapped = false;
+
+	for (i = 0; i < numDataPages; i++) {
+		queue->kernelIf->page[i] = alloc_pages(GFP_KERNEL, 0);
+		if (!queue->kernelIf->page[i])
+			goto fail;
+	}
+
+	if (QP_PINNED(flags)) {
+		queue->kernelIf->va = vmap(queue->kernelIf->page, numDataPages,
+					   VM_MAP, PAGE_KERNEL);
+		if (!queue->kernelIf->va)
+			goto fail;
+
+		queue->kernelIf->mapped = true;
+	}
+
+	return (void *)queue;
+
+fail:
+	qp_free_queue(queue, i * PAGE_SIZE);
+	return NULL;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * __qp_memcpy_to_queue --
+ *
+ *      Copies from a given buffer or iovector to a VMCI Queue.  Uses
+ *      kmap()/kunmap() to dynamically map/unmap required portions of the queue
+ *      by traversing the offset -> page translation structure for the queue.
+ *      Assumes that offset + size does not wrap around in the queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int __qp_memcpy_to_queue(struct vmci_queue *queue,	// OUT:
+				uint64_t queueOffset,	// IN:
+				const void *src,	// IN:
+				size_t size,	// IN:
+				bool isIovec)	// IN: if src is a struct iovec *
+{
+	struct vmci_queue_kern_if *kernelIf = queue->kernelIf;
+	size_t bytesCopied = 0;
+
+	while (bytesCopied < size) {
+		uint64_t pageIndex = (queueOffset + bytesCopied) / PAGE_SIZE;
+		size_t pageOffset =
+			(queueOffset + bytesCopied) & (PAGE_SIZE - 1);
+		void *va;
+		size_t toCopy;
+
+		if (!kernelIf->mapped)
+			va = kmap(kernelIf->page[pageIndex]);
+		else
+			va = (void *)((uint8_t *)kernelIf->va + (pageIndex * PAGE_SIZE));
+
+		if (size - bytesCopied > PAGE_SIZE - pageOffset) {
+			/* Enough payload to fill up from this page. */
+			toCopy = PAGE_SIZE - pageOffset;
+		} else {
+			toCopy = size - bytesCopied;
+		}
+
+		if (isIovec) {
+			struct iovec *iov = (struct iovec *)src;
+			int err;
+
+			/* The iovec will track bytesCopied internally. */
+			err = memcpy_fromiovec((uint8_t *) va + pageOffset,
+					       iov, toCopy);
+			if (err != 0) {
+				kunmap(kernelIf->page[pageIndex]);
+				return VMCI_ERROR_INVALID_ARGS;
+			}
+		} else {
+			memcpy((uint8_t *) va + pageOffset,
+			       (uint8_t *) src + bytesCopied, toCopy);
+		}
+
+		bytesCopied += toCopy;
+		if (!kernelIf->mapped)
+			kunmap(kernelIf->page[pageIndex]);
+	}
+
+	return VMCI_SUCCESS;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * __qp_memcpy_from_queue --
+ *
+ *      Copies to a given buffer or iovector from a VMCI Queue.  Uses
+ *      kmap()/kunmap() to dynamically map/unmap required portions of the queue
+ *      by traversing the offset -> page translation structure for the queue.
+ *      Assumes that offset + size does not wrap around in the queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int __qp_memcpy_from_queue(void *dest,	// OUT:
+				  const struct vmci_queue *queue,	// IN:
+				  uint64_t queueOffset,	// IN:
+				  size_t size,	// IN:
+				  bool isIovec)	// IN: if dest is a struct iovec *
+{
+	struct vmci_queue_kern_if *kernelIf = queue->kernelIf;
+	size_t bytesCopied = 0;
+
+	while (bytesCopied < size) {
+		uint64_t pageIndex = (queueOffset + bytesCopied) / PAGE_SIZE;
+		size_t pageOffset =
+			(queueOffset + bytesCopied) & (PAGE_SIZE - 1);
+		void *va;
+		size_t toCopy;
+
+		if (!kernelIf->mapped)
+			va = kmap(kernelIf->page[pageIndex]);
+		else
+			va = (void *)((uint8_t *)kernelIf->va + (pageIndex * PAGE_SIZE));
+
+		if (size - bytesCopied > PAGE_SIZE - pageOffset) {
+			/* Enough payload to fill up this page. */
+			toCopy = PAGE_SIZE - pageOffset;
+		} else {
+			toCopy = size - bytesCopied;
+		}
+
+		if (isIovec) {
+			struct iovec *iov = (struct iovec *)dest;
+			int err;
+
+			/* The iovec will track bytesCopied internally. */
+			err = memcpy_toiovec(iov, (uint8_t *) va + pageOffset,
+					     toCopy);
+			if (err != 0) {
+				kunmap(kernelIf->page[pageIndex]);
+				return VMCI_ERROR_INVALID_ARGS;
+			}
+		} else {
+			memcpy((uint8_t *) dest + bytesCopied,
+			       (uint8_t *) va + pageOffset, toCopy);
+		}
+
+		bytesCopied += toCopy;
+		if (!kernelIf->mapped)
+			kunmap(kernelIf->page[pageIndex]);
+	}
+
+	return VMCI_SUCCESS;
+}
+
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_alloc_ppn_set --
+ *
+ *      Allocates two list of PPNs --- one for the pages in the produce queue,
+ *      and the other for the pages in the consume queue. Intializes the list
+ *      of PPNs with the page frame numbers of the KVA for the two queues (and
+ *      the queue headers).
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory may be allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_alloc_ppn_set(void *prodQ,	// IN:
+			    uint64_t numProducePages,	// IN: for queue plus header
+			    void *consQ,	// IN:
+			    uint64_t numConsumePages,	// IN: for queue plus header
+			    struct PPNSet *ppnSet)	// OUT:
+{
+	uint32_t *producePPNs;
+	uint32_t *consumePPNs;
+	struct vmci_queue *produceQ = prodQ;
+	struct vmci_queue *consumeQ = consQ;
+	uint64_t i;
+
+	if (!produceQ || !numProducePages || !consumeQ ||
+	    !numConsumePages || !ppnSet)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	if (ppnSet->initialized)
+		return VMCI_ERROR_ALREADY_EXISTS;
+
+	producePPNs =
+		kmalloc(numProducePages * sizeof *producePPNs, GFP_KERNEL);
+	if (!producePPNs)
+		return VMCI_ERROR_NO_MEM;
+
+	consumePPNs =
+		kmalloc(numConsumePages * sizeof *consumePPNs, GFP_KERNEL);
+	if (!consumePPNs) {
+		kfree(producePPNs);
+		return VMCI_ERROR_NO_MEM;
+	}
+
+	producePPNs[0] = page_to_pfn(vmalloc_to_page(produceQ->qHeader));
+	for (i = 1; i < numProducePages; i++) {
+		unsigned long pfn;
+
+		producePPNs[i] = pfn =
+			page_to_pfn(produceQ->kernelIf->page[i - 1]);
+
+		/* Fail allocation if PFN isn't supported by hypervisor. */
+		if (sizeof pfn > sizeof *producePPNs && pfn != producePPNs[i])
+			goto ppnError;
+	}
+	consumePPNs[0] = page_to_pfn(vmalloc_to_page(consumeQ->qHeader));
+	for (i = 1; i < numConsumePages; i++) {
+		unsigned long pfn;
+
+		consumePPNs[i] = pfn =
+			page_to_pfn(consumeQ->kernelIf->page[i - 1]);
+
+		/* Fail allocation if PFN isn't supported by hypervisor. */
+		if (sizeof pfn > sizeof *consumePPNs && pfn != consumePPNs[i])
+			goto ppnError;
+	}
+
+	ppnSet->numProducePages = numProducePages;
+	ppnSet->numConsumePages = numConsumePages;
+	ppnSet->producePPNs = producePPNs;
+	ppnSet->consumePPNs = consumePPNs;
+	ppnSet->initialized = true;
+	return VMCI_SUCCESS;
+
+ppnError:
+	kfree(producePPNs);
+	kfree(consumePPNs);
+	return VMCI_ERROR_INVALID_ARGS;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_free_ppn_set --
+ *
+ *      Frees the two list of PPNs for a queue pair.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_free_ppn_set(struct PPNSet *ppnSet)	// IN:
+{
+	ASSERT(ppnSet);
+	if (ppnSet->initialized) {
+		/* Do not call these functions on NULL inputs. */
+		ASSERT(ppnSet->producePPNs && ppnSet->consumePPNs);
+		kfree(ppnSet->producePPNs);
+		kfree(ppnSet->consumePPNs);
+	}
+	memset(ppnSet, 0, sizeof *ppnSet);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_populate_ppn_set --
+ *
+ *      Populates the list of PPNs in the hypercall structure with the PPNS
+ *      of the produce queue and the consume queue.
+ *
+ * Results:
+ *      VMCI_SUCCESS.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_populate_ppn_set(uint8_t * callBuf,	// OUT:
+			       const struct PPNSet *ppnSet)	// IN:
+{
+	ASSERT(callBuf && ppnSet && ppnSet->initialized);
+	memcpy(callBuf, ppnSet->producePPNs,
+	       ppnSet->numProducePages * sizeof *ppnSet->producePPNs);
+	memcpy(callBuf +
+	       ppnSet->numProducePages * sizeof *ppnSet->producePPNs,
+	       ppnSet->consumePPNs,
+	       ppnSet->numConsumePages * sizeof *ppnSet->consumePPNs);
+
+	return VMCI_SUCCESS;
+}
+
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_memcpy_to_queue --
+ *
+ *      Copies from a given buffer to a VMCI Queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_memcpy_to_queue(struct vmci_queue *queue,	// OUT:
+				     uint64_t queueOffset,	// IN:
+				     const void *src,	// IN:
+				     size_t srcOffset,	// IN:
+				     size_t size,	// IN:
+				     int bufType)	// IN: Unused
+{
+	return __qp_memcpy_to_queue(queue, queueOffset,
+				    (uint8_t *) src + srcOffset, size, false);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_memcpy_from_queue --
+ *
+ *      Copies to a given buffer from a VMCI Queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_memcpy_from_queue(void *dest,	// OUT:
+				       size_t destOffset,	// IN:
+				       const struct vmci_queue *queue,	// IN:
+				       uint64_t queueOffset,	// IN:
+				       size_t size,	// IN:
+				       int bufType)	// IN: Unused
+{
+	return __qp_memcpy_from_queue((uint8_t *) dest + destOffset,
+				      queue, queueOffset, size, false);
+}
+
+/*
+ *----------------------------------------------------------------------------
+ *
+ * qp_memcpy_to_queue_iov --
+ *
+ *      Copies from a given iovec from a VMCI Queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+static int qp_memcpy_to_queue_iov(struct vmci_queue *queue,	// OUT:
+					 uint64_t queueOffset,	// IN:
+					 const void *src,	// IN: iovec
+					 size_t srcOffset,	// IN: ignored
+					 size_t size,	// IN:
+					 int bufType)	// IN: ignored
+{
+
+	/*
+	 * We ignore srcOffset because src is really a struct iovec * and will
+	 * maintain offset internally.
+	 */
+	return __qp_memcpy_to_queue(queue, queueOffset, src, size, true);
+}
+
+/*
+ *----------------------------------------------------------------------------
+ *
+ * qp_memcpy_from_queue_iov --
+ *
+ *      Copies to a given iovec from a VMCI Queue.
+ *
+ * Results:
+ *      Zero on success, negative error code on failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+static int qp_memcpy_from_queue_iov(void *dest,	// OUT: iovec
+					   size_t destOffset,	// IN: ignored
+					   const struct vmci_queue *queue,	// IN:
+					   uint64_t queueOffset,	// IN:
+					   size_t size,	// IN:
+					   int bufType)	// IN: ignored
+{
+	/*
+	 * We ignore destOffset because dest is really a struct iovec * and will
+	 * maintain offset internally.
+	 */
+	return __qp_memcpy_from_queue(dest, queue, queueOffset, size, true);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_AllocQueue --
+ *
+ *      Allocates kernel VA space of specified size plus space for the queue
+ *      and kernel interface.  This is different from the guest queue allocator,
+ *      because we do not allocate our own queue header/data pages here but
+ *      share those of the guest.
+ *
+ * Results:
+ *      A pointer to an allocated and initialized struct vmci_queue structure or NULL.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+struct vmci_queue *VMCIHost_AllocQueue(uint64_t size)	// IN:
+{
+	struct vmci_queue *queue;
+	const size_t numPages = dm_div_up(size, PAGE_SIZE) + 1;
+	const size_t queueSize = sizeof(*queue) + sizeof(*(queue->kernelIf));
+	const size_t queuePageSize = numPages * sizeof(*queue->kernelIf->page);
+
+	queue = kzalloc(queueSize + queuePageSize, GFP_KERNEL);
+	if (queue) {
+		queue->qHeader = NULL;
+		queue->savedHeader = NULL;
+		queue->kernelIf =
+			(struct vmci_queue_kern_if *)((uint8_t *) queue +
+						      sizeof(*queue));
+		queue->kernelIf->host = true;
+		queue->kernelIf->mutex = NULL;
+		queue->kernelIf->numPages = numPages;
+		queue->kernelIf->headerPage =
+			(struct page **)((uint8_t *) queue + queueSize);
+		queue->kernelIf->page = &queue->kernelIf->headerPage[1];
+		queue->kernelIf->va = NULL;
+		queue->kernelIf->mapped = false;
+	}
+
+	return queue;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_FreeQueue --
+ *
+ *      Frees kernel memory for a given queue (header plus translation
+ *      structure).
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      Memory is freed.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+void VMCIHost_FreeQueue(struct vmci_queue *queue,	// IN:
+			uint64_t queueSize)	// IN:
+{
+	if (queue)
+		kfree(queue);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCI_InitQueueMutex()
+ *
+ *       Initialize the mutex for the pair of queues.  This mutex is used to
+ *       protect the qHeader and the buffer from changing out from under any
+ *       users of either queue.  Of course, it's only any good if the mutexes
+ *       are actually acquired.  Queue structure must lie on non-paged memory
+ *       or we cannot guarantee access to the mutex.
+ *
+ * Results:
+ *       None.
+ *
+ * Side Effects:
+ *       None.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+void VMCI_InitQueueMutex(struct vmci_queue *produceQ,	// IN/OUT
+			 struct vmci_queue *consumeQ)	// IN/OUT
+{
+	ASSERT(produceQ);
+	ASSERT(consumeQ);
+	ASSERT(produceQ->kernelIf);
+	ASSERT(consumeQ->kernelIf);
+
+	/*
+	 * Only the host queue has shared state - the guest queues do not
+	 * need to synchronize access using a queue mutex.
+	 */
+
+	if (produceQ->kernelIf->host) {
+		produceQ->kernelIf->mutex = &produceQ->kernelIf->__mutex;
+		consumeQ->kernelIf->mutex = &produceQ->kernelIf->__mutex;
+		sema_init(produceQ->kernelIf->mutex, 1);
+	}
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCI_CleanupQueueMutex()
+ *
+ *       Cleans up the mutex for the pair of queues.
+ *
+ * Results:
+ *       None.
+ *
+ * Side Effects:
+ *       None.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+void VMCI_CleanupQueueMutex(struct vmci_queue *produceQ,	// IN/OUT
+			    struct vmci_queue *consumeQ)	// IN/OUT
+{
+	ASSERT(produceQ);
+	ASSERT(consumeQ);
+	ASSERT(produceQ->kernelIf);
+	ASSERT(consumeQ->kernelIf);
+
+	if (produceQ->kernelIf->host) {
+		produceQ->kernelIf->mutex = NULL;
+		consumeQ->kernelIf->mutex = NULL;
+	}
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCI_AcquireQueueMutex()
+ *
+ *       Acquire the mutex for the queue.  Note that the produceQ and
+ *       the consumeQ share a mutex.  So, only one of the two need to
+ *       be passed in to this routine.  Either will work just fine.
+ *
+ * Results:
+ *       None.
+ *
+ * Side Effects:
+ *       May block the caller.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+void VMCI_AcquireQueueMutex(struct vmci_queue *queue)	// IN
+{
+	ASSERT(queue);
+	ASSERT(queue->kernelIf);
+
+	if (queue->kernelIf->host) {
+		ASSERT(queue->kernelIf->mutex);
+		down(queue->kernelIf->mutex);
+	}
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCI_ReleaseQueueMutex()
+ *
+ *       Release the mutex for the queue.  Note that the produceQ and
+ *       the consumeQ share a mutex.  So, only one of the two need to
+ *       be passed in to this routine.  Either will work just fine.
+ *
+ * Results:
+ *       None.
+ *
+ * Side Effects:
+ *       May block the caller.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+void VMCI_ReleaseQueueMutex(struct vmci_queue *queue)	// IN
+{
+	ASSERT(queue);
+	ASSERT(queue->kernelIf);
+
+	if (queue->kernelIf->host) {
+		ASSERT(queue->kernelIf->mutex);
+		up(queue->kernelIf->mutex);
+	}
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIReleasePageStorePages --
+ *
+ *       Helper function to release pages in the PageStoreAttachInfo
+ *       previously obtained using get_user_pages.
+ *
+ * Results:
+ *       None.
+ *
+ * Side Effects:
+ *       None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void VMCIReleasePages(struct page **pages,	// IN
+			     uint64_t numPages,	// IN
+			     bool dirty)	// IN
+{
+	int i;
+
+	for (i = 0; i < numPages; i++) {
+		ASSERT(pages[i]);
+
+		if (dirty)
+			set_page_dirty(pages[i]);
+
+		page_cache_release(pages[i]);
+		pages[i] = NULL;
+	}
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_GetUserMemory --
+ *
+ *
+ *       Lock the user pages referenced by the {produce,consume}Buffer
+ *       struct into memory and populate the {produce,consume}Pages
+ *       arrays in the attach structure with them.
+ *
+ * Results:
+ *       VMCI_SUCCESS on sucess, negative error code on failure.
+ *
+ * Side Effects:
+ *       None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int VMCIHost_GetUserMemory(uint64_t produceUVA,	// IN
+			   uint64_t consumeUVA,	// IN
+			   struct vmci_queue *produceQ,	// OUT
+			   struct vmci_queue *consumeQ)	// OUT
+{
+	int retval;
+	int err = VMCI_SUCCESS;
+
+	down_write(&current->mm->mmap_sem);
+	retval = get_user_pages(current,
+				current->mm,
+				(uintptr_t) produceUVA,
+				produceQ->kernelIf->numPages,
+				1, 0, produceQ->kernelIf->headerPage, NULL);
+	if (retval < produceQ->kernelIf->numPages) {
+		pr_warn("get_user_pages(produce) failed (retval=%d)",
+			retval);
+		VMCIReleasePages(produceQ->kernelIf->headerPage, retval, false);
+		err = VMCI_ERROR_NO_MEM;
+		goto out;
+	}
+
+	retval = get_user_pages(current,
+				current->mm,
+				(uintptr_t) consumeUVA,
+				consumeQ->kernelIf->numPages,
+				1, 0, consumeQ->kernelIf->headerPage, NULL);
+	if (retval < consumeQ->kernelIf->numPages) {
+		pr_warn("get_user_pages(consume) failed (retval=%d)",
+			retval);
+		VMCIReleasePages(consumeQ->kernelIf->headerPage, retval, false);
+		VMCIReleasePages(produceQ->kernelIf->headerPage,
+				 produceQ->kernelIf->numPages, false);
+		err = VMCI_ERROR_NO_MEM;
+	}
+
+out:
+	up_write(&current->mm->mmap_sem);
+
+	return err;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_RegisterUserMemory --
+ *
+ *       Registers the specification of the user pages used for backing a queue
+ *       pair. Enough information to map in pages is stored in the OS specific
+ *       part of the struct vmci_queue structure.
+ *
+ * Results:
+ *       VMCI_SUCCESS on sucess, negative error code on failure.
+ *
+ * Side Effects:
+ *       None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int VMCIHost_RegisterUserMemory(QueuePairPageStore * pageStore,	// IN
+				struct vmci_queue *produceQ,	// OUT
+				struct vmci_queue *consumeQ)	// OUT
+{
+	uint64_t produceUVA;
+	uint64_t consumeUVA;
+
+	ASSERT(produceQ->kernelIf->headerPage
+	       && consumeQ->kernelIf->headerPage);
+
+	/*
+	 * The new style and the old style mapping only differs in that we either
+	 * get a single or two UVAs, so we split the single UVA range at the
+	 * appropriate spot.
+	 */
+
+	produceUVA = pageStore->pages;
+	consumeUVA =
+		pageStore->pages + produceQ->kernelIf->numPages * PAGE_SIZE;
+	return VMCIHost_GetUserMemory(produceUVA, consumeUVA, produceQ,
+				      consumeQ);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_UnregisterUserMemory --
+ *
+ *       Releases and removes the references to user pages stored in the attach
+ *       struct.
+ *
+ * Results:
+ *       None
+ *
+ * Side Effects:
+ *       Pages are released from the page cache and may become
+ *       swappable again.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+void VMCIHost_UnregisterUserMemory(struct vmci_queue *produceQ,	// IN/OUT
+				   struct vmci_queue *consumeQ)	// IN/OUT
+{
+	ASSERT(produceQ->kernelIf);
+	ASSERT(consumeQ->kernelIf);
+	ASSERT(!produceQ->qHeader && !consumeQ->qHeader);
+
+	VMCIReleasePages(produceQ->kernelIf->headerPage,
+			 produceQ->kernelIf->numPages, true);
+	memset(produceQ->kernelIf->headerPage, 0,
+	       sizeof *produceQ->kernelIf->headerPage *
+	       produceQ->kernelIf->numPages);
+	VMCIReleasePages(consumeQ->kernelIf->headerPage,
+			 consumeQ->kernelIf->numPages, true);
+	memset(consumeQ->kernelIf->headerPage, 0,
+	       sizeof *consumeQ->kernelIf->headerPage *
+	       consumeQ->kernelIf->numPages);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_MapQueues --
+ *
+ *       Once VMCIHost_RegisterUserMemory has been performed on a
+ *       queue, the queue pair headers can be mapped into the
+ *       kernel. Once mapped, they must be unmapped with
+ *       VMCIHost_UnmapQueues prior to calling
+ *       VMCIHost_UnregisterUserMemory.
+ *
+ * Results:
+ *       VMCI_SUCCESS if pages are mapped, appropriate error code otherwise.
+ *
+ * Side Effects:
+ *       Pages are pinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int VMCIHost_MapQueues(struct vmci_queue *produceQ,	// IN/OUT
+		       struct vmci_queue *consumeQ)	// IN/OUT
+{
+	int result;
+
+	if (!produceQ->qHeader || !consumeQ->qHeader) {
+		struct page *headers[2];
+
+		if (produceQ->qHeader != consumeQ->qHeader)
+			return VMCI_ERROR_QUEUEPAIR_MISMATCH;
+
+		if (produceQ->kernelIf->headerPage == NULL ||
+		    *produceQ->kernelIf->headerPage == NULL)
+			return VMCI_ERROR_UNAVAILABLE;
+
+		ASSERT(*produceQ->kernelIf->headerPage
+		       && *consumeQ->kernelIf->headerPage);
+
+		headers[0] = *produceQ->kernelIf->headerPage;
+		headers[1] = *consumeQ->kernelIf->headerPage;
+
+		produceQ->qHeader = vmap(headers, 2, VM_MAP, PAGE_KERNEL);
+		if (produceQ->qHeader != NULL) {
+			consumeQ->qHeader =
+				(struct vmci_queue_header *)((uint8_t *)
+							     produceQ->qHeader +
+							     PAGE_SIZE);
+			result = VMCI_SUCCESS;
+		} else {
+			pr_warn("vmap failed.");
+			result = VMCI_ERROR_NO_MEM;
+		}
+	} else {
+		result = VMCI_SUCCESS;
+	}
+
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_UnmapQueues --
+ *
+ *       Unmaps previously mapped queue pair headers from the kernel.
+ *
+ * Results:
+ *       VMCI_SUCCESS always.
+ *
+ * Side Effects:
+ *       Pages are unpinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int VMCIHost_UnmapQueues(uint32_t gid,	// IN
+			 struct vmci_queue *produceQ,	// IN/OUT
+			 struct vmci_queue *consumeQ)	// IN/OUT
+{
+	if (produceQ->qHeader) {
+		ASSERT(consumeQ->qHeader);
+
+		if (produceQ->qHeader < consumeQ->qHeader)
+			vunmap(produceQ->qHeader);
+		else
+			vunmap(consumeQ->qHeader);
+
+		produceQ->qHeader = NULL;
+		consumeQ->qHeader = NULL;
+	}
+
+	return VMCI_SUCCESS;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * VMCIHost_ReleaseUserMemory --
+ *       Release the reference to user pages stored in the attach
+ *       struct
+ *
+ * Results:
+ *       None
+ *
+ * Side Effects:
+ *       Pages are released from the page cache and may become
+ *       swappable again.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+void VMCIHost_ReleaseUserMemory(struct vmci_queue *produceQ,	// IN/OUT
+				struct vmci_queue *consumeQ)	// IN/OUT
+{
+	ASSERT(produceQ->kernelIf->headerPage);
+
+	VMCIHost_UnregisterUserMemory(produceQ, consumeQ);
+}
+
+
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_list_find --
+ *
+ *      Finds the entry in the list corresponding to a given handle. Assumes
+ *      that the list is locked.
+ *
+ * Results:
+ *      Pointer to entry.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static struct qp_entry *qp_list_find(struct qp_list *qpList,	// IN
+				     struct vmci_handle handle)	// IN
+{
+	struct qp_entry *entry;
+
+	if (VMCI_HANDLE_INVALID(handle))
+		return NULL;
+
+	list_for_each_entry(entry, &qpList->head, listItem) {
+		if (VMCI_HANDLE_EQUAL(entry->handle, handle))
+			return entry;
+	}
+
+	return NULL;
+}
+
+/*
+ *----------------------------------------------------------------------------
+ *
+ * qp_notify_peer_local --
+ *
+ *      Dispatches a queue pair event message directly into the local event
+ *      queue.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, error code otherwise
+ *
+ * Side effects:
+ *      None.
+ *
+ *----------------------------------------------------------------------------
+ */
+
+static int qp_notify_peer_local(bool attach,	// IN: attach or detach?
+				struct vmci_handle handle)	// IN: queue pair handle
+{
+	struct vmci_event_msg *eMsg;
+	struct vmci_event_payld_qp *ePayload;
+	/* buf is only 48 bytes. */
+	char buf[sizeof *eMsg + sizeof *ePayload];
+	uint32_t contextId;
+
+	contextId = VMCI_GetContextID();
+
+	eMsg = (struct vmci_event_msg *)buf;
+	ePayload = vmci_event_data_payload(&eMsg->eventData);
+
+	eMsg->hdr.dst = vmci_make_handle(contextId, VMCI_EVENT_HANDLER);
+	eMsg->hdr.src = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
+					 VMCI_CONTEXT_RESOURCE_ID);
+	eMsg->hdr.payloadSize =
+		sizeof *eMsg + sizeof *ePayload - sizeof eMsg->hdr;
+	eMsg->eventData.event =
+		attach ? VMCI_EVENT_QP_PEER_ATTACH : VMCI_EVENT_QP_PEER_DETACH;
+	ePayload->peerId = contextId;
+	ePayload->handle = handle;
+
+	return vmci_event_dispatch((struct vmci_dg *)eMsg);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_guest_endpoint_create --
+ *
+ *      Allocates and initializes a qp_guest_endpoint structure.
+ *      Allocates a QueuePair rid (and handle) iff the given entry has
+ *      an invalid handle.  0 through VMCI_RESERVED_RESOURCE_ID_MAX
+ *      are reserved handles.  Assumes that the QP list mutex is held
+ *      by the caller.
+ *
+ * Results:
+ *      Pointer to structure intialized.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static struct qp_guest_endpoint *qp_guest_endpoint_create(struct vmci_handle handle,	// IN
+							  uint32_t peer,	// IN
+							  uint32_t flags,	// IN
+							  uint64_t produceSize,	// IN
+							  uint64_t consumeSize,	// IN
+							  void *produceQ,	// IN
+							  void *consumeQ)	// IN
+{
+	static uint32_t queuePairRID = VMCI_RESERVED_RESOURCE_ID_MAX + 1;
+	struct qp_guest_endpoint *entry;
+	const uint64_t numPPNs = dm_div_up(produceSize, PAGE_SIZE) + dm_div_up(consumeSize, PAGE_SIZE) + 2;	/* One page each for the queue headers. */
+
+	ASSERT((produceSize || consumeSize) && produceQ && consumeQ);
+
+	if (VMCI_HANDLE_INVALID(handle)) {
+		uint32_t contextID = VMCI_GetContextID();
+		uint32_t oldRID = queuePairRID;
+
+		/*
+		 * Generate a unique QueuePair rid.  Keep on trying until we wrap around
+		 * in the RID space.
+		 */
+		ASSERT(oldRID > VMCI_RESERVED_RESOURCE_ID_MAX);
+		do {
+			handle = vmci_make_handle(contextID, queuePairRID);
+			entry = (struct qp_guest_endpoint *)
+				qp_list_find(&qpGuestEndpoints, handle);
+			queuePairRID++;
+
+			if (unlikely(!queuePairRID))
+				/* Skip the reserved rids. */
+				queuePairRID = 
+				  VMCI_RESERVED_RESOURCE_ID_MAX + 1;
+
+		} while (entry && queuePairRID != oldRID);
+
+		if (unlikely(entry != NULL)) {
+			ASSERT(queuePairRID == oldRID);
+			/*
+			 * We wrapped around --- no rids were free.
+			 */
+			return NULL;
+		}
+	}
+
+	ASSERT(!VMCI_HANDLE_INVALID(handle) &&
+	       qp_list_find(&qpGuestEndpoints, handle) == NULL);
+	entry = kzalloc(sizeof *entry, GFP_KERNEL);
+	if (entry) {
+		entry->qp.handle = handle;
+		entry->qp.peer = peer;
+		entry->qp.flags = flags;
+		entry->qp.produceSize = produceSize;
+		entry->qp.consumeSize = consumeSize;
+		entry->qp.refCount = 0;
+		entry->numPPNs = numPPNs;
+		entry->produceQ = produceQ;
+		entry->consumeQ = consumeQ;
+		INIT_LIST_HEAD(&entry->qp.listItem);
+	}
+	return entry;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_guest_endpoint_destroy --
+ *
+ *      Frees a QPGuestEndpoint structure.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_guest_endpoint_destroy(struct qp_guest_endpoint *entry)	// IN
+{
+	ASSERT(entry);
+	ASSERT(entry->qp.refCount == 0);
+
+	qp_free_ppn_set(&entry->ppnSet);
+	VMCI_CleanupQueueMutex(entry->produceQ, entry->consumeQ);
+	qp_free_queue(entry->produceQ, entry->qp.produceSize);
+	qp_free_queue(entry->consumeQ, entry->qp.consumeSize);
+	kfree(entry);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_alloc_hypercall --
+ *
+ *      Helper to make a QueuePairAlloc hypercall when the driver is
+ *      supporting a guest device.
+ *
+ * Results:
+ *      Result of the hypercall.
+ *
+ * Side effects:
+ *      Memory is allocated & freed.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_alloc_hypercall(const struct qp_guest_endpoint *entry)	// IN
+{
+	struct vmci_qp_alloc_msg *allocMsg;
+	size_t msgSize;
+	int result;
+
+	if (!entry || entry->numPPNs <= 2)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	ASSERT(!(entry->qp.flags & VMCI_QPFLAG_LOCAL));
+
+	msgSize = sizeof *allocMsg + (size_t) entry->numPPNs * sizeof(uint32_t);
+	allocMsg = kmalloc(msgSize, GFP_KERNEL);
+	if (!allocMsg)
+		return VMCI_ERROR_NO_MEM;
+
+	allocMsg->hdr.dst = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
+					     VMCI_QUEUEPAIR_ALLOC);
+	allocMsg->hdr.src = VMCI_ANON_SRC_HANDLE;
+	allocMsg->hdr.payloadSize = msgSize - VMCI_DG_HEADERSIZE;
+	allocMsg->handle = entry->qp.handle;
+	allocMsg->peer = entry->qp.peer;
+	allocMsg->flags = entry->qp.flags;
+	allocMsg->produceSize = entry->qp.produceSize;
+	allocMsg->consumeSize = entry->qp.consumeSize;
+	allocMsg->numPPNs = entry->numPPNs;
+
+	result =
+		qp_populate_ppn_set((uint8_t *) allocMsg + sizeof *allocMsg,
+				    &entry->ppnSet);
+	if (result == VMCI_SUCCESS)
+		result = vmci_send_dg((struct vmci_dg *)allocMsg);
+
+	kfree(allocMsg);
+
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_detatch_hypercall --
+ *
+ *      Helper to make a QueuePairDetach hypercall when the driver is
+ *      supporting a guest device.
+ *
+ * Results:
+ *      Result of the hypercall.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_detatch_hypercall(struct vmci_handle handle)	// IN
+{
+	struct vmci_qp_detach_msg detachMsg;
+
+	detachMsg.hdr.dst = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
+					     VMCI_QUEUEPAIR_DETACH);
+	detachMsg.hdr.src = VMCI_ANON_SRC_HANDLE;
+	detachMsg.hdr.payloadSize = sizeof handle;
+	detachMsg.handle = handle;
+
+	return vmci_send_dg((struct vmci_dg *)&detachMsg);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_list_add_entry --
+ *
+ *      Adds the given entry to the list. Assumes that the list is locked.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_list_add_entry(struct qp_list *qpList,	// IN
+				     struct qp_entry *entry)	// IN
+{
+	if (entry)
+		list_add(&entry->listItem, &qpList->head);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_list_remove_entry --
+ *
+ *      Removes the given entry from the list. Assumes that the list is locked.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_list_remove_entry(struct qp_list *qpList,	// IN
+					struct qp_entry *entry)	// IN
+{
+	if (entry)
+		list_del(&entry->listItem);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_detatch_guest_work --
+ *
+ *      Helper for VMCI QueuePair detach interface. Frees the physical
+ *      pages for the queue pair.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory may be freed.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_detatch_guest_work(struct vmci_handle handle)	// IN
+{
+	int result;
+	struct qp_guest_endpoint *entry;
+	uint32_t refCount = ~0;	/* To avoid compiler warning below */
+
+	ASSERT(!VMCI_HANDLE_INVALID(handle));
+
+	down(&qpGuestEndpoints.mutex);
+
+	entry = (struct qp_guest_endpoint *)
+		qp_list_find(&qpGuestEndpoints, handle);
+	if (!entry) {
+		up(&qpGuestEndpoints.mutex);
+		return VMCI_ERROR_NOT_FOUND;
+	}
+
+	ASSERT(entry->qp.refCount >= 1);
+
+	if (entry->qp.flags & VMCI_QPFLAG_LOCAL) {
+		result = VMCI_SUCCESS;
+
+		if (entry->qp.refCount > 1) {
+			result = qp_notify_peer_local(false, handle);
+			/*
+			 * We can fail to notify a local queuepair because we can't allocate.
+			 * We still want to release the entry if that happens, so don't bail
+			 * out yet.
+			 */
+		}
+	} else {
+		result = qp_detatch_hypercall(handle);
+		if (result < VMCI_SUCCESS) {
+			/*
+			 * We failed to notify a non-local queuepair.  That other queuepair
+			 * might still be accessing the shared memory, so don't release the
+			 * entry yet.  It will get cleaned up by VMCIQueuePair_Exit()
+			 * if necessary (assuming we are going away, otherwise why did this
+			 * fail?).
+			 */
+
+			up(&qpGuestEndpoints.mutex);
+			return result;
+		}
+	}
+
+	/*
+	 * If we get here then we either failed to notify a local queuepair, or
+	 * we succeeded in all cases.  Release the entry if required.
+	 */
+
+	entry->qp.refCount--;
+	if (entry->qp.refCount == 0)
+		qp_list_remove_entry(&qpGuestEndpoints, &entry->qp);
+
+	/* If we didn't remove the entry, this could change once we unlock. */
+	if (entry)
+		refCount = entry->qp.refCount;
+
+	up(&qpGuestEndpoints.mutex);
+
+	if (refCount == 0)
+		qp_guest_endpoint_destroy(entry);
+
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_alloc_guest_work --
+ *
+ *      This functions handles the actual allocation of a VMCI queue
+ *      pair guest endpoint. Allocates physical pages for the queue
+ *      pair. It makes OS dependent calls through generic wrappers.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory is allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_alloc_guest_work(struct vmci_handle *handle,	// IN/OUT
+			       struct vmci_queue **produceQ,	// OUT
+			       uint64_t produceSize,	// IN
+			       struct vmci_queue **consumeQ,	// OUT
+			       uint64_t consumeSize,	// IN
+			       uint32_t peer,	// IN
+			       uint32_t flags,	// IN
+			       uint32_t privFlags)	// IN
+{
+	const uint64_t numProducePages = dm_div_up(produceSize, PAGE_SIZE) + 1;
+	const uint64_t numConsumePages = dm_div_up(consumeSize, PAGE_SIZE) + 1;
+	void *myProduceQ = NULL;
+	void *myConsumeQ = NULL;
+	int result;
+	struct qp_guest_endpoint *queuePairEntry = NULL;
+
+	ASSERT(handle && produceQ && consumeQ && (produceSize || consumeSize));
+
+	if (privFlags != VMCI_NO_PRIVILEGE_FLAGS)
+		return VMCI_ERROR_NO_ACCESS;
+
+	down(&qpGuestEndpoints.mutex);
+
+	if ((queuePairEntry = (struct qp_guest_endpoint *)
+	     qp_list_find(&qpGuestEndpoints, *handle))) {
+		if (queuePairEntry->qp.flags & VMCI_QPFLAG_LOCAL) {
+			/* Local attach case. */
+			if (queuePairEntry->qp.refCount > 1) {
+				pr_devel("Error attempting to attach more than "
+					 "once.");
+				result = VMCI_ERROR_UNAVAILABLE;
+				goto errorKeepEntry;
+			}
+
+			if (queuePairEntry->qp.produceSize != consumeSize
+			    || queuePairEntry->qp.consumeSize !=
+			    produceSize
+			    || queuePairEntry->qp.flags !=
+			    (flags & ~VMCI_QPFLAG_ATTACH_ONLY)) {
+				pr_devel("Error mismatched queue pair in local "
+					 "attach.");
+				result = VMCI_ERROR_QUEUEPAIR_MISMATCH;
+				goto errorKeepEntry;
+			}
+
+			/*
+			 * Do a local attach.  We swap the consume and produce queues for the
+			 * attacher and deliver an attach event.
+			 */
+			result = qp_notify_peer_local(true, *handle);
+			if (result < VMCI_SUCCESS)
+				goto errorKeepEntry;
+
+			myProduceQ = queuePairEntry->consumeQ;
+			myConsumeQ = queuePairEntry->produceQ;
+			goto out;
+		}
+		result = VMCI_ERROR_ALREADY_EXISTS;
+		goto errorKeepEntry;
+	}
+
+	myProduceQ = qp_alloc_queue(produceSize, flags);
+	if (!myProduceQ) {
+		pr_warn("Error allocating pages for produce queue.");
+		result = VMCI_ERROR_NO_MEM;
+		goto error;
+	}
+
+	myConsumeQ = qp_alloc_queue(consumeSize, flags);
+	if (!myConsumeQ) {
+		pr_warn("Error allocating pages for consume queue.");
+		result = VMCI_ERROR_NO_MEM;
+		goto error;
+	}
+
+	queuePairEntry = qp_guest_endpoint_create(*handle, peer, flags,
+						  produceSize, consumeSize,
+						  myProduceQ, myConsumeQ);
+	if (!queuePairEntry) {
+		pr_warn("Error allocating memory in %s.", __FUNCTION__);
+		result = VMCI_ERROR_NO_MEM;
+		goto error;
+	}
+
+	result = qp_alloc_ppn_set(myProduceQ, numProducePages, myConsumeQ,
+				  numConsumePages, &queuePairEntry->ppnSet);
+	if (result < VMCI_SUCCESS) {
+		pr_warn("qp_alloc_ppn_set failed.");
+		goto error;
+	}
+
+	/*
+	 * It's only necessary to notify the host if this queue pair will be
+	 * attached to from another context.
+	 */
+	if (queuePairEntry->qp.flags & VMCI_QPFLAG_LOCAL) {
+		/* Local create case. */
+		uint32_t contextId = VMCI_GetContextID();
+
+		/*
+		 * Enforce similar checks on local queue pairs as we do for regular ones.
+		 * The handle's context must match the creator or attacher context id
+		 * (here they are both the current context id) and the attach-only flag
+		 * cannot exist during create.  We also ensure specified peer is this
+		 * context or an invalid one.
+		 */
+		if (queuePairEntry->qp.handle.context != contextId ||
+		    (queuePairEntry->qp.peer != VMCI_INVALID_ID &&
+		     queuePairEntry->qp.peer != contextId)) {
+			result = VMCI_ERROR_NO_ACCESS;
+			goto error;
+		}
+
+		if (queuePairEntry->qp.flags & VMCI_QPFLAG_ATTACH_ONLY) {
+			result = VMCI_ERROR_NOT_FOUND;
+			goto error;
+		}
+	} else {
+		result = qp_alloc_hypercall(queuePairEntry);
+		if (result < VMCI_SUCCESS) {
+			pr_warn("qp_alloc_hypercall result = %d.",
+				result);
+			goto error;
+		}
+	}
+
+	VMCI_InitQueueMutex((struct vmci_queue *)myProduceQ,
+			    (struct vmci_queue *)myConsumeQ);
+
+	qp_list_add_entry(&qpGuestEndpoints, &queuePairEntry->qp);
+
+out:
+	queuePairEntry->qp.refCount++;
+	*handle = queuePairEntry->qp.handle;
+	*produceQ = (struct vmci_queue *)myProduceQ;
+	*consumeQ = (struct vmci_queue *)myConsumeQ;
+
+	/*
+	 * We should initialize the queue pair header pages on a local queue pair
+	 * create.  For non-local queue pairs, the hypervisor initializes the header
+	 * pages in the create step.
+	 */
+	if ((queuePairEntry->qp.flags & VMCI_QPFLAG_LOCAL) &&
+	    queuePairEntry->qp.refCount == 1) {
+		vmci_q_header_init((*produceQ)->qHeader, *handle);
+		vmci_q_header_init((*consumeQ)->qHeader, *handle);
+	}
+
+	up(&qpGuestEndpoints.mutex);
+
+	return VMCI_SUCCESS;
+
+error:
+	up(&qpGuestEndpoints.mutex);
+	if (queuePairEntry) {
+		/* The queues will be freed inside the destroy routine. */
+		qp_guest_endpoint_destroy(queuePairEntry);
+	} else {
+		if (myProduceQ) {
+			qp_free_queue(myProduceQ, produceSize);
+		}
+		if (myConsumeQ) {
+			qp_free_queue(myConsumeQ, consumeSize);
+		}
+	}
+	return result;
+
+errorKeepEntry:
+	/* This path should only be used when an existing entry was found. */
+	ASSERT(queuePairEntry->qp.refCount > 0);
+	up(&qpGuestEndpoints.mutex);
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_broker_create --
+ *
+ *      The first endpoint issuing a queue pair allocation will create the state
+ *      of the queue pair in the queue pair broker.
+ *
+ *      If the creator is a guest, it will associate a VMX virtual address range
+ *      with the queue pair as specified by the pageStore. For compatibility with
+ *      older VMX'en, that would use a separate step to set the VMX virtual
+ *      address range, the virtual address range can be registered later using
+ *      vmci_qp_broker_set_page_store. In that case, a pageStore of NULL should be
+ *      used.
+ *
+ *      If the creator is the host, a pageStore of NULL should be used as well,
+ *      since the host is not able to supply a page store for the queue pair.
+ *
+ *      For older VMX and host callers, the queue pair will be created in the
+ *      VMCIQPB_CREATED_NO_MEM state, and for current VMX callers, it will be
+ *      created in VMCOQPB_CREATED_MEM state.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, appropriate error code otherwise.
+ *
+ * Side effects:
+ *      Memory will be allocated, and pages may be pinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_broker_create(struct vmci_handle handle,	// IN
+			    uint32_t peer,	// IN
+			    uint32_t flags,	// IN
+			    uint32_t privFlags,	// IN
+			    uint64_t produceSize,	// IN
+			    uint64_t consumeSize,	// IN
+			    QueuePairPageStore * pageStore,	// IN
+			    struct vmci_ctx *context,	// IN: Caller
+			    VMCIEventReleaseCB wakeupCB,	// IN
+			    void *clientData,	// IN
+			    struct qp_broker_entry **ent)	// OUT
+{
+	struct qp_broker_entry *entry = NULL;
+	const uint32_t contextId = vmci_ctx_get_id(context);
+	bool isLocal = flags & VMCI_QPFLAG_LOCAL;
+	int result;
+	uint64_t guestProduceSize;
+	uint64_t guestConsumeSize;
+
+	/*
+	 * Do not create if the caller asked not to.
+	 */
+
+	if (flags & VMCI_QPFLAG_ATTACH_ONLY) {
+		return VMCI_ERROR_NOT_FOUND;
+	}
+
+	/*
+	 * Creator's context ID should match handle's context ID or the creator
+	 * must allow the context in handle's context ID as the "peer".
+	 */
+
+	if (handle.context != contextId && handle.context != peer) {
+		return VMCI_ERROR_NO_ACCESS;
+	}
+
+	if (VMCI_CONTEXT_IS_VM(contextId) && VMCI_CONTEXT_IS_VM(peer)) {
+		return VMCI_ERROR_DST_UNREACHABLE;
+	}
+
+	/*
+	 * Creator's context ID for local queue pairs should match the
+	 * peer, if a peer is specified.
+	 */
+
+	if (isLocal && peer != VMCI_INVALID_ID && contextId != peer) {
+		return VMCI_ERROR_NO_ACCESS;
+	}
+
+	entry = kzalloc(sizeof *entry, GFP_ATOMIC);
+	if (!entry) {
+		return VMCI_ERROR_NO_MEM;
+	}
+
+	if (vmci_ctx_get_id(context) == VMCI_HOST_CONTEXT_ID && !isLocal) {
+		/*
+		 * The queue pair broker entry stores values from the guest
+		 * point of view, so a creating host side endpoint should swap
+		 * produce and consume values -- unless it is a local queue
+		 * pair, in which case no swapping is necessary, since the local
+		 * attacher will swap queues.
+		 */
+
+		guestProduceSize = consumeSize;
+		guestConsumeSize = produceSize;
+	} else {
+		guestProduceSize = produceSize;
+		guestConsumeSize = consumeSize;
+	}
+
+	entry->qp.handle = handle;
+	entry->qp.peer = peer;
+	entry->qp.flags = flags;
+	entry->qp.produceSize = guestProduceSize;
+	entry->qp.consumeSize = guestConsumeSize;
+	entry->qp.refCount = 1;
+	entry->createId = contextId;
+	entry->attachId = VMCI_INVALID_ID;
+	entry->state = VMCIQPB_NEW;
+	entry->requireTrustedAttach =
+		(context->privFlags & VMCI_PRIVILEGE_FLAG_RESTRICTED) ? true :
+		false;
+	entry->createdByTrusted =
+		(privFlags & VMCI_PRIVILEGE_FLAG_TRUSTED) ? true : false;
+	entry->vmciPageFiles = false;
+	entry->wakeupCB = wakeupCB;
+	entry->clientData = clientData;
+	entry->produceQ = VMCIHost_AllocQueue(guestProduceSize);
+	if (entry->produceQ == NULL) {
+		result = VMCI_ERROR_NO_MEM;
+		goto error;
+	}
+	entry->consumeQ = VMCIHost_AllocQueue(guestConsumeSize);
+	if (entry->consumeQ == NULL) {
+		result = VMCI_ERROR_NO_MEM;
+		goto error;
+	}
+
+	VMCI_InitQueueMutex(entry->produceQ, entry->consumeQ);
+
+	INIT_LIST_HEAD(&entry->qp.listItem);
+
+	if (isLocal) {
+		ASSERT(pageStore == NULL);
+
+		entry->localMem =
+			kmalloc(QPE_NUM_PAGES(entry->qp) * PAGE_SIZE, GFP_KERNEL);
+		if (entry->localMem == NULL) {
+			result = VMCI_ERROR_NO_MEM;
+			goto error;
+		}
+		entry->state = VMCIQPB_CREATED_MEM;
+		entry->produceQ->qHeader = entry->localMem;
+		entry->consumeQ->qHeader =
+			(struct vmci_queue_header *)((uint8_t *) entry->localMem +
+						     (dm_div_up
+						      (entry->qp.produceSize,
+						       PAGE_SIZE) + 1) * PAGE_SIZE);
+		vmci_q_header_init(entry->produceQ->qHeader, handle);
+		vmci_q_header_init(entry->consumeQ->qHeader, handle);
+	} else if (pageStore) {
+		ASSERT(entry->createId != VMCI_HOST_CONTEXT_ID || isLocal);
+
+		/*
+		 * The VMX already initialized the queue pair headers, so no
+		 * need for the kernel side to do that.
+		 */
+
+		result = VMCIHost_RegisterUserMemory(pageStore,
+						     entry->produceQ,
+						     entry->consumeQ);
+		if (result < VMCI_SUCCESS) {
+			goto error;
+		}
+		entry->state = VMCIQPB_CREATED_MEM;
+	} else {
+		/*
+		 * A create without a pageStore may be either a host side create (in which
+		 * case we are waiting for the guest side to supply the memory) or an old
+		 * style queue pair create (in which case we will expect a set page store
+		 * call as the next step).
+		 */
+
+		entry->state = VMCIQPB_CREATED_NO_MEM;
+	}
+
+	qp_list_add_entry(&qpBrokerList, &entry->qp);
+	if (ent != NULL)
+		*ent = entry;
+
+	vmci_ctx_qp_create(context, handle);
+
+	return VMCI_SUCCESS;
+
+error:
+	if (entry != NULL) {
+		if (entry->produceQ != NULL)
+			VMCIHost_FreeQueue(entry->produceQ, guestProduceSize);
+
+		if (entry->consumeQ != NULL)
+			VMCIHost_FreeQueue(entry->consumeQ, guestConsumeSize);
+
+		kfree(entry);
+	}
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_notify_peer --
+ *
+ *      Enqueues an event datagram to notify the peer VM attached to
+ *      the given queue pair handle about attach/detach event by the
+ *      given VM.
+ *
+ * Results:
+ *      Payload size of datagram enqueued on success, error code otherwise.
+ *
+ * Side effects:
+ *      Memory is allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_notify_peer(bool attach,	// IN: attach or detach?
+			  struct vmci_handle handle,	// IN
+			  uint32_t myId,	// IN
+			  uint32_t peerId)	// IN: CID of VM to notify
+{
+	int rv;
+	struct vmci_event_msg *eMsg;
+	struct vmci_event_payld_qp *evPayload;
+	char buf[sizeof *eMsg + sizeof *evPayload];
+
+	if (VMCI_HANDLE_INVALID(handle) || myId == VMCI_INVALID_ID ||
+	    peerId == VMCI_INVALID_ID)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	/*
+	 * Notification message contains: queue pair handle and
+	 * attaching/detaching VM's context id.
+	 */
+
+	eMsg = (struct vmci_event_msg *)buf;
+
+	/*
+	 * In vmci_ctx_enqueue_dg() we enforce the upper limit on number of
+	 * pending events from the hypervisor to a given VM otherwise a rogue VM
+	 * could do an arbitrary number of attach and detach operations causing memory
+	 * pressure in the host kernel.
+	 */
+
+	/* Clear out any garbage. */
+	memset(eMsg, 0, sizeof buf);
+
+	eMsg->hdr.dst = vmci_make_handle(peerId, VMCI_EVENT_HANDLER);
+	eMsg->hdr.src = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
+					 VMCI_CONTEXT_RESOURCE_ID);
+	eMsg->hdr.payloadSize =
+		sizeof *eMsg + sizeof *evPayload - sizeof eMsg->hdr;
+	eMsg->eventData.event =
+		attach ? VMCI_EVENT_QP_PEER_ATTACH : VMCI_EVENT_QP_PEER_DETACH;
+	evPayload = vmci_event_data_payload(&eMsg->eventData);
+	evPayload->handle = handle;
+	evPayload->peerId = myId;
+
+	rv = vmci_dg_dispatch(VMCI_HYPERVISOR_CONTEXT_ID,
+			      (struct vmci_dg *)eMsg, false);
+	if (rv < VMCI_SUCCESS)
+		pr_warn("Failed to enqueue QueuePair %s event datagram "
+			"for context (ID=0x%x).",
+			attach ? "ATTACH" : "DETACH", peerId);
+
+	return rv;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_broker_attach --
+ *
+ *      The second endpoint issuing a queue pair allocation will attach to the
+ *      queue pair registered with the queue pair broker.
+ *
+ *      If the attacher is a guest, it will associate a VMX virtual address range
+ *      with the queue pair as specified by the pageStore. At this point, the
+ *      already attach host endpoint may start using the queue pair, and an
+ *      attach event is sent to it. For compatibility with older VMX'en, that
+ *      used a separate step to set the VMX virtual address range, the virtual
+ *      address range can be registered later using vmci_qp_broker_set_page_store. In
+ *      that case, a pageStore of NULL should be used, and the attach event will
+ *      be generated once the actual page store has been set.
+ *
+ *      If the attacher is the host, a pageStore of NULL should be used as well,
+ *      since the page store information is already set by the guest.
+ *
+ *      For new VMX and host callers, the queue pair will be moved to the
+ *      VMCIQPB_ATTACHED_MEM state, and for older VMX callers, it will be
+ *      moved to the VMCOQPB_ATTACHED_NO_MEM state.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, appropriate error code otherwise.
+ *
+ * Side effects:
+ *      Memory will be allocated, and pages may be pinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_broker_attach(struct qp_broker_entry *entry,	// IN
+			    uint32_t peer,	// IN
+			    uint32_t flags,	// IN
+			    uint32_t privFlags,	// IN
+			    uint64_t produceSize,	// IN
+			    uint64_t consumeSize,	// IN
+			    QueuePairPageStore * pageStore,	// IN/OUT
+			    struct vmci_ctx *context,	// IN: Caller
+			    VMCIEventReleaseCB wakeupCB,	// IN
+			    void *clientData,	// IN
+			    struct qp_broker_entry **ent)	// OUT
+{
+	const uint32_t contextId = vmci_ctx_get_id(context);
+	bool isLocal = flags & VMCI_QPFLAG_LOCAL;
+	int result;
+
+	if (entry->state != VMCIQPB_CREATED_NO_MEM &&
+	    entry->state != VMCIQPB_CREATED_MEM)
+		return VMCI_ERROR_UNAVAILABLE;
+
+	if (isLocal) {
+		if (!(entry->qp.flags & VMCI_QPFLAG_LOCAL) ||
+		    contextId != entry->createId) {
+			return VMCI_ERROR_INVALID_ARGS;
+		}
+	} else if (contextId == entry->createId ||
+		   contextId == entry->attachId) {
+		return VMCI_ERROR_ALREADY_EXISTS;
+	}
+
+	ASSERT(entry->qp.refCount < 2);
+	ASSERT(entry->attachId == VMCI_INVALID_ID);
+
+	if (VMCI_CONTEXT_IS_VM(contextId) &&
+	    VMCI_CONTEXT_IS_VM(entry->createId))
+		return VMCI_ERROR_DST_UNREACHABLE;
+
+	/*
+	 * If we are attaching from a restricted context then the queuepair
+	 * must have been created by a trusted endpoint.
+	 */
+	if ((context->privFlags & VMCI_PRIVILEGE_FLAG_RESTRICTED) &&
+	    !entry->createdByTrusted)
+		return VMCI_ERROR_NO_ACCESS;
+
+	/*
+	 * If we are attaching to a queuepair that was created by a restricted
+	 * context then we must be trusted.
+	 */
+	if (entry->requireTrustedAttach &&
+	    (!(privFlags & VMCI_PRIVILEGE_FLAG_TRUSTED)))
+		return VMCI_ERROR_NO_ACCESS;
+
+	/*
+	 * If the creator specifies VMCI_INVALID_ID in "peer" field, access
+	 * control check is not performed.
+	 */
+
+	if (entry->qp.peer != VMCI_INVALID_ID && entry->qp.peer != contextId)
+		return VMCI_ERROR_NO_ACCESS;
+
+	if (entry->createId == VMCI_HOST_CONTEXT_ID) {
+		/*
+		 * Do not attach if the caller doesn't support Host Queue Pairs
+		 * and a host created this queue pair.
+		 */
+
+		if (!vmci_ctx_supports_host_qp(context))
+			return VMCI_ERROR_INVALID_RESOURCE;
+
+	} else if (contextId == VMCI_HOST_CONTEXT_ID) {
+		struct vmci_ctx *createContext;
+		bool supportsHostQP;
+
+		/*
+		 * Do not attach a host to a user created queue pair if that
+		 * user doesn't support host queue pair end points.
+		 */
+
+		createContext = vmci_ctx_get(entry->createId);
+		supportsHostQP = vmci_ctx_supports_host_qp(createContext);
+		vmci_ctx_release(createContext);
+
+		if (!supportsHostQP)
+			return VMCI_ERROR_INVALID_RESOURCE;
+	}
+
+	if ((entry->qp.flags & ~VMCI_QP_ASYMM) != (flags & ~VMCI_QP_ASYMM_PEER))
+		return VMCI_ERROR_QUEUEPAIR_MISMATCH;
+
+	if (contextId != VMCI_HOST_CONTEXT_ID) {
+		/*
+		 * The queue pair broker entry stores values from the guest
+		 * point of view, so an attaching guest should match the values
+		 * stored in the entry.
+		 */
+
+		if (entry->qp.produceSize != produceSize ||
+		    entry->qp.consumeSize != consumeSize) {
+			return VMCI_ERROR_QUEUEPAIR_MISMATCH;
+		}
+	} else if (entry->qp.produceSize != consumeSize ||
+		   entry->qp.consumeSize != produceSize) {
+		return VMCI_ERROR_QUEUEPAIR_MISMATCH;
+	}
+
+	if (contextId != VMCI_HOST_CONTEXT_ID) {
+		/*
+		 * If a guest attached to a queue pair, it will supply the backing memory.
+		 * If this is a pre NOVMVM vmx, the backing memory will be supplied by
+		 * calling vmci_qp_broker_set_page_store() following the return of the
+		 * vmci_qp_broker_alloc() call. If it is a vmx of version NOVMVM or later,
+		 * the page store must be supplied as part of the vmci_qp_broker_alloc call.
+		 * Under all circumstances must the initially created queue pair not have
+		 * any memory associated with it already.
+		 */
+
+		if (entry->state != VMCIQPB_CREATED_NO_MEM)
+			return VMCI_ERROR_INVALID_ARGS;
+
+		if (pageStore != NULL) {
+			/*
+			 * Patch up host state to point to guest supplied memory. The VMX
+			 * already initialized the queue pair headers, so no need for the
+			 * kernel side to do that.
+			 */
+
+			result = VMCIHost_RegisterUserMemory(pageStore,
+							     entry->produceQ,
+							     entry->consumeQ);
+			if (result < VMCI_SUCCESS)
+				return result;
+
+			/*
+			 * Preemptively load in the headers if non-blocking to
+			 * prevent blocking later.
+			 */
+			if (entry->qp.flags & VMCI_QPFLAG_NONBLOCK) {
+				result = VMCIHost_MapQueues(entry->produceQ,
+							    entry->consumeQ);
+				if (result < VMCI_SUCCESS) {
+					VMCIHost_ReleaseUserMemory(entry->
+								   produceQ,
+								   entry->
+								   consumeQ);
+					return result;
+				}
+			}
+
+			entry->state = VMCIQPB_ATTACHED_MEM;
+		} else {
+			entry->state = VMCIQPB_ATTACHED_NO_MEM;
+		}
+	} else if (entry->state == VMCIQPB_CREATED_NO_MEM) {
+		/*
+		 * The host side is attempting to attach to a queue pair that doesn't have
+		 * any memory associated with it. This must be a pre NOVMVM vmx that hasn't
+		 * set the page store information yet, or a quiesced VM.
+		 */
+
+		return VMCI_ERROR_UNAVAILABLE;
+	} else {
+		/*
+		 * For non-blocking queue pairs, we cannot rely on enqueue/dequeue to map
+		 * in the pages on the host-side, since it may block, so we make an attempt
+		 * here.
+		 */
+
+		if (flags & VMCI_QPFLAG_NONBLOCK) {
+			result =
+				VMCIHost_MapQueues(entry->produceQ,
+						   entry->consumeQ);
+			if (result < VMCI_SUCCESS)
+				return result;
+
+			entry->qp.flags |= flags &
+				(VMCI_QPFLAG_NONBLOCK | VMCI_QPFLAG_PINNED);
+		}
+
+		/* The host side has successfully attached to a queue pair. */
+		entry->state = VMCIQPB_ATTACHED_MEM;
+	}
+
+	if (entry->state == VMCIQPB_ATTACHED_MEM) {
+		result =
+			qp_notify_peer(true, entry->qp.handle, contextId,
+				       entry->createId);
+		if (result < VMCI_SUCCESS)
+			pr_warn("Failed to notify peer (ID=0x%x) of "
+				"attach to queue pair (handle=0x%x:0x%x).",
+				entry->createId, entry->qp.handle.context,
+				entry->qp.handle.resource);
+	}
+
+	entry->attachId = contextId;
+	entry->qp.refCount++;
+	if (wakeupCB) {
+		ASSERT(!entry->wakeupCB);
+		entry->wakeupCB = wakeupCB;
+		entry->clientData = clientData;
+	}
+
+	/*
+	 * When attaching to local queue pairs, the context already has
+	 * an entry tracking the queue pair, so don't add another one.
+	 */
+
+	if (!isLocal)
+		vmci_ctx_qp_create(context, entry->qp.handle);
+        else
+		ASSERT(vmci_ctx_qp_exists(context, entry->qp.handle));
+
+	if (ent != NULL)
+		*ent = entry;
+
+	return VMCI_SUCCESS;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_broker_alloc --
+ *
+ *      QueuePair_Alloc for use when setting up queue pair endpoints
+ *      on the host. Like QueuePair_Alloc, but returns a pointer to
+ *      the struct qp_broker_entry on success.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory may be allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_broker_alloc(struct vmci_handle handle,	// IN
+			   uint32_t peer,	// IN
+			   uint32_t flags,	// IN
+			   uint32_t privFlags,	// IN
+			   uint64_t produceSize,	// IN
+			   uint64_t consumeSize,	// IN
+			   QueuePairPageStore * pageStore,	// IN/OUT
+			   struct vmci_ctx *context,	// IN: Caller
+			   VMCIEventReleaseCB wakeupCB,	// IN
+			   void *clientData,	// IN
+			   struct qp_broker_entry **ent,	// OUT
+			   bool * swap)	// OUT: swap queues?
+{
+	const uint32_t contextId = vmci_ctx_get_id(context);
+	bool create;
+	struct qp_broker_entry *entry;
+	bool isLocal = flags & VMCI_QPFLAG_LOCAL;
+	int result;
+
+	if (VMCI_HANDLE_INVALID(handle) ||
+	    (flags & ~VMCI_QP_ALL_FLAGS) || isLocal ||
+	    !(produceSize || consumeSize) ||
+	    !context || contextId == VMCI_INVALID_ID ||
+	    handle.context == VMCI_INVALID_ID) {
+		return VMCI_ERROR_INVALID_ARGS;
+	}
+
+	if (pageStore && !VMCI_QP_PAGESTORE_IS_WELLFORMED(pageStore))
+		return VMCI_ERROR_INVALID_ARGS;
+
+	/*
+	 * In the initial argument check, we ensure that non-vmkernel hosts
+	 * are not allowed to create local queue pairs.
+	 */
+
+	ASSERT(!isLocal);
+
+	down(&qpBrokerList.mutex);
+
+	if (!isLocal && vmci_ctx_qp_exists(context, handle)) {
+		pr_devel("Context (ID=0x%x) already attached to queue "
+			 "pair (handle=0x%x:0x%x).", contextId,
+			 handle.context, handle.resource);
+		up(&qpBrokerList.mutex);
+		return VMCI_ERROR_ALREADY_EXISTS;
+	}
+
+	entry = (struct qp_broker_entry *)
+		qp_list_find(&qpBrokerList, handle);
+	if (!entry) {
+		create = true;
+		result =
+			qp_broker_create(handle, peer, flags, privFlags,
+					 produceSize, consumeSize, pageStore,
+					 context, wakeupCB, clientData, ent);
+	} else {
+		create = false;
+		result =
+			qp_broker_attach(entry, peer, flags, privFlags,
+					 produceSize, consumeSize, pageStore,
+					 context, wakeupCB, clientData, ent);
+	}
+
+	up(&qpBrokerList.mutex);
+
+	if (swap)
+		*swap = (contextId == VMCI_HOST_CONTEXT_ID) &&
+			!(create && isLocal);
+
+
+	return result;
+}
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * qp_alloc_host_work --
+ *
+ *    This function implements the kernel API for allocating a queue
+ *    pair.
+ *
+ * Results:
+ *     VMCI_SUCCESS on succes and appropriate failure code otherwise.
+ *
+ * Side effects:
+ *     May allocate memory.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static int qp_alloc_host_work(struct vmci_handle *handle,	// IN/OUT
+			      struct vmci_queue **produceQ,	// OUT
+			      uint64_t produceSize,	// IN
+			      struct vmci_queue **consumeQ,	// OUT
+			      uint64_t consumeSize,	// IN
+			      uint32_t peer,	// IN
+			      uint32_t flags,	// IN
+			      uint32_t privFlags,	// IN
+			      VMCIEventReleaseCB wakeupCB,	// IN
+			      void *clientData)	// IN
+{
+	struct vmci_ctx *context;
+	struct qp_broker_entry *entry;
+	int result;
+	bool swap;
+
+	if (VMCI_HANDLE_INVALID(*handle)) {
+		uint32_t resourceID = vmci_resource_get_id(VMCI_HOST_CONTEXT_ID);
+		if (resourceID == VMCI_INVALID_ID)
+			return VMCI_ERROR_NO_HANDLE;
+
+		*handle = vmci_make_handle(VMCI_HOST_CONTEXT_ID, resourceID);
+	}
+
+	context = vmci_ctx_get(VMCI_HOST_CONTEXT_ID);
+	ASSERT(context);
+
+	entry = NULL;
+	result =
+		qp_broker_alloc(*handle, peer, flags, privFlags,
+				produceSize, consumeSize, NULL, context,
+				wakeupCB, clientData, &entry, &swap);
+	if (result == VMCI_SUCCESS) {
+		if (swap) {
+			/*
+			 * If this is a local queue pair, the attacher will swap around produce
+			 * and consume queues.
+			 */
+
+			*produceQ = entry->consumeQ;
+			*consumeQ = entry->produceQ;
+		} else {
+			*produceQ = entry->produceQ;
+			*consumeQ = entry->consumeQ;
+		}
+	} else {
+		*handle = VMCI_INVALID_HANDLE;
+		pr_devel("queue pair broker failed to alloc (result=%d)"
+			 ".", result);
+	}
+	vmci_ctx_release(context);
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_alloc --
+ *
+ *      Allocates a VMCI QueuePair. Only checks validity of input
+ *      arguments. The real work is done in the host or guest
+ *      specific function.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, appropriate error code otherwise.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int vmci_qp_alloc(struct vmci_handle *handle,	// IN/OUT
+		  struct vmci_queue **produceQ,	// OUT
+		  uint64_t produceSize,	// IN
+		  struct vmci_queue **consumeQ,	// OUT
+		  uint64_t consumeSize,	// IN
+		  uint32_t peer,	// IN
+		  uint32_t flags,	// IN
+		  uint32_t privFlags,	// IN
+		  bool guestEndpoint,	// IN
+		  VMCIEventReleaseCB wakeupCB,	// IN
+		  void *clientData)	// IN
+{
+	if (!handle || !produceQ || !consumeQ || (!produceSize && !consumeSize)
+	    || (flags & ~VMCI_QP_ALL_FLAGS))
+		return VMCI_ERROR_INVALID_ARGS;
+
+	if (guestEndpoint)
+		return qp_alloc_guest_work(handle, produceQ,
+					   produceSize, consumeQ,
+					   consumeSize, peer,
+					   flags, privFlags);
+	else
+		return qp_alloc_host_work(handle, produceQ,
+					  produceSize, consumeQ,
+					  consumeSize, peer, flags,
+					  privFlags, wakeupCB,
+					  clientData);
+}
+
+/*
+ *----------------------------------------------------------------------
+ *
+ * qp_detatch_host_work --
+ *
+ *    This function implements the host kernel API for detaching from
+ *    a queue pair.
+ *
+ * Results:
+ *     VMCI_SUCCESS on success and appropriate failure code otherwise.
+ *
+ * Side effects:
+ *     May deallocate memory.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static int qp_detatch_host_work(struct vmci_handle handle)	// IN
+{
+	int result;
+	struct vmci_ctx *context;
+
+	context = vmci_ctx_get(VMCI_HOST_CONTEXT_ID);
+
+	result = vmci_qp_broker_detach(handle, context);
+
+	vmci_ctx_release(context);
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_detatch --
+ *
+ *      Detaches from a VMCI QueuePair. Only checks validity of input argument.
+ *      Real work is done in the host or guest specific function.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory is freed.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_detatch(struct vmci_handle handle,	// IN
+		      bool guestEndpoint)	// IN
+{
+	if (VMCI_HANDLE_INVALID(handle))
+		return VMCI_ERROR_INVALID_ARGS;
+
+	if (guestEndpoint)
+		return qp_detatch_guest_work(handle);
+	else
+		return qp_detatch_host_work(handle);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_list_init --
+ *
+ *      Initializes the list of QueuePairs.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static int qp_list_init(struct qp_list *qpList)	// IN
+{
+	INIT_LIST_HEAD(&qpList->head);
+	sema_init(&qpList->mutex, 1);
+	return VMCI_SUCCESS;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_list_get_head --
+ *
+ *      Returns the entry from the head of the list. Assumes that the list is
+ *      locked.
+ *
+ * Results:
+ *      Pointer to entry.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static struct qp_entry *qp_list_get_head(struct qp_list *qpList)
+{
+	if (!list_empty(&qpList->head)) {
+		struct qp_entry *entry =
+			list_first_entry(&qpList->head, struct qp_entry,
+					 listItem);
+		return entry;
+	}
+
+	return NULL;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_broker_init --
+ *
+ *      Initalizes queue pair broker state.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int __init vmci_qp_broker_init(void)
+{
+	return qp_list_init(&qpBrokerList);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_broker_exit --
+ *
+ *      Destroys the queue pair broker state.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+void vmci_qp_broker_exit(void)
+{
+	struct qp_broker_entry *entry;
+
+	down(&qpBrokerList.mutex);
+
+	while ((entry = (struct qp_broker_entry *)
+		qp_list_get_head(&qpBrokerList))) {
+		qp_list_remove_entry(&qpBrokerList, &entry->qp);
+		kfree(entry);
+	}
+
+	up(&qpBrokerList.mutex);
+	INIT_LIST_HEAD(&(qpBrokerList.head));
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_broker_alloc --
+ *
+ *      Requests that a queue pair be allocated with the VMCI queue
+ *      pair broker. Allocates a queue pair entry if one does not
+ *      exist. Attaches to one if it exists, and retrieves the page
+ *      files backing that QueuePair.  Assumes that the queue pair
+ *      broker lock is held.
+ *
+ * Results:
+ *      Success or failure.
+ *
+ * Side effects:
+ *      Memory may be allocated.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int vmci_qp_broker_alloc(struct vmci_handle handle,	// IN
+			 uint32_t peer,	// IN
+			 uint32_t flags,	// IN
+			 uint32_t privFlags,	// IN
+			 uint64_t produceSize,	// IN
+			 uint64_t consumeSize,	// IN
+			 QueuePairPageStore * pageStore,	// IN/OUT
+			 struct vmci_ctx *context)	// IN: Caller
+{
+	return qp_broker_alloc(handle, peer, flags, privFlags,
+			       produceSize, consumeSize,
+			       pageStore, context, NULL, NULL, NULL, NULL);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_broker_set_page_store --
+ *
+ *      VMX'en with versions lower than VMCI_VERSION_NOVMVM use a separate
+ *      step to add the UVAs of the VMX mapping of the queue pair. This function
+ *      provides backwards compatibility with such VMX'en, and takes care of
+ *      registering the page store for a queue pair previously allocated by the
+ *      VMX during create or attach. This function will move the queue pair state
+ *      to either from VMCIQBP_CREATED_NO_MEM to VMCIQBP_CREATED_MEM or
+ *      VMCIQBP_ATTACHED_NO_MEM to VMCIQBP_ATTACHED_MEM. If moving to the
+ *      attached state with memory, the queue pair is ready to be used by the
+ *      host peer, and an attached event will be generated.
+ *
+ *      Assumes that the queue pair broker lock is held.
+ *
+ *      This function is only used by the hosted platform, since there is no
+ *      issue with backwards compatibility for vmkernel.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, appropriate error code otherwise.
+ *
+ * Side effects:
+ *      Pages may get pinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int vmci_qp_broker_set_page_store(struct vmci_handle handle,	// IN
+				  uint64_t produceUVA,	// IN
+				  uint64_t consumeUVA,	// IN
+				  struct vmci_ctx *context)	// IN: Caller
+{
+	struct qp_broker_entry *entry;
+	int result;
+	const uint32_t contextId = vmci_ctx_get_id(context);
+
+	if (VMCI_HANDLE_INVALID(handle) || !context
+	    || contextId == VMCI_INVALID_ID)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	/*
+	 * We only support guest to host queue pairs, so the VMX must
+	 * supply UVAs for the mapped page files.
+	 */
+
+	if (produceUVA == 0 || consumeUVA == 0)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	down(&qpBrokerList.mutex);
+
+	if (!vmci_ctx_qp_exists(context, handle)) {
+		pr_warn("Context (ID=0x%x) not attached to queue pair "
+			"(handle=0x%x:0x%x).", contextId, handle.context,
+			handle.resource);
+		result = VMCI_ERROR_NOT_FOUND;
+		goto out;
+	}
+
+	entry = (struct qp_broker_entry *)
+		qp_list_find(&qpBrokerList, handle);
+	if (!entry) {
+		result = VMCI_ERROR_NOT_FOUND;
+		goto out;
+	}
+
+	/*
+	 * If I'm the owner then I can set the page store.
+	 *
+	 * Or, if a host created the QueuePair and I'm the attached peer
+	 * then I can set the page store.
+	 */
+
+	if (entry->createId != contextId &&
+	    (entry->createId != VMCI_HOST_CONTEXT_ID ||
+	     entry->attachId != contextId)) {
+		result = VMCI_ERROR_QUEUEPAIR_NOTOWNER;
+		goto out;
+	}
+
+	if (entry->state != VMCIQPB_CREATED_NO_MEM &&
+	    entry->state != VMCIQPB_ATTACHED_NO_MEM) {
+		result = VMCI_ERROR_UNAVAILABLE;
+		goto out;
+	}
+
+	result = VMCIHost_GetUserMemory(produceUVA, consumeUVA,
+					entry->produceQ, entry->consumeQ);
+	if (result < VMCI_SUCCESS)
+		goto out;
+
+	result = VMCIHost_MapQueues(entry->produceQ, entry->consumeQ);
+	if (result < VMCI_SUCCESS) {
+		VMCIHost_ReleaseUserMemory(entry->produceQ, entry->consumeQ);
+		goto out;
+	}
+
+	if (entry->state == VMCIQPB_CREATED_NO_MEM) {
+		entry->state = VMCIQPB_CREATED_MEM;
+	} else {
+		ASSERT(entry->state == VMCIQPB_ATTACHED_NO_MEM);
+		entry->state = VMCIQPB_ATTACHED_MEM;
+	}
+	entry->vmciPageFiles = true;
+
+	if (entry->state == VMCIQPB_ATTACHED_MEM) {
+		result =
+			qp_notify_peer(true, handle, contextId,
+				       entry->createId);
+		if (result < VMCI_SUCCESS) {
+			pr_warn("Failed to notify peer (ID=0x%x) of "
+				"attach to queue pair (handle=0x%x:0x%x).",
+				entry->createId, entry->qp.handle.context,
+				entry->qp.handle.resource);
+		}
+	}
+
+	result = VMCI_SUCCESS;
+out:
+	up(&qpBrokerList.mutex);
+	return result;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * qp_reset_saved_headers --
+ *
+ *      Resets saved queue headers for the given QP broker
+ *      entry. Should be used when guest memory becomes available
+ *      again, or the guest detaches.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+static void qp_reset_saved_headers(struct qp_broker_entry *entry)	// IN
+{
+	entry->produceQ->savedHeader = NULL;
+	entry->consumeQ->savedHeader = NULL;
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ *
+ * vmci_qp_broker_detach --
+ *
+ *      The main entry point for detaching from a queue pair registered with the
+ *      queue pair broker. If more than one endpoint is attached to the queue
+ *      pair, the first endpoint will mainly decrement a reference count and
+ *      generate a notification to its peer. The last endpoint will clean up
+ *      the queue pair state registered with the broker.
+ *
+ *      When a guest endpoint detaches, it will unmap and unregister the guest
+ *      memory backing the queue pair. If the host is still attached, it will
+ *      no longer be able to access the queue pair content.
+ *
+ *      If the queue pair is already in a state where there is no memory
+ *      registered for the queue pair (any *_NO_MEM state), it will transition to
+ *      the VMCIQPB_SHUTDOWN_NO_MEM state. This will also happen, if a guest
+ *      endpoint is the first of two endpoints to detach. If the host endpoint is
+ *      the first out of two to detach, the queue pair will move to the
+ *      VMCIQPB_SHUTDOWN_MEM state.
+ *
+ * Results:
+ *      VMCI_SUCCESS on success, appropriate error code otherwise.
+ *
+ * Side effects:
+ *      Memory may be freed, and pages may be unpinned.
+ *
+ *-----------------------------------------------------------------------------
+ */
+
+int vmci_qp_broker_detach(struct vmci_handle handle,	// IN
+			  struct vmci_ctx *context)	// IN
+{
+	struct qp_broker_entry *entry;
+	const uint32_t contextId = vmci_ctx_get_id(context);
+	uint32_t peerId;
+	bool isLocal = false;
+	int result;
+
+	if (VMCI_HANDLE_INVALID(handle) || !context
+	    || contextId == VMCI_INVALID_ID) {
+		return VMCI_ERROR_INVALID_ARGS;
+	}
+
+	down(&qpBrokerList.mutex);
+
+	if (!vmci_ctx_qp_exists(context, handle)) {
+		pr_devel("Context (ID=0x%x) not attached to queue pair "
+			 "(handle=0x%x:0x%x).", contextId, handle.context,
+			 handle.resource);
+		result = VMCI_ERROR_NOT_FOUND;
+		goto out;
+	}
+
+	entry = (struct qp_broker_entry *)
+		qp_list_find(&qpBrokerList, handle);
+	if (!entry) {
+		pr_devel("Context (ID=0x%x) reports being attached to "
+			 "queue pair(handle=0x%x:0x%x) that isn't present in "
+			 "broker.", contextId, handle.context,
+			 handle.resource);
+		result = VMCI_ERROR_NOT_FOUND;
+		goto out;
+	}
+
+	if (contextId != entry->createId && contextId != entry->attachId) {
+		result = VMCI_ERROR_QUEUEPAIR_NOTATTACHED;
+		goto out;
+	}
+
+	if (contextId == entry->createId) {
+		peerId = entry->attachId;
+		entry->createId = VMCI_INVALID_ID;
+	} else {
+		peerId = entry->createId;
+		entry->attachId = VMCI_INVALID_ID;
+	}
+	entry->qp.refCount--;
+
+	isLocal = entry->qp.flags & VMCI_QPFLAG_LOCAL;
+
+	if (contextId != VMCI_HOST_CONTEXT_ID) {
+		int result;
+		bool headersMapped;
+
+		ASSERT(!isLocal);
+
+		/*
+		 * Pre NOVMVM vmx'en may detach from a queue pair before setting the page
+		 * store, and in that case there is no user memory to detach from. Also,
+		 * more recent VMX'en may detach from a queue pair in the quiesced state.
+		 */
+
+		VMCI_AcquireQueueMutex(entry->produceQ);
+		headersMapped = entry->produceQ->qHeader
+			|| entry->consumeQ->qHeader;
+		if (QPBROKERSTATE_HAS_MEM(entry)) {
+			result =
+				VMCIHost_UnmapQueues
[… more lines in the raw message]

Lines of this file are not shown. View the raw message.

drivers/misc/vmw_vmci/vmci_queue_pair.h new file +258 -0

258 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
1.7.0.4

Part of the diff is not shown here. View the raw message.

#22 lore raw

RFC 9/11 Apply VMCI resource code

In reply to Andrew Stiegmann (stieg)

Tracks all used resources within the vmci code.

---
 drivers/misc/vmw_vmci/vmci_resource.c |  320 +++++++++++++++++++++++++++++++++
 drivers/misc/vmw_vmci/vmci_resource.h |   61 +++++++
 2 files changed, 381 insertions(+), 0 deletions(-)
 create mode 100644 drivers/misc/vmw_vmci/vmci_resource.c
 create mode 100644 drivers/misc/vmw_vmci/vmci_resource.h
drivers/misc/vmw_vmci/vmci_resource.c new file +320 -0
new file mode 100644
index 0000000..240654d
@@ -0,0 +1,320 @@
+/*
+ * VMware VMCI Driver
+ *
+ * Copyright (C) 2012 VMware, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation version 2 and no later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ */
+
+#include <linux/vmw_vmci_defs.h>
+
+#include "vmci_common_int.h"
+#include "vmci_hash_table.h"
+#include "vmci_resource.h"
+#include "vmci_driver.h"
+
+/* 0 through VMCI_RESERVED_RESOURCE_ID_MAX are reserved. */
+static uint32_t resourceID = VMCI_RESERVED_RESOURCE_ID_MAX + 1;
+static spinlock_t resourceIdLock;
+static struct vmci_hash_table *resourceTable = NULL;
+
+/* Public Resource Access Control API. */
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_init --
+ *
+ *      Initializes the VMCI Resource Access Control API. Creates a hashtable
+ *      to hold all resources, and registers vectors and callbacks for
+ *      hypercalls.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+int __init vmci_resource_init(void)
+{
+	spin_lock_init(&resourceIdLock);
+
+	resourceTable = vmci_hash_create(128);
+	if (resourceTable == NULL) {
+		pr_warn("Failed creating a resource hash table.");
+		return VMCI_ERROR_NO_MEM;
+	}
+
+	return VMCI_SUCCESS;
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_exit --
+ *
+ *      Cleans up resources.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+void vmci_resource_exit(void)
+{
+	if (resourceTable)
+		vmci_hash_destroy(resourceTable);
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ *  vmci_resource_get_id --
+ *
+ *     Return resource ID. The first VMCI_RESERVED_RESOURCE_ID_MAX are
+ *     reserved so we start from its value + 1.
+ *
+ *  Result:
+ *     VMCI resource id on success, VMCI_INVALID_ID on failure.
+ *
+ *  Side effects:
+ *     None.
+ *
+ *
+ *------------------------------------------------------------------------------
+ */
+
+uint32_t vmci_resource_get_id(uint32_t contextID)
+{
+	uint32_t oldRID = resourceID;
+	uint32_t currentRID;
+	bool foundRID = false;
+
+	/*
+	 * Generate a unique resource ID.  Keep on trying until we wrap around
+	 * in the RID space.
+	 */
+	ASSERT(oldRID > VMCI_RESERVED_RESOURCE_ID_MAX);
+
+	do {
+		struct vmci_handle handle;
+
+		spin_lock(&resourceIdLock);
+		currentRID = resourceID;
+		handle = vmci_make_handle(contextID, currentRID);
+		resourceID++;
+		if (unlikely(resourceID == VMCI_INVALID_ID)) {
+			/* Skip the reserved rids. */
+
+			resourceID = VMCI_RESERVED_RESOURCE_ID_MAX + 1;
+		}
+		spin_unlock(&resourceIdLock);
+		foundRID = !vmci_hash_exists(resourceTable, handle);
+	} while (!foundRID && resourceID != oldRID);
+
+	return (unlikely(!foundRID)) ? VMCI_INVALID_ID : currentRID;
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_add --
+ *
+ * Results:
+ *      VMCI_SUCCESS if successful, error code if not.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+int vmci_resource_add(struct vmci_resource *resource,	// IN
+		  enum vmci_resource_type resourceType,	// IN
+		  struct vmci_handle resourceHandle,	// IN
+		  VMCIResourceFreeCB containerFreeCB,	// IN
+		  void *containerObject)	// IN
+{
+	int result;
+
+	ASSERT(resource);
+
+	if (VMCI_HANDLE_EQUAL(resourceHandle, VMCI_INVALID_HANDLE)) {
+		pr_devel("Invalid argument resource (handle=0x%x:0x%x)",
+			 resourceHandle.context, resourceHandle.resource);
+		return VMCI_ERROR_INVALID_ARGS;
+	}
+
+	vmci_hash_init_entry(&resource->hashEntry, resourceHandle);
+	resource->type = resourceType;
+	resource->containerFreeCB = containerFreeCB;
+	resource->containerObject = containerObject;
+
+	/* Add resource to hashtable. */
+	result = vmci_hash_add(resourceTable, &resource->hashEntry);
+	if (result != VMCI_SUCCESS) {
+		pr_devel("Failed to add entry to hash table "
+			 "(result=%d).", result);
+		return result;
+	}
+
+	return result;
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_remove --
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+void vmci_resource_remove(struct vmci_handle resourceHandle,	// IN:
+		      enum vmci_resource_type resourceType)	// IN:
+{
+	struct vmci_resource *resource =
+		vmci_resource_get(resourceHandle, resourceType);
+
+	if (resource == NULL)
+		return;
+
+	/* Remove resource from hashtable. */
+	vmci_hash_remove(resourceTable, &resource->hashEntry);
+
+	vmci_resource_release(resource);
+	/* resource could be freed by now. */
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_get --
+ *
+ * Results:
+ *      Resource is successful. Otherwise NULL.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+struct vmci_resource *vmci_resource_get(struct vmci_handle resourceHandle,	// IN
+				    enum vmci_resource_type resourceType)	// IN
+{
+	struct vmci_resource *resource;
+	struct vmci_hash_entry *entry =
+		vmci_hash_get(resourceTable, resourceHandle);
+
+	if (entry == NULL)
+		return NULL;
+
+	resource = container_of(entry, struct vmci_resource, hashEntry);
+	if (resourceType == VMCI_RESOURCE_TYPE_ANY ||
+	    resource->type == resourceType)
+		return resource;
+
+	vmci_hash_release(resourceTable, entry);
+	return NULL;
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_hold --
+ *
+ *      Hold the given resource.  This will hold the hashtable entry.  This
+ *      is like doing a Get() but without having to lookup the resource by
+ *      handle.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+void vmci_resource_hold(struct vmci_resource *resource)
+{
+	ASSERT(resource);
+	vmci_hash_hold(resourceTable, &resource->hashEntry);
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_release --
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      resource's containerFreeCB will get called if last reference.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+int vmci_resource_release(struct vmci_resource *resource)
+{
+	int result;
+
+	ASSERT(resource);
+
+	result = vmci_hash_release(resourceTable, &resource->hashEntry);
+	if (result == VMCI_SUCCESS_ENTRY_DEAD && resource->containerFreeCB)
+		resource->containerFreeCB(resource->containerObject);
+
+	/*
+	 * We propagate the information back to caller in case it wants to know
+	 * whether entry was freed.
+	 */
+	return result;
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_handle --
+ *
+ *      Get the handle for the given resource.
+ *
+ * Results:
+ *      The resource's associated handle.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+struct vmci_handle vmci_resource_handle(struct vmci_resource *resource)
+{
+	ASSERT(resource);
+	return resource->hashEntry.handle;
+}
drivers/misc/vmw_vmci/vmci_resource.h new file +61 -0

61 lines not on this page · raw message

Signature · 1 line
1.7.0.4
#23 lore raw

RFC 9/11 Apply VMCI resource code

In reply to Andrew Stiegmann (stieg)

Tracks all used resources within the vmci code.

---
 drivers/misc/vmw_vmci/vmci_resource.c |  320 +++++++++++++++++++++++++++++++++
 drivers/misc/vmw_vmci/vmci_resource.h |   61 +++++++
 2 files changed, 381 insertions(+), 0 deletions(-)
 create mode 100644 drivers/misc/vmw_vmci/vmci_resource.c
 create mode 100644 drivers/misc/vmw_vmci/vmci_resource.h
drivers/misc/vmw_vmci/vmci_resource.c new file +320 -0
new file mode 100644
index 0000000..240654d
@@ -0,0 +1,320 @@
+/*
+ * VMware VMCI Driver
+ *
+ * Copyright (C) 2012 VMware, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation version 2 and no later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ */
+
+#include <linux/vmw_vmci_defs.h>
+
+#include "vmci_common_int.h"
+#include "vmci_hash_table.h"
+#include "vmci_resource.h"
+#include "vmci_driver.h"
+
+/* 0 through VMCI_RESERVED_RESOURCE_ID_MAX are reserved. */
+static uint32_t resourceID = VMCI_RESERVED_RESOURCE_ID_MAX + 1;
+static spinlock_t resourceIdLock;
+static struct vmci_hash_table *resourceTable = NULL;
+
+/* Public Resource Access Control API. */
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_init --
+ *
+ *      Initializes the VMCI Resource Access Control API. Creates a hashtable
+ *      to hold all resources, and registers vectors and callbacks for
+ *      hypercalls.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+int __init vmci_resource_init(void)
+{
+	spin_lock_init(&resourceIdLock);
+
+	resourceTable = vmci_hash_create(128);
+	if (resourceTable == NULL) {
+		pr_warn("Failed creating a resource hash table.");
+		return VMCI_ERROR_NO_MEM;
+	}
+
+	return VMCI_SUCCESS;
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_exit --
+ *
+ *      Cleans up resources.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+void vmci_resource_exit(void)
+{
+	if (resourceTable)
+		vmci_hash_destroy(resourceTable);
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ *  vmci_resource_get_id --
+ *
+ *     Return resource ID. The first VMCI_RESERVED_RESOURCE_ID_MAX are
+ *     reserved so we start from its value + 1.
+ *
+ *  Result:
+ *     VMCI resource id on success, VMCI_INVALID_ID on failure.
+ *
+ *  Side effects:
+ *     None.
+ *
+ *
+ *------------------------------------------------------------------------------
+ */
+
+uint32_t vmci_resource_get_id(uint32_t contextID)
+{
+	uint32_t oldRID = resourceID;
+	uint32_t currentRID;
+	bool foundRID = false;
+
+	/*
+	 * Generate a unique resource ID.  Keep on trying until we wrap around
+	 * in the RID space.
+	 */
+	ASSERT(oldRID > VMCI_RESERVED_RESOURCE_ID_MAX);
+
+	do {
+		struct vmci_handle handle;
+
+		spin_lock(&resourceIdLock);
+		currentRID = resourceID;
+		handle = vmci_make_handle(contextID, currentRID);
+		resourceID++;
+		if (unlikely(resourceID == VMCI_INVALID_ID)) {
+			/* Skip the reserved rids. */
+
+			resourceID = VMCI_RESERVED_RESOURCE_ID_MAX + 1;
+		}
+		spin_unlock(&resourceIdLock);
+		foundRID = !vmci_hash_exists(resourceTable, handle);
+	} while (!foundRID && resourceID != oldRID);
+
+	return (unlikely(!foundRID)) ? VMCI_INVALID_ID : currentRID;
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_add --
+ *
+ * Results:
+ *      VMCI_SUCCESS if successful, error code if not.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+int vmci_resource_add(struct vmci_resource *resource,	// IN
+		  enum vmci_resource_type resourceType,	// IN
+		  struct vmci_handle resourceHandle,	// IN
+		  VMCIResourceFreeCB containerFreeCB,	// IN
+		  void *containerObject)	// IN
+{
+	int result;
+
+	ASSERT(resource);
+
+	if (VMCI_HANDLE_EQUAL(resourceHandle, VMCI_INVALID_HANDLE)) {
+		pr_devel("Invalid argument resource (handle=0x%x:0x%x)",
+			 resourceHandle.context, resourceHandle.resource);
+		return VMCI_ERROR_INVALID_ARGS;
+	}
+
+	vmci_hash_init_entry(&resource->hashEntry, resourceHandle);
+	resource->type = resourceType;
+	resource->containerFreeCB = containerFreeCB;
+	resource->containerObject = containerObject;
+
+	/* Add resource to hashtable. */
+	result = vmci_hash_add(resourceTable, &resource->hashEntry);
+	if (result != VMCI_SUCCESS) {
+		pr_devel("Failed to add entry to hash table "
+			 "(result=%d).", result);
+		return result;
+	}
+
+	return result;
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_remove --
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+void vmci_resource_remove(struct vmci_handle resourceHandle,	// IN:
+		      enum vmci_resource_type resourceType)	// IN:
+{
+	struct vmci_resource *resource =
+		vmci_resource_get(resourceHandle, resourceType);
+
+	if (resource == NULL)
+		return;
+
+	/* Remove resource from hashtable. */
+	vmci_hash_remove(resourceTable, &resource->hashEntry);
+
+	vmci_resource_release(resource);
+	/* resource could be freed by now. */
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_get --
+ *
+ * Results:
+ *      Resource is successful. Otherwise NULL.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+struct vmci_resource *vmci_resource_get(struct vmci_handle resourceHandle,	// IN
+				    enum vmci_resource_type resourceType)	// IN
+{
+	struct vmci_resource *resource;
+	struct vmci_hash_entry *entry =
+		vmci_hash_get(resourceTable, resourceHandle);
+
+	if (entry == NULL)
+		return NULL;
+
+	resource = container_of(entry, struct vmci_resource, hashEntry);
+	if (resourceType == VMCI_RESOURCE_TYPE_ANY ||
+	    resource->type == resourceType)
+		return resource;
+
+	vmci_hash_release(resourceTable, entry);
+	return NULL;
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_hold --
+ *
+ *      Hold the given resource.  This will hold the hashtable entry.  This
+ *      is like doing a Get() but without having to lookup the resource by
+ *      handle.
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+void vmci_resource_hold(struct vmci_resource *resource)
+{
+	ASSERT(resource);
+	vmci_hash_hold(resourceTable, &resource->hashEntry);
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_release --
+ *
+ * Results:
+ *      None.
+ *
+ * Side effects:
+ *      resource's containerFreeCB will get called if last reference.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+int vmci_resource_release(struct vmci_resource *resource)
+{
+	int result;
+
+	ASSERT(resource);
+
+	result = vmci_hash_release(resourceTable, &resource->hashEntry);
+	if (result == VMCI_SUCCESS_ENTRY_DEAD && resource->containerFreeCB)
+		resource->containerFreeCB(resource->containerObject);
+
+	/*
+	 * We propagate the information back to caller in case it wants to know
+	 * whether entry was freed.
+	 */
+	return result;
+}
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ * vmci_resource_handle --
+ *
+ *      Get the handle for the given resource.
+ *
+ * Results:
+ *      The resource's associated handle.
+ *
+ * Side effects:
+ *      None.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+struct vmci_handle vmci_resource_handle(struct vmci_resource *resource)
+{
+	ASSERT(resource);
+	return resource->hashEntry.handle;
+}
drivers/misc/vmw_vmci/vmci_resource.h new file +61 -0

61 lines not on this page · raw message

Signature · 1 line
1.7.0.4
#24 lore raw

RFC 10/11 Apply vmci routing code

In reply to Andrew Stiegmann (stieg)

This code is responsible for routing between various hosts/guests as well as routing in nested scenarios.

---
 drivers/misc/vmw_vmci/vmci_route.c |  234 ++++++++++++++++++++++++++++++++++++
 drivers/misc/vmw_vmci/vmci_route.h |   34 +++++
 2 files changed, 268 insertions(+), 0 deletions(-)
 create mode 100644 drivers/misc/vmw_vmci/vmci_route.c
 create mode 100644 drivers/misc/vmw_vmci/vmci_route.h
drivers/misc/vmw_vmci/vmci_route.c new file +234 -0
new file mode 100644
index 0000000..4c9183c
@@ -0,0 +1,234 @@
+/*
+ * VMware VMCI Driver
+ *
+ * Copyright (C) 2012 VMware, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation version 2 and no later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ */
+
+#include <linux/vmw_vmci_api.h>
+#include <linux/vmw_vmci_defs.h>
+
+#include "vmci_common_int.h"
+#include "vmci_context.h"
+#include "vmci_driver.h"
+#include "vmci_route.h"
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ *  vmci_route --
+ *
+ *     Make a routing decision for the given source and destination handles.
+ *     This will try to determine the route using the handles and the available
+ *     devices.
+ *
+ *  Result:
+ *     A VMCIRoute value.
+ *
+ *  Side effects:
+ *     Sets the source context if it is invalid.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+int vmci_route(struct vmci_handle *src,	// IN/OUT
+	       const struct vmci_handle *dst,	// IN
+	       bool fromGuest,	// IN
+	       enum vmci_route *route)	// OUT
+{
+	bool hasHostDevice = vmci_host_code_active();
+	bool hasGuestDevice = vmci_guest_code_active();
+
+	ASSERT(src);
+	ASSERT(dst);
+	ASSERT(route);
+
+	*route = VMCI_ROUTE_NONE;
+
+	/*
+	 * "fromGuest" is only ever set to true by IOCTL_VMCI_DATAGRAM_SEND (or by
+	 * the vmkernel equivalent), which comes from the VMX, so we know it is
+	 * coming from a guest.
+	 *
+	 * To avoid inconsistencies, test these once.  We will test them again
+	 * when we do the actual send to ensure that we do not touch a non-existent
+	 * device.
+	 */
+
+	/* Must have a valid destination context. */
+	if (VMCI_INVALID_ID == dst->context)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	/* Anywhere to hypervisor. */
+	if (VMCI_HYPERVISOR_CONTEXT_ID == dst->context) {
+
+		/*
+		 * If this message already came from a guest then we cannot send it
+		 * to the hypervisor.  It must come from a local client.
+		 */
+		if (fromGuest)
+			return VMCI_ERROR_DST_UNREACHABLE;
+
+		/* We must be acting as a guest in order to send to the hypervisor. */
+		if (!hasGuestDevice)
+			return VMCI_ERROR_DEVICE_NOT_FOUND;
+
+		/* And we cannot send if the source is the host context. */
+		if (VMCI_HOST_CONTEXT_ID == src->context)
+			return VMCI_ERROR_INVALID_ARGS;
+
+		/*
+		 * If the client passed the ANON source handle then respect it (both
+		 * context and resource are invalid).  However, if they passed only
+		 * an invalid context, then they probably mean ANY, in which case we
+		 * should set the real context here before passing it down.
+		 */
+		if (VMCI_INVALID_ID == src->context && VMCI_INVALID_ID != src->resource)
+			src->context = VMCI_GetContextID();
+
+		/* Send from local client down to the hypervisor. */
+		*route = VMCI_ROUTE_AS_GUEST;
+		return VMCI_SUCCESS;
+	}
+
+	/* Anywhere to local client on host. */
+	if (VMCI_HOST_CONTEXT_ID == dst->context) {
+		/*
+		 * If it is not from a guest but we are acting as a guest, then we need
+		 * to send it down to the host.  Note that if we are also acting as a
+		 * host then this will prevent us from sending from local client to
+		 * local client, but we accept that restriction as a way to remove
+		 * any ambiguity from the host context.
+		 */
+		if (src->context == VMCI_HYPERVISOR_CONTEXT_ID) {
+			/*
+			 * If the hypervisor is the source, this is host local
+			 * communication. The hypervisor may send vmci event
+			 * datagrams to the host itself, but it will never send
+			 * datagrams to an "outer host" through the guest device.
+			 */
+
+			if (hasHostDevice) {
+				*route = VMCI_ROUTE_AS_HOST;
+				return VMCI_SUCCESS;
+			} else {
+				return VMCI_ERROR_DEVICE_NOT_FOUND;
+			}
+		}
+
+		if (!fromGuest && hasGuestDevice) {
+			/* If no source context then use the current. */
+			if (VMCI_INVALID_ID == src->context)
+				src->context = VMCI_GetContextID();
+
+			/* Send it from local client down to the host. */
+			*route = VMCI_ROUTE_AS_GUEST;
+			return VMCI_SUCCESS;
+		}
+
+		/*
+		 * Otherwise we already received it from a guest and it is destined
+		 * for a local client on this host, or it is from another local client
+		 * on this host.  We must be acting as a host to service it.
+		 */
+		if (!hasHostDevice)
+			return VMCI_ERROR_DEVICE_NOT_FOUND;
+
+		if (VMCI_INVALID_ID == src->context) {
+			/*
+			 * If it came from a guest then it must have a valid context.
+			 * Otherwise we can use the host context.
+			 */
+
+			if (fromGuest)
+				return VMCI_ERROR_INVALID_ARGS;
+
+			src->context = VMCI_HOST_CONTEXT_ID;
+		}
+
+		/* Route to local client. */
+		*route = VMCI_ROUTE_AS_HOST;
+		return VMCI_SUCCESS;
+	}
+
+	/* If we are acting as a host then this might be destined for a guest. */
+	if (hasHostDevice) {
+		/* It will have a context if it is meant for a guest. */
+		if (vmci_ctx_exists(dst->context)) {
+			if (VMCI_INVALID_ID == src->context) {
+				/*
+				 * If it came from a guest then it must have a valid context.
+				 * Otherwise we can use the host context.
+				 */
+
+				if (fromGuest)
+					return VMCI_ERROR_INVALID_ARGS;
+
+				src->context = VMCI_HOST_CONTEXT_ID;
+			} else if (VMCI_CONTEXT_IS_VM(src->context) &&
+				   src->context != dst->context) {
+				/*
+				 * VM to VM communication is not allowed. Since we catch
+				 * all communication destined for the host above, this
+				 * must be destined for a VM since there is a valid
+				 * context.
+				 */
+
+				ASSERT(VMCI_CONTEXT_IS_VM(dst->context));
+
+				return VMCI_ERROR_DST_UNREACHABLE;
+			}
+
+			/* Pass it up to the guest. */
+			*route = VMCI_ROUTE_AS_HOST;
+			return VMCI_SUCCESS;
+		} else if (!hasGuestDevice) {
+			/*
+			 * The host is attempting to reach a CID without an active context, and
+			 * we can't send it down, since we have no guest device.
+			 */
+
+			return VMCI_ERROR_DST_UNREACHABLE;
+		}
+	}
+
+	/*
+	 * We must be a guest trying to send to another guest, which means
+	 * we need to send it down to the host. We do not filter out VM to
+	 * VM communication here, since we want to be able to use the guest
+	 * driver on older versions that do support VM to VM communication.
+	 */
+	if (!hasGuestDevice) {
+		/*
+		 * Ending up here means we have neither guest nor host device. That
+		 * shouldn't happen, since any VMCI client in the kernel should have done
+		 * a successful VMCI_DeviceGet.
+		 */
+
+		ASSERT(false);
+		return VMCI_ERROR_DEVICE_NOT_FOUND;
+	}
+
+	/* If no source context then use the current context. */
+	if (VMCI_INVALID_ID == src->context)
+		src->context = VMCI_GetContextID();
+
+	/*
+	 * Send it from local client down to the host, which will route it to
+	 * the other guest for us.
+	 */
+	*route = VMCI_ROUTE_AS_GUEST;
+	return VMCI_SUCCESS;
+}
drivers/misc/vmw_vmci/vmci_route.h new file +34 -0
new file mode 100644
index 0000000..c53f86e
@@ -0,0 +1,34 @@
+/*
+ * VMware VMCI Driver
+ *
+ * Copyright (C) 2012 VMware, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation version 2 and no later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ */
+
+#ifndef _VMCI_ROUTE_H_
+#define _VMCI_ROUTE_H_
+
+#include <linux/vmw_vmci_defs.h>
+
+enum vmci_route {
+	VMCI_ROUTE_NONE,
+	VMCI_ROUTE_AS_HOST,
+	VMCI_ROUTE_AS_GUEST,
+};
+
+int vmci_route(struct vmci_handle *src, const struct vmci_handle *dst,
+	       bool fromGuest, enum vmci_route *route);
+
+#endif				// _VMCI_ROUTE_H_
Signature · 1 line
1.7.0.4
#25 lore raw

RFC 10/11 Apply vmci routing code

In reply to Andrew Stiegmann (stieg)

This code is responsible for routing between various hosts/guests as well as routing in nested scenarios.

---
 drivers/misc/vmw_vmci/vmci_route.c |  234 ++++++++++++++++++++++++++++++++++++
 drivers/misc/vmw_vmci/vmci_route.h |   34 +++++
 2 files changed, 268 insertions(+), 0 deletions(-)
 create mode 100644 drivers/misc/vmw_vmci/vmci_route.c
 create mode 100644 drivers/misc/vmw_vmci/vmci_route.h
drivers/misc/vmw_vmci/vmci_route.c new file +234 -0
new file mode 100644
index 0000000..4c9183c
@@ -0,0 +1,234 @@
+/*
+ * VMware VMCI Driver
+ *
+ * Copyright (C) 2012 VMware, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation version 2 and no later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ */
+
+#include <linux/vmw_vmci_api.h>
+#include <linux/vmw_vmci_defs.h>
+
+#include "vmci_common_int.h"
+#include "vmci_context.h"
+#include "vmci_driver.h"
+#include "vmci_route.h"
+
+/*
+ *------------------------------------------------------------------------------
+ *
+ *  vmci_route --
+ *
+ *     Make a routing decision for the given source and destination handles.
+ *     This will try to determine the route using the handles and the available
+ *     devices.
+ *
+ *  Result:
+ *     A VMCIRoute value.
+ *
+ *  Side effects:
+ *     Sets the source context if it is invalid.
+ *
+ *------------------------------------------------------------------------------
+ */
+
+int vmci_route(struct vmci_handle *src,	// IN/OUT
+	       const struct vmci_handle *dst,	// IN
+	       bool fromGuest,	// IN
+	       enum vmci_route *route)	// OUT
+{
+	bool hasHostDevice = vmci_host_code_active();
+	bool hasGuestDevice = vmci_guest_code_active();
+
+	ASSERT(src);
+	ASSERT(dst);
+	ASSERT(route);
+
+	*route = VMCI_ROUTE_NONE;
+
+	/*
+	 * "fromGuest" is only ever set to true by IOCTL_VMCI_DATAGRAM_SEND (or by
+	 * the vmkernel equivalent), which comes from the VMX, so we know it is
+	 * coming from a guest.
+	 *
+	 * To avoid inconsistencies, test these once.  We will test them again
+	 * when we do the actual send to ensure that we do not touch a non-existent
+	 * device.
+	 */
+
+	/* Must have a valid destination context. */
+	if (VMCI_INVALID_ID == dst->context)
+		return VMCI_ERROR_INVALID_ARGS;
+
+	/* Anywhere to hypervisor. */
+	if (VMCI_HYPERVISOR_CONTEXT_ID == dst->context) {
+
+		/*
+		 * If this message already came from a guest then we cannot send it
+		 * to the hypervisor.  It must come from a local client.
+		 */
+		if (fromGuest)
+			return VMCI_ERROR_DST_UNREACHABLE;
+
+		/* We must be acting as a guest in order to send to the hypervisor. */
+		if (!hasGuestDevice)
+			return VMCI_ERROR_DEVICE_NOT_FOUND;
+
+		/* And we cannot send if the source is the host context. */
+		if (VMCI_HOST_CONTEXT_ID == src->context)
+			return VMCI_ERROR_INVALID_ARGS;
+
+		/*
+		 * If the client passed the ANON source handle then respect it (both
+		 * context and resource are invalid).  However, if they passed only
+		 * an invalid context, then they probably mean ANY, in which case we
+		 * should set the real context here before passing it down.
+		 */
+		if (VMCI_INVALID_ID == src->context && VMCI_INVALID_ID != src->resource)
+			src->context = VMCI_GetContextID();
+
+		/* Send from local client down to the hypervisor. */
+		*route = VMCI_ROUTE_AS_GUEST;
+		return VMCI_SUCCESS;
+	}
+
+	/* Anywhere to local client on host. */
+	if (VMCI_HOST_CONTEXT_ID == dst->context) {
+		/*
+		 * If it is not from a guest but we are acting as a guest, then we need
+		 * to send it down to the host.  Note that if we are also acting as a
+		 * host then this will prevent us from sending from local client to
+		 * local client, but we accept that restriction as a way to remove
+		 * any ambiguity from the host context.
+		 */
+		if (src->context == VMCI_HYPERVISOR_CONTEXT_ID) {
+			/*
+			 * If the hypervisor is the source, this is host local
+			 * communication. The hypervisor may send vmci event
+			 * datagrams to the host itself, but it will never send
+			 * datagrams to an "outer host" through the guest device.
+			 */
+
+			if (hasHostDevice) {
+				*route = VMCI_ROUTE_AS_HOST;
+				return VMCI_SUCCESS;
+			} else {
+				return VMCI_ERROR_DEVICE_NOT_FOUND;
+			}
+		}
+
+		if (!fromGuest && hasGuestDevice) {
+			/* If no source context then use the current. */
+			if (VMCI_INVALID_ID == src->context)
+				src->context = VMCI_GetContextID();
+
+			/* Send it from local client down to the host. */
+			*route = VMCI_ROUTE_AS_GUEST;
+			return VMCI_SUCCESS;
+		}
+
+		/*
+		 * Otherwise we already received it from a guest and it is destined
+		 * for a local client on this host, or it is from another local client
+		 * on this host.  We must be acting as a host to service it.
+		 */
+		if (!hasHostDevice)
+			return VMCI_ERROR_DEVICE_NOT_FOUND;
+
+		if (VMCI_INVALID_ID == src->context) {
+			/*
+			 * If it came from a guest then it must have a valid context.
+			 * Otherwise we can use the host context.
+			 */
+
+			if (fromGuest)
+				return VMCI_ERROR_INVALID_ARGS;
+
+			src->context = VMCI_HOST_CONTEXT_ID;
+		}
+
+		/* Route to local client. */
+		*route = VMCI_ROUTE_AS_HOST;
+		return VMCI_SUCCESS;
+	}
+
+	/* If we are acting as a host then this might be destined for a guest. */
+	if (hasHostDevice) {
+		/* It will have a context if it is meant for a guest. */
+		if (vmci_ctx_exists(dst->context)) {
+			if (VMCI_INVALID_ID == src->context) {
+				/*
+				 * If it came from a guest then it must have a valid context.
+				 * Otherwise we can use the host context.
+				 */
+
+				if (fromGuest)
+					return VMCI_ERROR_INVALID_ARGS;
+
+				src->context = VMCI_HOST_CONTEXT_ID;
+			} else if (VMCI_CONTEXT_IS_VM(src->context) &&
+				   src->context != dst->context) {
+				/*
+				 * VM to VM communication is not allowed. Since we catch
+				 * all communication destined for the host above, this
+				 * must be destined for a VM since there is a valid
+				 * context.
+				 */
+
+				ASSERT(VMCI_CONTEXT_IS_VM(dst->context));
+
+				return VMCI_ERROR_DST_UNREACHABLE;
+			}
+
+			/* Pass it up to the guest. */
+			*route = VMCI_ROUTE_AS_HOST;
+			return VMCI_SUCCESS;
+		} else if (!hasGuestDevice) {
+			/*
+			 * The host is attempting to reach a CID without an active context, and
+			 * we can't send it down, since we have no guest device.
+			 */
+
+			return VMCI_ERROR_DST_UNREACHABLE;
+		}
+	}
+
+	/*
+	 * We must be a guest trying to send to another guest, which means
+	 * we need to send it down to the host. We do not filter out VM to
+	 * VM communication here, since we want to be able to use the guest
+	 * driver on older versions that do support VM to VM communication.
+	 */
+	if (!hasGuestDevice) {
+		/*
+		 * Ending up here means we have neither guest nor host device. That
+		 * shouldn't happen, since any VMCI client in the kernel should have done
+		 * a successful VMCI_DeviceGet.
+		 */
+
+		ASSERT(false);
+		return VMCI_ERROR_DEVICE_NOT_FOUND;
+	}
+
+	/* If no source context then use the current context. */
+	if (VMCI_INVALID_ID == src->context)
+		src->context = VMCI_GetContextID();
+
+	/*
+	 * Send it from local client down to the host, which will route it to
+	 * the other guest for us.
+	 */
+	*route = VMCI_ROUTE_AS_GUEST;
+	return VMCI_SUCCESS;
+}
drivers/misc/vmw_vmci/vmci_route.h new file +34 -0
new file mode 100644
index 0000000..c53f86e
@@ -0,0 +1,34 @@
+/*
+ * VMware VMCI Driver
+ *
+ * Copyright (C) 2012 VMware, Inc. All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation version 2 and no later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ */
+
+#ifndef _VMCI_ROUTE_H_
+#define _VMCI_ROUTE_H_
+
+#include <linux/vmw_vmci_defs.h>
+
+enum vmci_route {
+	VMCI_ROUTE_NONE,
+	VMCI_ROUTE_AS_HOST,
+	VMCI_ROUTE_AS_GUEST,
+};
+
+int vmci_route(struct vmci_handle *src, const struct vmci_handle *dst,
+	       bool fromGuest, enum vmci_route *route);
+
+#endif				// _VMCI_ROUTE_H_
Signature · 1 line
1.7.0.4
#26 lore raw

RFC 11/11 Apply the header code to make VMCI build

In reply to Andrew Stiegmann (stieg)

Adds all the necessary files to enable building of the VMCI module with the Linux Makefiles and Kconfig systems. Also adds the header files used for building modules against the driver.

---
 drivers/misc/Kconfig                    |    1 +
 drivers/misc/Makefile                   |    1 +
 drivers/misc/vmw_vmci/Kconfig           |   16 +
 drivers/misc/vmw_vmci/Makefile          |   43 ++
 drivers/misc/vmw_vmci/vmci_common_int.h |   72 +++
 include/linux/vmw_vmci_api.h            |  103 ++++
 include/linux/vmw_vmci_defs.h           | 1003 +++++++++++++++++++++++++++++++
 7 files changed, 1239 insertions(+), 0 deletions(-)
 create mode 100644 drivers/misc/vmw_vmci/Kconfig
 create mode 100644 drivers/misc/vmw_vmci/Makefile
 create mode 100644 drivers/misc/vmw_vmci/vmci_common_int.h
 create mode 100644 include/linux/vmw_vmci_api.h
 create mode 100644 include/linux/vmw_vmci_defs.h
drivers/misc/Kconfig +1 -0
index c779509..05314e1 100644
@@ -506,4 +506,5 @@ source "drivers/misc/ti-st/Kconfig"
 source "drivers/misc/lis3lv02d/Kconfig"
 source "drivers/misc/carma/Kconfig"
 source "drivers/misc/altera-stapl/Kconfig"
+source "drivers/misc/vmw_vmci/Kconfig"
 endmenu
drivers/misc/Makefile +1 -0
index 3e1d801..cb69a3c 100644
@@ -49,3 +49,4 @@ obj-y				+= carma/
 obj-$(CONFIG_USB_SWITCH_FSA9480) += fsa9480.o
 obj-$(CONFIG_ALTERA_STAPL)	+=altera-stapl/
 obj-$(CONFIG_MAX8997_MUIC)	+= max8997-muic.o
+obj-y				+= vmw_vmci/
drivers/misc/vmw_vmci/Kconfig new file +16 -0
new file mode 100644
index 0000000..55015e7
@@ -0,0 +1,16 @@
+#
+# VMware VMCI device
+#
+
+config VMWARE_VMCI
+	tristate "VMware VMCI Driver"
+	depends on X86
+	help
+	  This is VMware's Virtual Machine Communication Interface.  It enables
+	  high-speed communication between host and guest in a virtual
+	  environment via the VMCI virtual device.
+
+	  If unsure, say N.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called vmw_vmci.
drivers/misc/vmw_vmci/Makefile new file +43 -0

43 lines not on this page · raw message

drivers/misc/vmw_vmci/vmci_common_int.h new file +72 -0

72 lines not on this page · raw message

include/linux/vmw_vmci_api.h new file +103 -0

103 lines not on this page · raw message

include/linux/vmw_vmci_defs.h new file +1003 -0

1,003 lines not on this page · raw message

Signature · 1 line
1.7.0.4
#27 lore raw

RFC 11/11 Apply the header code to make VMCI build

In reply to Andrew Stiegmann (stieg)

Adds all the necessary files to enable building of the VMCI module with the Linux Makefiles and Kconfig systems. Also adds the header files used for building modules against the driver.

---
 drivers/misc/Kconfig                    |    1 +
 drivers/misc/Makefile                   |    1 +
 drivers/misc/vmw_vmci/Kconfig           |   16 +
 drivers/misc/vmw_vmci/Makefile          |   43 ++
 drivers/misc/vmw_vmci/vmci_common_int.h |   72 +++
 include/linux/vmw_vmci_api.h            |  103 ++++
 include/linux/vmw_vmci_defs.h           | 1003 +++++++++++++++++++++++++++++++
 7 files changed, 1239 insertions(+), 0 deletions(-)
 create mode 100644 drivers/misc/vmw_vmci/Kconfig
 create mode 100644 drivers/misc/vmw_vmci/Makefile
 create mode 100644 drivers/misc/vmw_vmci/vmci_common_int.h
 create mode 100644 include/linux/vmw_vmci_api.h
 create mode 100644 include/linux/vmw_vmci_defs.h
drivers/misc/Kconfig +1 -0
index c779509..05314e1 100644
@@ -506,4 +506,5 @@ source "drivers/misc/ti-st/Kconfig"
 source "drivers/misc/lis3lv02d/Kconfig"
 source "drivers/misc/carma/Kconfig"
 source "drivers/misc/altera-stapl/Kconfig"
+source "drivers/misc/vmw_vmci/Kconfig"
 endmenu
drivers/misc/Makefile +1 -0
index 3e1d801..cb69a3c 100644
@@ -49,3 +49,4 @@ obj-y				+= carma/
 obj-$(CONFIG_USB_SWITCH_FSA9480) += fsa9480.o
 obj-$(CONFIG_ALTERA_STAPL)	+=altera-stapl/
 obj-$(CONFIG_MAX8997_MUIC)	+= max8997-muic.o
+obj-y				+= vmw_vmci/
drivers/misc/vmw_vmci/Kconfig new file +16 -0
new file mode 100644
index 0000000..55015e7
@@ -0,0 +1,16 @@
+#
+# VMware VMCI device
+#
+
+config VMWARE_VMCI
+	tristate "VMware VMCI Driver"
+	depends on X86
+	help
+	  This is VMware's Virtual Machine Communication Interface.  It enables
+	  high-speed communication between host and guest in a virtual
+	  environment via the VMCI virtual device.
+
+	  If unsure, say N.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called vmw_vmci.
drivers/misc/vmw_vmci/Makefile new file +43 -0

43 lines not on this page · raw message

drivers/misc/vmw_vmci/vmci_common_int.h new file +72 -0

72 lines not on this page · raw message

include/linux/vmw_vmci_api.h new file +103 -0

103 lines not on this page · raw message

include/linux/vmw_vmci_defs.h new file +1003 -0

1,003 lines not on this page · raw message

Signature · 1 line
1.7.0.4
maintainer
#28 lore raw
In reply to Andrew Stiegmann (stieg)
Quoted 21 lines · Andrew Stiegmann (stieg)

In an effort to improve the out-of-the-box experience with Linux kernels for VMware users, VMware is working on readying the Virtual Machine Communication Interface (vmw_vmci) and VMCI Sockets (vmw_vsock) kernel modules for inclusion in the Linux kernel. The purpose of this post is to acquire feedback on the vmw_vmci kernel module. The vmw_vsock kernel module will be presented in a later post.

VMCI allows virtual machines to communicate with host kernel modules and the VMware hypervisors. User level applications both in a virtual machine and on the host can use vmw_vmci through VMCI Sockets, a socket address family designed to be compatible with UDP and TCP at the interface level. Today, VMCI and VMCI Sockets are used by the VMware shared folders (HGFS) and various VMware Tools components inside the guest for zero-config, network-less access to VMware host services. In addition to this, VMware's users are using VMCI Sockets for various applications, where network access of the virtual machine is restricted or non-existent. Examples of this are VMs communicating with device proxies for proprietary hardware running as host applications and automated testing of applications running within virtual machines.

Quoted 9 lines

In a virtual machine, VMCI is exposed as a regular PCI device. The primary communication mechanisms supported are a point-to-point bidirectional transport based on a pair of memory-mapped queues, and asynchronous notifications in the form of datagrams and doorbells. These features are available to kernel level components such as HGFS and VMCI Sockets through the VMCI kernel API. In addition to this, the VMCI kernel API provides support for receiving events related to the state of the VMCI communication channels, and the virtual machine itself.

Don't we have something like this already for KVM and maybe Xen? virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

thanks,

greg k-h

maintainer
#29 lore raw
In reply to Andrew Stiegmann (stieg)
Quoted 21 lines · Andrew Stiegmann (stieg)

In an effort to improve the out-of-the-box experience with Linux kernels for VMware users, VMware is working on readying the Virtual Machine Communication Interface (vmw_vmci) and VMCI Sockets (vmw_vsock) kernel modules for inclusion in the Linux kernel. The purpose of this post is to acquire feedback on the vmw_vmci kernel module. The vmw_vsock kernel module will be presented in a later post.

VMCI allows virtual machines to communicate with host kernel modules and the VMware hypervisors. User level applications both in a virtual machine and on the host can use vmw_vmci through VMCI Sockets, a socket address family designed to be compatible with UDP and TCP at the interface level. Today, VMCI and VMCI Sockets are used by the VMware shared folders (HGFS) and various VMware Tools components inside the guest for zero-config, network-less access to VMware host services. In addition to this, VMware's users are using VMCI Sockets for various applications, where network access of the virtual machine is restricted or non-existent. Examples of this are VMs communicating with device proxies for proprietary hardware running as host applications and automated testing of applications running within virtual machines.

Quoted 9 lines

In a virtual machine, VMCI is exposed as a regular PCI device. The primary communication mechanisms supported are a point-to-point bidirectional transport based on a pair of memory-mapped queues, and asynchronous notifications in the form of datagrams and doorbells. These features are available to kernel level components such as HGFS and VMCI Sockets through the VMCI kernel API. In addition to this, the VMCI kernel API provides support for receiving events related to the state of the VMCI communication channels, and the virtual machine itself.

Don't we have something like this already for KVM and maybe Xen? virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

thanks,

greg k-h

#30 lore raw
Quoted 32 lines · Greg KH
Quoted 21 lines · Andrew Stiegmann (stieg)

In an effort to improve the out-of-the-box experience with Linux kernels for VMware users, VMware is working on readying the Virtual Machine Communication Interface (vmw_vmci) and VMCI Sockets (vmw_vsock) kernel modules for inclusion in the Linux kernel. The purpose of this post is to acquire feedback on the vmw_vmci kernel module. The vmw_vsock kernel module will be presented in a later post.

VMCI allows virtual machines to communicate with host kernel modules and the VMware hypervisors. User level applications both in a virtual machine and on the host can use vmw_vmci through VMCI Sockets, a socket address family designed to be compatible with UDP and TCP at the interface level. Today, VMCI and VMCI Sockets are used by the VMware shared folders (HGFS) and various VMware Tools components inside the guest for zero-config, network-less access to VMware host services. In addition to this, VMware's users are using VMCI Sockets for various applications, where network access of the virtual machine is restricted or non-existent. Examples of this are VMs communicating with device proxies for proprietary hardware running as host applications and automated testing of applications running within virtual machines.

Quoted 9 lines

In a virtual machine, VMCI is exposed as a regular PCI device. The primary communication mechanisms supported are a point-to-point bidirectional transport based on a pair of memory-mapped queues, and asynchronous notifications in the form of datagrams and doorbells. These features are available to kernel level components such as HGFS and VMCI Sockets through the VMCI kernel API. In addition to this, the VMCI kernel API provides support for receiving events related to the state of the VMCI communication channels, and the virtual machine itself.

Quoted 1 line

Don't we have something like this already for KVM and maybe Xen?

We have virtio-serial driver for guest-host communication:
http://fedoraproject.org/wiki/Features/VirtioSerial
http://www.linux-kvm.org/page/VMchannel_Requirements

Amit Shah, the writer is CCed as well as kvm-devel.

Quoted 6 lines

virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

KVM uses virtio-serial as a pci device which has 'ports' on top of it. The ports acts like channels that can be created dynamically and allows guest userspace <-> host userspace communication. In theory, the kvm mechanism should be a good fit for other hypervisors.

Nevertheless, despite my biased love for KVM, I bet it would be 'tricky' for VMW to change their hardware model and shift to virtio hardware abstraction. In addition, they'll be required to change existing apps that use their socket code.

One can bunker in our rightful requirement of 'upstream first' but this may slow/vanish the benefits of getting VMW code upstream for out of the box experience for Linux users.

IMHO, let's be practical and include this pci device (pending standard review) but _require_ that the VMCI sockets family will be a general mechanism that may be used over virtio-serial as well. Andrew, it would be the best to work w/ Amit and various other KVM hackers to get your (changed) code upstream.

Regards,
Dor

Quoted 9 lines

thanks,

greg k-h
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/

#31 lore raw
In reply to Greg KH

Greg,

Thanks so much for the comments and apologies for the delayed response.

Quoted 7 lines

Don't we have something like this already for KVM and maybe Xen? virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

The VMCI virtual device for which this driver is intended has been around a lot longer than this submission might suggest. The virtual hardware was released in a product before Rusty sent his RFC and quite a bit before it made it to mainline; there was, regrettably, no virtio then.

As such, it was designed to be its own transport, and it's something that is now very much fixed at the hardware level (enhancements not withstanding), and which we have to support all the way back.

In addition to that, our hypervisor endpoints are written using the existing device backend; virtio doesn't currently make a lot of sense for them, and would require a lot of additional work.

All of this is unfortunate. While I agree that virtio is certainly the right approach, and we need to avoid this proliferation, I think at this point we'd really like to try and upstream this in its current form. There's certainly the possibility going forwards that we could add a glue layer, such that other clients could use virtio if they're willing to write their own hypervisor endpoints.

Does that sound reasonable?

Again, many thanks for taking the time to review this.

Kind regards,
- Andy King

#32 lore raw
In reply to Greg KH

Greg,

Thanks so much for the comments and apologies for the delayed response.

Quoted 7 lines

Don't we have something like this already for KVM and maybe Xen? virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

The VMCI virtual device for which this driver is intended has been around a lot longer than this submission might suggest. The virtual hardware was released in a product before Rusty sent his RFC and quite a bit before it made it to mainline; there was, regrettably, no virtio then.

As such, it was designed to be its own transport, and it's something that is now very much fixed at the hardware level (enhancements not withstanding), and which we have to support all the way back.

In addition to that, our hypervisor endpoints are written using the existing device backend; virtio doesn't currently make a lot of sense for them, and would require a lot of additional work.

All of this is unfortunate. While I agree that virtio is certainly the right approach, and we need to avoid this proliferation, I think at this point we'd really like to try and upstream this in its current form. There's certainly the possibility going forwards that we could add a glue layer, such that other clients could use virtio if they're willing to write their own hypervisor endpoints.

Does that sound reasonable?

Again, many thanks for taking the time to review this.

Kind regards,
- Andy King

maintainer
#33 lore raw
Quoted 18 lines · Andy King

Greg,

Thanks so much for the comments and apologies for the delayed response.

Quoted 7 lines

Don't we have something like this already for KVM and maybe Xen? virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

The VMCI virtual device for which this driver is intended has been around a lot longer than this submission might suggest. The virtual hardware was released in a product before Rusty sent his RFC and quite a bit before it made it to mainline; there was, regrettably, no virtio then.

Quoted 3 lines

As such, it was designed to be its own transport, and it's something that is now very much fixed at the hardware level (enhancements not withstanding), and which we have to support all the way back.

What "hardware" are you refering to here?

Quoted 4 lines

In addition to that, our hypervisor endpoints are written using the existing device backend; virtio doesn't currently make a lot of sense for them, and would require a lot of additional work.

Quoted 8 lines

All of this is unfortunate. While I agree that virtio is certainly the right approach, and we need to avoid this proliferation, I think at this point we'd really like to try and upstream this in its current form. There's certainly the possibility going forwards that we could add a glue layer, such that other clients could use virtio if they're willing to write their own hypervisor endpoints.

Does that sound reasonable?

Not really, why should we take an interface that is tied to something that you are saying isn't something we should be using? Don't you also have control over the hypervisor side of things in order to properly design this type of thing?

thanks,

greg k-h

maintainer
#34 lore raw
In reply to Andy King
Quoted 18 lines · Andy King

Greg,

Thanks so much for the comments and apologies for the delayed response.

Quoted 7 lines

Don't we have something like this already for KVM and maybe Xen? virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

The VMCI virtual device for which this driver is intended has been around a lot longer than this submission might suggest. The virtual hardware was released in a product before Rusty sent his RFC and quite a bit before it made it to mainline; there was, regrettably, no virtio then.

Quoted 3 lines

As such, it was designed to be its own transport, and it's something that is now very much fixed at the hardware level (enhancements not withstanding), and which we have to support all the way back.

What "hardware" are you refering to here?

Quoted 4 lines

In addition to that, our hypervisor endpoints are written using the existing device backend; virtio doesn't currently make a lot of sense for them, and would require a lot of additional work.

Quoted 8 lines

All of this is unfortunate. While I agree that virtio is certainly the right approach, and we need to avoid this proliferation, I think at this point we'd really like to try and upstream this in its current form. There's certainly the possibility going forwards that we could add a glue layer, such that other clients could use virtio if they're willing to write their own hypervisor endpoints.

Does that sound reasonable?

Not really, why should we take an interface that is tied to something that you are saying isn't something we should be using? Don't you also have control over the hypervisor side of things in order to properly design this type of thing?

thanks,

greg k-h

#35 lore raw

Hi Greg,

Quoted 19 lines · Greg KH
Quoted 18 lines · Andy King

Greg,

Thanks so much for the comments and apologies for the delayed response.

Quoted 7 lines

Don't we have something like this already for KVM and maybe Xen? virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

The VMCI virtual device for which this driver is intended has been around a lot longer than this submission might suggest. The virtual hardware was released in a product before Rusty sent his RFC and quite a bit before it made it to mainline; there was, regrettably, no virtio then.

Quoted 5 lines
Quoted 3 lines

As such, it was designed to be its own transport, and it's something that is now very much fixed at the hardware level (enhancements not withstanding), and which we have to support all the way back.

What "hardware" are you refering to here?

The virtual hardware that is currently shipping and has been shipping for a few years.

Quoted 12 lines
Quoted 12 lines

In addition to that, our hypervisor endpoints are written using the existing device backend; virtio doesn't currently make a lot of sense for them, and would require a lot of additional work.

All of this is unfortunate. While I agree that virtio is certainly the right approach, and we need to avoid this proliferation, I think at this point we'd really like to try and upstream this in its current form. There's certainly the possibility going forwards that we could add a glue layer, such that other clients could use virtio if they're willing to write their own hypervisor endpoints.

Quoted 4 lines
Quoted 1 line

Does that sound reasonable?

Not really, why should we take an interface that is tied to something that you are saying isn't something we should be using?

That is not what Andy said. If virtio was available when we started shipping VMCI then we certainly could have used that, but since it wasn't there we invented something else.

Quoted 3 lines

Don't you also
have control over the hypervisor side of things in order to properly design this type of thing?

We do not have a time machine to go back and change products that we already shipped to the customers. It is probably the same story as with Hyper-V's vmbus which is not virtio.

Besides, virtio is not available on non-Linux guests with we have to support as well, and than affected the design decisions in hypervisor layer that have been made several years ago.

Thanks,
Dmitry

maintainer
#36 lore raw
Quoted 43 lines · Dmitry Torokhov

Hi Greg,

Quoted 19 lines · Greg KH
Quoted 18 lines · Andy King

Greg,

Thanks so much for the comments and apologies for the delayed response.

Quoted 7 lines

Don't we have something like this already for KVM and maybe Xen? virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

The VMCI virtual device for which this driver is intended has been around a lot longer than this submission might suggest. The virtual hardware was released in a product before Rusty sent his RFC and quite a bit before it made it to mainline; there was, regrettably, no virtio then.

Quoted 5 lines
Quoted 3 lines

As such, it was designed to be its own transport, and it's something that is now very much fixed at the hardware level (enhancements not withstanding), and which we have to support all the way back.

What "hardware" are you refering to here?

The virtual hardware that is currently shipping and has been shipping for a few years.

Quoted 12 lines
Quoted 12 lines

In addition to that, our hypervisor endpoints are written using the existing device backend; virtio doesn't currently make a lot of sense for them, and would require a lot of additional work.

All of this is unfortunate. While I agree that virtio is certainly the right approach, and we need to avoid this proliferation, I think at this point we'd really like to try and upstream this in its current form. There's certainly the possibility going forwards that we could add a glue layer, such that other clients could use virtio if they're willing to write their own hypervisor endpoints.

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

Does that sound reasonable?

Not really, why should we take an interface that is tied to something that you are saying isn't something we should be using?

That is not what Andy said. If virtio was available when we started shipping VMCI then we certainly could have used that, but since it wasn't there we invented something else.

Ok, that makes sense.

Quoted 11 lines
Quoted 3 lines

Don't you also
have control over the hypervisor side of things in order to properly design this type of thing?

We do not have a time machine to go back and change products that we already shipped to the customers. It is probably the same story as with Hyper-V's vmbus which is not virtio.

Besides, virtio is not available on non-Linux guests with we have to support as well, and than affected the design decisions in hypervisor layer that have been made several years ago.

Ok, thanks for clearing that up, I was confused here.

greg k-h

#37 lore raw
Quoted 46 lines · Greg KH
Quoted 45 lines · Dmitry Torokhov

Hi Greg,

Quoted 19 lines · Greg KH
Quoted 18 lines · Andy King

Greg,

Thanks so much for the comments and apologies for the delayed response.

Quoted 7 lines

Don't we have something like this already for KVM and maybe Xen? virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

The VMCI virtual device for which this driver is intended has been around a lot longer than this submission might suggest. The virtual hardware was released in a product before Rusty sent his RFC and quite a bit before it made it to mainline; there was, regrettably, no virtio then.

Quoted 5 lines
Quoted 3 lines

As such, it was designed to be its own transport, and it's something that is now very much fixed at the hardware level (enhancements not withstanding), and which we have to support all the way back.

What "hardware" are you refering to here?

The virtual hardware that is currently shipping and has been shipping for a few years.

Quoted 14 lines
Quoted 13 lines

In addition to that, our hypervisor endpoints are written using the existing device backend; virtio doesn't currently make a lot of sense for them, and would require a lot of additional work.

All of this is unfortunate. While I agree that virtio is certainly the right approach, and we need to avoid this proliferation, I think at this point we'd really like to try and upstream this in its current form. There's certainly the possibility going forwards that we could add a glue layer, such that other clients could use virtio if they're willing to write their own hypervisor endpoints.

Does that sound reasonable?

Quoted 20 lines
Quoted 6 lines
Quoted 2 lines

Not really, why should we take an interface that is tied to something that you are saying isn't something we should be using?

That is not what Andy said. If virtio was available when we started shipping VMCI then we certainly could have used that, but since it wasn't there we invented something else.

Ok, that makes sense.

Quoted 11 lines
Quoted 3 lines

Don't you also
have control over the hypervisor side of things in order to properly design this type of thing?

We do not have a time machine to go back and change products that we already shipped to the customers. It is probably the same story as with Hyper-V's vmbus which is not virtio.

Besides, virtio is not available on non-Linux guests with we have to support as well, and than affected the design decisions in hypervisor layer that have been made several years ago.

Indeed there is no time machine and I definitely agree you won't be able to port VMCI to virtio-serial w/o major breakage for existing users.

Nevertheless, as I wrote on my previous feedback [1], you can make the VMCI socket generic in a way that virtio-serial users would be able to enjoy. This way VMW users will get out of the box experience w/o any change while KVM users will get socket abstraction layer which carry some benefit over the virtio-serial ports.

Dor

[1] https://lkml.org/lkml/2012/5/16/126

Quoted 8 lines

Ok, thanks for clearing that up, I was confused here.

greg k-h
_______________________________________________
Virtualization mailing list
[email protected]
https://lists.linuxfoundation.org/mailman/listinfo/virtualization

#38 lore raw
In reply to Greg KH
Quoted 46 lines · Greg KH
Quoted 45 lines · Dmitry Torokhov

Hi Greg,

Quoted 19 lines · Greg KH
Quoted 18 lines · Andy King

Greg,

Thanks so much for the comments and apologies for the delayed response.

Quoted 7 lines

Don't we have something like this already for KVM and maybe Xen? virtio? Can't you use that code instead of a new block of code that is only used by vmware users? It has virtual pci devices which should give you what you want/need here, right?

If not, why doesn't that work for you? Would it be easier to just extend it?

The VMCI virtual device for which this driver is intended has been around a lot longer than this submission might suggest. The virtual hardware was released in a product before Rusty sent his RFC and quite a bit before it made it to mainline; there was, regrettably, no virtio then.

Quoted 5 lines
Quoted 3 lines

As such, it was designed to be its own transport, and it's something that is now very much fixed at the hardware level (enhancements not withstanding), and which we have to support all the way back.

What "hardware" are you refering to here?

The virtual hardware that is currently shipping and has been shipping for a few years.

Quoted 14 lines
Quoted 13 lines

In addition to that, our hypervisor endpoints are written using the existing device backend; virtio doesn't currently make a lot of sense for them, and would require a lot of additional work.

All of this is unfortunate. While I agree that virtio is certainly the right approach, and we need to avoid this proliferation, I think at this point we'd really like to try and upstream this in its current form. There's certainly the possibility going forwards that we could add a glue layer, such that other clients could use virtio if they're willing to write their own hypervisor endpoints.

Does that sound reasonable?

Quoted 20 lines
Quoted 6 lines
Quoted 2 lines

Not really, why should we take an interface that is tied to something that you are saying isn't something we should be using?

That is not what Andy said. If virtio was available when we started shipping VMCI then we certainly could have used that, but since it wasn't there we invented something else.

Ok, that makes sense.

Quoted 11 lines
Quoted 3 lines

Don't you also
have control over the hypervisor side of things in order to properly design this type of thing?

We do not have a time machine to go back and change products that we already shipped to the customers. It is probably the same story as with Hyper-V's vmbus which is not virtio.

Besides, virtio is not available on non-Linux guests with we have to support as well, and than affected the design decisions in hypervisor layer that have been made several years ago.

Indeed there is no time machine and I definitely agree you won't be able to port VMCI to virtio-serial w/o major breakage for existing users.

Nevertheless, as I wrote on my previous feedback [1], you can make the VMCI socket generic in a way that virtio-serial users would be able to enjoy. This way VMW users will get out of the box experience w/o any change while KVM users will get socket abstraction layer which carry some benefit over the virtio-serial ports.

Dor

[1] https://lkml.org/lkml/2012/5/16/126

Quoted 8 lines

Ok, thanks for clearing that up, I was confused here.

greg k-h
_______________________________________________
Virtualization mailing list
[email protected]
https://lists.linuxfoundation.org/mailman/listinfo/virtualization