GNU Linux-libre 4.19.207-gnu1
[releases.git] / drivers / misc / vmw_vmci / vmci_queue_pair.c
1 /*
2  * VMware VMCI Driver
3  *
4  * Copyright (C) 2012 VMware, Inc. All rights reserved.
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation version 2 and no later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13  * for more details.
14  */
15
16 #include <linux/vmw_vmci_defs.h>
17 #include <linux/vmw_vmci_api.h>
18 #include <linux/highmem.h>
19 #include <linux/kernel.h>
20 #include <linux/mm.h>
21 #include <linux/module.h>
22 #include <linux/mutex.h>
23 #include <linux/pagemap.h>
24 #include <linux/pci.h>
25 #include <linux/sched.h>
26 #include <linux/slab.h>
27 #include <linux/uio.h>
28 #include <linux/wait.h>
29 #include <linux/vmalloc.h>
30 #include <linux/skbuff.h>
31
32 #include "vmci_handle_array.h"
33 #include "vmci_queue_pair.h"
34 #include "vmci_datagram.h"
35 #include "vmci_resource.h"
36 #include "vmci_context.h"
37 #include "vmci_driver.h"
38 #include "vmci_event.h"
39 #include "vmci_route.h"
40
41 /*
42  * In the following, we will distinguish between two kinds of VMX processes -
43  * the ones with versions lower than VMCI_VERSION_NOVMVM that use specialized
44  * VMCI page files in the VMX and supporting VM to VM communication and the
45  * newer ones that use the guest memory directly. We will in the following
46  * refer to the older VMX versions as old-style VMX'en, and the newer ones as
47  * new-style VMX'en.
48  *
49  * The state transition datagram is as follows (the VMCIQPB_ prefix has been
50  * removed for readability) - see below for more details on the transtions:
51  *
52  *            --------------  NEW  -------------
53  *            |                                |
54  *           \_/                              \_/
55  *     CREATED_NO_MEM <-----------------> CREATED_MEM
56  *            |    |                           |
57  *            |    o-----------------------o   |
58  *            |                            |   |
59  *           \_/                          \_/ \_/
60  *     ATTACHED_NO_MEM <----------------> ATTACHED_MEM
61  *            |                            |   |
62  *            |     o----------------------o   |
63  *            |     |                          |
64  *           \_/   \_/                        \_/
65  *     SHUTDOWN_NO_MEM <----------------> SHUTDOWN_MEM
66  *            |                                |
67  *            |                                |
68  *            -------------> gone <-------------
69  *
70  * In more detail. When a VMCI queue pair is first created, it will be in the
71  * VMCIQPB_NEW state. It will then move into one of the following states:
72  *
73  * - VMCIQPB_CREATED_NO_MEM: this state indicates that either:
74  *
75  *     - the created was performed by a host endpoint, in which case there is
76  *       no backing memory yet.
77  *
78  *     - the create was initiated by an old-style VMX, that uses
79  *       vmci_qp_broker_set_page_store to specify the UVAs of the queue pair at
80  *       a later point in time. This state can be distinguished from the one
81  *       above by the context ID of the creator. A host side is not allowed to
82  *       attach until the page store has been set.
83  *
84  * - VMCIQPB_CREATED_MEM: this state is the result when the queue pair
85  *     is created by a VMX using the queue pair device backend that
86  *     sets the UVAs of the queue pair immediately and stores the
87  *     information for later attachers. At this point, it is ready for
88  *     the host side to attach to it.
89  *
90  * Once the queue pair is in one of the created states (with the exception of
91  * the case mentioned for older VMX'en above), it is possible to attach to the
92  * queue pair. Again we have two new states possible:
93  *
94  * - VMCIQPB_ATTACHED_MEM: this state can be reached through the following
95  *   paths:
96  *
97  *     - from VMCIQPB_CREATED_NO_MEM when a new-style VMX allocates a queue
98  *       pair, and attaches to a queue pair previously created by the host side.
99  *
100  *     - from VMCIQPB_CREATED_MEM when the host side attaches to a queue pair
101  *       already created by a guest.
102  *
103  *     - from VMCIQPB_ATTACHED_NO_MEM, when an old-style VMX calls
104  *       vmci_qp_broker_set_page_store (see below).
105  *
106  * - VMCIQPB_ATTACHED_NO_MEM: If the queue pair already was in the
107  *     VMCIQPB_CREATED_NO_MEM due to a host side create, an old-style VMX will
108  *     bring the queue pair into this state. Once vmci_qp_broker_set_page_store
109  *     is called to register the user memory, the VMCIQPB_ATTACH_MEM state
110  *     will be entered.
111  *
112  * From the attached queue pair, the queue pair can enter the shutdown states
113  * when either side of the queue pair detaches. If the guest side detaches
114  * first, the queue pair will enter the VMCIQPB_SHUTDOWN_NO_MEM state, where
115  * the content of the queue pair will no longer be available. If the host
116  * side detaches first, the queue pair will either enter the
117  * VMCIQPB_SHUTDOWN_MEM, if the guest memory is currently mapped, or
118  * VMCIQPB_SHUTDOWN_NO_MEM, if the guest memory is not mapped
119  * (e.g., the host detaches while a guest is stunned).
120  *
121  * New-style VMX'en will also unmap guest memory, if the guest is
122  * quiesced, e.g., during a snapshot operation. In that case, the guest
123  * memory will no longer be available, and the queue pair will transition from
124  * *_MEM state to a *_NO_MEM state. The VMX may later map the memory once more,
125  * in which case the queue pair will transition from the *_NO_MEM state at that
126  * point back to the *_MEM state. Note that the *_NO_MEM state may have changed,
127  * since the peer may have either attached or detached in the meantime. The
128  * values are laid out such that ++ on a state will move from a *_NO_MEM to a
129  * *_MEM state, and vice versa.
130  */
131
132 /* The Kernel specific component of the struct vmci_queue structure. */
133 struct vmci_queue_kern_if {
134         struct mutex __mutex;   /* Protects the queue. */
135         struct mutex *mutex;    /* Shared by producer and consumer queues. */
136         size_t num_pages;       /* Number of pages incl. header. */
137         bool host;              /* Host or guest? */
138         union {
139                 struct {
140                         dma_addr_t *pas;
141                         void **vas;
142                 } g;            /* Used by the guest. */
143                 struct {
144                         struct page **page;
145                         struct page **header_page;
146                 } h;            /* Used by the host. */
147         } u;
148 };
149
150 /*
151  * This structure is opaque to the clients.
152  */
153 struct vmci_qp {
154         struct vmci_handle handle;
155         struct vmci_queue *produce_q;
156         struct vmci_queue *consume_q;
157         u64 produce_q_size;
158         u64 consume_q_size;
159         u32 peer;
160         u32 flags;
161         u32 priv_flags;
162         bool guest_endpoint;
163         unsigned int blocked;
164         unsigned int generation;
165         wait_queue_head_t event;
166 };
167
168 enum qp_broker_state {
169         VMCIQPB_NEW,
170         VMCIQPB_CREATED_NO_MEM,
171         VMCIQPB_CREATED_MEM,
172         VMCIQPB_ATTACHED_NO_MEM,
173         VMCIQPB_ATTACHED_MEM,
174         VMCIQPB_SHUTDOWN_NO_MEM,
175         VMCIQPB_SHUTDOWN_MEM,
176         VMCIQPB_GONE
177 };
178
179 #define QPBROKERSTATE_HAS_MEM(_qpb) (_qpb->state == VMCIQPB_CREATED_MEM || \
180                                      _qpb->state == VMCIQPB_ATTACHED_MEM || \
181                                      _qpb->state == VMCIQPB_SHUTDOWN_MEM)
182
183 /*
184  * In the queue pair broker, we always use the guest point of view for
185  * the produce and consume queue values and references, e.g., the
186  * produce queue size stored is the guests produce queue size. The
187  * host endpoint will need to swap these around. The only exception is
188  * the local queue pairs on the host, in which case the host endpoint
189  * that creates the queue pair will have the right orientation, and
190  * the attaching host endpoint will need to swap.
191  */
192 struct qp_entry {
193         struct list_head list_item;
194         struct vmci_handle handle;
195         u32 peer;
196         u32 flags;
197         u64 produce_size;
198         u64 consume_size;
199         u32 ref_count;
200 };
201
202 struct qp_broker_entry {
203         struct vmci_resource resource;
204         struct qp_entry qp;
205         u32 create_id;
206         u32 attach_id;
207         enum qp_broker_state state;
208         bool require_trusted_attach;
209         bool created_by_trusted;
210         bool vmci_page_files;   /* Created by VMX using VMCI page files */
211         struct vmci_queue *produce_q;
212         struct vmci_queue *consume_q;
213         struct vmci_queue_header saved_produce_q;
214         struct vmci_queue_header saved_consume_q;
215         vmci_event_release_cb wakeup_cb;
216         void *client_data;
217         void *local_mem;        /* Kernel memory for local queue pair */
218 };
219
220 struct qp_guest_endpoint {
221         struct vmci_resource resource;
222         struct qp_entry qp;
223         u64 num_ppns;
224         void *produce_q;
225         void *consume_q;
226         struct ppn_set ppn_set;
227 };
228
229 struct qp_list {
230         struct list_head head;
231         struct mutex mutex;     /* Protect queue list. */
232 };
233
234 static struct qp_list qp_broker_list = {
235         .head = LIST_HEAD_INIT(qp_broker_list.head),
236         .mutex = __MUTEX_INITIALIZER(qp_broker_list.mutex),
237 };
238
239 static struct qp_list qp_guest_endpoints = {
240         .head = LIST_HEAD_INIT(qp_guest_endpoints.head),
241         .mutex = __MUTEX_INITIALIZER(qp_guest_endpoints.mutex),
242 };
243
244 #define INVALID_VMCI_GUEST_MEM_ID  0
245 #define QPE_NUM_PAGES(_QPE) ((u32) \
246                              (DIV_ROUND_UP(_QPE.produce_size, PAGE_SIZE) + \
247                               DIV_ROUND_UP(_QPE.consume_size, PAGE_SIZE) + 2))
248
249
250 /*
251  * Frees kernel VA space for a given queue and its queue header, and
252  * frees physical data pages.
253  */
254 static void qp_free_queue(void *q, u64 size)
255 {
256         struct vmci_queue *queue = q;
257
258         if (queue) {
259                 u64 i;
260
261                 /* Given size does not include header, so add in a page here. */
262                 for (i = 0; i < DIV_ROUND_UP(size, PAGE_SIZE) + 1; i++) {
263                         dma_free_coherent(&vmci_pdev->dev, PAGE_SIZE,
264                                           queue->kernel_if->u.g.vas[i],
265                                           queue->kernel_if->u.g.pas[i]);
266                 }
267
268                 vfree(queue);
269         }
270 }
271
272 /*
273  * Allocates kernel queue pages of specified size with IOMMU mappings,
274  * plus space for the queue structure/kernel interface and the queue
275  * header.
276  */
277 static void *qp_alloc_queue(u64 size, u32 flags)
278 {
279         u64 i;
280         struct vmci_queue *queue;
281         size_t pas_size;
282         size_t vas_size;
283         size_t queue_size = sizeof(*queue) + sizeof(*queue->kernel_if);
284         u64 num_pages;
285
286         if (size > SIZE_MAX - PAGE_SIZE)
287                 return NULL;
288         num_pages = DIV_ROUND_UP(size, PAGE_SIZE) + 1;
289         if (num_pages >
290                  (SIZE_MAX - queue_size) /
291                  (sizeof(*queue->kernel_if->u.g.pas) +
292                   sizeof(*queue->kernel_if->u.g.vas)))
293                 return NULL;
294
295         pas_size = num_pages * sizeof(*queue->kernel_if->u.g.pas);
296         vas_size = num_pages * sizeof(*queue->kernel_if->u.g.vas);
297         queue_size += pas_size + vas_size;
298
299         queue = vmalloc(queue_size);
300         if (!queue)
301                 return NULL;
302
303         queue->q_header = NULL;
304         queue->saved_header = NULL;
305         queue->kernel_if = (struct vmci_queue_kern_if *)(queue + 1);
306         queue->kernel_if->mutex = NULL;
307         queue->kernel_if->num_pages = num_pages;
308         queue->kernel_if->u.g.pas = (dma_addr_t *)(queue->kernel_if + 1);
309         queue->kernel_if->u.g.vas =
310                 (void **)((u8 *)queue->kernel_if->u.g.pas + pas_size);
311         queue->kernel_if->host = false;
312
313         for (i = 0; i < num_pages; i++) {
314                 queue->kernel_if->u.g.vas[i] =
315                         dma_alloc_coherent(&vmci_pdev->dev, PAGE_SIZE,
316                                            &queue->kernel_if->u.g.pas[i],
317                                            GFP_KERNEL);
318                 if (!queue->kernel_if->u.g.vas[i]) {
319                         /* Size excl. the header. */
320                         qp_free_queue(queue, i * PAGE_SIZE);
321                         return NULL;
322                 }
323         }
324
325         /* Queue header is the first page. */
326         queue->q_header = queue->kernel_if->u.g.vas[0];
327
328         return queue;
329 }
330
331 /*
332  * Copies from a given buffer or iovector to a VMCI Queue.  Uses
333  * kmap()/kunmap() to dynamically map/unmap required portions of the queue
334  * by traversing the offset -> page translation structure for the queue.
335  * Assumes that offset + size does not wrap around in the queue.
336  */
337 static int qp_memcpy_to_queue_iter(struct vmci_queue *queue,
338                                   u64 queue_offset,
339                                   struct iov_iter *from,
340                                   size_t size)
341 {
342         struct vmci_queue_kern_if *kernel_if = queue->kernel_if;
343         size_t bytes_copied = 0;
344
345         while (bytes_copied < size) {
346                 const u64 page_index =
347                         (queue_offset + bytes_copied) / PAGE_SIZE;
348                 const size_t page_offset =
349                     (queue_offset + bytes_copied) & (PAGE_SIZE - 1);
350                 void *va;
351                 size_t to_copy;
352
353                 if (kernel_if->host)
354                         va = kmap(kernel_if->u.h.page[page_index]);
355                 else
356                         va = kernel_if->u.g.vas[page_index + 1];
357                         /* Skip header. */
358
359                 if (size - bytes_copied > PAGE_SIZE - page_offset)
360                         /* Enough payload to fill up from this page. */
361                         to_copy = PAGE_SIZE - page_offset;
362                 else
363                         to_copy = size - bytes_copied;
364
365                 if (!copy_from_iter_full((u8 *)va + page_offset, to_copy,
366                                          from)) {
367                         if (kernel_if->host)
368                                 kunmap(kernel_if->u.h.page[page_index]);
369                         return VMCI_ERROR_INVALID_ARGS;
370                 }
371                 bytes_copied += to_copy;
372                 if (kernel_if->host)
373                         kunmap(kernel_if->u.h.page[page_index]);
374         }
375
376         return VMCI_SUCCESS;
377 }
378
379 /*
380  * Copies to a given buffer or iovector from a VMCI Queue.  Uses
381  * kmap()/kunmap() to dynamically map/unmap required portions of the queue
382  * by traversing the offset -> page translation structure for the queue.
383  * Assumes that offset + size does not wrap around in the queue.
384  */
385 static int qp_memcpy_from_queue_iter(struct iov_iter *to,
386                                     const struct vmci_queue *queue,
387                                     u64 queue_offset, size_t size)
388 {
389         struct vmci_queue_kern_if *kernel_if = queue->kernel_if;
390         size_t bytes_copied = 0;
391
392         while (bytes_copied < size) {
393                 const u64 page_index =
394                         (queue_offset + bytes_copied) / PAGE_SIZE;
395                 const size_t page_offset =
396                     (queue_offset + bytes_copied) & (PAGE_SIZE - 1);
397                 void *va;
398                 size_t to_copy;
399                 int err;
400
401                 if (kernel_if->host)
402                         va = kmap(kernel_if->u.h.page[page_index]);
403                 else
404                         va = kernel_if->u.g.vas[page_index + 1];
405                         /* Skip header. */
406
407                 if (size - bytes_copied > PAGE_SIZE - page_offset)
408                         /* Enough payload to fill up this page. */
409                         to_copy = PAGE_SIZE - page_offset;
410                 else
411                         to_copy = size - bytes_copied;
412
413                 err = copy_to_iter((u8 *)va + page_offset, to_copy, to);
414                 if (err != to_copy) {
415                         if (kernel_if->host)
416                                 kunmap(kernel_if->u.h.page[page_index]);
417                         return VMCI_ERROR_INVALID_ARGS;
418                 }
419                 bytes_copied += to_copy;
420                 if (kernel_if->host)
421                         kunmap(kernel_if->u.h.page[page_index]);
422         }
423
424         return VMCI_SUCCESS;
425 }
426
427 /*
428  * Allocates two list of PPNs --- one for the pages in the produce queue,
429  * and the other for the pages in the consume queue. Intializes the list
430  * of PPNs with the page frame numbers of the KVA for the two queues (and
431  * the queue headers).
432  */
433 static int qp_alloc_ppn_set(void *prod_q,
434                             u64 num_produce_pages,
435                             void *cons_q,
436                             u64 num_consume_pages, struct ppn_set *ppn_set)
437 {
438         u32 *produce_ppns;
439         u32 *consume_ppns;
440         struct vmci_queue *produce_q = prod_q;
441         struct vmci_queue *consume_q = cons_q;
442         u64 i;
443
444         if (!produce_q || !num_produce_pages || !consume_q ||
445             !num_consume_pages || !ppn_set)
446                 return VMCI_ERROR_INVALID_ARGS;
447
448         if (ppn_set->initialized)
449                 return VMCI_ERROR_ALREADY_EXISTS;
450
451         produce_ppns =
452             kmalloc_array(num_produce_pages, sizeof(*produce_ppns),
453                           GFP_KERNEL);
454         if (!produce_ppns)
455                 return VMCI_ERROR_NO_MEM;
456
457         consume_ppns =
458             kmalloc_array(num_consume_pages, sizeof(*consume_ppns),
459                           GFP_KERNEL);
460         if (!consume_ppns) {
461                 kfree(produce_ppns);
462                 return VMCI_ERROR_NO_MEM;
463         }
464
465         for (i = 0; i < num_produce_pages; i++) {
466                 unsigned long pfn;
467
468                 produce_ppns[i] =
469                         produce_q->kernel_if->u.g.pas[i] >> PAGE_SHIFT;
470                 pfn = produce_ppns[i];
471
472                 /* Fail allocation if PFN isn't supported by hypervisor. */
473                 if (sizeof(pfn) > sizeof(*produce_ppns)
474                     && pfn != produce_ppns[i])
475                         goto ppn_error;
476         }
477
478         for (i = 0; i < num_consume_pages; i++) {
479                 unsigned long pfn;
480
481                 consume_ppns[i] =
482                         consume_q->kernel_if->u.g.pas[i] >> PAGE_SHIFT;
483                 pfn = consume_ppns[i];
484
485                 /* Fail allocation if PFN isn't supported by hypervisor. */
486                 if (sizeof(pfn) > sizeof(*consume_ppns)
487                     && pfn != consume_ppns[i])
488                         goto ppn_error;
489         }
490
491         ppn_set->num_produce_pages = num_produce_pages;
492         ppn_set->num_consume_pages = num_consume_pages;
493         ppn_set->produce_ppns = produce_ppns;
494         ppn_set->consume_ppns = consume_ppns;
495         ppn_set->initialized = true;
496         return VMCI_SUCCESS;
497
498  ppn_error:
499         kfree(produce_ppns);
500         kfree(consume_ppns);
501         return VMCI_ERROR_INVALID_ARGS;
502 }
503
504 /*
505  * Frees the two list of PPNs for a queue pair.
506  */
507 static void qp_free_ppn_set(struct ppn_set *ppn_set)
508 {
509         if (ppn_set->initialized) {
510                 /* Do not call these functions on NULL inputs. */
511                 kfree(ppn_set->produce_ppns);
512                 kfree(ppn_set->consume_ppns);
513         }
514         memset(ppn_set, 0, sizeof(*ppn_set));
515 }
516
517 /*
518  * Populates the list of PPNs in the hypercall structure with the PPNS
519  * of the produce queue and the consume queue.
520  */
521 static int qp_populate_ppn_set(u8 *call_buf, const struct ppn_set *ppn_set)
522 {
523         memcpy(call_buf, ppn_set->produce_ppns,
524                ppn_set->num_produce_pages * sizeof(*ppn_set->produce_ppns));
525         memcpy(call_buf +
526                ppn_set->num_produce_pages * sizeof(*ppn_set->produce_ppns),
527                ppn_set->consume_ppns,
528                ppn_set->num_consume_pages * sizeof(*ppn_set->consume_ppns));
529
530         return VMCI_SUCCESS;
531 }
532
533 /*
534  * Allocates kernel VA space of specified size plus space for the queue
535  * and kernel interface.  This is different from the guest queue allocator,
536  * because we do not allocate our own queue header/data pages here but
537  * share those of the guest.
538  */
539 static struct vmci_queue *qp_host_alloc_queue(u64 size)
540 {
541         struct vmci_queue *queue;
542         size_t queue_page_size;
543         u64 num_pages;
544         const size_t queue_size = sizeof(*queue) + sizeof(*(queue->kernel_if));
545
546         if (size > SIZE_MAX - PAGE_SIZE)
547                 return NULL;
548         num_pages = DIV_ROUND_UP(size, PAGE_SIZE) + 1;
549         if (num_pages > (SIZE_MAX - queue_size) /
550                  sizeof(*queue->kernel_if->u.h.page))
551                 return NULL;
552
553         queue_page_size = num_pages * sizeof(*queue->kernel_if->u.h.page);
554
555         if (queue_size + queue_page_size > KMALLOC_MAX_SIZE)
556                 return NULL;
557
558         queue = kzalloc(queue_size + queue_page_size, GFP_KERNEL);
559         if (queue) {
560                 queue->q_header = NULL;
561                 queue->saved_header = NULL;
562                 queue->kernel_if = (struct vmci_queue_kern_if *)(queue + 1);
563                 queue->kernel_if->host = true;
564                 queue->kernel_if->mutex = NULL;
565                 queue->kernel_if->num_pages = num_pages;
566                 queue->kernel_if->u.h.header_page =
567                     (struct page **)((u8 *)queue + queue_size);
568                 queue->kernel_if->u.h.page =
569                         &queue->kernel_if->u.h.header_page[1];
570         }
571
572         return queue;
573 }
574
575 /*
576  * Frees kernel memory for a given queue (header plus translation
577  * structure).
578  */
579 static void qp_host_free_queue(struct vmci_queue *queue, u64 queue_size)
580 {
581         kfree(queue);
582 }
583
584 /*
585  * Initialize the mutex for the pair of queues.  This mutex is used to
586  * protect the q_header and the buffer from changing out from under any
587  * users of either queue.  Of course, it's only any good if the mutexes
588  * are actually acquired.  Queue structure must lie on non-paged memory
589  * or we cannot guarantee access to the mutex.
590  */
591 static void qp_init_queue_mutex(struct vmci_queue *produce_q,
592                                 struct vmci_queue *consume_q)
593 {
594         /*
595          * Only the host queue has shared state - the guest queues do not
596          * need to synchronize access using a queue mutex.
597          */
598
599         if (produce_q->kernel_if->host) {
600                 produce_q->kernel_if->mutex = &produce_q->kernel_if->__mutex;
601                 consume_q->kernel_if->mutex = &produce_q->kernel_if->__mutex;
602                 mutex_init(produce_q->kernel_if->mutex);
603         }
604 }
605
606 /*
607  * Cleans up the mutex for the pair of queues.
608  */
609 static void qp_cleanup_queue_mutex(struct vmci_queue *produce_q,
610                                    struct vmci_queue *consume_q)
611 {
612         if (produce_q->kernel_if->host) {
613                 produce_q->kernel_if->mutex = NULL;
614                 consume_q->kernel_if->mutex = NULL;
615         }
616 }
617
618 /*
619  * Acquire the mutex for the queue.  Note that the produce_q and
620  * the consume_q share a mutex.  So, only one of the two need to
621  * be passed in to this routine.  Either will work just fine.
622  */
623 static void qp_acquire_queue_mutex(struct vmci_queue *queue)
624 {
625         if (queue->kernel_if->host)
626                 mutex_lock(queue->kernel_if->mutex);
627 }
628
629 /*
630  * Release the mutex for the queue.  Note that the produce_q and
631  * the consume_q share a mutex.  So, only one of the two need to
632  * be passed in to this routine.  Either will work just fine.
633  */
634 static void qp_release_queue_mutex(struct vmci_queue *queue)
635 {
636         if (queue->kernel_if->host)
637                 mutex_unlock(queue->kernel_if->mutex);
638 }
639
640 /*
641  * Helper function to release pages in the PageStoreAttachInfo
642  * previously obtained using get_user_pages.
643  */
644 static void qp_release_pages(struct page **pages,
645                              u64 num_pages, bool dirty)
646 {
647         int i;
648
649         for (i = 0; i < num_pages; i++) {
650                 if (dirty)
651                         set_page_dirty_lock(pages[i]);
652
653                 put_page(pages[i]);
654                 pages[i] = NULL;
655         }
656 }
657
658 /*
659  * Lock the user pages referenced by the {produce,consume}Buffer
660  * struct into memory and populate the {produce,consume}Pages
661  * arrays in the attach structure with them.
662  */
663 static int qp_host_get_user_memory(u64 produce_uva,
664                                    u64 consume_uva,
665                                    struct vmci_queue *produce_q,
666                                    struct vmci_queue *consume_q)
667 {
668         int retval;
669         int err = VMCI_SUCCESS;
670
671         retval = get_user_pages_fast((uintptr_t) produce_uva,
672                                      produce_q->kernel_if->num_pages, 1,
673                                      produce_q->kernel_if->u.h.header_page);
674         if (retval < (int)produce_q->kernel_if->num_pages) {
675                 pr_debug("get_user_pages_fast(produce) failed (retval=%d)",
676                         retval);
677                 if (retval > 0)
678                         qp_release_pages(produce_q->kernel_if->u.h.header_page,
679                                         retval, false);
680                 err = VMCI_ERROR_NO_MEM;
681                 goto out;
682         }
683
684         retval = get_user_pages_fast((uintptr_t) consume_uva,
685                                      consume_q->kernel_if->num_pages, 1,
686                                      consume_q->kernel_if->u.h.header_page);
687         if (retval < (int)consume_q->kernel_if->num_pages) {
688                 pr_debug("get_user_pages_fast(consume) failed (retval=%d)",
689                         retval);
690                 if (retval > 0)
691                         qp_release_pages(consume_q->kernel_if->u.h.header_page,
692                                         retval, false);
693                 qp_release_pages(produce_q->kernel_if->u.h.header_page,
694                                  produce_q->kernel_if->num_pages, false);
695                 err = VMCI_ERROR_NO_MEM;
696         }
697
698  out:
699         return err;
700 }
701
702 /*
703  * Registers the specification of the user pages used for backing a queue
704  * pair. Enough information to map in pages is stored in the OS specific
705  * part of the struct vmci_queue structure.
706  */
707 static int qp_host_register_user_memory(struct vmci_qp_page_store *page_store,
708                                         struct vmci_queue *produce_q,
709                                         struct vmci_queue *consume_q)
710 {
711         u64 produce_uva;
712         u64 consume_uva;
713
714         /*
715          * The new style and the old style mapping only differs in
716          * that we either get a single or two UVAs, so we split the
717          * single UVA range at the appropriate spot.
718          */
719         produce_uva = page_store->pages;
720         consume_uva = page_store->pages +
721             produce_q->kernel_if->num_pages * PAGE_SIZE;
722         return qp_host_get_user_memory(produce_uva, consume_uva, produce_q,
723                                        consume_q);
724 }
725
726 /*
727  * Releases and removes the references to user pages stored in the attach
728  * struct.  Pages are released from the page cache and may become
729  * swappable again.
730  */
731 static void qp_host_unregister_user_memory(struct vmci_queue *produce_q,
732                                            struct vmci_queue *consume_q)
733 {
734         qp_release_pages(produce_q->kernel_if->u.h.header_page,
735                          produce_q->kernel_if->num_pages, true);
736         memset(produce_q->kernel_if->u.h.header_page, 0,
737                sizeof(*produce_q->kernel_if->u.h.header_page) *
738                produce_q->kernel_if->num_pages);
739         qp_release_pages(consume_q->kernel_if->u.h.header_page,
740                          consume_q->kernel_if->num_pages, true);
741         memset(consume_q->kernel_if->u.h.header_page, 0,
742                sizeof(*consume_q->kernel_if->u.h.header_page) *
743                consume_q->kernel_if->num_pages);
744 }
745
746 /*
747  * Once qp_host_register_user_memory has been performed on a
748  * queue, the queue pair headers can be mapped into the
749  * kernel. Once mapped, they must be unmapped with
750  * qp_host_unmap_queues prior to calling
751  * qp_host_unregister_user_memory.
752  * Pages are pinned.
753  */
754 static int qp_host_map_queues(struct vmci_queue *produce_q,
755                               struct vmci_queue *consume_q)
756 {
757         int result;
758
759         if (!produce_q->q_header || !consume_q->q_header) {
760                 struct page *headers[2];
761
762                 if (produce_q->q_header != consume_q->q_header)
763                         return VMCI_ERROR_QUEUEPAIR_MISMATCH;
764
765                 if (produce_q->kernel_if->u.h.header_page == NULL ||
766                     *produce_q->kernel_if->u.h.header_page == NULL)
767                         return VMCI_ERROR_UNAVAILABLE;
768
769                 headers[0] = *produce_q->kernel_if->u.h.header_page;
770                 headers[1] = *consume_q->kernel_if->u.h.header_page;
771
772                 produce_q->q_header = vmap(headers, 2, VM_MAP, PAGE_KERNEL);
773                 if (produce_q->q_header != NULL) {
774                         consume_q->q_header =
775                             (struct vmci_queue_header *)((u8 *)
776                                                          produce_q->q_header +
777                                                          PAGE_SIZE);
778                         result = VMCI_SUCCESS;
779                 } else {
780                         pr_warn("vmap failed\n");
781                         result = VMCI_ERROR_NO_MEM;
782                 }
783         } else {
784                 result = VMCI_SUCCESS;
785         }
786
787         return result;
788 }
789
790 /*
791  * Unmaps previously mapped queue pair headers from the kernel.
792  * Pages are unpinned.
793  */
794 static int qp_host_unmap_queues(u32 gid,
795                                 struct vmci_queue *produce_q,
796                                 struct vmci_queue *consume_q)
797 {
798         if (produce_q->q_header) {
799                 if (produce_q->q_header < consume_q->q_header)
800                         vunmap(produce_q->q_header);
801                 else
802                         vunmap(consume_q->q_header);
803
804                 produce_q->q_header = NULL;
805                 consume_q->q_header = NULL;
806         }
807
808         return VMCI_SUCCESS;
809 }
810
811 /*
812  * Finds the entry in the list corresponding to a given handle. Assumes
813  * that the list is locked.
814  */
815 static struct qp_entry *qp_list_find(struct qp_list *qp_list,
816                                      struct vmci_handle handle)
817 {
818         struct qp_entry *entry;
819
820         if (vmci_handle_is_invalid(handle))
821                 return NULL;
822
823         list_for_each_entry(entry, &qp_list->head, list_item) {
824                 if (vmci_handle_is_equal(entry->handle, handle))
825                         return entry;
826         }
827
828         return NULL;
829 }
830
831 /*
832  * Finds the entry in the list corresponding to a given handle.
833  */
834 static struct qp_guest_endpoint *
835 qp_guest_handle_to_entry(struct vmci_handle handle)
836 {
837         struct qp_guest_endpoint *entry;
838         struct qp_entry *qp = qp_list_find(&qp_guest_endpoints, handle);
839
840         entry = qp ? container_of(
841                 qp, struct qp_guest_endpoint, qp) : NULL;
842         return entry;
843 }
844
845 /*
846  * Finds the entry in the list corresponding to a given handle.
847  */
848 static struct qp_broker_entry *
849 qp_broker_handle_to_entry(struct vmci_handle handle)
850 {
851         struct qp_broker_entry *entry;
852         struct qp_entry *qp = qp_list_find(&qp_broker_list, handle);
853
854         entry = qp ? container_of(
855                 qp, struct qp_broker_entry, qp) : NULL;
856         return entry;
857 }
858
859 /*
860  * Dispatches a queue pair event message directly into the local event
861  * queue.
862  */
863 static int qp_notify_peer_local(bool attach, struct vmci_handle handle)
864 {
865         u32 context_id = vmci_get_context_id();
866         struct vmci_event_qp ev;
867
868         ev.msg.hdr.dst = vmci_make_handle(context_id, VMCI_EVENT_HANDLER);
869         ev.msg.hdr.src = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
870                                           VMCI_CONTEXT_RESOURCE_ID);
871         ev.msg.hdr.payload_size = sizeof(ev) - sizeof(ev.msg.hdr);
872         ev.msg.event_data.event =
873             attach ? VMCI_EVENT_QP_PEER_ATTACH : VMCI_EVENT_QP_PEER_DETACH;
874         ev.payload.peer_id = context_id;
875         ev.payload.handle = handle;
876
877         return vmci_event_dispatch(&ev.msg.hdr);
878 }
879
880 /*
881  * Allocates and initializes a qp_guest_endpoint structure.
882  * Allocates a queue_pair rid (and handle) iff the given entry has
883  * an invalid handle.  0 through VMCI_RESERVED_RESOURCE_ID_MAX
884  * are reserved handles.  Assumes that the QP list mutex is held
885  * by the caller.
886  */
887 static struct qp_guest_endpoint *
888 qp_guest_endpoint_create(struct vmci_handle handle,
889                          u32 peer,
890                          u32 flags,
891                          u64 produce_size,
892                          u64 consume_size,
893                          void *produce_q,
894                          void *consume_q)
895 {
896         int result;
897         struct qp_guest_endpoint *entry;
898         /* One page each for the queue headers. */
899         const u64 num_ppns = DIV_ROUND_UP(produce_size, PAGE_SIZE) +
900             DIV_ROUND_UP(consume_size, PAGE_SIZE) + 2;
901
902         if (vmci_handle_is_invalid(handle)) {
903                 u32 context_id = vmci_get_context_id();
904
905                 handle = vmci_make_handle(context_id, VMCI_INVALID_ID);
906         }
907
908         entry = kzalloc(sizeof(*entry), GFP_KERNEL);
909         if (entry) {
910                 entry->qp.peer = peer;
911                 entry->qp.flags = flags;
912                 entry->qp.produce_size = produce_size;
913                 entry->qp.consume_size = consume_size;
914                 entry->qp.ref_count = 0;
915                 entry->num_ppns = num_ppns;
916                 entry->produce_q = produce_q;
917                 entry->consume_q = consume_q;
918                 INIT_LIST_HEAD(&entry->qp.list_item);
919
920                 /* Add resource obj */
921                 result = vmci_resource_add(&entry->resource,
922                                            VMCI_RESOURCE_TYPE_QPAIR_GUEST,
923                                            handle);
924                 entry->qp.handle = vmci_resource_handle(&entry->resource);
925                 if ((result != VMCI_SUCCESS) ||
926                     qp_list_find(&qp_guest_endpoints, entry->qp.handle)) {
927                         pr_warn("Failed to add new resource (handle=0x%x:0x%x), error: %d",
928                                 handle.context, handle.resource, result);
929                         kfree(entry);
930                         entry = NULL;
931                 }
932         }
933         return entry;
934 }
935
936 /*
937  * Frees a qp_guest_endpoint structure.
938  */
939 static void qp_guest_endpoint_destroy(struct qp_guest_endpoint *entry)
940 {
941         qp_free_ppn_set(&entry->ppn_set);
942         qp_cleanup_queue_mutex(entry->produce_q, entry->consume_q);
943         qp_free_queue(entry->produce_q, entry->qp.produce_size);
944         qp_free_queue(entry->consume_q, entry->qp.consume_size);
945         /* Unlink from resource hash table and free callback */
946         vmci_resource_remove(&entry->resource);
947
948         kfree(entry);
949 }
950
951 /*
952  * Helper to make a queue_pairAlloc hypercall when the driver is
953  * supporting a guest device.
954  */
955 static int qp_alloc_hypercall(const struct qp_guest_endpoint *entry)
956 {
957         struct vmci_qp_alloc_msg *alloc_msg;
958         size_t msg_size;
959         int result;
960
961         if (!entry || entry->num_ppns <= 2)
962                 return VMCI_ERROR_INVALID_ARGS;
963
964         msg_size = sizeof(*alloc_msg) +
965             (size_t) entry->num_ppns * sizeof(u32);
966         alloc_msg = kmalloc(msg_size, GFP_KERNEL);
967         if (!alloc_msg)
968                 return VMCI_ERROR_NO_MEM;
969
970         alloc_msg->hdr.dst = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
971                                               VMCI_QUEUEPAIR_ALLOC);
972         alloc_msg->hdr.src = VMCI_ANON_SRC_HANDLE;
973         alloc_msg->hdr.payload_size = msg_size - VMCI_DG_HEADERSIZE;
974         alloc_msg->handle = entry->qp.handle;
975         alloc_msg->peer = entry->qp.peer;
976         alloc_msg->flags = entry->qp.flags;
977         alloc_msg->produce_size = entry->qp.produce_size;
978         alloc_msg->consume_size = entry->qp.consume_size;
979         alloc_msg->num_ppns = entry->num_ppns;
980
981         result = qp_populate_ppn_set((u8 *)alloc_msg + sizeof(*alloc_msg),
982                                      &entry->ppn_set);
983         if (result == VMCI_SUCCESS)
984                 result = vmci_send_datagram(&alloc_msg->hdr);
985
986         kfree(alloc_msg);
987
988         return result;
989 }
990
991 /*
992  * Helper to make a queue_pairDetach hypercall when the driver is
993  * supporting a guest device.
994  */
995 static int qp_detatch_hypercall(struct vmci_handle handle)
996 {
997         struct vmci_qp_detach_msg detach_msg;
998
999         detach_msg.hdr.dst = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
1000                                               VMCI_QUEUEPAIR_DETACH);
1001         detach_msg.hdr.src = VMCI_ANON_SRC_HANDLE;
1002         detach_msg.hdr.payload_size = sizeof(handle);
1003         detach_msg.handle = handle;
1004
1005         return vmci_send_datagram(&detach_msg.hdr);
1006 }
1007
1008 /*
1009  * Adds the given entry to the list. Assumes that the list is locked.
1010  */
1011 static void qp_list_add_entry(struct qp_list *qp_list, struct qp_entry *entry)
1012 {
1013         if (entry)
1014                 list_add(&entry->list_item, &qp_list->head);
1015 }
1016
1017 /*
1018  * Removes the given entry from the list. Assumes that the list is locked.
1019  */
1020 static void qp_list_remove_entry(struct qp_list *qp_list,
1021                                  struct qp_entry *entry)
1022 {
1023         if (entry)
1024                 list_del(&entry->list_item);
1025 }
1026
1027 /*
1028  * Helper for VMCI queue_pair detach interface. Frees the physical
1029  * pages for the queue pair.
1030  */
1031 static int qp_detatch_guest_work(struct vmci_handle handle)
1032 {
1033         int result;
1034         struct qp_guest_endpoint *entry;
1035         u32 ref_count = ~0;     /* To avoid compiler warning below */
1036
1037         mutex_lock(&qp_guest_endpoints.mutex);
1038
1039         entry = qp_guest_handle_to_entry(handle);
1040         if (!entry) {
1041                 mutex_unlock(&qp_guest_endpoints.mutex);
1042                 return VMCI_ERROR_NOT_FOUND;
1043         }
1044
1045         if (entry->qp.flags & VMCI_QPFLAG_LOCAL) {
1046                 result = VMCI_SUCCESS;
1047
1048                 if (entry->qp.ref_count > 1) {
1049                         result = qp_notify_peer_local(false, handle);
1050                         /*
1051                          * We can fail to notify a local queuepair
1052                          * because we can't allocate.  We still want
1053                          * to release the entry if that happens, so
1054                          * don't bail out yet.
1055                          */
1056                 }
1057         } else {
1058                 result = qp_detatch_hypercall(handle);
1059                 if (result < VMCI_SUCCESS) {
1060                         /*
1061                          * We failed to notify a non-local queuepair.
1062                          * That other queuepair might still be
1063                          * accessing the shared memory, so don't
1064                          * release the entry yet.  It will get cleaned
1065                          * up by VMCIqueue_pair_Exit() if necessary
1066                          * (assuming we are going away, otherwise why
1067                          * did this fail?).
1068                          */
1069
1070                         mutex_unlock(&qp_guest_endpoints.mutex);
1071                         return result;
1072                 }
1073         }
1074
1075         /*
1076          * If we get here then we either failed to notify a local queuepair, or
1077          * we succeeded in all cases.  Release the entry if required.
1078          */
1079
1080         entry->qp.ref_count--;
1081         if (entry->qp.ref_count == 0)
1082                 qp_list_remove_entry(&qp_guest_endpoints, &entry->qp);
1083
1084         /* If we didn't remove the entry, this could change once we unlock. */
1085         if (entry)
1086                 ref_count = entry->qp.ref_count;
1087
1088         mutex_unlock(&qp_guest_endpoints.mutex);
1089
1090         if (ref_count == 0)
1091                 qp_guest_endpoint_destroy(entry);
1092
1093         return result;
1094 }
1095
1096 /*
1097  * This functions handles the actual allocation of a VMCI queue
1098  * pair guest endpoint. Allocates physical pages for the queue
1099  * pair. It makes OS dependent calls through generic wrappers.
1100  */
1101 static int qp_alloc_guest_work(struct vmci_handle *handle,
1102                                struct vmci_queue **produce_q,
1103                                u64 produce_size,
1104                                struct vmci_queue **consume_q,
1105                                u64 consume_size,
1106                                u32 peer,
1107                                u32 flags,
1108                                u32 priv_flags)
1109 {
1110         const u64 num_produce_pages =
1111             DIV_ROUND_UP(produce_size, PAGE_SIZE) + 1;
1112         const u64 num_consume_pages =
1113             DIV_ROUND_UP(consume_size, PAGE_SIZE) + 1;
1114         void *my_produce_q = NULL;
1115         void *my_consume_q = NULL;
1116         int result;
1117         struct qp_guest_endpoint *queue_pair_entry = NULL;
1118
1119         if (priv_flags != VMCI_NO_PRIVILEGE_FLAGS)
1120                 return VMCI_ERROR_NO_ACCESS;
1121
1122         mutex_lock(&qp_guest_endpoints.mutex);
1123
1124         queue_pair_entry = qp_guest_handle_to_entry(*handle);
1125         if (queue_pair_entry) {
1126                 if (queue_pair_entry->qp.flags & VMCI_QPFLAG_LOCAL) {
1127                         /* Local attach case. */
1128                         if (queue_pair_entry->qp.ref_count > 1) {
1129                                 pr_devel("Error attempting to attach more than once\n");
1130                                 result = VMCI_ERROR_UNAVAILABLE;
1131                                 goto error_keep_entry;
1132                         }
1133
1134                         if (queue_pair_entry->qp.produce_size != consume_size ||
1135                             queue_pair_entry->qp.consume_size !=
1136                             produce_size ||
1137                             queue_pair_entry->qp.flags !=
1138                             (flags & ~VMCI_QPFLAG_ATTACH_ONLY)) {
1139                                 pr_devel("Error mismatched queue pair in local attach\n");
1140                                 result = VMCI_ERROR_QUEUEPAIR_MISMATCH;
1141                                 goto error_keep_entry;
1142                         }
1143
1144                         /*
1145                          * Do a local attach.  We swap the consume and
1146                          * produce queues for the attacher and deliver
1147                          * an attach event.
1148                          */
1149                         result = qp_notify_peer_local(true, *handle);
1150                         if (result < VMCI_SUCCESS)
1151                                 goto error_keep_entry;
1152
1153                         my_produce_q = queue_pair_entry->consume_q;
1154                         my_consume_q = queue_pair_entry->produce_q;
1155                         goto out;
1156                 }
1157
1158                 result = VMCI_ERROR_ALREADY_EXISTS;
1159                 goto error_keep_entry;
1160         }
1161
1162         my_produce_q = qp_alloc_queue(produce_size, flags);
1163         if (!my_produce_q) {
1164                 pr_warn("Error allocating pages for produce queue\n");
1165                 result = VMCI_ERROR_NO_MEM;
1166                 goto error;
1167         }
1168
1169         my_consume_q = qp_alloc_queue(consume_size, flags);
1170         if (!my_consume_q) {
1171                 pr_warn("Error allocating pages for consume queue\n");
1172                 result = VMCI_ERROR_NO_MEM;
1173                 goto error;
1174         }
1175
1176         queue_pair_entry = qp_guest_endpoint_create(*handle, peer, flags,
1177                                                     produce_size, consume_size,
1178                                                     my_produce_q, my_consume_q);
1179         if (!queue_pair_entry) {
1180                 pr_warn("Error allocating memory in %s\n", __func__);
1181                 result = VMCI_ERROR_NO_MEM;
1182                 goto error;
1183         }
1184
1185         result = qp_alloc_ppn_set(my_produce_q, num_produce_pages, my_consume_q,
1186                                   num_consume_pages,
1187                                   &queue_pair_entry->ppn_set);
1188         if (result < VMCI_SUCCESS) {
1189                 pr_warn("qp_alloc_ppn_set failed\n");
1190                 goto error;
1191         }
1192
1193         /*
1194          * It's only necessary to notify the host if this queue pair will be
1195          * attached to from another context.
1196          */
1197         if (queue_pair_entry->qp.flags & VMCI_QPFLAG_LOCAL) {
1198                 /* Local create case. */
1199                 u32 context_id = vmci_get_context_id();
1200
1201                 /*
1202                  * Enforce similar checks on local queue pairs as we
1203                  * do for regular ones.  The handle's context must
1204                  * match the creator or attacher context id (here they
1205                  * are both the current context id) and the
1206                  * attach-only flag cannot exist during create.  We
1207                  * also ensure specified peer is this context or an
1208                  * invalid one.
1209                  */
1210                 if (queue_pair_entry->qp.handle.context != context_id ||
1211                     (queue_pair_entry->qp.peer != VMCI_INVALID_ID &&
1212                      queue_pair_entry->qp.peer != context_id)) {
1213                         result = VMCI_ERROR_NO_ACCESS;
1214                         goto error;
1215                 }
1216
1217                 if (queue_pair_entry->qp.flags & VMCI_QPFLAG_ATTACH_ONLY) {
1218                         result = VMCI_ERROR_NOT_FOUND;
1219                         goto error;
1220                 }
1221         } else {
1222                 result = qp_alloc_hypercall(queue_pair_entry);
1223                 if (result < VMCI_SUCCESS) {
1224                         pr_warn("qp_alloc_hypercall result = %d\n", result);
1225                         goto error;
1226                 }
1227         }
1228
1229         qp_init_queue_mutex((struct vmci_queue *)my_produce_q,
1230                             (struct vmci_queue *)my_consume_q);
1231
1232         qp_list_add_entry(&qp_guest_endpoints, &queue_pair_entry->qp);
1233
1234  out:
1235         queue_pair_entry->qp.ref_count++;
1236         *handle = queue_pair_entry->qp.handle;
1237         *produce_q = (struct vmci_queue *)my_produce_q;
1238         *consume_q = (struct vmci_queue *)my_consume_q;
1239
1240         /*
1241          * We should initialize the queue pair header pages on a local
1242          * queue pair create.  For non-local queue pairs, the
1243          * hypervisor initializes the header pages in the create step.
1244          */
1245         if ((queue_pair_entry->qp.flags & VMCI_QPFLAG_LOCAL) &&
1246             queue_pair_entry->qp.ref_count == 1) {
1247                 vmci_q_header_init((*produce_q)->q_header, *handle);
1248                 vmci_q_header_init((*consume_q)->q_header, *handle);
1249         }
1250
1251         mutex_unlock(&qp_guest_endpoints.mutex);
1252
1253         return VMCI_SUCCESS;
1254
1255  error:
1256         mutex_unlock(&qp_guest_endpoints.mutex);
1257         if (queue_pair_entry) {
1258                 /* The queues will be freed inside the destroy routine. */
1259                 qp_guest_endpoint_destroy(queue_pair_entry);
1260         } else {
1261                 qp_free_queue(my_produce_q, produce_size);
1262                 qp_free_queue(my_consume_q, consume_size);
1263         }
1264         return result;
1265
1266  error_keep_entry:
1267         /* This path should only be used when an existing entry was found. */
1268         mutex_unlock(&qp_guest_endpoints.mutex);
1269         return result;
1270 }
1271
1272 /*
1273  * The first endpoint issuing a queue pair allocation will create the state
1274  * of the queue pair in the queue pair broker.
1275  *
1276  * If the creator is a guest, it will associate a VMX virtual address range
1277  * with the queue pair as specified by the page_store. For compatibility with
1278  * older VMX'en, that would use a separate step to set the VMX virtual
1279  * address range, the virtual address range can be registered later using
1280  * vmci_qp_broker_set_page_store. In that case, a page_store of NULL should be
1281  * used.
1282  *
1283  * If the creator is the host, a page_store of NULL should be used as well,
1284  * since the host is not able to supply a page store for the queue pair.
1285  *
1286  * For older VMX and host callers, the queue pair will be created in the
1287  * VMCIQPB_CREATED_NO_MEM state, and for current VMX callers, it will be
1288  * created in VMCOQPB_CREATED_MEM state.
1289  */
1290 static int qp_broker_create(struct vmci_handle handle,
1291                             u32 peer,
1292                             u32 flags,
1293                             u32 priv_flags,
1294                             u64 produce_size,
1295                             u64 consume_size,
1296                             struct vmci_qp_page_store *page_store,
1297                             struct vmci_ctx *context,
1298                             vmci_event_release_cb wakeup_cb,
1299                             void *client_data, struct qp_broker_entry **ent)
1300 {
1301         struct qp_broker_entry *entry = NULL;
1302         const u32 context_id = vmci_ctx_get_id(context);
1303         bool is_local = flags & VMCI_QPFLAG_LOCAL;
1304         int result;
1305         u64 guest_produce_size;
1306         u64 guest_consume_size;
1307
1308         /* Do not create if the caller asked not to. */
1309         if (flags & VMCI_QPFLAG_ATTACH_ONLY)
1310                 return VMCI_ERROR_NOT_FOUND;
1311
1312         /*
1313          * Creator's context ID should match handle's context ID or the creator
1314          * must allow the context in handle's context ID as the "peer".
1315          */
1316         if (handle.context != context_id && handle.context != peer)
1317                 return VMCI_ERROR_NO_ACCESS;
1318
1319         if (VMCI_CONTEXT_IS_VM(context_id) && VMCI_CONTEXT_IS_VM(peer))
1320                 return VMCI_ERROR_DST_UNREACHABLE;
1321
1322         /*
1323          * Creator's context ID for local queue pairs should match the
1324          * peer, if a peer is specified.
1325          */
1326         if (is_local && peer != VMCI_INVALID_ID && context_id != peer)
1327                 return VMCI_ERROR_NO_ACCESS;
1328
1329         entry = kzalloc(sizeof(*entry), GFP_ATOMIC);
1330         if (!entry)
1331                 return VMCI_ERROR_NO_MEM;
1332
1333         if (vmci_ctx_get_id(context) == VMCI_HOST_CONTEXT_ID && !is_local) {
1334                 /*
1335                  * The queue pair broker entry stores values from the guest
1336                  * point of view, so a creating host side endpoint should swap
1337                  * produce and consume values -- unless it is a local queue
1338                  * pair, in which case no swapping is necessary, since the local
1339                  * attacher will swap queues.
1340                  */
1341
1342                 guest_produce_size = consume_size;
1343                 guest_consume_size = produce_size;
1344         } else {
1345                 guest_produce_size = produce_size;
1346                 guest_consume_size = consume_size;
1347         }
1348
1349         entry->qp.handle = handle;
1350         entry->qp.peer = peer;
1351         entry->qp.flags = flags;
1352         entry->qp.produce_size = guest_produce_size;
1353         entry->qp.consume_size = guest_consume_size;
1354         entry->qp.ref_count = 1;
1355         entry->create_id = context_id;
1356         entry->attach_id = VMCI_INVALID_ID;
1357         entry->state = VMCIQPB_NEW;
1358         entry->require_trusted_attach =
1359             !!(context->priv_flags & VMCI_PRIVILEGE_FLAG_RESTRICTED);
1360         entry->created_by_trusted =
1361             !!(priv_flags & VMCI_PRIVILEGE_FLAG_TRUSTED);
1362         entry->vmci_page_files = false;
1363         entry->wakeup_cb = wakeup_cb;
1364         entry->client_data = client_data;
1365         entry->produce_q = qp_host_alloc_queue(guest_produce_size);
1366         if (entry->produce_q == NULL) {
1367                 result = VMCI_ERROR_NO_MEM;
1368                 goto error;
1369         }
1370         entry->consume_q = qp_host_alloc_queue(guest_consume_size);
1371         if (entry->consume_q == NULL) {
1372                 result = VMCI_ERROR_NO_MEM;
1373                 goto error;
1374         }
1375
1376         qp_init_queue_mutex(entry->produce_q, entry->consume_q);
1377
1378         INIT_LIST_HEAD(&entry->qp.list_item);
1379
1380         if (is_local) {
1381                 u8 *tmp;
1382
1383                 entry->local_mem = kcalloc(QPE_NUM_PAGES(entry->qp),
1384                                            PAGE_SIZE, GFP_KERNEL);
1385                 if (entry->local_mem == NULL) {
1386                         result = VMCI_ERROR_NO_MEM;
1387                         goto error;
1388                 }
1389                 entry->state = VMCIQPB_CREATED_MEM;
1390                 entry->produce_q->q_header = entry->local_mem;
1391                 tmp = (u8 *)entry->local_mem + PAGE_SIZE *
1392                     (DIV_ROUND_UP(entry->qp.produce_size, PAGE_SIZE) + 1);
1393                 entry->consume_q->q_header = (struct vmci_queue_header *)tmp;
1394         } else if (page_store) {
1395                 /*
1396                  * The VMX already initialized the queue pair headers, so no
1397                  * need for the kernel side to do that.
1398                  */
1399                 result = qp_host_register_user_memory(page_store,
1400                                                       entry->produce_q,
1401                                                       entry->consume_q);
1402                 if (result < VMCI_SUCCESS)
1403                         goto error;
1404
1405                 entry->state = VMCIQPB_CREATED_MEM;
1406         } else {
1407                 /*
1408                  * A create without a page_store may be either a host
1409                  * side create (in which case we are waiting for the
1410                  * guest side to supply the memory) or an old style
1411                  * queue pair create (in which case we will expect a
1412                  * set page store call as the next step).
1413                  */
1414                 entry->state = VMCIQPB_CREATED_NO_MEM;
1415         }
1416
1417         qp_list_add_entry(&qp_broker_list, &entry->qp);
1418         if (ent != NULL)
1419                 *ent = entry;
1420
1421         /* Add to resource obj */
1422         result = vmci_resource_add(&entry->resource,
1423                                    VMCI_RESOURCE_TYPE_QPAIR_HOST,
1424                                    handle);
1425         if (result != VMCI_SUCCESS) {
1426                 pr_warn("Failed to add new resource (handle=0x%x:0x%x), error: %d",
1427                         handle.context, handle.resource, result);
1428                 goto error;
1429         }
1430
1431         entry->qp.handle = vmci_resource_handle(&entry->resource);
1432         if (is_local) {
1433                 vmci_q_header_init(entry->produce_q->q_header,
1434                                    entry->qp.handle);
1435                 vmci_q_header_init(entry->consume_q->q_header,
1436                                    entry->qp.handle);
1437         }
1438
1439         vmci_ctx_qp_create(context, entry->qp.handle);
1440
1441         return VMCI_SUCCESS;
1442
1443  error:
1444         if (entry != NULL) {
1445                 qp_host_free_queue(entry->produce_q, guest_produce_size);
1446                 qp_host_free_queue(entry->consume_q, guest_consume_size);
1447                 kfree(entry);
1448         }
1449
1450         return result;
1451 }
1452
1453 /*
1454  * Enqueues an event datagram to notify the peer VM attached to
1455  * the given queue pair handle about attach/detach event by the
1456  * given VM.  Returns Payload size of datagram enqueued on
1457  * success, error code otherwise.
1458  */
1459 static int qp_notify_peer(bool attach,
1460                           struct vmci_handle handle,
1461                           u32 my_id,
1462                           u32 peer_id)
1463 {
1464         int rv;
1465         struct vmci_event_qp ev;
1466
1467         if (vmci_handle_is_invalid(handle) || my_id == VMCI_INVALID_ID ||
1468             peer_id == VMCI_INVALID_ID)
1469                 return VMCI_ERROR_INVALID_ARGS;
1470
1471         /*
1472          * In vmci_ctx_enqueue_datagram() we enforce the upper limit on
1473          * number of pending events from the hypervisor to a given VM
1474          * otherwise a rogue VM could do an arbitrary number of attach
1475          * and detach operations causing memory pressure in the host
1476          * kernel.
1477          */
1478
1479         ev.msg.hdr.dst = vmci_make_handle(peer_id, VMCI_EVENT_HANDLER);
1480         ev.msg.hdr.src = vmci_make_handle(VMCI_HYPERVISOR_CONTEXT_ID,
1481                                           VMCI_CONTEXT_RESOURCE_ID);
1482         ev.msg.hdr.payload_size = sizeof(ev) - sizeof(ev.msg.hdr);
1483         ev.msg.event_data.event = attach ?
1484             VMCI_EVENT_QP_PEER_ATTACH : VMCI_EVENT_QP_PEER_DETACH;
1485         ev.payload.handle = handle;
1486         ev.payload.peer_id = my_id;
1487
1488         rv = vmci_datagram_dispatch(VMCI_HYPERVISOR_CONTEXT_ID,
1489                                     &ev.msg.hdr, false);
1490         if (rv < VMCI_SUCCESS)
1491                 pr_warn("Failed to enqueue queue_pair %s event datagram for context (ID=0x%x)\n",
1492                         attach ? "ATTACH" : "DETACH", peer_id);
1493
1494         return rv;
1495 }
1496
1497 /*
1498  * The second endpoint issuing a queue pair allocation will attach to
1499  * the queue pair registered with the queue pair broker.
1500  *
1501  * If the attacher is a guest, it will associate a VMX virtual address
1502  * range with the queue pair as specified by the page_store. At this
1503  * point, the already attach host endpoint may start using the queue
1504  * pair, and an attach event is sent to it. For compatibility with
1505  * older VMX'en, that used a separate step to set the VMX virtual
1506  * address range, the virtual address range can be registered later
1507  * using vmci_qp_broker_set_page_store. In that case, a page_store of
1508  * NULL should be used, and the attach event will be generated once
1509  * the actual page store has been set.
1510  *
1511  * If the attacher is the host, a page_store of NULL should be used as
1512  * well, since the page store information is already set by the guest.
1513  *
1514  * For new VMX and host callers, the queue pair will be moved to the
1515  * VMCIQPB_ATTACHED_MEM state, and for older VMX callers, it will be
1516  * moved to the VMCOQPB_ATTACHED_NO_MEM state.
1517  */
1518 static int qp_broker_attach(struct qp_broker_entry *entry,
1519                             u32 peer,
1520                             u32 flags,
1521                             u32 priv_flags,
1522                             u64 produce_size,
1523                             u64 consume_size,
1524                             struct vmci_qp_page_store *page_store,
1525                             struct vmci_ctx *context,
1526                             vmci_event_release_cb wakeup_cb,
1527                             void *client_data,
1528                             struct qp_broker_entry **ent)
1529 {
1530         const u32 context_id = vmci_ctx_get_id(context);
1531         bool is_local = flags & VMCI_QPFLAG_LOCAL;
1532         int result;
1533
1534         if (entry->state != VMCIQPB_CREATED_NO_MEM &&
1535             entry->state != VMCIQPB_CREATED_MEM)
1536                 return VMCI_ERROR_UNAVAILABLE;
1537
1538         if (is_local) {
1539                 if (!(entry->qp.flags & VMCI_QPFLAG_LOCAL) ||
1540                     context_id != entry->create_id) {
1541                         return VMCI_ERROR_INVALID_ARGS;
1542                 }
1543         } else if (context_id == entry->create_id ||
1544                    context_id == entry->attach_id) {
1545                 return VMCI_ERROR_ALREADY_EXISTS;
1546         }
1547
1548         if (VMCI_CONTEXT_IS_VM(context_id) &&
1549             VMCI_CONTEXT_IS_VM(entry->create_id))
1550                 return VMCI_ERROR_DST_UNREACHABLE;
1551
1552         /*
1553          * If we are attaching from a restricted context then the queuepair
1554          * must have been created by a trusted endpoint.
1555          */
1556         if ((context->priv_flags & VMCI_PRIVILEGE_FLAG_RESTRICTED) &&
1557             !entry->created_by_trusted)
1558                 return VMCI_ERROR_NO_ACCESS;
1559
1560         /*
1561          * If we are attaching to a queuepair that was created by a restricted
1562          * context then we must be trusted.
1563          */
1564         if (entry->require_trusted_attach &&
1565             (!(priv_flags & VMCI_PRIVILEGE_FLAG_TRUSTED)))
1566                 return VMCI_ERROR_NO_ACCESS;
1567
1568         /*
1569          * If the creator specifies VMCI_INVALID_ID in "peer" field, access
1570          * control check is not performed.
1571          */
1572         if (entry->qp.peer != VMCI_INVALID_ID && entry->qp.peer != context_id)
1573                 return VMCI_ERROR_NO_ACCESS;
1574
1575         if (entry->create_id == VMCI_HOST_CONTEXT_ID) {
1576                 /*
1577                  * Do not attach if the caller doesn't support Host Queue Pairs
1578                  * and a host created this queue pair.
1579                  */
1580
1581                 if (!vmci_ctx_supports_host_qp(context))
1582                         return VMCI_ERROR_INVALID_RESOURCE;
1583
1584         } else if (context_id == VMCI_HOST_CONTEXT_ID) {
1585                 struct vmci_ctx *create_context;
1586                 bool supports_host_qp;
1587
1588                 /*
1589                  * Do not attach a host to a user created queue pair if that
1590                  * user doesn't support host queue pair end points.
1591                  */
1592
1593                 create_context = vmci_ctx_get(entry->create_id);
1594                 supports_host_qp = vmci_ctx_supports_host_qp(create_context);
1595                 vmci_ctx_put(create_context);
1596
1597                 if (!supports_host_qp)
1598                         return VMCI_ERROR_INVALID_RESOURCE;
1599         }
1600
1601         if ((entry->qp.flags & ~VMCI_QP_ASYMM) != (flags & ~VMCI_QP_ASYMM_PEER))
1602                 return VMCI_ERROR_QUEUEPAIR_MISMATCH;
1603
1604         if (context_id != VMCI_HOST_CONTEXT_ID) {
1605                 /*
1606                  * The queue pair broker entry stores values from the guest
1607                  * point of view, so an attaching guest should match the values
1608                  * stored in the entry.
1609                  */
1610
1611                 if (entry->qp.produce_size != produce_size ||
1612                     entry->qp.consume_size != consume_size) {
1613                         return VMCI_ERROR_QUEUEPAIR_MISMATCH;
1614                 }
1615         } else if (entry->qp.produce_size != consume_size ||
1616                    entry->qp.consume_size != produce_size) {
1617                 return VMCI_ERROR_QUEUEPAIR_MISMATCH;
1618         }
1619
1620         if (context_id != VMCI_HOST_CONTEXT_ID) {
1621                 /*
1622                  * If a guest attached to a queue pair, it will supply
1623                  * the backing memory.  If this is a pre NOVMVM vmx,
1624                  * the backing memory will be supplied by calling
1625                  * vmci_qp_broker_set_page_store() following the
1626                  * return of the vmci_qp_broker_alloc() call. If it is
1627                  * a vmx of version NOVMVM or later, the page store
1628                  * must be supplied as part of the
1629                  * vmci_qp_broker_alloc call.  Under all circumstances
1630                  * must the initially created queue pair not have any
1631                  * memory associated with it already.
1632                  */
1633
1634                 if (entry->state != VMCIQPB_CREATED_NO_MEM)
1635                         return VMCI_ERROR_INVALID_ARGS;
1636
1637                 if (page_store != NULL) {
1638                         /*
1639                          * Patch up host state to point to guest
1640                          * supplied memory. The VMX already
1641                          * initialized the queue pair headers, so no
1642                          * need for the kernel side to do that.
1643                          */
1644
1645                         result = qp_host_register_user_memory(page_store,
1646                                                               entry->produce_q,
1647                                                               entry->consume_q);
1648                         if (result < VMCI_SUCCESS)
1649                                 return result;
1650
1651                         entry->state = VMCIQPB_ATTACHED_MEM;
1652                 } else {
1653                         entry->state = VMCIQPB_ATTACHED_NO_MEM;
1654                 }
1655         } else if (entry->state == VMCIQPB_CREATED_NO_MEM) {
1656                 /*
1657                  * The host side is attempting to attach to a queue
1658                  * pair that doesn't have any memory associated with
1659                  * it. This must be a pre NOVMVM vmx that hasn't set
1660                  * the page store information yet, or a quiesced VM.
1661                  */
1662
1663                 return VMCI_ERROR_UNAVAILABLE;
1664         } else {
1665                 /* The host side has successfully attached to a queue pair. */
1666                 entry->state = VMCIQPB_ATTACHED_MEM;
1667         }
1668
1669         if (entry->state == VMCIQPB_ATTACHED_MEM) {
1670                 result =
1671                     qp_notify_peer(true, entry->qp.handle, context_id,
1672                                    entry->create_id);
1673                 if (result < VMCI_SUCCESS)
1674                         pr_warn("Failed to notify peer (ID=0x%x) of attach to queue pair (handle=0x%x:0x%x)\n",
1675                                 entry->create_id, entry->qp.handle.context,
1676                                 entry->qp.handle.resource);
1677         }
1678
1679         entry->attach_id = context_id;
1680         entry->qp.ref_count++;
1681         if (wakeup_cb) {
1682                 entry->wakeup_cb = wakeup_cb;
1683                 entry->client_data = client_data;
1684         }
1685
1686         /*
1687          * When attaching to local queue pairs, the context already has
1688          * an entry tracking the queue pair, so don't add another one.
1689          */
1690         if (!is_local)
1691                 vmci_ctx_qp_create(context, entry->qp.handle);
1692
1693         if (ent != NULL)
1694                 *ent = entry;
1695
1696         return VMCI_SUCCESS;
1697 }
1698
1699 /*
1700  * queue_pair_Alloc for use when setting up queue pair endpoints
1701  * on the host.
1702  */
1703 static int qp_broker_alloc(struct vmci_handle handle,
1704                            u32 peer,
1705                            u32 flags,
1706                            u32 priv_flags,
1707                            u64 produce_size,
1708                            u64 consume_size,
1709                            struct vmci_qp_page_store *page_store,
1710                            struct vmci_ctx *context,
1711                            vmci_event_release_cb wakeup_cb,
1712                            void *client_data,
1713                            struct qp_broker_entry **ent,
1714                            bool *swap)
1715 {
1716         const u32 context_id = vmci_ctx_get_id(context);
1717         bool create;
1718         struct qp_broker_entry *entry = NULL;
1719         bool is_local = flags & VMCI_QPFLAG_LOCAL;
1720         int result;
1721
1722         if (vmci_handle_is_invalid(handle) ||
1723             (flags & ~VMCI_QP_ALL_FLAGS) || is_local ||
1724             !(produce_size || consume_size) ||
1725             !context || context_id == VMCI_INVALID_ID ||
1726             handle.context == VMCI_INVALID_ID) {
1727                 return VMCI_ERROR_INVALID_ARGS;
1728         }
1729
1730         if (page_store && !VMCI_QP_PAGESTORE_IS_WELLFORMED(page_store))
1731                 return VMCI_ERROR_INVALID_ARGS;
1732
1733         /*
1734          * In the initial argument check, we ensure that non-vmkernel hosts
1735          * are not allowed to create local queue pairs.
1736          */
1737
1738         mutex_lock(&qp_broker_list.mutex);
1739
1740         if (!is_local && vmci_ctx_qp_exists(context, handle)) {
1741                 pr_devel("Context (ID=0x%x) already attached to queue pair (handle=0x%x:0x%x)\n",
1742                          context_id, handle.context, handle.resource);
1743                 mutex_unlock(&qp_broker_list.mutex);
1744                 return VMCI_ERROR_ALREADY_EXISTS;
1745         }
1746
1747         if (handle.resource != VMCI_INVALID_ID)
1748                 entry = qp_broker_handle_to_entry(handle);
1749
1750         if (!entry) {
1751                 create = true;
1752                 result =
1753                     qp_broker_create(handle, peer, flags, priv_flags,
1754                                      produce_size, consume_size, page_store,
1755                                      context, wakeup_cb, client_data, ent);
1756         } else {
1757                 create = false;
1758                 result =
1759                     qp_broker_attach(entry, peer, flags, priv_flags,
1760                                      produce_size, consume_size, page_store,
1761                                      context, wakeup_cb, client_data, ent);
1762         }
1763
1764         mutex_unlock(&qp_broker_list.mutex);
1765
1766         if (swap)
1767                 *swap = (context_id == VMCI_HOST_CONTEXT_ID) &&
1768                     !(create && is_local);
1769
1770         return result;
1771 }
1772
1773 /*
1774  * This function implements the kernel API for allocating a queue
1775  * pair.
1776  */
1777 static int qp_alloc_host_work(struct vmci_handle *handle,
1778                               struct vmci_queue **produce_q,
1779                               u64 produce_size,
1780                               struct vmci_queue **consume_q,
1781                               u64 consume_size,
1782                               u32 peer,
1783                               u32 flags,
1784                               u32 priv_flags,
1785                               vmci_event_release_cb wakeup_cb,
1786                               void *client_data)
1787 {
1788         struct vmci_handle new_handle;
1789         struct vmci_ctx *context;
1790         struct qp_broker_entry *entry;
1791         int result;
1792         bool swap;
1793
1794         if (vmci_handle_is_invalid(*handle)) {
1795                 new_handle = vmci_make_handle(
1796                         VMCI_HOST_CONTEXT_ID, VMCI_INVALID_ID);
1797         } else
1798                 new_handle = *handle;
1799
1800         context = vmci_ctx_get(VMCI_HOST_CONTEXT_ID);
1801         entry = NULL;
1802         result =
1803             qp_broker_alloc(new_handle, peer, flags, priv_flags,
1804                             produce_size, consume_size, NULL, context,
1805                             wakeup_cb, client_data, &entry, &swap);
1806         if (result == VMCI_SUCCESS) {
1807                 if (swap) {
1808                         /*
1809                          * If this is a local queue pair, the attacher
1810                          * will swap around produce and consume
1811                          * queues.
1812                          */
1813
1814                         *produce_q = entry->consume_q;
1815                         *consume_q = entry->produce_q;
1816                 } else {
1817                         *produce_q = entry->produce_q;
1818                         *consume_q = entry->consume_q;
1819                 }
1820
1821                 *handle = vmci_resource_handle(&entry->resource);
1822         } else {
1823                 *handle = VMCI_INVALID_HANDLE;
1824                 pr_devel("queue pair broker failed to alloc (result=%d)\n",
1825                          result);
1826         }
1827         vmci_ctx_put(context);
1828         return result;
1829 }
1830
1831 /*
1832  * Allocates a VMCI queue_pair. Only checks validity of input
1833  * arguments. The real work is done in the host or guest
1834  * specific function.
1835  */
1836 int vmci_qp_alloc(struct vmci_handle *handle,
1837                   struct vmci_queue **produce_q,
1838                   u64 produce_size,
1839                   struct vmci_queue **consume_q,
1840                   u64 consume_size,
1841                   u32 peer,
1842                   u32 flags,
1843                   u32 priv_flags,
1844                   bool guest_endpoint,
1845                   vmci_event_release_cb wakeup_cb,
1846                   void *client_data)
1847 {
1848         if (!handle || !produce_q || !consume_q ||
1849             (!produce_size && !consume_size) || (flags & ~VMCI_QP_ALL_FLAGS))
1850                 return VMCI_ERROR_INVALID_ARGS;
1851
1852         if (guest_endpoint) {
1853                 return qp_alloc_guest_work(handle, produce_q,
1854                                            produce_size, consume_q,
1855                                            consume_size, peer,
1856                                            flags, priv_flags);
1857         } else {
1858                 return qp_alloc_host_work(handle, produce_q,
1859                                           produce_size, consume_q,
1860                                           consume_size, peer, flags,
1861                                           priv_flags, wakeup_cb, client_data);
1862         }
1863 }
1864
1865 /*
1866  * This function implements the host kernel API for detaching from
1867  * a queue pair.
1868  */
1869 static int qp_detatch_host_work(struct vmci_handle handle)
1870 {
1871         int result;
1872         struct vmci_ctx *context;
1873
1874         context = vmci_ctx_get(VMCI_HOST_CONTEXT_ID);
1875
1876         result = vmci_qp_broker_detach(handle, context);
1877
1878         vmci_ctx_put(context);
1879         return result;
1880 }
1881
1882 /*
1883  * Detaches from a VMCI queue_pair. Only checks validity of input argument.
1884  * Real work is done in the host or guest specific function.
1885  */
1886 static int qp_detatch(struct vmci_handle handle, bool guest_endpoint)
1887 {
1888         if (vmci_handle_is_invalid(handle))
1889                 return VMCI_ERROR_INVALID_ARGS;
1890
1891         if (guest_endpoint)
1892                 return qp_detatch_guest_work(handle);
1893         else
1894                 return qp_detatch_host_work(handle);
1895 }
1896
1897 /*
1898  * Returns the entry from the head of the list. Assumes that the list is
1899  * locked.
1900  */
1901 static struct qp_entry *qp_list_get_head(struct qp_list *qp_list)
1902 {
1903         if (!list_empty(&qp_list->head)) {
1904                 struct qp_entry *entry =
1905                     list_first_entry(&qp_list->head, struct qp_entry,
1906                                      list_item);
1907                 return entry;
1908         }
1909
1910         return NULL;
1911 }
1912
1913 void vmci_qp_broker_exit(void)
1914 {
1915         struct qp_entry *entry;
1916         struct qp_broker_entry *be;
1917
1918         mutex_lock(&qp_broker_list.mutex);
1919
1920         while ((entry = qp_list_get_head(&qp_broker_list))) {
1921                 be = (struct qp_broker_entry *)entry;
1922
1923                 qp_list_remove_entry(&qp_broker_list, entry);
1924                 kfree(be);
1925         }
1926
1927         mutex_unlock(&qp_broker_list.mutex);
1928 }
1929
1930 /*
1931  * Requests that a queue pair be allocated with the VMCI queue
1932  * pair broker. Allocates a queue pair entry if one does not
1933  * exist. Attaches to one if it exists, and retrieves the page
1934  * files backing that queue_pair.  Assumes that the queue pair
1935  * broker lock is held.
1936  */
1937 int vmci_qp_broker_alloc(struct vmci_handle handle,
1938                          u32 peer,
1939                          u32 flags,
1940                          u32 priv_flags,
1941                          u64 produce_size,
1942                          u64 consume_size,
1943                          struct vmci_qp_page_store *page_store,
1944                          struct vmci_ctx *context)
1945 {
1946         return qp_broker_alloc(handle, peer, flags, priv_flags,
1947                                produce_size, consume_size,
1948                                page_store, context, NULL, NULL, NULL, NULL);
1949 }
1950
1951 /*
1952  * VMX'en with versions lower than VMCI_VERSION_NOVMVM use a separate
1953  * step to add the UVAs of the VMX mapping of the queue pair. This function
1954  * provides backwards compatibility with such VMX'en, and takes care of
1955  * registering the page store for a queue pair previously allocated by the
1956  * VMX during create or attach. This function will move the queue pair state
1957  * to either from VMCIQBP_CREATED_NO_MEM to VMCIQBP_CREATED_MEM or
1958  * VMCIQBP_ATTACHED_NO_MEM to VMCIQBP_ATTACHED_MEM. If moving to the
1959  * attached state with memory, the queue pair is ready to be used by the
1960  * host peer, and an attached event will be generated.
1961  *
1962  * Assumes that the queue pair broker lock is held.
1963  *
1964  * This function is only used by the hosted platform, since there is no
1965  * issue with backwards compatibility for vmkernel.
1966  */
1967 int vmci_qp_broker_set_page_store(struct vmci_handle handle,
1968                                   u64 produce_uva,
1969                                   u64 consume_uva,
1970                                   struct vmci_ctx *context)
1971 {
1972         struct qp_broker_entry *entry;
1973         int result;
1974         const u32 context_id = vmci_ctx_get_id(context);
1975
1976         if (vmci_handle_is_invalid(handle) || !context ||
1977             context_id == VMCI_INVALID_ID)
1978                 return VMCI_ERROR_INVALID_ARGS;
1979
1980         /*
1981          * We only support guest to host queue pairs, so the VMX must
1982          * supply UVAs for the mapped page files.
1983          */
1984
1985         if (produce_uva == 0 || consume_uva == 0)
1986                 return VMCI_ERROR_INVALID_ARGS;
1987
1988         mutex_lock(&qp_broker_list.mutex);
1989
1990         if (!vmci_ctx_qp_exists(context, handle)) {
1991                 pr_warn("Context (ID=0x%x) not attached to queue pair (handle=0x%x:0x%x)\n",
1992                         context_id, handle.context, handle.resource);
1993                 result = VMCI_ERROR_NOT_FOUND;
1994                 goto out;
1995         }
1996
1997         entry = qp_broker_handle_to_entry(handle);
1998         if (!entry) {
1999                 result = VMCI_ERROR_NOT_FOUND;
2000                 goto out;
2001         }
2002
2003         /*
2004          * If I'm the owner then I can set the page store.
2005          *
2006          * Or, if a host created the queue_pair and I'm the attached peer
2007          * then I can set the page store.
2008          */
2009         if (entry->create_id != context_id &&
2010             (entry->create_id != VMCI_HOST_CONTEXT_ID ||
2011              entry->attach_id != context_id)) {
2012                 result = VMCI_ERROR_QUEUEPAIR_NOTOWNER;
2013                 goto out;
2014         }
2015
2016         if (entry->state != VMCIQPB_CREATED_NO_MEM &&
2017             entry->state != VMCIQPB_ATTACHED_NO_MEM) {
2018                 result = VMCI_ERROR_UNAVAILABLE;
2019                 goto out;
2020         }
2021
2022         result = qp_host_get_user_memory(produce_uva, consume_uva,
2023                                          entry->produce_q, entry->consume_q);
2024         if (result < VMCI_SUCCESS)
2025                 goto out;
2026
2027         result = qp_host_map_queues(entry->produce_q, entry->consume_q);
2028         if (result < VMCI_SUCCESS) {
2029                 qp_host_unregister_user_memory(entry->produce_q,
2030                                                entry->consume_q);
2031                 goto out;
2032         }
2033
2034         if (entry->state == VMCIQPB_CREATED_NO_MEM)
2035                 entry->state = VMCIQPB_CREATED_MEM;
2036         else
2037                 entry->state = VMCIQPB_ATTACHED_MEM;
2038
2039         entry->vmci_page_files = true;
2040
2041         if (entry->state == VMCIQPB_ATTACHED_MEM) {
2042                 result =
2043                     qp_notify_peer(true, handle, context_id, entry->create_id);
2044                 if (result < VMCI_SUCCESS) {
2045                         pr_warn("Failed to notify peer (ID=0x%x) of attach to queue pair (handle=0x%x:0x%x)\n",
2046                                 entry->create_id, entry->qp.handle.context,
2047                                 entry->qp.handle.resource);
2048                 }
2049         }
2050
2051         result = VMCI_SUCCESS;
2052  out:
2053         mutex_unlock(&qp_broker_list.mutex);
2054         return result;
2055 }
2056
2057 /*
2058  * Resets saved queue headers for the given QP broker
2059  * entry. Should be used when guest memory becomes available
2060  * again, or the guest detaches.
2061  */
2062 static void qp_reset_saved_headers(struct qp_broker_entry *entry)
2063 {
2064         entry->produce_q->saved_header = NULL;
2065         entry->consume_q->saved_header = NULL;
2066 }
2067
2068 /*
2069  * The main entry point for detaching from a queue pair registered with the
2070  * queue pair broker. If more than one endpoint is attached to the queue
2071  * pair, the first endpoint will mainly decrement a reference count and
2072  * generate a notification to its peer. The last endpoint will clean up
2073  * the queue pair state registered with the broker.
2074  *
2075  * When a guest endpoint detaches, it will unmap and unregister the guest
2076  * memory backing the queue pair. If the host is still attached, it will
2077  * no longer be able to access the queue pair content.
2078  *
2079  * If the queue pair is already in a state where there is no memory
2080  * registered for the queue pair (any *_NO_MEM state), it will transition to
2081  * the VMCIQPB_SHUTDOWN_NO_MEM state. This will also happen, if a guest
2082  * endpoint is the first of two endpoints to detach. If the host endpoint is
2083  * the first out of two to detach, the queue pair will move to the
2084  * VMCIQPB_SHUTDOWN_MEM state.
2085  */
2086 int vmci_qp_broker_detach(struct vmci_handle handle, struct vmci_ctx *context)
2087 {
2088         struct qp_broker_entry *entry;
2089         const u32 context_id = vmci_ctx_get_id(context);
2090         u32 peer_id;
2091         bool is_local = false;
2092         int result;
2093
2094         if (vmci_handle_is_invalid(handle) || !context ||
2095             context_id == VMCI_INVALID_ID) {
2096                 return VMCI_ERROR_INVALID_ARGS;
2097         }
2098
2099         mutex_lock(&qp_broker_list.mutex);
2100
2101         if (!vmci_ctx_qp_exists(context, handle)) {
2102                 pr_devel("Context (ID=0x%x) not attached to queue pair (handle=0x%x:0x%x)\n",
2103                          context_id, handle.context, handle.resource);
2104                 result = VMCI_ERROR_NOT_FOUND;
2105                 goto out;
2106         }
2107
2108         entry = qp_broker_handle_to_entry(handle);
2109         if (!entry) {
2110                 pr_devel("Context (ID=0x%x) reports being attached to queue pair(handle=0x%x:0x%x) that isn't present in broker\n",
2111                          context_id, handle.context, handle.resource);
2112                 result = VMCI_ERROR_NOT_FOUND;
2113                 goto out;
2114         }
2115
2116         if (context_id != entry->create_id && context_id != entry->attach_id) {
2117                 result = VMCI_ERROR_QUEUEPAIR_NOTATTACHED;
2118                 goto out;
2119         }
2120
2121         if (context_id == entry->create_id) {
2122                 peer_id = entry->attach_id;
2123                 entry->create_id = VMCI_INVALID_ID;
2124         } else {
2125                 peer_id = entry->create_id;
2126                 entry->attach_id = VMCI_INVALID_ID;
2127         }
2128         entry->qp.ref_count--;
2129
2130         is_local = entry->qp.flags & VMCI_QPFLAG_LOCAL;
2131
2132         if (context_id != VMCI_HOST_CONTEXT_ID) {
2133                 bool headers_mapped;
2134
2135                 /*
2136                  * Pre NOVMVM vmx'en may detach from a queue pair
2137                  * before setting the page store, and in that case
2138                  * there is no user memory to detach from. Also, more
2139                  * recent VMX'en may detach from a queue pair in the
2140                  * quiesced state.
2141                  */
2142
2143                 qp_acquire_queue_mutex(entry->produce_q);
2144                 headers_mapped = entry->produce_q->q_header ||
2145                     entry->consume_q->q_header;
2146                 if (QPBROKERSTATE_HAS_MEM(entry)) {
2147                         result =
2148                             qp_host_unmap_queues(INVALID_VMCI_GUEST_MEM_ID,
2149                                                  entry->produce_q,
2150                                                  entry->consume_q);
2151                         if (result < VMCI_SUCCESS)
2152                                 pr_warn("Failed to unmap queue headers for queue pair (handle=0x%x:0x%x,result=%d)\n",
2153                                         handle.context, handle.resource,
2154                                         result);
2155
2156                         qp_host_unregister_user_memory(entry->produce_q,
2157                                                        entry->consume_q);
2158
2159                 }
2160
2161                 if (!headers_mapped)
2162                         qp_reset_saved_headers(entry);
2163
2164                 qp_release_queue_mutex(entry->produce_q);
2165
2166                 if (!headers_mapped && entry->wakeup_cb)
2167                         entry->wakeup_cb(entry->client_data);
2168
2169         } else {
2170                 if (entry->wakeup_cb) {
2171                         entry->wakeup_cb = NULL;
2172                         entry->client_data = NULL;
2173                 }
2174         }
2175
2176         if (entry->qp.ref_count == 0) {
2177                 qp_list_remove_entry(&qp_broker_list, &entry->qp);
2178
2179                 if (is_local)
2180                         kfree(entry->local_mem);
2181
2182                 qp_cleanup_queue_mutex(entry->produce_q, entry->consume_q);
2183                 qp_host_free_queue(entry->produce_q, entry->qp.produce_size);
2184                 qp_host_free_queue(entry->consume_q, entry->qp.consume_size);
2185                 /* Unlink from resource hash table and free callback */
2186                 vmci_resource_remove(&entry->resource);
2187
2188                 kfree(entry);
2189
2190                 vmci_ctx_qp_destroy(context, handle);
2191         } else {
2192                 qp_notify_peer(false, handle, context_id, peer_id);
2193                 if (context_id == VMCI_HOST_CONTEXT_ID &&
2194                     QPBROKERSTATE_HAS_MEM(entry)) {
2195                         entry->state = VMCIQPB_SHUTDOWN_MEM;
2196                 } else {
2197                         entry->state = VMCIQPB_SHUTDOWN_NO_MEM;
2198                 }
2199
2200                 if (!is_local)
2201                         vmci_ctx_qp_destroy(context, handle);
2202
2203         }
2204         result = VMCI_SUCCESS;
2205  out:
2206         mutex_unlock(&qp_broker_list.mutex);
2207         return result;
2208 }
2209
2210 /*
2211  * Establishes the necessary mappings for a queue pair given a
2212  * reference to the queue pair guest memory. This is usually
2213  * called when a guest is unquiesced and the VMX is allowed to
2214  * map guest memory once again.
2215  */
2216 int vmci_qp_broker_map(struct vmci_handle handle,
2217                        struct vmci_ctx *context,
2218                        u64 guest_mem)
2219 {
2220         struct qp_broker_entry *entry;
2221         const u32 context_id = vmci_ctx_get_id(context);
2222         int result;
2223
2224         if (vmci_handle_is_invalid(handle) || !context ||
2225             context_id == VMCI_INVALID_ID)
2226                 return VMCI_ERROR_INVALID_ARGS;
2227
2228         mutex_lock(&qp_broker_list.mutex);
2229
2230         if (!vmci_ctx_qp_exists(context, handle)) {
2231                 pr_devel("Context (ID=0x%x) not attached to queue pair (handle=0x%x:0x%x)\n",
2232                          context_id, handle.context, handle.resource);
2233                 result = VMCI_ERROR_NOT_FOUND;
2234                 goto out;
2235         }
2236
2237         entry = qp_broker_handle_to_entry(handle);
2238         if (!entry) {
2239                 pr_devel("Context (ID=0x%x) reports being attached to queue pair (handle=0x%x:0x%x) that isn't present in broker\n",
2240                          context_id, handle.context, handle.resource);
2241                 result = VMCI_ERROR_NOT_FOUND;
2242                 goto out;
2243         }
2244
2245         if (context_id != entry->create_id && context_id != entry->attach_id) {
2246                 result = VMCI_ERROR_QUEUEPAIR_NOTATTACHED;
2247                 goto out;
2248         }
2249
2250         result = VMCI_SUCCESS;
2251
2252         if (context_id != VMCI_HOST_CONTEXT_ID &&
2253             !QPBROKERSTATE_HAS_MEM(entry)) {
2254                 struct vmci_qp_page_store page_store;
2255
2256                 page_store.pages = guest_mem;
2257                 page_store.len = QPE_NUM_PAGES(entry->qp);
2258
2259                 qp_acquire_queue_mutex(entry->produce_q);
2260                 qp_reset_saved_headers(entry);
2261                 result =
2262                     qp_host_register_user_memory(&page_store,
2263                                                  entry->produce_q,
2264                                                  entry->consume_q);
2265                 qp_release_queue_mutex(entry->produce_q);
2266                 if (result == VMCI_SUCCESS) {
2267                         /* Move state from *_NO_MEM to *_MEM */
2268
2269                         entry->state++;
2270
2271                         if (entry->wakeup_cb)
2272                                 entry->wakeup_cb(entry->client_data);
2273                 }
2274         }
2275
2276  out:
2277         mutex_unlock(&qp_broker_list.mutex);
2278         return result;
2279 }
2280
2281 /*
2282  * Saves a snapshot of the queue headers for the given QP broker
2283  * entry. Should be used when guest memory is unmapped.
2284  * Results:
2285  * VMCI_SUCCESS on success, appropriate error code if guest memory
2286  * can't be accessed..
2287  */
2288 static int qp_save_headers(struct qp_broker_entry *entry)
2289 {
2290         int result;
2291
2292         if (entry->produce_q->saved_header != NULL &&
2293             entry->consume_q->saved_header != NULL) {
2294                 /*
2295                  *  If the headers have already been saved, we don't need to do
2296                  *  it again, and we don't want to map in the headers
2297                  *  unnecessarily.
2298                  */
2299
2300                 return VMCI_SUCCESS;
2301         }
2302
2303         if (NULL == entry->produce_q->q_header ||
2304             NULL == entry->consume_q->q_header) {
2305                 result = qp_host_map_queues(entry->produce_q, entry->consume_q);
2306                 if (result < VMCI_SUCCESS)
2307                         return result;
2308         }
2309
2310         memcpy(&entry->saved_produce_q, entry->produce_q->q_header,
2311                sizeof(entry->saved_produce_q));
2312         entry->produce_q->saved_header = &entry->saved_produce_q;
2313         memcpy(&entry->saved_consume_q, entry->consume_q->q_header,
2314                sizeof(entry->saved_consume_q));
2315         entry->consume_q->saved_header = &entry->saved_consume_q;
2316
2317         return VMCI_SUCCESS;
2318 }
2319
2320 /*
2321  * Removes all references to the guest memory of a given queue pair, and
2322  * will move the queue pair from state *_MEM to *_NO_MEM. It is usually
2323  * called when a VM is being quiesced where access to guest memory should
2324  * avoided.
2325  */
2326 int vmci_qp_broker_unmap(struct vmci_handle handle,
2327                          struct vmci_ctx *context,
2328                          u32 gid)
2329 {
2330         struct qp_broker_entry *entry;
2331         const u32 context_id = vmci_ctx_get_id(context);
2332         int result;
2333
2334         if (vmci_handle_is_invalid(handle) || !context ||
2335             context_id == VMCI_INVALID_ID)
2336                 return VMCI_ERROR_INVALID_ARGS;
2337
2338         mutex_lock(&qp_broker_list.mutex);
2339
2340         if (!vmci_ctx_qp_exists(context, handle)) {
2341                 pr_devel("Context (ID=0x%x) not attached to queue pair (handle=0x%x:0x%x)\n",
2342                          context_id, handle.context, handle.resource);
2343                 result = VMCI_ERROR_NOT_FOUND;
2344                 goto out;
2345         }
2346
2347         entry = qp_broker_handle_to_entry(handle);
2348         if (!entry) {
2349                 pr_devel("Context (ID=0x%x) reports being attached to queue pair (handle=0x%x:0x%x) that isn't present in broker\n",
2350                          context_id, handle.context, handle.resource);
2351                 result = VMCI_ERROR_NOT_FOUND;
2352                 goto out;
2353         }
2354
2355         if (context_id != entry->create_id && context_id != entry->attach_id) {
2356                 result = VMCI_ERROR_QUEUEPAIR_NOTATTACHED;
2357                 goto out;
2358         }
2359
2360         if (context_id != VMCI_HOST_CONTEXT_ID &&
2361             QPBROKERSTATE_HAS_MEM(entry)) {
2362                 qp_acquire_queue_mutex(entry->produce_q);
2363                 result = qp_save_headers(entry);
2364                 if (result < VMCI_SUCCESS)
2365                         pr_warn("Failed to save queue headers for queue pair (handle=0x%x:0x%x,result=%d)\n",
2366                                 handle.context, handle.resource, result);
2367
2368                 qp_host_unmap_queues(gid, entry->produce_q, entry->consume_q);
2369
2370                 /*
2371                  * On hosted, when we unmap queue pairs, the VMX will also
2372                  * unmap the guest memory, so we invalidate the previously
2373                  * registered memory. If the queue pair is mapped again at a
2374                  * later point in time, we will need to reregister the user
2375                  * memory with a possibly new user VA.
2376                  */
2377                 qp_host_unregister_user_memory(entry->produce_q,
2378                                                entry->consume_q);
2379
2380                 /*
2381                  * Move state from *_MEM to *_NO_MEM.
2382                  */
2383                 entry->state--;
2384
2385                 qp_release_queue_mutex(entry->produce_q);
2386         }
2387
2388         result = VMCI_SUCCESS;
2389
2390  out:
2391         mutex_unlock(&qp_broker_list.mutex);
2392         return result;
2393 }
2394
2395 /*
2396  * Destroys all guest queue pair endpoints. If active guest queue
2397  * pairs still exist, hypercalls to attempt detach from these
2398  * queue pairs will be made. Any failure to detach is silently
2399  * ignored.
2400  */
2401 void vmci_qp_guest_endpoints_exit(void)
2402 {
2403         struct qp_entry *entry;
2404         struct qp_guest_endpoint *ep;
2405
2406         mutex_lock(&qp_guest_endpoints.mutex);
2407
2408         while ((entry = qp_list_get_head(&qp_guest_endpoints))) {
2409                 ep = (struct qp_guest_endpoint *)entry;
2410
2411                 /* Don't make a hypercall for local queue_pairs. */
2412                 if (!(entry->flags & VMCI_QPFLAG_LOCAL))
2413                         qp_detatch_hypercall(entry->handle);
2414
2415                 /* We cannot fail the exit, so let's reset ref_count. */
2416                 entry->ref_count = 0;
2417                 qp_list_remove_entry(&qp_guest_endpoints, entry);
2418
2419                 qp_guest_endpoint_destroy(ep);
2420         }
2421
2422         mutex_unlock(&qp_guest_endpoints.mutex);
2423 }
2424
2425 /*
2426  * Helper routine that will lock the queue pair before subsequent
2427  * operations.
2428  * Note: Non-blocking on the host side is currently only implemented in ESX.
2429  * Since non-blocking isn't yet implemented on the host personality we
2430  * have no reason to acquire a spin lock.  So to avoid the use of an
2431  * unnecessary lock only acquire the mutex if we can block.
2432  */
2433 static void qp_lock(const struct vmci_qp *qpair)
2434 {
2435         qp_acquire_queue_mutex(qpair->produce_q);
2436 }
2437
2438 /*
2439  * Helper routine that unlocks the queue pair after calling
2440  * qp_lock.
2441  */
2442 static void qp_unlock(const struct vmci_qp *qpair)
2443 {
2444         qp_release_queue_mutex(qpair->produce_q);
2445 }
2446
2447 /*
2448  * The queue headers may not be mapped at all times. If a queue is
2449  * currently not mapped, it will be attempted to do so.
2450  */
2451 static int qp_map_queue_headers(struct vmci_queue *produce_q,
2452                                 struct vmci_queue *consume_q)
2453 {
2454         int result;
2455
2456         if (NULL == produce_q->q_header || NULL == consume_q->q_header) {
2457                 result = qp_host_map_queues(produce_q, consume_q);
2458                 if (result < VMCI_SUCCESS)
2459                         return (produce_q->saved_header &&
2460                                 consume_q->saved_header) ?
2461                             VMCI_ERROR_QUEUEPAIR_NOT_READY :
2462                             VMCI_ERROR_QUEUEPAIR_NOTATTACHED;
2463         }
2464
2465         return VMCI_SUCCESS;
2466 }
2467
2468 /*
2469  * Helper routine that will retrieve the produce and consume
2470  * headers of a given queue pair. If the guest memory of the
2471  * queue pair is currently not available, the saved queue headers
2472  * will be returned, if these are available.
2473  */
2474 static int qp_get_queue_headers(const struct vmci_qp *qpair,
2475                                 struct vmci_queue_header **produce_q_header,
2476                                 struct vmci_queue_header **consume_q_header)
2477 {
2478         int result;
2479
2480         result = qp_map_queue_headers(qpair->produce_q, qpair->consume_q);
2481         if (result == VMCI_SUCCESS) {
2482                 *produce_q_header = qpair->produce_q->q_header;
2483                 *consume_q_header = qpair->consume_q->q_header;
2484         } else if (qpair->produce_q->saved_header &&
2485                    qpair->consume_q->saved_header) {
2486                 *produce_q_header = qpair->produce_q->saved_header;
2487                 *consume_q_header = qpair->consume_q->saved_header;
2488                 result = VMCI_SUCCESS;
2489         }
2490
2491         return result;
2492 }
2493
2494 /*
2495  * Callback from VMCI queue pair broker indicating that a queue
2496  * pair that was previously not ready, now either is ready or
2497  * gone forever.
2498  */
2499 static int qp_wakeup_cb(void *client_data)
2500 {
2501         struct vmci_qp *qpair = (struct vmci_qp *)client_data;
2502
2503         qp_lock(qpair);
2504         while (qpair->blocked > 0) {
2505                 qpair->blocked--;
2506                 qpair->generation++;
2507                 wake_up(&qpair->event);
2508         }
2509         qp_unlock(qpair);
2510
2511         return VMCI_SUCCESS;
2512 }
2513
2514 /*
2515  * Makes the calling thread wait for the queue pair to become
2516  * ready for host side access.  Returns true when thread is
2517  * woken up after queue pair state change, false otherwise.
2518  */
2519 static bool qp_wait_for_ready_queue(struct vmci_qp *qpair)
2520 {
2521         unsigned int generation;
2522
2523         qpair->blocked++;
2524         generation = qpair->generation;
2525         qp_unlock(qpair);
2526         wait_event(qpair->event, generation != qpair->generation);
2527         qp_lock(qpair);
2528
2529         return true;
2530 }
2531
2532 /*
2533  * Enqueues a given buffer to the produce queue using the provided
2534  * function. As many bytes as possible (space available in the queue)
2535  * are enqueued.  Assumes the queue->mutex has been acquired.  Returns
2536  * VMCI_ERROR_QUEUEPAIR_NOSPACE if no space was available to enqueue
2537  * data, VMCI_ERROR_INVALID_SIZE, if any queue pointer is outside the
2538  * queue (as defined by the queue size), VMCI_ERROR_INVALID_ARGS, if
2539  * an error occured when accessing the buffer,
2540  * VMCI_ERROR_QUEUEPAIR_NOTATTACHED, if the queue pair pages aren't
2541  * available.  Otherwise, the number of bytes written to the queue is
2542  * returned.  Updates the tail pointer of the produce queue.
2543  */
2544 static ssize_t qp_enqueue_locked(struct vmci_queue *produce_q,
2545                                  struct vmci_queue *consume_q,
2546                                  const u64 produce_q_size,
2547                                  struct iov_iter *from)
2548 {
2549         s64 free_space;
2550         u64 tail;
2551         size_t buf_size = iov_iter_count(from);
2552         size_t written;
2553         ssize_t result;
2554
2555         result = qp_map_queue_headers(produce_q, consume_q);
2556         if (unlikely(result != VMCI_SUCCESS))
2557                 return result;
2558
2559         free_space = vmci_q_header_free_space(produce_q->q_header,
2560                                               consume_q->q_header,
2561                                               produce_q_size);
2562         if (free_space == 0)
2563                 return VMCI_ERROR_QUEUEPAIR_NOSPACE;
2564
2565         if (free_space < VMCI_SUCCESS)
2566                 return (ssize_t) free_space;
2567
2568         written = (size_t) (free_space > buf_size ? buf_size : free_space);
2569         tail = vmci_q_header_producer_tail(produce_q->q_header);
2570         if (likely(tail + written < produce_q_size)) {
2571                 result = qp_memcpy_to_queue_iter(produce_q, tail, from, written);
2572         } else {
2573                 /* Tail pointer wraps around. */
2574
2575                 const size_t tmp = (size_t) (produce_q_size - tail);
2576
2577                 result = qp_memcpy_to_queue_iter(produce_q, tail, from, tmp);
2578                 if (result >= VMCI_SUCCESS)
2579                         result = qp_memcpy_to_queue_iter(produce_q, 0, from,
2580                                                  written - tmp);
2581         }
2582
2583         if (result < VMCI_SUCCESS)
2584                 return result;
2585
2586         vmci_q_header_add_producer_tail(produce_q->q_header, written,
2587                                         produce_q_size);
2588         return written;
2589 }
2590
2591 /*
2592  * Dequeues data (if available) from the given consume queue. Writes data
2593  * to the user provided buffer using the provided function.
2594  * Assumes the queue->mutex has been acquired.
2595  * Results:
2596  * VMCI_ERROR_QUEUEPAIR_NODATA if no data was available to dequeue.
2597  * VMCI_ERROR_INVALID_SIZE, if any queue pointer is outside the queue
2598  * (as defined by the queue size).
2599  * VMCI_ERROR_INVALID_ARGS, if an error occured when accessing the buffer.
2600  * Otherwise the number of bytes dequeued is returned.
2601  * Side effects:
2602  * Updates the head pointer of the consume queue.
2603  */
2604 static ssize_t qp_dequeue_locked(struct vmci_queue *produce_q,
2605                                  struct vmci_queue *consume_q,
2606                                  const u64 consume_q_size,
2607                                  struct iov_iter *to,
2608                                  bool update_consumer)
2609 {
2610         size_t buf_size = iov_iter_count(to);
2611         s64 buf_ready;
2612         u64 head;
2613         size_t read;
2614         ssize_t result;
2615
2616         result = qp_map_queue_headers(produce_q, consume_q);
2617         if (unlikely(result != VMCI_SUCCESS))
2618                 return result;
2619
2620         buf_ready = vmci_q_header_buf_ready(consume_q->q_header,
2621                                             produce_q->q_header,
2622                                             consume_q_size);
2623         if (buf_ready == 0)
2624                 return VMCI_ERROR_QUEUEPAIR_NODATA;
2625
2626         if (buf_ready < VMCI_SUCCESS)
2627                 return (ssize_t) buf_ready;
2628
2629         read = (size_t) (buf_ready > buf_size ? buf_size : buf_ready);
2630         head = vmci_q_header_consumer_head(produce_q->q_header);
2631         if (likely(head + read < consume_q_size)) {
2632                 result = qp_memcpy_from_queue_iter(to, consume_q, head, read);
2633         } else {
2634                 /* Head pointer wraps around. */
2635
2636                 const size_t tmp = (size_t) (consume_q_size - head);
2637
2638                 result = qp_memcpy_from_queue_iter(to, consume_q, head, tmp);
2639                 if (result >= VMCI_SUCCESS)
2640                         result = qp_memcpy_from_queue_iter(to, consume_q, 0,
2641                                                    read - tmp);
2642
2643         }
2644
2645         if (result < VMCI_SUCCESS)
2646                 return result;
2647
2648         if (update_consumer)
2649                 vmci_q_header_add_consumer_head(produce_q->q_header,
2650                                                 read, consume_q_size);
2651
2652         return read;
2653 }
2654
2655 /*
2656  * vmci_qpair_alloc() - Allocates a queue pair.
2657  * @qpair:      Pointer for the new vmci_qp struct.
2658  * @handle:     Handle to track the resource.
2659  * @produce_qsize:      Desired size of the producer queue.
2660  * @consume_qsize:      Desired size of the consumer queue.
2661  * @peer:       ContextID of the peer.
2662  * @flags:      VMCI flags.
2663  * @priv_flags: VMCI priviledge flags.
2664  *
2665  * This is the client interface for allocating the memory for a
2666  * vmci_qp structure and then attaching to the underlying
2667  * queue.  If an error occurs allocating the memory for the
2668  * vmci_qp structure no attempt is made to attach.  If an
2669  * error occurs attaching, then the structure is freed.
2670  */
2671 int vmci_qpair_alloc(struct vmci_qp **qpair,
2672                      struct vmci_handle *handle,
2673                      u64 produce_qsize,
2674                      u64 consume_qsize,
2675                      u32 peer,
2676                      u32 flags,
2677                      u32 priv_flags)
2678 {
2679         struct vmci_qp *my_qpair;
2680         int retval;
2681         struct vmci_handle src = VMCI_INVALID_HANDLE;
2682         struct vmci_handle dst = vmci_make_handle(peer, VMCI_INVALID_ID);
2683         enum vmci_route route;
2684         vmci_event_release_cb wakeup_cb;
2685         void *client_data;
2686
2687         /*
2688          * Restrict the size of a queuepair.  The device already
2689          * enforces a limit on the total amount of memory that can be
2690          * allocated to queuepairs for a guest.  However, we try to
2691          * allocate this memory before we make the queuepair
2692          * allocation hypercall.  On Linux, we allocate each page
2693          * separately, which means rather than fail, the guest will
2694          * thrash while it tries to allocate, and will become
2695          * increasingly unresponsive to the point where it appears to
2696          * be hung.  So we place a limit on the size of an individual
2697          * queuepair here, and leave the device to enforce the
2698          * restriction on total queuepair memory.  (Note that this
2699          * doesn't prevent all cases; a user with only this much
2700          * physical memory could still get into trouble.)  The error
2701          * used by the device is NO_RESOURCES, so use that here too.
2702          */
2703
2704         if (produce_qsize + consume_qsize < max(produce_qsize, consume_qsize) ||
2705             produce_qsize + consume_qsize > VMCI_MAX_GUEST_QP_MEMORY)
2706                 return VMCI_ERROR_NO_RESOURCES;
2707
2708         retval = vmci_route(&src, &dst, false, &route);
2709         if (retval < VMCI_SUCCESS)
2710                 route = vmci_guest_code_active() ?
2711                     VMCI_ROUTE_AS_GUEST : VMCI_ROUTE_AS_HOST;
2712
2713         if (flags & (VMCI_QPFLAG_NONBLOCK | VMCI_QPFLAG_PINNED)) {
2714                 pr_devel("NONBLOCK OR PINNED set");
2715                 return VMCI_ERROR_INVALID_ARGS;
2716         }
2717
2718         my_qpair = kzalloc(sizeof(*my_qpair), GFP_KERNEL);
2719         if (!my_qpair)
2720                 return VMCI_ERROR_NO_MEM;
2721
2722         my_qpair->produce_q_size = produce_qsize;
2723         my_qpair->consume_q_size = consume_qsize;
2724         my_qpair->peer = peer;
2725         my_qpair->flags = flags;
2726         my_qpair->priv_flags = priv_flags;
2727
2728         wakeup_cb = NULL;
2729         client_data = NULL;
2730
2731         if (VMCI_ROUTE_AS_HOST == route) {
2732                 my_qpair->guest_endpoint = false;
2733                 if (!(flags & VMCI_QPFLAG_LOCAL)) {
2734                         my_qpair->blocked = 0;
2735                         my_qpair->generation = 0;
2736                         init_waitqueue_head(&my_qpair->event);
2737                         wakeup_cb = qp_wakeup_cb;
2738                         client_data = (void *)my_qpair;
2739                 }
2740         } else {
2741                 my_qpair->guest_endpoint = true;
2742         }
2743
2744         retval = vmci_qp_alloc(handle,
2745                                &my_qpair->produce_q,
2746                                my_qpair->produce_q_size,
2747                                &my_qpair->consume_q,
2748                                my_qpair->consume_q_size,
2749                                my_qpair->peer,
2750                                my_qpair->flags,
2751                                my_qpair->priv_flags,
2752                                my_qpair->guest_endpoint,
2753                                wakeup_cb, client_data);
2754
2755         if (retval < VMCI_SUCCESS) {
2756                 kfree(my_qpair);
2757                 return retval;
2758         }
2759
2760         *qpair = my_qpair;
2761         my_qpair->handle = *handle;
2762
2763         return retval;
2764 }
2765 EXPORT_SYMBOL_GPL(vmci_qpair_alloc);
2766
2767 /*
2768  * vmci_qpair_detach() - Detatches the client from a queue pair.
2769  * @qpair:      Reference of a pointer to the qpair struct.
2770  *
2771  * This is the client interface for detaching from a VMCIQPair.
2772  * Note that this routine will free the memory allocated for the
2773  * vmci_qp structure too.
2774  */
2775 int vmci_qpair_detach(struct vmci_qp **qpair)
2776 {
2777         int result;
2778         struct vmci_qp *old_qpair;
2779
2780         if (!qpair || !(*qpair))
2781                 return VMCI_ERROR_INVALID_ARGS;
2782
2783         old_qpair = *qpair;
2784         result = qp_detatch(old_qpair->handle, old_qpair->guest_endpoint);
2785
2786         /*
2787          * The guest can fail to detach for a number of reasons, and
2788          * if it does so, it will cleanup the entry (if there is one).
2789          * The host can fail too, but it won't cleanup the entry
2790          * immediately, it will do that later when the context is
2791          * freed.  Either way, we need to release the qpair struct
2792          * here; there isn't much the caller can do, and we don't want
2793          * to leak.
2794          */
2795
2796         memset(old_qpair, 0, sizeof(*old_qpair));
2797         old_qpair->handle = VMCI_INVALID_HANDLE;
2798         old_qpair->peer = VMCI_INVALID_ID;
2799         kfree(old_qpair);
2800         *qpair = NULL;
2801
2802         return result;
2803 }
2804 EXPORT_SYMBOL_GPL(vmci_qpair_detach);
2805
2806 /*
2807  * vmci_qpair_get_produce_indexes() - Retrieves the indexes of the producer.
2808  * @qpair:      Pointer to the queue pair struct.
2809  * @producer_tail:      Reference used for storing producer tail index.
2810  * @consumer_head:      Reference used for storing the consumer head index.
2811  *
2812  * This is the client interface for getting the current indexes of the
2813  * QPair from the point of the view of the caller as the producer.
2814  */
2815 int vmci_qpair_get_produce_indexes(const struct vmci_qp *qpair,
2816                                    u64 *producer_tail,
2817                                    u64 *consumer_head)
2818 {
2819         struct vmci_queue_header *produce_q_header;
2820         struct vmci_queue_header *consume_q_header;
2821         int result;
2822
2823         if (!qpair)
2824                 return VMCI_ERROR_INVALID_ARGS;
2825
2826         qp_lock(qpair);
2827         result =
2828             qp_get_queue_headers(qpair, &produce_q_header, &consume_q_header);
2829         if (result == VMCI_SUCCESS)
2830                 vmci_q_header_get_pointers(produce_q_header, consume_q_header,
2831                                            producer_tail, consumer_head);
2832         qp_unlock(qpair);
2833
2834         if (result == VMCI_SUCCESS &&
2835             ((producer_tail && *producer_tail >= qpair->produce_q_size) ||
2836              (consumer_head && *consumer_head >= qpair->produce_q_size)))
2837                 return VMCI_ERROR_INVALID_SIZE;
2838
2839         return result;
2840 }
2841 EXPORT_SYMBOL_GPL(vmci_qpair_get_produce_indexes);
2842
2843 /*
2844  * vmci_qpair_get_consume_indexes() - Retrieves the indexes of the consumer.
2845  * @qpair:      Pointer to the queue pair struct.
2846  * @consumer_tail:      Reference used for storing consumer tail index.
2847  * @producer_head:      Reference used for storing the producer head index.
2848  *
2849  * This is the client interface for getting the current indexes of the
2850  * QPair from the point of the view of the caller as the consumer.
2851  */
2852 int vmci_qpair_get_consume_indexes(const struct vmci_qp *qpair,
2853                                    u64 *consumer_tail,
2854                                    u64 *producer_head)
2855 {
2856         struct vmci_queue_header *produce_q_header;
2857         struct vmci_queue_header *consume_q_header;
2858         int result;
2859
2860         if (!qpair)
2861                 return VMCI_ERROR_INVALID_ARGS;
2862
2863         qp_lock(qpair);
2864         result =
2865             qp_get_queue_headers(qpair, &produce_q_header, &consume_q_header);
2866         if (result == VMCI_SUCCESS)
2867                 vmci_q_header_get_pointers(consume_q_header, produce_q_header,
2868                                            consumer_tail, producer_head);
2869         qp_unlock(qpair);
2870
2871         if (result == VMCI_SUCCESS &&
2872             ((consumer_tail && *consumer_tail >= qpair->consume_q_size) ||
2873              (producer_head && *producer_head >= qpair->consume_q_size)))
2874                 return VMCI_ERROR_INVALID_SIZE;
2875
2876         return result;
2877 }
2878 EXPORT_SYMBOL_GPL(vmci_qpair_get_consume_indexes);
2879
2880 /*
2881  * vmci_qpair_produce_free_space() - Retrieves free space in producer queue.
2882  * @qpair:      Pointer to the queue pair struct.
2883  *
2884  * This is the client interface for getting the amount of free
2885  * space in the QPair from the point of the view of the caller as
2886  * the producer which is the common case.  Returns < 0 if err, else
2887  * available bytes into which data can be enqueued if > 0.
2888  */
2889 s64 vmci_qpair_produce_free_space(const struct vmci_qp *qpair)
2890 {
2891         struct vmci_queue_header *produce_q_header;
2892         struct vmci_queue_header *consume_q_header;
2893         s64 result;
2894
2895         if (!qpair)
2896                 return VMCI_ERROR_INVALID_ARGS;
2897
2898         qp_lock(qpair);
2899         result =
2900             qp_get_queue_headers(qpair, &produce_q_header, &consume_q_header);
2901         if (result == VMCI_SUCCESS)
2902                 result = vmci_q_header_free_space(produce_q_header,
2903                                                   consume_q_header,
2904                                                   qpair->produce_q_size);
2905         else
2906                 result = 0;
2907
2908         qp_unlock(qpair);
2909
2910         return result;
2911 }
2912 EXPORT_SYMBOL_GPL(vmci_qpair_produce_free_space);
2913
2914 /*
2915  * vmci_qpair_consume_free_space() - Retrieves free space in consumer queue.
2916  * @qpair:      Pointer to the queue pair struct.
2917  *
2918  * This is the client interface for getting the amount of free
2919  * space in the QPair from the point of the view of the caller as
2920  * the consumer which is not the common case.  Returns < 0 if err, else
2921  * available bytes into which data can be enqueued if > 0.
2922  */
2923 s64 vmci_qpair_consume_free_space(const struct vmci_qp *qpair)
2924 {
2925         struct vmci_queue_header *produce_q_header;
2926         struct vmci_queue_header *consume_q_header;
2927         s64 result;
2928
2929         if (!qpair)
2930                 return VMCI_ERROR_INVALID_ARGS;
2931
2932         qp_lock(qpair);
2933         result =
2934             qp_get_queue_headers(qpair, &produce_q_header, &consume_q_header);
2935         if (result == VMCI_SUCCESS)
2936                 result = vmci_q_header_free_space(consume_q_header,
2937                                                   produce_q_header,
2938                                                   qpair->consume_q_size);
2939         else
2940                 result = 0;
2941
2942         qp_unlock(qpair);
2943
2944         return result;
2945 }
2946 EXPORT_SYMBOL_GPL(vmci_qpair_consume_free_space);
2947
2948 /*
2949  * vmci_qpair_produce_buf_ready() - Gets bytes ready to read from
2950  * producer queue.
2951  * @qpair:      Pointer to the queue pair struct.
2952  *
2953  * This is the client interface for getting the amount of
2954  * enqueued data in the QPair from the point of the view of the
2955  * caller as the producer which is not the common case.  Returns < 0 if err,
2956  * else available bytes that may be read.
2957  */
2958 s64 vmci_qpair_produce_buf_ready(const struct vmci_qp *qpair)
2959 {
2960         struct vmci_queue_header *produce_q_header;
2961         struct vmci_queue_header *consume_q_header;
2962         s64 result;
2963
2964         if (!qpair)
2965                 return VMCI_ERROR_INVALID_ARGS;
2966
2967         qp_lock(qpair);
2968         result =
2969             qp_get_queue_headers(qpair, &produce_q_header, &consume_q_header);
2970         if (result == VMCI_SUCCESS)
2971                 result = vmci_q_header_buf_ready(produce_q_header,
2972                                                  consume_q_header,
2973                                                  qpair->produce_q_size);
2974         else
2975                 result = 0;
2976
2977         qp_unlock(qpair);
2978
2979         return result;
2980 }
2981 EXPORT_SYMBOL_GPL(vmci_qpair_produce_buf_ready);
2982
2983 /*
2984  * vmci_qpair_consume_buf_ready() - Gets bytes ready to read from
2985  * consumer queue.
2986  * @qpair:      Pointer to the queue pair struct.
2987  *
2988  * This is the client interface for getting the amount of
2989  * enqueued data in the QPair from the point of the view of the
2990  * caller as the consumer which is the normal case.  Returns < 0 if err,
2991  * else available bytes that may be read.
2992  */
2993 s64 vmci_qpair_consume_buf_ready(const struct vmci_qp *qpair)
2994 {
2995         struct vmci_queue_header *produce_q_header;
2996         struct vmci_queue_header *consume_q_header;
2997         s64 result;
2998
2999         if (!qpair)
3000                 return VMCI_ERROR_INVALID_ARGS;
3001
3002         qp_lock(qpair);
3003         result =
3004             qp_get_queue_headers(qpair, &produce_q_header, &consume_q_header);
3005         if (result == VMCI_SUCCESS)
3006                 result = vmci_q_header_buf_ready(consume_q_header,
3007                                                  produce_q_header,
3008                                                  qpair->consume_q_size);
3009         else
3010                 result = 0;
3011
3012         qp_unlock(qpair);
3013
3014         return result;
3015 }
3016 EXPORT_SYMBOL_GPL(vmci_qpair_consume_buf_ready);
3017
3018 /*
3019  * vmci_qpair_enqueue() - Throw data on the queue.
3020  * @qpair:      Pointer to the queue pair struct.
3021  * @buf:        Pointer to buffer containing data
3022  * @buf_size:   Length of buffer.
3023  * @buf_type:   Buffer type (Unused).
3024  *
3025  * This is the client interface for enqueueing data into the queue.
3026  * Returns number of bytes enqueued or < 0 on error.
3027  */
3028 ssize_t vmci_qpair_enqueue(struct vmci_qp *qpair,
3029                            const void *buf,
3030                            size_t buf_size,
3031                            int buf_type)
3032 {
3033         ssize_t result;
3034         struct iov_iter from;
3035         struct kvec v = {.iov_base = (void *)buf, .iov_len = buf_size};
3036
3037         if (!qpair || !buf)
3038                 return VMCI_ERROR_INVALID_ARGS;
3039
3040         iov_iter_kvec(&from, WRITE | ITER_KVEC, &v, 1, buf_size);
3041
3042         qp_lock(qpair);
3043
3044         do {
3045                 result = qp_enqueue_locked(qpair->produce_q,
3046                                            qpair->consume_q,
3047                                            qpair->produce_q_size,
3048                                            &from);
3049
3050                 if (result == VMCI_ERROR_QUEUEPAIR_NOT_READY &&
3051                     !qp_wait_for_ready_queue(qpair))
3052                         result = VMCI_ERROR_WOULD_BLOCK;
3053
3054         } while (result == VMCI_ERROR_QUEUEPAIR_NOT_READY);
3055
3056         qp_unlock(qpair);
3057
3058         return result;
3059 }
3060 EXPORT_SYMBOL_GPL(vmci_qpair_enqueue);
3061
3062 /*
3063  * vmci_qpair_dequeue() - Get data from the queue.
3064  * @qpair:      Pointer to the queue pair struct.
3065  * @buf:        Pointer to buffer for the data
3066  * @buf_size:   Length of buffer.
3067  * @buf_type:   Buffer type (Unused).
3068  *
3069  * This is the client interface for dequeueing data from the queue.
3070  * Returns number of bytes dequeued or < 0 on error.
3071  */
3072 ssize_t vmci_qpair_dequeue(struct vmci_qp *qpair,
3073                            void *buf,
3074                            size_t buf_size,
3075                            int buf_type)
3076 {
3077         ssize_t result;
3078         struct iov_iter to;
3079         struct kvec v = {.iov_base = buf, .iov_len = buf_size};
3080
3081         if (!qpair || !buf)
3082                 return VMCI_ERROR_INVALID_ARGS;
3083
3084         iov_iter_kvec(&to, READ | ITER_KVEC, &v, 1, buf_size);
3085
3086         qp_lock(qpair);
3087
3088         do {
3089                 result = qp_dequeue_locked(qpair->produce_q,
3090                                            qpair->consume_q,
3091                                            qpair->consume_q_size,
3092                                            &to, true);
3093
3094                 if (result == VMCI_ERROR_QUEUEPAIR_NOT_READY &&
3095                     !qp_wait_for_ready_queue(qpair))
3096                         result = VMCI_ERROR_WOULD_BLOCK;
3097
3098         } while (result == VMCI_ERROR_QUEUEPAIR_NOT_READY);
3099
3100         qp_unlock(qpair);
3101
3102         return result;
3103 }
3104 EXPORT_SYMBOL_GPL(vmci_qpair_dequeue);
3105
3106 /*
3107  * vmci_qpair_peek() - Peek at the data in the queue.
3108  * @qpair:      Pointer to the queue pair struct.
3109  * @buf:        Pointer to buffer for the data
3110  * @buf_size:   Length of buffer.
3111  * @buf_type:   Buffer type (Unused on Linux).
3112  *
3113  * This is the client interface for peeking into a queue.  (I.e.,
3114  * copy data from the queue without updating the head pointer.)
3115  * Returns number of bytes dequeued or < 0 on error.
3116  */
3117 ssize_t vmci_qpair_peek(struct vmci_qp *qpair,
3118                         void *buf,
3119                         size_t buf_size,
3120                         int buf_type)
3121 {
3122         struct iov_iter to;
3123         struct kvec v = {.iov_base = buf, .iov_len = buf_size};
3124         ssize_t result;
3125
3126         if (!qpair || !buf)
3127                 return VMCI_ERROR_INVALID_ARGS;
3128
3129         iov_iter_kvec(&to, READ | ITER_KVEC, &v, 1, buf_size);
3130
3131         qp_lock(qpair);
3132
3133         do {
3134                 result = qp_dequeue_locked(qpair->produce_q,
3135                                            qpair->consume_q,
3136                                            qpair->consume_q_size,
3137                                            &to, false);
3138
3139                 if (result == VMCI_ERROR_QUEUEPAIR_NOT_READY &&
3140                     !qp_wait_for_ready_queue(qpair))
3141                         result = VMCI_ERROR_WOULD_BLOCK;
3142
3143         } while (result == VMCI_ERROR_QUEUEPAIR_NOT_READY);
3144
3145         qp_unlock(qpair);
3146
3147         return result;
3148 }
3149 EXPORT_SYMBOL_GPL(vmci_qpair_peek);
3150
3151 /*
3152  * vmci_qpair_enquev() - Throw data on the queue using iov.
3153  * @qpair:      Pointer to the queue pair struct.
3154  * @iov:        Pointer to buffer containing data
3155  * @iov_size:   Length of buffer.
3156  * @buf_type:   Buffer type (Unused).
3157  *
3158  * This is the client interface for enqueueing data into the queue.
3159  * This function uses IO vectors to handle the work. Returns number
3160  * of bytes enqueued or < 0 on error.
3161  */
3162 ssize_t vmci_qpair_enquev(struct vmci_qp *qpair,
3163                           struct msghdr *msg,
3164                           size_t iov_size,
3165                           int buf_type)
3166 {
3167         ssize_t result;
3168
3169         if (!qpair)
3170                 return VMCI_ERROR_INVALID_ARGS;
3171
3172         qp_lock(qpair);
3173
3174         do {
3175                 result = qp_enqueue_locked(qpair->produce_q,
3176                                            qpair->consume_q,
3177                                            qpair->produce_q_size,
3178                                            &msg->msg_iter);
3179
3180                 if (result == VMCI_ERROR_QUEUEPAIR_NOT_READY &&
3181                     !qp_wait_for_ready_queue(qpair))
3182                         result = VMCI_ERROR_WOULD_BLOCK;
3183
3184         } while (result == VMCI_ERROR_QUEUEPAIR_NOT_READY);
3185
3186         qp_unlock(qpair);
3187
3188         return result;
3189 }
3190 EXPORT_SYMBOL_GPL(vmci_qpair_enquev);
3191
3192 /*
3193  * vmci_qpair_dequev() - Get data from the queue using iov.
3194  * @qpair:      Pointer to the queue pair struct.
3195  * @iov:        Pointer to buffer for the data
3196  * @iov_size:   Length of buffer.
3197  * @buf_type:   Buffer type (Unused).
3198  *
3199  * This is the client interface for dequeueing data from the queue.
3200  * This function uses IO vectors to handle the work. Returns number
3201  * of bytes dequeued or < 0 on error.
3202  */
3203 ssize_t vmci_qpair_dequev(struct vmci_qp *qpair,
3204                           struct msghdr *msg,
3205                           size_t iov_size,
3206                           int buf_type)
3207 {
3208         ssize_t result;
3209
3210         if (!qpair)
3211                 return VMCI_ERROR_INVALID_ARGS;
3212
3213         qp_lock(qpair);
3214
3215         do {
3216                 result = qp_dequeue_locked(qpair->produce_q,
3217                                            qpair->consume_q,
3218                                            qpair->consume_q_size,
3219                                            &msg->msg_iter, true);
3220
3221                 if (result == VMCI_ERROR_QUEUEPAIR_NOT_READY &&
3222                     !qp_wait_for_ready_queue(qpair))
3223                         result = VMCI_ERROR_WOULD_BLOCK;
3224
3225         } while (result == VMCI_ERROR_QUEUEPAIR_NOT_READY);
3226
3227         qp_unlock(qpair);
3228
3229         return result;
3230 }
3231 EXPORT_SYMBOL_GPL(vmci_qpair_dequev);
3232
3233 /*
3234  * vmci_qpair_peekv() - Peek at the data in the queue using iov.
3235  * @qpair:      Pointer to the queue pair struct.
3236  * @iov:        Pointer to buffer for the data
3237  * @iov_size:   Length of buffer.
3238  * @buf_type:   Buffer type (Unused on Linux).
3239  *
3240  * This is the client interface for peeking into a queue.  (I.e.,
3241  * copy data from the queue without updating the head pointer.)
3242  * This function uses IO vectors to handle the work. Returns number
3243  * of bytes peeked or < 0 on error.
3244  */
3245 ssize_t vmci_qpair_peekv(struct vmci_qp *qpair,
3246                          struct msghdr *msg,
3247                          size_t iov_size,
3248                          int buf_type)
3249 {
3250         ssize_t result;
3251
3252         if (!qpair)
3253                 return VMCI_ERROR_INVALID_ARGS;
3254
3255         qp_lock(qpair);
3256
3257         do {
3258                 result = qp_dequeue_locked(qpair->produce_q,
3259                                            qpair->consume_q,
3260                                            qpair->consume_q_size,
3261                                            &msg->msg_iter, false);
3262
3263                 if (result == VMCI_ERROR_QUEUEPAIR_NOT_READY &&
3264                     !qp_wait_for_ready_queue(qpair))
3265                         result = VMCI_ERROR_WOULD_BLOCK;
3266
3267         } while (result == VMCI_ERROR_QUEUEPAIR_NOT_READY);
3268
3269         qp_unlock(qpair);
3270         return result;
3271 }
3272 EXPORT_SYMBOL_GPL(vmci_qpair_peekv);