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