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