e6548910e79ff8186a862ae54378af5b7f559805
[platform/kernel/linux-starfive.git] / drivers / xen / grant-table.c
1 /******************************************************************************
2  * grant_table.c
3  *
4  * Granting foreign access to our memory reservation.
5  *
6  * Copyright (c) 2005-2006, Christopher Clark
7  * Copyright (c) 2004-2005, K A Fraser
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License version 2
11  * as published by the Free Software Foundation; or, when distributed
12  * separately from the Linux kernel or incorporated into other
13  * software packages, subject to the following license:
14  *
15  * Permission is hereby granted, free of charge, to any person obtaining a copy
16  * of this source file (the "Software"), to deal in the Software without
17  * restriction, including without limitation the rights to use, copy, modify,
18  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
19  * and to permit persons to whom the Software is furnished to do so, subject to
20  * the following conditions:
21  *
22  * The above copyright notice and this permission notice shall be included in
23  * all copies or substantial portions of the Software.
24  *
25  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
30  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
31  * IN THE SOFTWARE.
32  */
33
34 #define pr_fmt(fmt) "xen:" KBUILD_MODNAME ": " fmt
35
36 #include <linux/memblock.h>
37 #include <linux/sched.h>
38 #include <linux/mm.h>
39 #include <linux/slab.h>
40 #include <linux/vmalloc.h>
41 #include <linux/uaccess.h>
42 #include <linux/io.h>
43 #include <linux/delay.h>
44 #include <linux/hardirq.h>
45 #include <linux/workqueue.h>
46 #include <linux/ratelimit.h>
47 #include <linux/moduleparam.h>
48 #ifdef CONFIG_XEN_GRANT_DMA_ALLOC
49 #include <linux/dma-mapping.h>
50 #endif
51
52 #include <xen/xen.h>
53 #include <xen/interface/xen.h>
54 #include <xen/page.h>
55 #include <xen/grant_table.h>
56 #include <xen/interface/memory.h>
57 #include <xen/hvc-console.h>
58 #include <xen/swiotlb-xen.h>
59 #include <xen/balloon.h>
60 #ifdef CONFIG_X86
61 #include <asm/xen/cpuid.h>
62 #endif
63 #include <xen/mem-reservation.h>
64 #include <asm/xen/hypercall.h>
65 #include <asm/xen/interface.h>
66
67 #include <asm/sync_bitops.h>
68
69 /* External tools reserve first few grant table entries. */
70 #define NR_RESERVED_ENTRIES 8
71 #define GNTTAB_LIST_END 0xffffffff
72
73 static grant_ref_t **gnttab_list;
74 static unsigned int nr_grant_frames;
75 static int gnttab_free_count;
76 static grant_ref_t gnttab_free_head;
77 static DEFINE_SPINLOCK(gnttab_list_lock);
78 struct grant_frames xen_auto_xlat_grant_frames;
79 static unsigned int xen_gnttab_version;
80 module_param_named(version, xen_gnttab_version, uint, 0);
81
82 static union {
83         struct grant_entry_v1 *v1;
84         union grant_entry_v2 *v2;
85         void *addr;
86 } gnttab_shared;
87
88 /*This is a structure of function pointers for grant table*/
89 struct gnttab_ops {
90         /*
91          * Version of the grant interface.
92          */
93         unsigned int version;
94         /*
95          * Grant refs per grant frame.
96          */
97         unsigned int grefs_per_grant_frame;
98         /*
99          * Mapping a list of frames for storing grant entries. Frames parameter
100          * is used to store grant table address when grant table being setup,
101          * nr_gframes is the number of frames to map grant table. Returning
102          * GNTST_okay means success and negative value means failure.
103          */
104         int (*map_frames)(xen_pfn_t *frames, unsigned int nr_gframes);
105         /*
106          * Release a list of frames which are mapped in map_frames for grant
107          * entry status.
108          */
109         void (*unmap_frames)(void);
110         /*
111          * Introducing a valid entry into the grant table, granting the frame of
112          * this grant entry to domain for accessing or transfering. Ref
113          * parameter is reference of this introduced grant entry, domid is id of
114          * granted domain, frame is the page frame to be granted, and flags is
115          * status of the grant entry to be updated.
116          */
117         void (*update_entry)(grant_ref_t ref, domid_t domid,
118                              unsigned long frame, unsigned flags);
119         /*
120          * Stop granting a grant entry to domain for accessing. Ref parameter is
121          * reference of a grant entry whose grant access will be stopped,
122          * readonly is not in use in this function. If the grant entry is
123          * currently mapped for reading or writing, just return failure(==0)
124          * directly and don't tear down the grant access. Otherwise, stop grant
125          * access for this entry and return success(==1).
126          */
127         int (*end_foreign_access_ref)(grant_ref_t ref, int readonly);
128         /*
129          * Stop granting a grant entry to domain for transfer. Ref parameter is
130          * reference of a grant entry whose grant transfer will be stopped. If
131          * tranfer has not started, just reclaim the grant entry and return
132          * failure(==0). Otherwise, wait for the transfer to complete and then
133          * return the frame.
134          */
135         unsigned long (*end_foreign_transfer_ref)(grant_ref_t ref);
136 };
137
138 struct unmap_refs_callback_data {
139         struct completion completion;
140         int result;
141 };
142
143 static const struct gnttab_ops *gnttab_interface;
144
145 /* This reflects status of grant entries, so act as a global value. */
146 static grant_status_t *grstatus;
147
148 static struct gnttab_free_callback *gnttab_free_callback_list;
149
150 static int gnttab_expand(unsigned int req_entries);
151
152 #define RPP (PAGE_SIZE / sizeof(grant_ref_t))
153 #define SPP (PAGE_SIZE / sizeof(grant_status_t))
154
155 static inline grant_ref_t *__gnttab_entry(grant_ref_t entry)
156 {
157         return &gnttab_list[(entry) / RPP][(entry) % RPP];
158 }
159 /* This can be used as an l-value */
160 #define gnttab_entry(entry) (*__gnttab_entry(entry))
161
162 static int get_free_entries(unsigned count)
163 {
164         unsigned long flags;
165         int ref, rc = 0;
166         grant_ref_t head;
167
168         spin_lock_irqsave(&gnttab_list_lock, flags);
169
170         if ((gnttab_free_count < count) &&
171             ((rc = gnttab_expand(count - gnttab_free_count)) < 0)) {
172                 spin_unlock_irqrestore(&gnttab_list_lock, flags);
173                 return rc;
174         }
175
176         ref = head = gnttab_free_head;
177         gnttab_free_count -= count;
178         while (count-- > 1)
179                 head = gnttab_entry(head);
180         gnttab_free_head = gnttab_entry(head);
181         gnttab_entry(head) = GNTTAB_LIST_END;
182
183         spin_unlock_irqrestore(&gnttab_list_lock, flags);
184
185         return ref;
186 }
187
188 static void do_free_callbacks(void)
189 {
190         struct gnttab_free_callback *callback, *next;
191
192         callback = gnttab_free_callback_list;
193         gnttab_free_callback_list = NULL;
194
195         while (callback != NULL) {
196                 next = callback->next;
197                 if (gnttab_free_count >= callback->count) {
198                         callback->next = NULL;
199                         callback->fn(callback->arg);
200                 } else {
201                         callback->next = gnttab_free_callback_list;
202                         gnttab_free_callback_list = callback;
203                 }
204                 callback = next;
205         }
206 }
207
208 static inline void check_free_callbacks(void)
209 {
210         if (unlikely(gnttab_free_callback_list))
211                 do_free_callbacks();
212 }
213
214 static void put_free_entry(grant_ref_t ref)
215 {
216         unsigned long flags;
217         spin_lock_irqsave(&gnttab_list_lock, flags);
218         gnttab_entry(ref) = gnttab_free_head;
219         gnttab_free_head = ref;
220         gnttab_free_count++;
221         check_free_callbacks();
222         spin_unlock_irqrestore(&gnttab_list_lock, flags);
223 }
224
225 /*
226  * Following applies to gnttab_update_entry_v1 and gnttab_update_entry_v2.
227  * Introducing a valid entry into the grant table:
228  *  1. Write ent->domid.
229  *  2. Write ent->frame:
230  *      GTF_permit_access:   Frame to which access is permitted.
231  *      GTF_accept_transfer: Pseudo-phys frame slot being filled by new
232  *                           frame, or zero if none.
233  *  3. Write memory barrier (WMB).
234  *  4. Write ent->flags, inc. valid type.
235  */
236 static void gnttab_update_entry_v1(grant_ref_t ref, domid_t domid,
237                                    unsigned long frame, unsigned flags)
238 {
239         gnttab_shared.v1[ref].domid = domid;
240         gnttab_shared.v1[ref].frame = frame;
241         wmb();
242         gnttab_shared.v1[ref].flags = flags;
243 }
244
245 static void gnttab_update_entry_v2(grant_ref_t ref, domid_t domid,
246                                    unsigned long frame, unsigned int flags)
247 {
248         gnttab_shared.v2[ref].hdr.domid = domid;
249         gnttab_shared.v2[ref].full_page.frame = frame;
250         wmb();  /* Hypervisor concurrent accesses. */
251         gnttab_shared.v2[ref].hdr.flags = GTF_permit_access | flags;
252 }
253
254 /*
255  * Public grant-issuing interface functions
256  */
257 void gnttab_grant_foreign_access_ref(grant_ref_t ref, domid_t domid,
258                                      unsigned long frame, int readonly)
259 {
260         gnttab_interface->update_entry(ref, domid, frame,
261                            GTF_permit_access | (readonly ? GTF_readonly : 0));
262 }
263 EXPORT_SYMBOL_GPL(gnttab_grant_foreign_access_ref);
264
265 int gnttab_grant_foreign_access(domid_t domid, unsigned long frame,
266                                 int readonly)
267 {
268         int ref;
269
270         ref = get_free_entries(1);
271         if (unlikely(ref < 0))
272                 return -ENOSPC;
273
274         gnttab_grant_foreign_access_ref(ref, domid, frame, readonly);
275
276         return ref;
277 }
278 EXPORT_SYMBOL_GPL(gnttab_grant_foreign_access);
279
280 static int gnttab_end_foreign_access_ref_v1(grant_ref_t ref, int readonly)
281 {
282         u16 flags, nflags;
283         u16 *pflags;
284
285         pflags = &gnttab_shared.v1[ref].flags;
286         nflags = *pflags;
287         do {
288                 flags = nflags;
289                 if (flags & (GTF_reading|GTF_writing))
290                         return 0;
291         } while ((nflags = sync_cmpxchg(pflags, flags, 0)) != flags);
292
293         return 1;
294 }
295
296 static int gnttab_end_foreign_access_ref_v2(grant_ref_t ref, int readonly)
297 {
298         gnttab_shared.v2[ref].hdr.flags = 0;
299         mb();   /* Concurrent access by hypervisor. */
300         if (grstatus[ref] & (GTF_reading|GTF_writing)) {
301                 return 0;
302         } else {
303                 /*
304                  * The read of grstatus needs to have acquire semantics.
305                  *  On x86, reads already have that, and we just need to
306                  * protect against compiler reorderings.
307                  * On other architectures we may need a full barrier.
308                  */
309 #ifdef CONFIG_X86
310                 barrier();
311 #else
312                 mb();
313 #endif
314         }
315
316         return 1;
317 }
318
319 static inline int _gnttab_end_foreign_access_ref(grant_ref_t ref, int readonly)
320 {
321         return gnttab_interface->end_foreign_access_ref(ref, readonly);
322 }
323
324 int gnttab_end_foreign_access_ref(grant_ref_t ref, int readonly)
325 {
326         if (_gnttab_end_foreign_access_ref(ref, readonly))
327                 return 1;
328         pr_warn("WARNING: g.e. %#x still in use!\n", ref);
329         return 0;
330 }
331 EXPORT_SYMBOL_GPL(gnttab_end_foreign_access_ref);
332
333 struct deferred_entry {
334         struct list_head list;
335         grant_ref_t ref;
336         bool ro;
337         uint16_t warn_delay;
338         struct page *page;
339 };
340 static LIST_HEAD(deferred_list);
341 static void gnttab_handle_deferred(struct timer_list *);
342 static DEFINE_TIMER(deferred_timer, gnttab_handle_deferred);
343
344 static void gnttab_handle_deferred(struct timer_list *unused)
345 {
346         unsigned int nr = 10;
347         struct deferred_entry *first = NULL;
348         unsigned long flags;
349
350         spin_lock_irqsave(&gnttab_list_lock, flags);
351         while (nr--) {
352                 struct deferred_entry *entry
353                         = list_first_entry(&deferred_list,
354                                            struct deferred_entry, list);
355
356                 if (entry == first)
357                         break;
358                 list_del(&entry->list);
359                 spin_unlock_irqrestore(&gnttab_list_lock, flags);
360                 if (_gnttab_end_foreign_access_ref(entry->ref, entry->ro)) {
361                         put_free_entry(entry->ref);
362                         if (entry->page) {
363                                 pr_debug("freeing g.e. %#x (pfn %#lx)\n",
364                                          entry->ref, page_to_pfn(entry->page));
365                                 put_page(entry->page);
366                         } else
367                                 pr_info("freeing g.e. %#x\n", entry->ref);
368                         kfree(entry);
369                         entry = NULL;
370                 } else {
371                         if (!--entry->warn_delay)
372                                 pr_info("g.e. %#x still pending\n", entry->ref);
373                         if (!first)
374                                 first = entry;
375                 }
376                 spin_lock_irqsave(&gnttab_list_lock, flags);
377                 if (entry)
378                         list_add_tail(&entry->list, &deferred_list);
379                 else if (list_empty(&deferred_list))
380                         break;
381         }
382         if (!list_empty(&deferred_list) && !timer_pending(&deferred_timer)) {
383                 deferred_timer.expires = jiffies + HZ;
384                 add_timer(&deferred_timer);
385         }
386         spin_unlock_irqrestore(&gnttab_list_lock, flags);
387 }
388
389 static void gnttab_add_deferred(grant_ref_t ref, bool readonly,
390                                 struct page *page)
391 {
392         struct deferred_entry *entry = kmalloc(sizeof(*entry), GFP_ATOMIC);
393         const char *what = KERN_WARNING "leaking";
394
395         if (entry) {
396                 unsigned long flags;
397
398                 entry->ref = ref;
399                 entry->ro = readonly;
400                 entry->page = page;
401                 entry->warn_delay = 60;
402                 spin_lock_irqsave(&gnttab_list_lock, flags);
403                 list_add_tail(&entry->list, &deferred_list);
404                 if (!timer_pending(&deferred_timer)) {
405                         deferred_timer.expires = jiffies + HZ;
406                         add_timer(&deferred_timer);
407                 }
408                 spin_unlock_irqrestore(&gnttab_list_lock, flags);
409                 what = KERN_DEBUG "deferring";
410         }
411         printk("%s g.e. %#x (pfn %#lx)\n",
412                what, ref, page ? page_to_pfn(page) : -1);
413 }
414
415 int gnttab_try_end_foreign_access(grant_ref_t ref)
416 {
417         int ret = _gnttab_end_foreign_access_ref(ref, 0);
418
419         if (ret)
420                 put_free_entry(ref);
421
422         return ret;
423 }
424 EXPORT_SYMBOL_GPL(gnttab_try_end_foreign_access);
425
426 void gnttab_end_foreign_access(grant_ref_t ref, int readonly,
427                                unsigned long page)
428 {
429         if (gnttab_try_end_foreign_access(ref)) {
430                 if (page != 0)
431                         put_page(virt_to_page(page));
432         } else
433                 gnttab_add_deferred(ref, readonly,
434                                     page ? virt_to_page(page) : NULL);
435 }
436 EXPORT_SYMBOL_GPL(gnttab_end_foreign_access);
437
438 int gnttab_grant_foreign_transfer(domid_t domid, unsigned long pfn)
439 {
440         int ref;
441
442         ref = get_free_entries(1);
443         if (unlikely(ref < 0))
444                 return -ENOSPC;
445         gnttab_grant_foreign_transfer_ref(ref, domid, pfn);
446
447         return ref;
448 }
449 EXPORT_SYMBOL_GPL(gnttab_grant_foreign_transfer);
450
451 void gnttab_grant_foreign_transfer_ref(grant_ref_t ref, domid_t domid,
452                                        unsigned long pfn)
453 {
454         gnttab_interface->update_entry(ref, domid, pfn, GTF_accept_transfer);
455 }
456 EXPORT_SYMBOL_GPL(gnttab_grant_foreign_transfer_ref);
457
458 static unsigned long gnttab_end_foreign_transfer_ref_v1(grant_ref_t ref)
459 {
460         unsigned long frame;
461         u16           flags;
462         u16          *pflags;
463
464         pflags = &gnttab_shared.v1[ref].flags;
465
466         /*
467          * If a transfer is not even yet started, try to reclaim the grant
468          * reference and return failure (== 0).
469          */
470         while (!((flags = *pflags) & GTF_transfer_committed)) {
471                 if (sync_cmpxchg(pflags, flags, 0) == flags)
472                         return 0;
473                 cpu_relax();
474         }
475
476         /* If a transfer is in progress then wait until it is completed. */
477         while (!(flags & GTF_transfer_completed)) {
478                 flags = *pflags;
479                 cpu_relax();
480         }
481
482         rmb();  /* Read the frame number /after/ reading completion status. */
483         frame = gnttab_shared.v1[ref].frame;
484         BUG_ON(frame == 0);
485
486         return frame;
487 }
488
489 static unsigned long gnttab_end_foreign_transfer_ref_v2(grant_ref_t ref)
490 {
491         unsigned long frame;
492         u16           flags;
493         u16          *pflags;
494
495         pflags = &gnttab_shared.v2[ref].hdr.flags;
496
497         /*
498          * If a transfer is not even yet started, try to reclaim the grant
499          * reference and return failure (== 0).
500          */
501         while (!((flags = *pflags) & GTF_transfer_committed)) {
502                 if (sync_cmpxchg(pflags, flags, 0) == flags)
503                         return 0;
504                 cpu_relax();
505         }
506
507         /* If a transfer is in progress then wait until it is completed. */
508         while (!(flags & GTF_transfer_completed)) {
509                 flags = *pflags;
510                 cpu_relax();
511         }
512
513         rmb();  /* Read the frame number /after/ reading completion status. */
514         frame = gnttab_shared.v2[ref].full_page.frame;
515         BUG_ON(frame == 0);
516
517         return frame;
518 }
519
520 unsigned long gnttab_end_foreign_transfer_ref(grant_ref_t ref)
521 {
522         return gnttab_interface->end_foreign_transfer_ref(ref);
523 }
524 EXPORT_SYMBOL_GPL(gnttab_end_foreign_transfer_ref);
525
526 unsigned long gnttab_end_foreign_transfer(grant_ref_t ref)
527 {
528         unsigned long frame = gnttab_end_foreign_transfer_ref(ref);
529         put_free_entry(ref);
530         return frame;
531 }
532 EXPORT_SYMBOL_GPL(gnttab_end_foreign_transfer);
533
534 void gnttab_free_grant_reference(grant_ref_t ref)
535 {
536         put_free_entry(ref);
537 }
538 EXPORT_SYMBOL_GPL(gnttab_free_grant_reference);
539
540 void gnttab_free_grant_references(grant_ref_t head)
541 {
542         grant_ref_t ref;
543         unsigned long flags;
544         int count = 1;
545         if (head == GNTTAB_LIST_END)
546                 return;
547         spin_lock_irqsave(&gnttab_list_lock, flags);
548         ref = head;
549         while (gnttab_entry(ref) != GNTTAB_LIST_END) {
550                 ref = gnttab_entry(ref);
551                 count++;
552         }
553         gnttab_entry(ref) = gnttab_free_head;
554         gnttab_free_head = head;
555         gnttab_free_count += count;
556         check_free_callbacks();
557         spin_unlock_irqrestore(&gnttab_list_lock, flags);
558 }
559 EXPORT_SYMBOL_GPL(gnttab_free_grant_references);
560
561 int gnttab_alloc_grant_references(u16 count, grant_ref_t *head)
562 {
563         int h = get_free_entries(count);
564
565         if (h < 0)
566                 return -ENOSPC;
567
568         *head = h;
569
570         return 0;
571 }
572 EXPORT_SYMBOL_GPL(gnttab_alloc_grant_references);
573
574 int gnttab_empty_grant_references(const grant_ref_t *private_head)
575 {
576         return (*private_head == GNTTAB_LIST_END);
577 }
578 EXPORT_SYMBOL_GPL(gnttab_empty_grant_references);
579
580 int gnttab_claim_grant_reference(grant_ref_t *private_head)
581 {
582         grant_ref_t g = *private_head;
583         if (unlikely(g == GNTTAB_LIST_END))
584                 return -ENOSPC;
585         *private_head = gnttab_entry(g);
586         return g;
587 }
588 EXPORT_SYMBOL_GPL(gnttab_claim_grant_reference);
589
590 void gnttab_release_grant_reference(grant_ref_t *private_head,
591                                     grant_ref_t release)
592 {
593         gnttab_entry(release) = *private_head;
594         *private_head = release;
595 }
596 EXPORT_SYMBOL_GPL(gnttab_release_grant_reference);
597
598 void gnttab_request_free_callback(struct gnttab_free_callback *callback,
599                                   void (*fn)(void *), void *arg, u16 count)
600 {
601         unsigned long flags;
602         struct gnttab_free_callback *cb;
603
604         spin_lock_irqsave(&gnttab_list_lock, flags);
605
606         /* Check if the callback is already on the list */
607         cb = gnttab_free_callback_list;
608         while (cb) {
609                 if (cb == callback)
610                         goto out;
611                 cb = cb->next;
612         }
613
614         callback->fn = fn;
615         callback->arg = arg;
616         callback->count = count;
617         callback->next = gnttab_free_callback_list;
618         gnttab_free_callback_list = callback;
619         check_free_callbacks();
620 out:
621         spin_unlock_irqrestore(&gnttab_list_lock, flags);
622 }
623 EXPORT_SYMBOL_GPL(gnttab_request_free_callback);
624
625 void gnttab_cancel_free_callback(struct gnttab_free_callback *callback)
626 {
627         struct gnttab_free_callback **pcb;
628         unsigned long flags;
629
630         spin_lock_irqsave(&gnttab_list_lock, flags);
631         for (pcb = &gnttab_free_callback_list; *pcb; pcb = &(*pcb)->next) {
632                 if (*pcb == callback) {
633                         *pcb = callback->next;
634                         break;
635                 }
636         }
637         spin_unlock_irqrestore(&gnttab_list_lock, flags);
638 }
639 EXPORT_SYMBOL_GPL(gnttab_cancel_free_callback);
640
641 static unsigned int gnttab_frames(unsigned int frames, unsigned int align)
642 {
643         return (frames * gnttab_interface->grefs_per_grant_frame + align - 1) /
644                align;
645 }
646
647 static int grow_gnttab_list(unsigned int more_frames)
648 {
649         unsigned int new_nr_grant_frames, extra_entries, i;
650         unsigned int nr_glist_frames, new_nr_glist_frames;
651         unsigned int grefs_per_frame;
652
653         grefs_per_frame = gnttab_interface->grefs_per_grant_frame;
654
655         new_nr_grant_frames = nr_grant_frames + more_frames;
656         extra_entries = more_frames * grefs_per_frame;
657
658         nr_glist_frames = gnttab_frames(nr_grant_frames, RPP);
659         new_nr_glist_frames = gnttab_frames(new_nr_grant_frames, RPP);
660         for (i = nr_glist_frames; i < new_nr_glist_frames; i++) {
661                 gnttab_list[i] = (grant_ref_t *)__get_free_page(GFP_ATOMIC);
662                 if (!gnttab_list[i])
663                         goto grow_nomem;
664         }
665
666
667         for (i = grefs_per_frame * nr_grant_frames;
668              i < grefs_per_frame * new_nr_grant_frames - 1; i++)
669                 gnttab_entry(i) = i + 1;
670
671         gnttab_entry(i) = gnttab_free_head;
672         gnttab_free_head = grefs_per_frame * nr_grant_frames;
673         gnttab_free_count += extra_entries;
674
675         nr_grant_frames = new_nr_grant_frames;
676
677         check_free_callbacks();
678
679         return 0;
680
681 grow_nomem:
682         while (i-- > nr_glist_frames)
683                 free_page((unsigned long) gnttab_list[i]);
684         return -ENOMEM;
685 }
686
687 static unsigned int __max_nr_grant_frames(void)
688 {
689         struct gnttab_query_size query;
690         int rc;
691
692         query.dom = DOMID_SELF;
693
694         rc = HYPERVISOR_grant_table_op(GNTTABOP_query_size, &query, 1);
695         if ((rc < 0) || (query.status != GNTST_okay))
696                 return 4; /* Legacy max supported number of frames */
697
698         return query.max_nr_frames;
699 }
700
701 unsigned int gnttab_max_grant_frames(void)
702 {
703         unsigned int xen_max = __max_nr_grant_frames();
704         static unsigned int boot_max_nr_grant_frames;
705
706         /* First time, initialize it properly. */
707         if (!boot_max_nr_grant_frames)
708                 boot_max_nr_grant_frames = __max_nr_grant_frames();
709
710         if (xen_max > boot_max_nr_grant_frames)
711                 return boot_max_nr_grant_frames;
712         return xen_max;
713 }
714 EXPORT_SYMBOL_GPL(gnttab_max_grant_frames);
715
716 int gnttab_setup_auto_xlat_frames(phys_addr_t addr)
717 {
718         xen_pfn_t *pfn;
719         unsigned int max_nr_gframes = __max_nr_grant_frames();
720         unsigned int i;
721         void *vaddr;
722
723         if (xen_auto_xlat_grant_frames.count)
724                 return -EINVAL;
725
726         vaddr = xen_remap(addr, XEN_PAGE_SIZE * max_nr_gframes);
727         if (vaddr == NULL) {
728                 pr_warn("Failed to ioremap gnttab share frames (addr=%pa)!\n",
729                         &addr);
730                 return -ENOMEM;
731         }
732         pfn = kcalloc(max_nr_gframes, sizeof(pfn[0]), GFP_KERNEL);
733         if (!pfn) {
734                 xen_unmap(vaddr);
735                 return -ENOMEM;
736         }
737         for (i = 0; i < max_nr_gframes; i++)
738                 pfn[i] = XEN_PFN_DOWN(addr) + i;
739
740         xen_auto_xlat_grant_frames.vaddr = vaddr;
741         xen_auto_xlat_grant_frames.pfn = pfn;
742         xen_auto_xlat_grant_frames.count = max_nr_gframes;
743
744         return 0;
745 }
746 EXPORT_SYMBOL_GPL(gnttab_setup_auto_xlat_frames);
747
748 void gnttab_free_auto_xlat_frames(void)
749 {
750         if (!xen_auto_xlat_grant_frames.count)
751                 return;
752         kfree(xen_auto_xlat_grant_frames.pfn);
753         xen_unmap(xen_auto_xlat_grant_frames.vaddr);
754
755         xen_auto_xlat_grant_frames.pfn = NULL;
756         xen_auto_xlat_grant_frames.count = 0;
757         xen_auto_xlat_grant_frames.vaddr = NULL;
758 }
759 EXPORT_SYMBOL_GPL(gnttab_free_auto_xlat_frames);
760
761 int gnttab_pages_set_private(int nr_pages, struct page **pages)
762 {
763         int i;
764
765         for (i = 0; i < nr_pages; i++) {
766 #if BITS_PER_LONG < 64
767                 struct xen_page_foreign *foreign;
768
769                 foreign = kzalloc(sizeof(*foreign), GFP_KERNEL);
770                 if (!foreign)
771                         return -ENOMEM;
772
773                 set_page_private(pages[i], (unsigned long)foreign);
774 #endif
775                 SetPagePrivate(pages[i]);
776         }
777
778         return 0;
779 }
780 EXPORT_SYMBOL_GPL(gnttab_pages_set_private);
781
782 /**
783  * gnttab_alloc_pages - alloc pages suitable for grant mapping into
784  * @nr_pages: number of pages to alloc
785  * @pages: returns the pages
786  */
787 int gnttab_alloc_pages(int nr_pages, struct page **pages)
788 {
789         int ret;
790
791         ret = xen_alloc_unpopulated_pages(nr_pages, pages);
792         if (ret < 0)
793                 return ret;
794
795         ret = gnttab_pages_set_private(nr_pages, pages);
796         if (ret < 0)
797                 gnttab_free_pages(nr_pages, pages);
798
799         return ret;
800 }
801 EXPORT_SYMBOL_GPL(gnttab_alloc_pages);
802
803 #ifdef CONFIG_XEN_UNPOPULATED_ALLOC
804 static inline void cache_init(struct gnttab_page_cache *cache)
805 {
806         cache->pages = NULL;
807 }
808
809 static inline bool cache_empty(struct gnttab_page_cache *cache)
810 {
811         return !cache->pages;
812 }
813
814 static inline struct page *cache_deq(struct gnttab_page_cache *cache)
815 {
816         struct page *page;
817
818         page = cache->pages;
819         cache->pages = page->zone_device_data;
820
821         return page;
822 }
823
824 static inline void cache_enq(struct gnttab_page_cache *cache, struct page *page)
825 {
826         page->zone_device_data = cache->pages;
827         cache->pages = page;
828 }
829 #else
830 static inline void cache_init(struct gnttab_page_cache *cache)
831 {
832         INIT_LIST_HEAD(&cache->pages);
833 }
834
835 static inline bool cache_empty(struct gnttab_page_cache *cache)
836 {
837         return list_empty(&cache->pages);
838 }
839
840 static inline struct page *cache_deq(struct gnttab_page_cache *cache)
841 {
842         struct page *page;
843
844         page = list_first_entry(&cache->pages, struct page, lru);
845         list_del(&page->lru);
846
847         return page;
848 }
849
850 static inline void cache_enq(struct gnttab_page_cache *cache, struct page *page)
851 {
852         list_add(&page->lru, &cache->pages);
853 }
854 #endif
855
856 void gnttab_page_cache_init(struct gnttab_page_cache *cache)
857 {
858         spin_lock_init(&cache->lock);
859         cache_init(cache);
860         cache->num_pages = 0;
861 }
862 EXPORT_SYMBOL_GPL(gnttab_page_cache_init);
863
864 int gnttab_page_cache_get(struct gnttab_page_cache *cache, struct page **page)
865 {
866         unsigned long flags;
867
868         spin_lock_irqsave(&cache->lock, flags);
869
870         if (cache_empty(cache)) {
871                 spin_unlock_irqrestore(&cache->lock, flags);
872                 return gnttab_alloc_pages(1, page);
873         }
874
875         page[0] = cache_deq(cache);
876         cache->num_pages--;
877
878         spin_unlock_irqrestore(&cache->lock, flags);
879
880         return 0;
881 }
882 EXPORT_SYMBOL_GPL(gnttab_page_cache_get);
883
884 void gnttab_page_cache_put(struct gnttab_page_cache *cache, struct page **page,
885                            unsigned int num)
886 {
887         unsigned long flags;
888         unsigned int i;
889
890         spin_lock_irqsave(&cache->lock, flags);
891
892         for (i = 0; i < num; i++)
893                 cache_enq(cache, page[i]);
894         cache->num_pages += num;
895
896         spin_unlock_irqrestore(&cache->lock, flags);
897 }
898 EXPORT_SYMBOL_GPL(gnttab_page_cache_put);
899
900 void gnttab_page_cache_shrink(struct gnttab_page_cache *cache, unsigned int num)
901 {
902         struct page *page[10];
903         unsigned int i = 0;
904         unsigned long flags;
905
906         spin_lock_irqsave(&cache->lock, flags);
907
908         while (cache->num_pages > num) {
909                 page[i] = cache_deq(cache);
910                 cache->num_pages--;
911                 if (++i == ARRAY_SIZE(page)) {
912                         spin_unlock_irqrestore(&cache->lock, flags);
913                         gnttab_free_pages(i, page);
914                         i = 0;
915                         spin_lock_irqsave(&cache->lock, flags);
916                 }
917         }
918
919         spin_unlock_irqrestore(&cache->lock, flags);
920
921         if (i != 0)
922                 gnttab_free_pages(i, page);
923 }
924 EXPORT_SYMBOL_GPL(gnttab_page_cache_shrink);
925
926 void gnttab_pages_clear_private(int nr_pages, struct page **pages)
927 {
928         int i;
929
930         for (i = 0; i < nr_pages; i++) {
931                 if (PagePrivate(pages[i])) {
932 #if BITS_PER_LONG < 64
933                         kfree((void *)page_private(pages[i]));
934 #endif
935                         ClearPagePrivate(pages[i]);
936                 }
937         }
938 }
939 EXPORT_SYMBOL_GPL(gnttab_pages_clear_private);
940
941 /**
942  * gnttab_free_pages - free pages allocated by gnttab_alloc_pages()
943  * @nr_pages; number of pages to free
944  * @pages: the pages
945  */
946 void gnttab_free_pages(int nr_pages, struct page **pages)
947 {
948         gnttab_pages_clear_private(nr_pages, pages);
949         xen_free_unpopulated_pages(nr_pages, pages);
950 }
951 EXPORT_SYMBOL_GPL(gnttab_free_pages);
952
953 #ifdef CONFIG_XEN_GRANT_DMA_ALLOC
954 /**
955  * gnttab_dma_alloc_pages - alloc DMAable pages suitable for grant mapping into
956  * @args: arguments to the function
957  */
958 int gnttab_dma_alloc_pages(struct gnttab_dma_alloc_args *args)
959 {
960         unsigned long pfn, start_pfn;
961         size_t size;
962         int i, ret;
963
964         size = args->nr_pages << PAGE_SHIFT;
965         if (args->coherent)
966                 args->vaddr = dma_alloc_coherent(args->dev, size,
967                                                  &args->dev_bus_addr,
968                                                  GFP_KERNEL | __GFP_NOWARN);
969         else
970                 args->vaddr = dma_alloc_wc(args->dev, size,
971                                            &args->dev_bus_addr,
972                                            GFP_KERNEL | __GFP_NOWARN);
973         if (!args->vaddr) {
974                 pr_debug("Failed to allocate DMA buffer of size %zu\n", size);
975                 return -ENOMEM;
976         }
977
978         start_pfn = __phys_to_pfn(args->dev_bus_addr);
979         for (pfn = start_pfn, i = 0; pfn < start_pfn + args->nr_pages;
980                         pfn++, i++) {
981                 struct page *page = pfn_to_page(pfn);
982
983                 args->pages[i] = page;
984                 args->frames[i] = xen_page_to_gfn(page);
985                 xenmem_reservation_scrub_page(page);
986         }
987
988         xenmem_reservation_va_mapping_reset(args->nr_pages, args->pages);
989
990         ret = xenmem_reservation_decrease(args->nr_pages, args->frames);
991         if (ret != args->nr_pages) {
992                 pr_debug("Failed to decrease reservation for DMA buffer\n");
993                 ret = -EFAULT;
994                 goto fail;
995         }
996
997         ret = gnttab_pages_set_private(args->nr_pages, args->pages);
998         if (ret < 0)
999                 goto fail;
1000
1001         return 0;
1002
1003 fail:
1004         gnttab_dma_free_pages(args);
1005         return ret;
1006 }
1007 EXPORT_SYMBOL_GPL(gnttab_dma_alloc_pages);
1008
1009 /**
1010  * gnttab_dma_free_pages - free DMAable pages
1011  * @args: arguments to the function
1012  */
1013 int gnttab_dma_free_pages(struct gnttab_dma_alloc_args *args)
1014 {
1015         size_t size;
1016         int i, ret;
1017
1018         gnttab_pages_clear_private(args->nr_pages, args->pages);
1019
1020         for (i = 0; i < args->nr_pages; i++)
1021                 args->frames[i] = page_to_xen_pfn(args->pages[i]);
1022
1023         ret = xenmem_reservation_increase(args->nr_pages, args->frames);
1024         if (ret != args->nr_pages) {
1025                 pr_debug("Failed to increase reservation for DMA buffer\n");
1026                 ret = -EFAULT;
1027         } else {
1028                 ret = 0;
1029         }
1030
1031         xenmem_reservation_va_mapping_update(args->nr_pages, args->pages,
1032                                              args->frames);
1033
1034         size = args->nr_pages << PAGE_SHIFT;
1035         if (args->coherent)
1036                 dma_free_coherent(args->dev, size,
1037                                   args->vaddr, args->dev_bus_addr);
1038         else
1039                 dma_free_wc(args->dev, size,
1040                             args->vaddr, args->dev_bus_addr);
1041         return ret;
1042 }
1043 EXPORT_SYMBOL_GPL(gnttab_dma_free_pages);
1044 #endif
1045
1046 /* Handling of paged out grant targets (GNTST_eagain) */
1047 #define MAX_DELAY 256
1048 static inline void
1049 gnttab_retry_eagain_gop(unsigned int cmd, void *gop, int16_t *status,
1050                                                 const char *func)
1051 {
1052         unsigned delay = 1;
1053
1054         do {
1055                 BUG_ON(HYPERVISOR_grant_table_op(cmd, gop, 1));
1056                 if (*status == GNTST_eagain)
1057                         msleep(delay++);
1058         } while ((*status == GNTST_eagain) && (delay < MAX_DELAY));
1059
1060         if (delay >= MAX_DELAY) {
1061                 pr_err("%s: %s eagain grant\n", func, current->comm);
1062                 *status = GNTST_bad_page;
1063         }
1064 }
1065
1066 void gnttab_batch_map(struct gnttab_map_grant_ref *batch, unsigned count)
1067 {
1068         struct gnttab_map_grant_ref *op;
1069
1070         if (HYPERVISOR_grant_table_op(GNTTABOP_map_grant_ref, batch, count))
1071                 BUG();
1072         for (op = batch; op < batch + count; op++)
1073                 if (op->status == GNTST_eagain)
1074                         gnttab_retry_eagain_gop(GNTTABOP_map_grant_ref, op,
1075                                                 &op->status, __func__);
1076 }
1077 EXPORT_SYMBOL_GPL(gnttab_batch_map);
1078
1079 void gnttab_batch_copy(struct gnttab_copy *batch, unsigned count)
1080 {
1081         struct gnttab_copy *op;
1082
1083         if (HYPERVISOR_grant_table_op(GNTTABOP_copy, batch, count))
1084                 BUG();
1085         for (op = batch; op < batch + count; op++)
1086                 if (op->status == GNTST_eagain)
1087                         gnttab_retry_eagain_gop(GNTTABOP_copy, op,
1088                                                 &op->status, __func__);
1089 }
1090 EXPORT_SYMBOL_GPL(gnttab_batch_copy);
1091
1092 void gnttab_foreach_grant_in_range(struct page *page,
1093                                    unsigned int offset,
1094                                    unsigned int len,
1095                                    xen_grant_fn_t fn,
1096                                    void *data)
1097 {
1098         unsigned int goffset;
1099         unsigned int glen;
1100         unsigned long xen_pfn;
1101
1102         len = min_t(unsigned int, PAGE_SIZE - offset, len);
1103         goffset = xen_offset_in_page(offset);
1104
1105         xen_pfn = page_to_xen_pfn(page) + XEN_PFN_DOWN(offset);
1106
1107         while (len) {
1108                 glen = min_t(unsigned int, XEN_PAGE_SIZE - goffset, len);
1109                 fn(pfn_to_gfn(xen_pfn), goffset, glen, data);
1110
1111                 goffset = 0;
1112                 xen_pfn++;
1113                 len -= glen;
1114         }
1115 }
1116 EXPORT_SYMBOL_GPL(gnttab_foreach_grant_in_range);
1117
1118 void gnttab_foreach_grant(struct page **pages,
1119                           unsigned int nr_grefs,
1120                           xen_grant_fn_t fn,
1121                           void *data)
1122 {
1123         unsigned int goffset = 0;
1124         unsigned long xen_pfn = 0;
1125         unsigned int i;
1126
1127         for (i = 0; i < nr_grefs; i++) {
1128                 if ((i % XEN_PFN_PER_PAGE) == 0) {
1129                         xen_pfn = page_to_xen_pfn(pages[i / XEN_PFN_PER_PAGE]);
1130                         goffset = 0;
1131                 }
1132
1133                 fn(pfn_to_gfn(xen_pfn), goffset, XEN_PAGE_SIZE, data);
1134
1135                 goffset += XEN_PAGE_SIZE;
1136                 xen_pfn++;
1137         }
1138 }
1139
1140 int gnttab_map_refs(struct gnttab_map_grant_ref *map_ops,
1141                     struct gnttab_map_grant_ref *kmap_ops,
1142                     struct page **pages, unsigned int count)
1143 {
1144         int i, ret;
1145
1146         ret = HYPERVISOR_grant_table_op(GNTTABOP_map_grant_ref, map_ops, count);
1147         if (ret)
1148                 return ret;
1149
1150         for (i = 0; i < count; i++) {
1151                 switch (map_ops[i].status) {
1152                 case GNTST_okay:
1153                 {
1154                         struct xen_page_foreign *foreign;
1155
1156                         SetPageForeign(pages[i]);
1157                         foreign = xen_page_foreign(pages[i]);
1158                         foreign->domid = map_ops[i].dom;
1159                         foreign->gref = map_ops[i].ref;
1160                         break;
1161                 }
1162
1163                 case GNTST_no_device_space:
1164                         pr_warn_ratelimited("maptrack limit reached, can't map all guest pages\n");
1165                         break;
1166
1167                 case GNTST_eagain:
1168                         /* Retry eagain maps */
1169                         gnttab_retry_eagain_gop(GNTTABOP_map_grant_ref,
1170                                                 map_ops + i,
1171                                                 &map_ops[i].status, __func__);
1172                         /* Test status in next loop iteration. */
1173                         i--;
1174                         break;
1175
1176                 default:
1177                         break;
1178                 }
1179         }
1180
1181         return set_foreign_p2m_mapping(map_ops, kmap_ops, pages, count);
1182 }
1183 EXPORT_SYMBOL_GPL(gnttab_map_refs);
1184
1185 int gnttab_unmap_refs(struct gnttab_unmap_grant_ref *unmap_ops,
1186                       struct gnttab_unmap_grant_ref *kunmap_ops,
1187                       struct page **pages, unsigned int count)
1188 {
1189         unsigned int i;
1190         int ret;
1191
1192         ret = HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref, unmap_ops, count);
1193         if (ret)
1194                 return ret;
1195
1196         for (i = 0; i < count; i++)
1197                 ClearPageForeign(pages[i]);
1198
1199         return clear_foreign_p2m_mapping(unmap_ops, kunmap_ops, pages, count);
1200 }
1201 EXPORT_SYMBOL_GPL(gnttab_unmap_refs);
1202
1203 #define GNTTAB_UNMAP_REFS_DELAY 5
1204
1205 static void __gnttab_unmap_refs_async(struct gntab_unmap_queue_data* item);
1206
1207 static void gnttab_unmap_work(struct work_struct *work)
1208 {
1209         struct gntab_unmap_queue_data
1210                 *unmap_data = container_of(work, 
1211                                            struct gntab_unmap_queue_data,
1212                                            gnttab_work.work);
1213         if (unmap_data->age != UINT_MAX)
1214                 unmap_data->age++;
1215         __gnttab_unmap_refs_async(unmap_data);
1216 }
1217
1218 static void __gnttab_unmap_refs_async(struct gntab_unmap_queue_data* item)
1219 {
1220         int ret;
1221         int pc;
1222
1223         for (pc = 0; pc < item->count; pc++) {
1224                 if (page_count(item->pages[pc]) > 1) {
1225                         unsigned long delay = GNTTAB_UNMAP_REFS_DELAY * (item->age + 1);
1226                         schedule_delayed_work(&item->gnttab_work,
1227                                               msecs_to_jiffies(delay));
1228                         return;
1229                 }
1230         }
1231
1232         ret = gnttab_unmap_refs(item->unmap_ops, item->kunmap_ops,
1233                                 item->pages, item->count);
1234         item->done(ret, item);
1235 }
1236
1237 void gnttab_unmap_refs_async(struct gntab_unmap_queue_data* item)
1238 {
1239         INIT_DELAYED_WORK(&item->gnttab_work, gnttab_unmap_work);
1240         item->age = 0;
1241
1242         __gnttab_unmap_refs_async(item);
1243 }
1244 EXPORT_SYMBOL_GPL(gnttab_unmap_refs_async);
1245
1246 static void unmap_refs_callback(int result,
1247                 struct gntab_unmap_queue_data *data)
1248 {
1249         struct unmap_refs_callback_data *d = data->data;
1250
1251         d->result = result;
1252         complete(&d->completion);
1253 }
1254
1255 int gnttab_unmap_refs_sync(struct gntab_unmap_queue_data *item)
1256 {
1257         struct unmap_refs_callback_data data;
1258
1259         init_completion(&data.completion);
1260         item->data = &data;
1261         item->done = &unmap_refs_callback;
1262         gnttab_unmap_refs_async(item);
1263         wait_for_completion(&data.completion);
1264
1265         return data.result;
1266 }
1267 EXPORT_SYMBOL_GPL(gnttab_unmap_refs_sync);
1268
1269 static unsigned int nr_status_frames(unsigned int nr_grant_frames)
1270 {
1271         return gnttab_frames(nr_grant_frames, SPP);
1272 }
1273
1274 static int gnttab_map_frames_v1(xen_pfn_t *frames, unsigned int nr_gframes)
1275 {
1276         int rc;
1277
1278         rc = arch_gnttab_map_shared(frames, nr_gframes,
1279                                     gnttab_max_grant_frames(),
1280                                     &gnttab_shared.addr);
1281         BUG_ON(rc);
1282
1283         return 0;
1284 }
1285
1286 static void gnttab_unmap_frames_v1(void)
1287 {
1288         arch_gnttab_unmap(gnttab_shared.addr, nr_grant_frames);
1289 }
1290
1291 static int gnttab_map_frames_v2(xen_pfn_t *frames, unsigned int nr_gframes)
1292 {
1293         uint64_t *sframes;
1294         unsigned int nr_sframes;
1295         struct gnttab_get_status_frames getframes;
1296         int rc;
1297
1298         nr_sframes = nr_status_frames(nr_gframes);
1299
1300         /* No need for kzalloc as it is initialized in following hypercall
1301          * GNTTABOP_get_status_frames.
1302          */
1303         sframes = kmalloc_array(nr_sframes, sizeof(uint64_t), GFP_ATOMIC);
1304         if (!sframes)
1305                 return -ENOMEM;
1306
1307         getframes.dom        = DOMID_SELF;
1308         getframes.nr_frames  = nr_sframes;
1309         set_xen_guest_handle(getframes.frame_list, sframes);
1310
1311         rc = HYPERVISOR_grant_table_op(GNTTABOP_get_status_frames,
1312                                        &getframes, 1);
1313         if (rc == -ENOSYS) {
1314                 kfree(sframes);
1315                 return -ENOSYS;
1316         }
1317
1318         BUG_ON(rc || getframes.status);
1319
1320         rc = arch_gnttab_map_status(sframes, nr_sframes,
1321                                     nr_status_frames(gnttab_max_grant_frames()),
1322                                     &grstatus);
1323         BUG_ON(rc);
1324         kfree(sframes);
1325
1326         rc = arch_gnttab_map_shared(frames, nr_gframes,
1327                                     gnttab_max_grant_frames(),
1328                                     &gnttab_shared.addr);
1329         BUG_ON(rc);
1330
1331         return 0;
1332 }
1333
1334 static void gnttab_unmap_frames_v2(void)
1335 {
1336         arch_gnttab_unmap(gnttab_shared.addr, nr_grant_frames);
1337         arch_gnttab_unmap(grstatus, nr_status_frames(nr_grant_frames));
1338 }
1339
1340 static int gnttab_map(unsigned int start_idx, unsigned int end_idx)
1341 {
1342         struct gnttab_setup_table setup;
1343         xen_pfn_t *frames;
1344         unsigned int nr_gframes = end_idx + 1;
1345         int rc;
1346
1347         if (xen_feature(XENFEAT_auto_translated_physmap)) {
1348                 struct xen_add_to_physmap xatp;
1349                 unsigned int i = end_idx;
1350                 rc = 0;
1351                 BUG_ON(xen_auto_xlat_grant_frames.count < nr_gframes);
1352                 /*
1353                  * Loop backwards, so that the first hypercall has the largest
1354                  * index, ensuring that the table will grow only once.
1355                  */
1356                 do {
1357                         xatp.domid = DOMID_SELF;
1358                         xatp.idx = i;
1359                         xatp.space = XENMAPSPACE_grant_table;
1360                         xatp.gpfn = xen_auto_xlat_grant_frames.pfn[i];
1361                         rc = HYPERVISOR_memory_op(XENMEM_add_to_physmap, &xatp);
1362                         if (rc != 0) {
1363                                 pr_warn("grant table add_to_physmap failed, err=%d\n",
1364                                         rc);
1365                                 break;
1366                         }
1367                 } while (i-- > start_idx);
1368
1369                 return rc;
1370         }
1371
1372         /* No need for kzalloc as it is initialized in following hypercall
1373          * GNTTABOP_setup_table.
1374          */
1375         frames = kmalloc_array(nr_gframes, sizeof(unsigned long), GFP_ATOMIC);
1376         if (!frames)
1377                 return -ENOMEM;
1378
1379         setup.dom        = DOMID_SELF;
1380         setup.nr_frames  = nr_gframes;
1381         set_xen_guest_handle(setup.frame_list, frames);
1382
1383         rc = HYPERVISOR_grant_table_op(GNTTABOP_setup_table, &setup, 1);
1384         if (rc == -ENOSYS) {
1385                 kfree(frames);
1386                 return -ENOSYS;
1387         }
1388
1389         BUG_ON(rc || setup.status);
1390
1391         rc = gnttab_interface->map_frames(frames, nr_gframes);
1392
1393         kfree(frames);
1394
1395         return rc;
1396 }
1397
1398 static const struct gnttab_ops gnttab_v1_ops = {
1399         .version                        = 1,
1400         .grefs_per_grant_frame          = XEN_PAGE_SIZE /
1401                                           sizeof(struct grant_entry_v1),
1402         .map_frames                     = gnttab_map_frames_v1,
1403         .unmap_frames                   = gnttab_unmap_frames_v1,
1404         .update_entry                   = gnttab_update_entry_v1,
1405         .end_foreign_access_ref         = gnttab_end_foreign_access_ref_v1,
1406         .end_foreign_transfer_ref       = gnttab_end_foreign_transfer_ref_v1,
1407 };
1408
1409 static const struct gnttab_ops gnttab_v2_ops = {
1410         .version                        = 2,
1411         .grefs_per_grant_frame          = XEN_PAGE_SIZE /
1412                                           sizeof(union grant_entry_v2),
1413         .map_frames                     = gnttab_map_frames_v2,
1414         .unmap_frames                   = gnttab_unmap_frames_v2,
1415         .update_entry                   = gnttab_update_entry_v2,
1416         .end_foreign_access_ref         = gnttab_end_foreign_access_ref_v2,
1417         .end_foreign_transfer_ref       = gnttab_end_foreign_transfer_ref_v2,
1418 };
1419
1420 static bool gnttab_need_v2(void)
1421 {
1422 #ifdef CONFIG_X86
1423         uint32_t base, width;
1424
1425         if (xen_pv_domain()) {
1426                 base = xen_cpuid_base();
1427                 if (cpuid_eax(base) < 5)
1428                         return false;   /* Information not available, use V1. */
1429                 width = cpuid_ebx(base + 5) &
1430                         XEN_CPUID_MACHINE_ADDRESS_WIDTH_MASK;
1431                 return width > 32 + PAGE_SHIFT;
1432         }
1433 #endif
1434         return !!(max_possible_pfn >> 32);
1435 }
1436
1437 static void gnttab_request_version(void)
1438 {
1439         long rc;
1440         struct gnttab_set_version gsv;
1441
1442         if (gnttab_need_v2())
1443                 gsv.version = 2;
1444         else
1445                 gsv.version = 1;
1446
1447         /* Boot parameter overrides automatic selection. */
1448         if (xen_gnttab_version >= 1 && xen_gnttab_version <= 2)
1449                 gsv.version = xen_gnttab_version;
1450
1451         rc = HYPERVISOR_grant_table_op(GNTTABOP_set_version, &gsv, 1);
1452         if (rc == 0 && gsv.version == 2)
1453                 gnttab_interface = &gnttab_v2_ops;
1454         else
1455                 gnttab_interface = &gnttab_v1_ops;
1456         pr_info("Grant tables using version %d layout\n",
1457                 gnttab_interface->version);
1458 }
1459
1460 static int gnttab_setup(void)
1461 {
1462         unsigned int max_nr_gframes;
1463
1464         max_nr_gframes = gnttab_max_grant_frames();
1465         if (max_nr_gframes < nr_grant_frames)
1466                 return -ENOSYS;
1467
1468         if (xen_feature(XENFEAT_auto_translated_physmap) && gnttab_shared.addr == NULL) {
1469                 gnttab_shared.addr = xen_auto_xlat_grant_frames.vaddr;
1470                 if (gnttab_shared.addr == NULL) {
1471                         pr_warn("gnttab share frames is not mapped!\n");
1472                         return -ENOMEM;
1473                 }
1474         }
1475         return gnttab_map(0, nr_grant_frames - 1);
1476 }
1477
1478 int gnttab_resume(void)
1479 {
1480         gnttab_request_version();
1481         return gnttab_setup();
1482 }
1483
1484 int gnttab_suspend(void)
1485 {
1486         if (!xen_feature(XENFEAT_auto_translated_physmap))
1487                 gnttab_interface->unmap_frames();
1488         return 0;
1489 }
1490
1491 static int gnttab_expand(unsigned int req_entries)
1492 {
1493         int rc;
1494         unsigned int cur, extra;
1495
1496         cur = nr_grant_frames;
1497         extra = ((req_entries + gnttab_interface->grefs_per_grant_frame - 1) /
1498                  gnttab_interface->grefs_per_grant_frame);
1499         if (cur + extra > gnttab_max_grant_frames()) {
1500                 pr_warn_ratelimited("xen/grant-table: max_grant_frames reached"
1501                                     " cur=%u extra=%u limit=%u"
1502                                     " gnttab_free_count=%u req_entries=%u\n",
1503                                     cur, extra, gnttab_max_grant_frames(),
1504                                     gnttab_free_count, req_entries);
1505                 return -ENOSPC;
1506         }
1507
1508         rc = gnttab_map(cur, cur + extra - 1);
1509         if (rc == 0)
1510                 rc = grow_gnttab_list(extra);
1511
1512         return rc;
1513 }
1514
1515 int gnttab_init(void)
1516 {
1517         int i;
1518         unsigned long max_nr_grant_frames;
1519         unsigned int max_nr_glist_frames, nr_glist_frames;
1520         unsigned int nr_init_grefs;
1521         int ret;
1522
1523         gnttab_request_version();
1524         max_nr_grant_frames = gnttab_max_grant_frames();
1525         nr_grant_frames = 1;
1526
1527         /* Determine the maximum number of frames required for the
1528          * grant reference free list on the current hypervisor.
1529          */
1530         max_nr_glist_frames = (max_nr_grant_frames *
1531                                gnttab_interface->grefs_per_grant_frame / RPP);
1532
1533         gnttab_list = kmalloc_array(max_nr_glist_frames,
1534                                     sizeof(grant_ref_t *),
1535                                     GFP_KERNEL);
1536         if (gnttab_list == NULL)
1537                 return -ENOMEM;
1538
1539         nr_glist_frames = gnttab_frames(nr_grant_frames, RPP);
1540         for (i = 0; i < nr_glist_frames; i++) {
1541                 gnttab_list[i] = (grant_ref_t *)__get_free_page(GFP_KERNEL);
1542                 if (gnttab_list[i] == NULL) {
1543                         ret = -ENOMEM;
1544                         goto ini_nomem;
1545                 }
1546         }
1547
1548         ret = arch_gnttab_init(max_nr_grant_frames,
1549                                nr_status_frames(max_nr_grant_frames));
1550         if (ret < 0)
1551                 goto ini_nomem;
1552
1553         if (gnttab_setup() < 0) {
1554                 ret = -ENODEV;
1555                 goto ini_nomem;
1556         }
1557
1558         nr_init_grefs = nr_grant_frames *
1559                         gnttab_interface->grefs_per_grant_frame;
1560
1561         for (i = NR_RESERVED_ENTRIES; i < nr_init_grefs - 1; i++)
1562                 gnttab_entry(i) = i + 1;
1563
1564         gnttab_entry(nr_init_grefs - 1) = GNTTAB_LIST_END;
1565         gnttab_free_count = nr_init_grefs - NR_RESERVED_ENTRIES;
1566         gnttab_free_head  = NR_RESERVED_ENTRIES;
1567
1568         printk("Grant table initialized\n");
1569         return 0;
1570
1571  ini_nomem:
1572         for (i--; i >= 0; i--)
1573                 free_page((unsigned long)gnttab_list[i]);
1574         kfree(gnttab_list);
1575         return ret;
1576 }
1577 EXPORT_SYMBOL_GPL(gnttab_init);
1578
1579 static int __gnttab_init(void)
1580 {
1581         if (!xen_domain())
1582                 return -ENODEV;
1583
1584         /* Delay grant-table initialization in the PV on HVM case */
1585         if (xen_hvm_domain() && !xen_pvh_domain())
1586                 return 0;
1587
1588         return gnttab_init();
1589 }
1590 /* Starts after core_initcall so that xen_pvh_gnttab_setup can be called
1591  * beforehand to initialize xen_auto_xlat_grant_frames. */
1592 core_initcall_sync(__gnttab_init);