GNU Linux-libre 4.9.317-gnu1
[releases.git] / drivers / xen / xenbus / xenbus_client.c
1 /******************************************************************************
2  * Client-facing interface for the Xenbus driver.  In other words, the
3  * interface between the Xenbus and the device-specific code, be it the
4  * frontend or the backend of that driver.
5  *
6  * Copyright (C) 2005 XenSource Ltd
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License version 2
10  * as published by the Free Software Foundation; or, when distributed
11  * separately from the Linux kernel or incorporated into other
12  * software packages, subject to the following license:
13  *
14  * Permission is hereby granted, free of charge, to any person obtaining a copy
15  * of this source file (the "Software"), to deal in the Software without
16  * restriction, including without limitation the rights to use, copy, modify,
17  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
18  * and to permit persons to whom the Software is furnished to do so, subject to
19  * the following conditions:
20  *
21  * The above copyright notice and this permission notice shall be included in
22  * all copies or substantial portions of the Software.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
29  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
30  * IN THE SOFTWARE.
31  */
32
33 #include <linux/mm.h>
34 #include <linux/slab.h>
35 #include <linux/types.h>
36 #include <linux/spinlock.h>
37 #include <linux/vmalloc.h>
38 #include <linux/export.h>
39 #include <asm/xen/hypervisor.h>
40 #include <xen/page.h>
41 #include <xen/interface/xen.h>
42 #include <xen/interface/event_channel.h>
43 #include <xen/balloon.h>
44 #include <xen/events.h>
45 #include <xen/grant_table.h>
46 #include <xen/xenbus.h>
47 #include <xen/xen.h>
48 #include <xen/features.h>
49
50 #include "xenbus_probe.h"
51
52 #define XENBUS_PAGES(_grants)   (DIV_ROUND_UP(_grants, XEN_PFN_PER_PAGE))
53
54 #define XENBUS_MAX_RING_PAGES   (XENBUS_PAGES(XENBUS_MAX_RING_GRANTS))
55
56 struct xenbus_map_node {
57         struct list_head next;
58         union {
59                 struct {
60                         struct vm_struct *area;
61                 } pv;
62                 struct {
63                         struct page *pages[XENBUS_MAX_RING_PAGES];
64                         unsigned long addrs[XENBUS_MAX_RING_GRANTS];
65                         void *addr;
66                 } hvm;
67         };
68         grant_handle_t handles[XENBUS_MAX_RING_GRANTS];
69         unsigned int   nr_handles;
70 };
71
72 static DEFINE_SPINLOCK(xenbus_valloc_lock);
73 static LIST_HEAD(xenbus_valloc_pages);
74
75 struct xenbus_ring_ops {
76         int (*map)(struct xenbus_device *dev,
77                    grant_ref_t *gnt_refs, unsigned int nr_grefs,
78                    void **vaddr);
79         int (*unmap)(struct xenbus_device *dev, void *vaddr);
80 };
81
82 static const struct xenbus_ring_ops *ring_ops __read_mostly;
83
84 const char *xenbus_strstate(enum xenbus_state state)
85 {
86         static const char *const name[] = {
87                 [ XenbusStateUnknown      ] = "Unknown",
88                 [ XenbusStateInitialising ] = "Initialising",
89                 [ XenbusStateInitWait     ] = "InitWait",
90                 [ XenbusStateInitialised  ] = "Initialised",
91                 [ XenbusStateConnected    ] = "Connected",
92                 [ XenbusStateClosing      ] = "Closing",
93                 [ XenbusStateClosed       ] = "Closed",
94                 [XenbusStateReconfiguring] = "Reconfiguring",
95                 [XenbusStateReconfigured] = "Reconfigured",
96         };
97         return (state < ARRAY_SIZE(name)) ? name[state] : "INVALID";
98 }
99 EXPORT_SYMBOL_GPL(xenbus_strstate);
100
101 /**
102  * xenbus_watch_path - register a watch
103  * @dev: xenbus device
104  * @path: path to watch
105  * @watch: watch to register
106  * @callback: callback to register
107  *
108  * Register a @watch on the given path, using the given xenbus_watch structure
109  * for storage, and the given @callback function as the callback.  Return 0 on
110  * success, or -errno on error.  On success, the given @path will be saved as
111  * @watch->node, and remains the caller's to free.  On error, @watch->node will
112  * be NULL, the device will switch to %XenbusStateClosing, and the error will
113  * be saved in the store.
114  */
115 int xenbus_watch_path(struct xenbus_device *dev, const char *path,
116                       struct xenbus_watch *watch,
117                       bool (*will_handle)(struct xenbus_watch *,
118                                           const char **, unsigned int),
119                       void (*callback)(struct xenbus_watch *,
120                                        const char **, unsigned int))
121 {
122         int err;
123
124         watch->node = path;
125         watch->will_handle = will_handle;
126         watch->callback = callback;
127
128         err = register_xenbus_watch(watch);
129
130         if (err) {
131                 watch->node = NULL;
132                 watch->will_handle = NULL;
133                 watch->callback = NULL;
134                 xenbus_dev_fatal(dev, err, "adding watch on %s", path);
135         }
136
137         return err;
138 }
139 EXPORT_SYMBOL_GPL(xenbus_watch_path);
140
141
142 /**
143  * xenbus_watch_pathfmt - register a watch on a sprintf-formatted path
144  * @dev: xenbus device
145  * @watch: watch to register
146  * @callback: callback to register
147  * @pathfmt: format of path to watch
148  *
149  * Register a watch on the given @path, using the given xenbus_watch
150  * structure for storage, and the given @callback function as the callback.
151  * Return 0 on success, or -errno on error.  On success, the watched path
152  * (@path/@path2) will be saved as @watch->node, and becomes the caller's to
153  * kfree().  On error, watch->node will be NULL, so the caller has nothing to
154  * free, the device will switch to %XenbusStateClosing, and the error will be
155  * saved in the store.
156  */
157 int xenbus_watch_pathfmt(struct xenbus_device *dev,
158                          struct xenbus_watch *watch,
159                          bool (*will_handle)(struct xenbus_watch *,
160                                              const char **, unsigned int),
161                          void (*callback)(struct xenbus_watch *,
162                                         const char **, unsigned int),
163                          const char *pathfmt, ...)
164 {
165         int err;
166         va_list ap;
167         char *path;
168
169         va_start(ap, pathfmt);
170         path = kvasprintf(GFP_NOIO | __GFP_HIGH, pathfmt, ap);
171         va_end(ap);
172
173         if (!path) {
174                 xenbus_dev_fatal(dev, -ENOMEM, "allocating path for watch");
175                 return -ENOMEM;
176         }
177         err = xenbus_watch_path(dev, path, watch, will_handle, callback);
178
179         if (err)
180                 kfree(path);
181         return err;
182 }
183 EXPORT_SYMBOL_GPL(xenbus_watch_pathfmt);
184
185 static void xenbus_switch_fatal(struct xenbus_device *, int, int,
186                                 const char *, ...);
187
188 static int
189 __xenbus_switch_state(struct xenbus_device *dev,
190                       enum xenbus_state state, int depth)
191 {
192         /* We check whether the state is currently set to the given value, and
193            if not, then the state is set.  We don't want to unconditionally
194            write the given state, because we don't want to fire watches
195            unnecessarily.  Furthermore, if the node has gone, we don't write
196            to it, as the device will be tearing down, and we don't want to
197            resurrect that directory.
198
199            Note that, because of this cached value of our state, this
200            function will not take a caller's Xenstore transaction
201            (something it was trying to in the past) because dev->state
202            would not get reset if the transaction was aborted.
203          */
204
205         struct xenbus_transaction xbt;
206         int current_state;
207         int err, abort;
208
209         if (state == dev->state)
210                 return 0;
211
212 again:
213         abort = 1;
214
215         err = xenbus_transaction_start(&xbt);
216         if (err) {
217                 xenbus_switch_fatal(dev, depth, err, "starting transaction");
218                 return 0;
219         }
220
221         err = xenbus_scanf(xbt, dev->nodename, "state", "%d", &current_state);
222         if (err != 1)
223                 goto abort;
224
225         err = xenbus_printf(xbt, dev->nodename, "state", "%d", state);
226         if (err) {
227                 xenbus_switch_fatal(dev, depth, err, "writing new state");
228                 goto abort;
229         }
230
231         abort = 0;
232 abort:
233         err = xenbus_transaction_end(xbt, abort);
234         if (err) {
235                 if (err == -EAGAIN && !abort)
236                         goto again;
237                 xenbus_switch_fatal(dev, depth, err, "ending transaction");
238         } else
239                 dev->state = state;
240
241         return 0;
242 }
243
244 /**
245  * xenbus_switch_state
246  * @dev: xenbus device
247  * @state: new state
248  *
249  * Advertise in the store a change of the given driver to the given new_state.
250  * Return 0 on success, or -errno on error.  On error, the device will switch
251  * to XenbusStateClosing, and the error will be saved in the store.
252  */
253 int xenbus_switch_state(struct xenbus_device *dev, enum xenbus_state state)
254 {
255         return __xenbus_switch_state(dev, state, 0);
256 }
257
258 EXPORT_SYMBOL_GPL(xenbus_switch_state);
259
260 int xenbus_frontend_closed(struct xenbus_device *dev)
261 {
262         xenbus_switch_state(dev, XenbusStateClosed);
263         complete(&dev->down);
264         return 0;
265 }
266 EXPORT_SYMBOL_GPL(xenbus_frontend_closed);
267
268 /**
269  * Return the path to the error node for the given device, or NULL on failure.
270  * If the value returned is non-NULL, then it is the caller's to kfree.
271  */
272 static char *error_path(struct xenbus_device *dev)
273 {
274         return kasprintf(GFP_KERNEL, "error/%s", dev->nodename);
275 }
276
277
278 static void xenbus_va_dev_error(struct xenbus_device *dev, int err,
279                                 const char *fmt, va_list ap)
280 {
281         unsigned int len;
282         char *printf_buffer = NULL;
283         char *path_buffer = NULL;
284
285 #define PRINTF_BUFFER_SIZE 4096
286         printf_buffer = kmalloc(PRINTF_BUFFER_SIZE, GFP_KERNEL);
287         if (printf_buffer == NULL)
288                 goto fail;
289
290         len = sprintf(printf_buffer, "%i ", -err);
291         vsnprintf(printf_buffer+len, PRINTF_BUFFER_SIZE-len, fmt, ap);
292
293         dev_err(&dev->dev, "%s\n", printf_buffer);
294
295         path_buffer = error_path(dev);
296
297         if (path_buffer == NULL) {
298                 dev_err(&dev->dev, "failed to write error node for %s (%s)\n",
299                        dev->nodename, printf_buffer);
300                 goto fail;
301         }
302
303         if (xenbus_write(XBT_NIL, path_buffer, "error", printf_buffer) != 0) {
304                 dev_err(&dev->dev, "failed to write error node for %s (%s)\n",
305                        dev->nodename, printf_buffer);
306                 goto fail;
307         }
308
309 fail:
310         kfree(printf_buffer);
311         kfree(path_buffer);
312 }
313
314
315 /**
316  * xenbus_dev_error
317  * @dev: xenbus device
318  * @err: error to report
319  * @fmt: error message format
320  *
321  * Report the given negative errno into the store, along with the given
322  * formatted message.
323  */
324 void xenbus_dev_error(struct xenbus_device *dev, int err, const char *fmt, ...)
325 {
326         va_list ap;
327
328         va_start(ap, fmt);
329         xenbus_va_dev_error(dev, err, fmt, ap);
330         va_end(ap);
331 }
332 EXPORT_SYMBOL_GPL(xenbus_dev_error);
333
334 /**
335  * xenbus_dev_fatal
336  * @dev: xenbus device
337  * @err: error to report
338  * @fmt: error message format
339  *
340  * Equivalent to xenbus_dev_error(dev, err, fmt, args), followed by
341  * xenbus_switch_state(dev, XenbusStateClosing) to schedule an orderly
342  * closedown of this driver and its peer.
343  */
344
345 void xenbus_dev_fatal(struct xenbus_device *dev, int err, const char *fmt, ...)
346 {
347         va_list ap;
348
349         va_start(ap, fmt);
350         xenbus_va_dev_error(dev, err, fmt, ap);
351         va_end(ap);
352
353         xenbus_switch_state(dev, XenbusStateClosing);
354 }
355 EXPORT_SYMBOL_GPL(xenbus_dev_fatal);
356
357 /**
358  * Equivalent to xenbus_dev_fatal(dev, err, fmt, args), but helps
359  * avoiding recursion within xenbus_switch_state.
360  */
361 static void xenbus_switch_fatal(struct xenbus_device *dev, int depth, int err,
362                                 const char *fmt, ...)
363 {
364         va_list ap;
365
366         va_start(ap, fmt);
367         xenbus_va_dev_error(dev, err, fmt, ap);
368         va_end(ap);
369
370         if (!depth)
371                 __xenbus_switch_state(dev, XenbusStateClosing, 1);
372 }
373
374 /**
375  * xenbus_grant_ring
376  * @dev: xenbus device
377  * @vaddr: starting virtual address of the ring
378  * @nr_pages: number of pages to be granted
379  * @grefs: grant reference array to be filled in
380  *
381  * Grant access to the given @vaddr to the peer of the given device.
382  * Then fill in @grefs with grant references.  Return 0 on success, or
383  * -errno on error.  On error, the device will switch to
384  * XenbusStateClosing, and the error will be saved in the store.
385  */
386 int xenbus_grant_ring(struct xenbus_device *dev, void *vaddr,
387                       unsigned int nr_pages, grant_ref_t *grefs)
388 {
389         int err;
390         unsigned int i;
391         grant_ref_t gref_head;
392
393         err = gnttab_alloc_grant_references(nr_pages, &gref_head);
394         if (err) {
395                 xenbus_dev_fatal(dev, err, "granting access to ring page");
396                 return err;
397         }
398
399         for (i = 0; i < nr_pages; i++) {
400                 unsigned long gfn;
401
402                 if (is_vmalloc_addr(vaddr))
403                         gfn = pfn_to_gfn(vmalloc_to_pfn(vaddr));
404                 else
405                         gfn = virt_to_gfn(vaddr);
406
407                 grefs[i] = gnttab_claim_grant_reference(&gref_head);
408                 gnttab_grant_foreign_access_ref(grefs[i], dev->otherend_id,
409                                                 gfn, 0);
410
411                 vaddr = vaddr + XEN_PAGE_SIZE;
412         }
413
414         return 0;
415 }
416 EXPORT_SYMBOL_GPL(xenbus_grant_ring);
417
418
419 /**
420  * Allocate an event channel for the given xenbus_device, assigning the newly
421  * created local port to *port.  Return 0 on success, or -errno on error.  On
422  * error, the device will switch to XenbusStateClosing, and the error will be
423  * saved in the store.
424  */
425 int xenbus_alloc_evtchn(struct xenbus_device *dev, int *port)
426 {
427         struct evtchn_alloc_unbound alloc_unbound;
428         int err;
429
430         alloc_unbound.dom = DOMID_SELF;
431         alloc_unbound.remote_dom = dev->otherend_id;
432
433         err = HYPERVISOR_event_channel_op(EVTCHNOP_alloc_unbound,
434                                           &alloc_unbound);
435         if (err)
436                 xenbus_dev_fatal(dev, err, "allocating event channel");
437         else
438                 *port = alloc_unbound.port;
439
440         return err;
441 }
442 EXPORT_SYMBOL_GPL(xenbus_alloc_evtchn);
443
444
445 /**
446  * Free an existing event channel. Returns 0 on success or -errno on error.
447  */
448 int xenbus_free_evtchn(struct xenbus_device *dev, int port)
449 {
450         struct evtchn_close close;
451         int err;
452
453         close.port = port;
454
455         err = HYPERVISOR_event_channel_op(EVTCHNOP_close, &close);
456         if (err)
457                 xenbus_dev_error(dev, err, "freeing event channel %d", port);
458
459         return err;
460 }
461 EXPORT_SYMBOL_GPL(xenbus_free_evtchn);
462
463
464 /**
465  * xenbus_map_ring_valloc
466  * @dev: xenbus device
467  * @gnt_refs: grant reference array
468  * @nr_grefs: number of grant references
469  * @vaddr: pointer to address to be filled out by mapping
470  *
471  * Map @nr_grefs pages of memory into this domain from another
472  * domain's grant table.  xenbus_map_ring_valloc allocates @nr_grefs
473  * pages of virtual address space, maps the pages to that address, and
474  * sets *vaddr to that address.  Returns 0 on success, and GNTST_*
475  * (see xen/include/interface/grant_table.h) or -ENOMEM / -EINVAL on
476  * error. If an error is returned, device will switch to
477  * XenbusStateClosing and the error message will be saved in XenStore.
478  */
479 int xenbus_map_ring_valloc(struct xenbus_device *dev, grant_ref_t *gnt_refs,
480                            unsigned int nr_grefs, void **vaddr)
481 {
482         int err;
483
484         err = ring_ops->map(dev, gnt_refs, nr_grefs, vaddr);
485         /* Some hypervisors are buggy and can return 1. */
486         if (err > 0)
487                 err = GNTST_general_error;
488
489         return err;
490 }
491 EXPORT_SYMBOL_GPL(xenbus_map_ring_valloc);
492
493 /* N.B. sizeof(phys_addr_t) doesn't always equal to sizeof(unsigned
494  * long), e.g. 32-on-64.  Caller is responsible for preparing the
495  * right array to feed into this function */
496 static int __xenbus_map_ring(struct xenbus_device *dev,
497                              grant_ref_t *gnt_refs,
498                              unsigned int nr_grefs,
499                              grant_handle_t *handles,
500                              phys_addr_t *addrs,
501                              unsigned int flags,
502                              bool *leaked)
503 {
504         struct gnttab_map_grant_ref map[XENBUS_MAX_RING_GRANTS];
505         struct gnttab_unmap_grant_ref unmap[XENBUS_MAX_RING_GRANTS];
506         int i, j;
507         int err = GNTST_okay;
508
509         if (nr_grefs > XENBUS_MAX_RING_GRANTS)
510                 return -EINVAL;
511
512         for (i = 0; i < nr_grefs; i++) {
513                 memset(&map[i], 0, sizeof(map[i]));
514                 gnttab_set_map_op(&map[i], addrs[i], flags, gnt_refs[i],
515                                   dev->otherend_id);
516                 handles[i] = INVALID_GRANT_HANDLE;
517         }
518
519         gnttab_batch_map(map, i);
520
521         for (i = 0; i < nr_grefs; i++) {
522                 if (map[i].status != GNTST_okay) {
523                         err = map[i].status;
524                         xenbus_dev_fatal(dev, map[i].status,
525                                          "mapping in shared page %d from domain %d",
526                                          gnt_refs[i], dev->otherend_id);
527                         goto fail;
528                 } else
529                         handles[i] = map[i].handle;
530         }
531
532         return GNTST_okay;
533
534  fail:
535         for (i = j = 0; i < nr_grefs; i++) {
536                 if (handles[i] != INVALID_GRANT_HANDLE) {
537                         memset(&unmap[j], 0, sizeof(unmap[j]));
538                         gnttab_set_unmap_op(&unmap[j], (phys_addr_t)addrs[i],
539                                             GNTMAP_host_map, handles[i]);
540                         j++;
541                 }
542         }
543
544         if (HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref, unmap, j))
545                 BUG();
546
547         *leaked = false;
548         for (i = 0; i < j; i++) {
549                 if (unmap[i].status != GNTST_okay) {
550                         *leaked = true;
551                         break;
552                 }
553         }
554
555         return err;
556 }
557
558 static int xenbus_map_ring_valloc_pv(struct xenbus_device *dev,
559                                      grant_ref_t *gnt_refs,
560                                      unsigned int nr_grefs,
561                                      void **vaddr)
562 {
563         struct xenbus_map_node *node;
564         struct vm_struct *area;
565         pte_t *ptes[XENBUS_MAX_RING_GRANTS];
566         phys_addr_t phys_addrs[XENBUS_MAX_RING_GRANTS];
567         int err = GNTST_okay;
568         int i;
569         bool leaked;
570
571         *vaddr = NULL;
572
573         if (nr_grefs > XENBUS_MAX_RING_GRANTS)
574                 return -EINVAL;
575
576         node = kzalloc(sizeof(*node), GFP_KERNEL);
577         if (!node)
578                 return -ENOMEM;
579
580         area = alloc_vm_area(XEN_PAGE_SIZE * nr_grefs, ptes);
581         if (!area) {
582                 kfree(node);
583                 return -ENOMEM;
584         }
585
586         for (i = 0; i < nr_grefs; i++)
587                 phys_addrs[i] = arbitrary_virt_to_machine(ptes[i]).maddr;
588
589         err = __xenbus_map_ring(dev, gnt_refs, nr_grefs, node->handles,
590                                 phys_addrs,
591                                 GNTMAP_host_map | GNTMAP_contains_pte,
592                                 &leaked);
593         if (err)
594                 goto failed;
595
596         node->nr_handles = nr_grefs;
597         node->pv.area = area;
598
599         spin_lock(&xenbus_valloc_lock);
600         list_add(&node->next, &xenbus_valloc_pages);
601         spin_unlock(&xenbus_valloc_lock);
602
603         *vaddr = area->addr;
604         return 0;
605
606 failed:
607         if (!leaked)
608                 free_vm_area(area);
609         else
610                 pr_alert("leaking VM area %p size %u page(s)", area, nr_grefs);
611
612         kfree(node);
613         return err;
614 }
615
616 struct map_ring_valloc_hvm
617 {
618         unsigned int idx;
619
620         /* Why do we need two arrays? See comment of __xenbus_map_ring */
621         phys_addr_t phys_addrs[XENBUS_MAX_RING_GRANTS];
622         unsigned long addrs[XENBUS_MAX_RING_GRANTS];
623 };
624
625 static void xenbus_map_ring_setup_grant_hvm(unsigned long gfn,
626                                             unsigned int goffset,
627                                             unsigned int len,
628                                             void *data)
629 {
630         struct map_ring_valloc_hvm *info = data;
631         unsigned long vaddr = (unsigned long)gfn_to_virt(gfn);
632
633         info->phys_addrs[info->idx] = vaddr;
634         info->addrs[info->idx] = vaddr;
635
636         info->idx++;
637 }
638
639 static int xenbus_map_ring_valloc_hvm(struct xenbus_device *dev,
640                                       grant_ref_t *gnt_ref,
641                                       unsigned int nr_grefs,
642                                       void **vaddr)
643 {
644         struct xenbus_map_node *node;
645         int err;
646         void *addr;
647         bool leaked = false;
648         struct map_ring_valloc_hvm info = {
649                 .idx = 0,
650         };
651         unsigned int nr_pages = XENBUS_PAGES(nr_grefs);
652
653         if (nr_grefs > XENBUS_MAX_RING_GRANTS)
654                 return -EINVAL;
655
656         *vaddr = NULL;
657
658         node = kzalloc(sizeof(*node), GFP_KERNEL);
659         if (!node)
660                 return -ENOMEM;
661
662         err = alloc_xenballooned_pages(nr_pages, node->hvm.pages);
663         if (err)
664                 goto out_err;
665
666         gnttab_foreach_grant(node->hvm.pages, nr_grefs,
667                              xenbus_map_ring_setup_grant_hvm,
668                              &info);
669
670         err = __xenbus_map_ring(dev, gnt_ref, nr_grefs, node->handles,
671                                 info.phys_addrs, GNTMAP_host_map, &leaked);
672         node->nr_handles = nr_grefs;
673
674         if (err)
675                 goto out_free_ballooned_pages;
676
677         addr = vmap(node->hvm.pages, nr_pages, VM_MAP | VM_IOREMAP,
678                     PAGE_KERNEL);
679         if (!addr) {
680                 err = -ENOMEM;
681                 goto out_xenbus_unmap_ring;
682         }
683
684         node->hvm.addr = addr;
685
686         spin_lock(&xenbus_valloc_lock);
687         list_add(&node->next, &xenbus_valloc_pages);
688         spin_unlock(&xenbus_valloc_lock);
689
690         *vaddr = addr;
691         return 0;
692
693  out_xenbus_unmap_ring:
694         if (!leaked)
695                 xenbus_unmap_ring(dev, node->handles, nr_grefs, info.addrs);
696         else
697                 pr_alert("leaking %p size %u page(s)",
698                          addr, nr_pages);
699  out_free_ballooned_pages:
700         if (!leaked)
701                 free_xenballooned_pages(nr_pages, node->hvm.pages);
702  out_err:
703         kfree(node);
704         return err;
705 }
706
707
708 /**
709  * xenbus_map_ring
710  * @dev: xenbus device
711  * @gnt_refs: grant reference array
712  * @nr_grefs: number of grant reference
713  * @handles: pointer to grant handle to be filled
714  * @vaddrs: addresses to be mapped to
715  * @leaked: fail to clean up a failed map, caller should not free vaddr
716  *
717  * Map pages of memory into this domain from another domain's grant table.
718  * xenbus_map_ring does not allocate the virtual address space (you must do
719  * this yourself!). It only maps in the pages to the specified address.
720  * Returns 0 on success, and GNTST_* (see xen/include/interface/grant_table.h)
721  * or -ENOMEM / -EINVAL on error. If an error is returned, device will switch to
722  * XenbusStateClosing and the first error message will be saved in XenStore.
723  * Further more if we fail to map the ring, caller should check @leaked.
724  * If @leaked is not zero it means xenbus_map_ring fails to clean up, caller
725  * should not free the address space of @vaddr.
726  */
727 int xenbus_map_ring(struct xenbus_device *dev, grant_ref_t *gnt_refs,
728                     unsigned int nr_grefs, grant_handle_t *handles,
729                     unsigned long *vaddrs, bool *leaked)
730 {
731         phys_addr_t phys_addrs[XENBUS_MAX_RING_GRANTS];
732         int i;
733
734         if (nr_grefs > XENBUS_MAX_RING_GRANTS)
735                 return -EINVAL;
736
737         for (i = 0; i < nr_grefs; i++)
738                 phys_addrs[i] = (unsigned long)vaddrs[i];
739
740         return __xenbus_map_ring(dev, gnt_refs, nr_grefs, handles,
741                                  phys_addrs, GNTMAP_host_map, leaked);
742 }
743 EXPORT_SYMBOL_GPL(xenbus_map_ring);
744
745
746 /**
747  * xenbus_unmap_ring_vfree
748  * @dev: xenbus device
749  * @vaddr: addr to unmap
750  *
751  * Based on Rusty Russell's skeleton driver's unmap_page.
752  * Unmap a page of memory in this domain that was imported from another domain.
753  * Use xenbus_unmap_ring_vfree if you mapped in your memory with
754  * xenbus_map_ring_valloc (it will free the virtual address space).
755  * Returns 0 on success and returns GNTST_* on error
756  * (see xen/include/interface/grant_table.h).
757  */
758 int xenbus_unmap_ring_vfree(struct xenbus_device *dev, void *vaddr)
759 {
760         return ring_ops->unmap(dev, vaddr);
761 }
762 EXPORT_SYMBOL_GPL(xenbus_unmap_ring_vfree);
763
764 static int xenbus_unmap_ring_vfree_pv(struct xenbus_device *dev, void *vaddr)
765 {
766         struct xenbus_map_node *node;
767         struct gnttab_unmap_grant_ref unmap[XENBUS_MAX_RING_GRANTS];
768         unsigned int level;
769         int i;
770         bool leaked = false;
771         int err;
772
773         spin_lock(&xenbus_valloc_lock);
774         list_for_each_entry(node, &xenbus_valloc_pages, next) {
775                 if (node->pv.area->addr == vaddr) {
776                         list_del(&node->next);
777                         goto found;
778                 }
779         }
780         node = NULL;
781  found:
782         spin_unlock(&xenbus_valloc_lock);
783
784         if (!node) {
785                 xenbus_dev_error(dev, -ENOENT,
786                                  "can't find mapped virtual address %p", vaddr);
787                 return GNTST_bad_virt_addr;
788         }
789
790         for (i = 0; i < node->nr_handles; i++) {
791                 unsigned long addr;
792
793                 memset(&unmap[i], 0, sizeof(unmap[i]));
794                 addr = (unsigned long)vaddr + (XEN_PAGE_SIZE * i);
795                 unmap[i].host_addr = arbitrary_virt_to_machine(
796                         lookup_address(addr, &level)).maddr;
797                 unmap[i].dev_bus_addr = 0;
798                 unmap[i].handle = node->handles[i];
799         }
800
801         if (HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref, unmap, i))
802                 BUG();
803
804         err = GNTST_okay;
805         leaked = false;
806         for (i = 0; i < node->nr_handles; i++) {
807                 if (unmap[i].status != GNTST_okay) {
808                         leaked = true;
809                         xenbus_dev_error(dev, unmap[i].status,
810                                          "unmapping page at handle %d error %d",
811                                          node->handles[i], unmap[i].status);
812                         err = unmap[i].status;
813                         break;
814                 }
815         }
816
817         if (!leaked)
818                 free_vm_area(node->pv.area);
819         else
820                 pr_alert("leaking VM area %p size %u page(s)",
821                          node->pv.area, node->nr_handles);
822
823         kfree(node);
824         return err;
825 }
826
827 struct unmap_ring_vfree_hvm
828 {
829         unsigned int idx;
830         unsigned long addrs[XENBUS_MAX_RING_GRANTS];
831 };
832
833 static void xenbus_unmap_ring_setup_grant_hvm(unsigned long gfn,
834                                               unsigned int goffset,
835                                               unsigned int len,
836                                               void *data)
837 {
838         struct unmap_ring_vfree_hvm *info = data;
839
840         info->addrs[info->idx] = (unsigned long)gfn_to_virt(gfn);
841
842         info->idx++;
843 }
844
845 static int xenbus_unmap_ring_vfree_hvm(struct xenbus_device *dev, void *vaddr)
846 {
847         int rv;
848         struct xenbus_map_node *node;
849         void *addr;
850         struct unmap_ring_vfree_hvm info = {
851                 .idx = 0,
852         };
853         unsigned int nr_pages;
854
855         spin_lock(&xenbus_valloc_lock);
856         list_for_each_entry(node, &xenbus_valloc_pages, next) {
857                 addr = node->hvm.addr;
858                 if (addr == vaddr) {
859                         list_del(&node->next);
860                         goto found;
861                 }
862         }
863         node = addr = NULL;
864  found:
865         spin_unlock(&xenbus_valloc_lock);
866
867         if (!node) {
868                 xenbus_dev_error(dev, -ENOENT,
869                                  "can't find mapped virtual address %p", vaddr);
870                 return GNTST_bad_virt_addr;
871         }
872
873         nr_pages = XENBUS_PAGES(node->nr_handles);
874
875         gnttab_foreach_grant(node->hvm.pages, node->nr_handles,
876                              xenbus_unmap_ring_setup_grant_hvm,
877                              &info);
878
879         rv = xenbus_unmap_ring(dev, node->handles, node->nr_handles,
880                                info.addrs);
881         if (!rv) {
882                 vunmap(vaddr);
883                 free_xenballooned_pages(nr_pages, node->hvm.pages);
884         }
885         else
886                 WARN(1, "Leaking %p, size %u page(s)\n", vaddr, nr_pages);
887
888         kfree(node);
889         return rv;
890 }
891
892 /**
893  * xenbus_unmap_ring
894  * @dev: xenbus device
895  * @handles: grant handle array
896  * @nr_handles: number of handles in the array
897  * @vaddrs: addresses to unmap
898  *
899  * Unmap memory in this domain that was imported from another domain.
900  * Returns 0 on success and returns GNTST_* on error
901  * (see xen/include/interface/grant_table.h).
902  */
903 int xenbus_unmap_ring(struct xenbus_device *dev,
904                       grant_handle_t *handles, unsigned int nr_handles,
905                       unsigned long *vaddrs)
906 {
907         struct gnttab_unmap_grant_ref unmap[XENBUS_MAX_RING_GRANTS];
908         int i;
909         int err;
910
911         if (nr_handles > XENBUS_MAX_RING_GRANTS)
912                 return -EINVAL;
913
914         for (i = 0; i < nr_handles; i++)
915                 gnttab_set_unmap_op(&unmap[i], vaddrs[i],
916                                     GNTMAP_host_map, handles[i]);
917
918         if (HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref, unmap, i))
919                 BUG();
920
921         err = GNTST_okay;
922         for (i = 0; i < nr_handles; i++) {
923                 if (unmap[i].status != GNTST_okay) {
924                         xenbus_dev_error(dev, unmap[i].status,
925                                          "unmapping page at handle %d error %d",
926                                          handles[i], unmap[i].status);
927                         err = unmap[i].status;
928                         break;
929                 }
930         }
931
932         return err;
933 }
934 EXPORT_SYMBOL_GPL(xenbus_unmap_ring);
935
936
937 /**
938  * xenbus_read_driver_state
939  * @path: path for driver
940  *
941  * Return the state of the driver rooted at the given store path, or
942  * XenbusStateUnknown if no state can be read.
943  */
944 enum xenbus_state xenbus_read_driver_state(const char *path)
945 {
946         enum xenbus_state result;
947         int err = xenbus_gather(XBT_NIL, path, "state", "%d", &result, NULL);
948         if (err)
949                 result = XenbusStateUnknown;
950
951         return result;
952 }
953 EXPORT_SYMBOL_GPL(xenbus_read_driver_state);
954
955 static const struct xenbus_ring_ops ring_ops_pv = {
956         .map = xenbus_map_ring_valloc_pv,
957         .unmap = xenbus_unmap_ring_vfree_pv,
958 };
959
960 static const struct xenbus_ring_ops ring_ops_hvm = {
961         .map = xenbus_map_ring_valloc_hvm,
962         .unmap = xenbus_unmap_ring_vfree_hvm,
963 };
964
965 void __init xenbus_ring_ops_init(void)
966 {
967         if (!xen_feature(XENFEAT_auto_translated_physmap))
968                 ring_ops = &ring_ops_pv;
969         else
970                 ring_ops = &ring_ops_hvm;
971 }