1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 
3 /*
4  * Xen frontend/backend page directory based shared buffer
5  * helper module.
6  *
7  * Copyright (C) 2018 EPAM Systems Inc.
8  *
9  * Author: Oleksandr Andrushchenko <oleksandr_andrushchenko@epam.com>
10  */
11 
12 #include <linux/module.h>
13 #include <linux/errno.h>
14 #include <linux/mm.h>
15 
16 #include <asm/xen/hypervisor.h>
17 #include <xen/balloon.h>
18 #include <xen/xen.h>
19 #include <xen/xenbus.h>
20 #include <xen/interface/io/ring.h>
21 
22 #include <xen/xen-front-pgdir-shbuf.h>
23 
24 #ifndef GRANT_INVALID_REF
25 /*
26  * FIXME: usage of grant reference 0 as invalid grant reference:
27  * grant reference 0 is valid, but never exposed to a PV driver,
28  * because of the fact it is already in use/reserved by the PV console.
29  */
30 #define GRANT_INVALID_REF	0
31 #endif
32 
33 /**
34  * This structure represents the structure of a shared page
35  * that contains grant references to the pages of the shared
36  * buffer. This structure is common to many Xen para-virtualized
37  * protocols at include/xen/interface/io/
38  */
39 struct xen_page_directory {
40 	grant_ref_t gref_dir_next_page;
41 	grant_ref_t gref[1]; /* Variable length */
42 };
43 
44 /**
45  * Shared buffer ops which are differently implemented
46  * depending on the allocation mode, e.g. if the buffer
47  * is allocated by the corresponding backend or frontend.
48  * Some of the operations.
49  */
50 struct xen_front_pgdir_shbuf_ops {
51 	/*
52 	 * Calculate number of grefs required to handle this buffer,
53 	 * e.g. if grefs are required for page directory only or the buffer
54 	 * pages as well.
55 	 */
56 	void (*calc_num_grefs)(struct xen_front_pgdir_shbuf *buf);
57 
58 	/* Fill page directory according to para-virtual display protocol. */
59 	void (*fill_page_dir)(struct xen_front_pgdir_shbuf *buf);
60 
61 	/* Claim grant references for the pages of the buffer. */
62 	int (*grant_refs_for_buffer)(struct xen_front_pgdir_shbuf *buf,
63 				     grant_ref_t *priv_gref_head, int gref_idx);
64 
65 	/* Map grant references of the buffer. */
66 	int (*map)(struct xen_front_pgdir_shbuf *buf);
67 
68 	/* Unmap grant references of the buffer. */
69 	int (*unmap)(struct xen_front_pgdir_shbuf *buf);
70 };
71 
72 /**
73  * Get granted reference to the very first page of the
74  * page directory. Usually this is passed to the backend,
75  * so it can find/fill the grant references to the buffer's
76  * pages.
77  *
78  * \param buf shared buffer which page directory is of interest.
79  * \return granted reference to the very first page of the
80  * page directory.
81  */
82 grant_ref_t
83 xen_front_pgdir_shbuf_get_dir_start(struct xen_front_pgdir_shbuf *buf)
84 {
85 	if (!buf->grefs)
86 		return GRANT_INVALID_REF;
87 
88 	return buf->grefs[0];
89 }
90 EXPORT_SYMBOL_GPL(xen_front_pgdir_shbuf_get_dir_start);
91 
92 /**
93  * Map granted references of the shared buffer.
94  *
95  * Depending on the shared buffer mode of allocation
96  * (be_alloc flag) this can either do nothing (for buffers
97  * shared by the frontend itself) or map the provided granted
98  * references onto the backing storage (buf->pages).
99  *
100  * \param buf shared buffer which grants to be maped.
101  * \return zero on success or a negative number on failure.
102  */
103 int xen_front_pgdir_shbuf_map(struct xen_front_pgdir_shbuf *buf)
104 {
105 	if (buf->ops && buf->ops->map)
106 		return buf->ops->map(buf);
107 
108 	/* No need to map own grant references. */
109 	return 0;
110 }
111 EXPORT_SYMBOL_GPL(xen_front_pgdir_shbuf_map);
112 
113 /**
114  * Unmap granted references of the shared buffer.
115  *
116  * Depending on the shared buffer mode of allocation
117  * (be_alloc flag) this can either do nothing (for buffers
118  * shared by the frontend itself) or unmap the provided granted
119  * references.
120  *
121  * \param buf shared buffer which grants to be unmaped.
122  * \return zero on success or a negative number on failure.
123  */
124 int xen_front_pgdir_shbuf_unmap(struct xen_front_pgdir_shbuf *buf)
125 {
126 	if (buf->ops && buf->ops->unmap)
127 		return buf->ops->unmap(buf);
128 
129 	/* No need to unmap own grant references. */
130 	return 0;
131 }
132 EXPORT_SYMBOL_GPL(xen_front_pgdir_shbuf_unmap);
133 
134 /**
135  * Free all the resources of the shared buffer.
136  *
137  * \param buf shared buffer which resources to be freed.
138  */
139 void xen_front_pgdir_shbuf_free(struct xen_front_pgdir_shbuf *buf)
140 {
141 	if (buf->grefs) {
142 		int i;
143 
144 		for (i = 0; i < buf->num_grefs; i++)
145 			if (buf->grefs[i] != GRANT_INVALID_REF)
146 				gnttab_end_foreign_access(buf->grefs[i], 0UL);
147 	}
148 	kfree(buf->grefs);
149 	kfree(buf->directory);
150 }
151 EXPORT_SYMBOL_GPL(xen_front_pgdir_shbuf_free);
152 
153 /*
154  * Number of grefs a page can hold with respect to the
155  * struct xen_page_directory header.
156  */
157 #define XEN_NUM_GREFS_PER_PAGE ((PAGE_SIZE - \
158 				 offsetof(struct xen_page_directory, \
159 					  gref)) / sizeof(grant_ref_t))
160 
161 /**
162  * Get the number of pages the page directory consumes itself.
163  *
164  * \param buf shared buffer.
165  */
166 static int get_num_pages_dir(struct xen_front_pgdir_shbuf *buf)
167 {
168 	return DIV_ROUND_UP(buf->num_pages, XEN_NUM_GREFS_PER_PAGE);
169 }
170 
171 /**
172  * Calculate the number of grant references needed to share the buffer
173  * and its pages when backend allocates the buffer.
174  *
175  * \param buf shared buffer.
176  */
177 static void backend_calc_num_grefs(struct xen_front_pgdir_shbuf *buf)
178 {
179 	/* Only for pages the page directory consumes itself. */
180 	buf->num_grefs = get_num_pages_dir(buf);
181 }
182 
183 /**
184  * Calculate the number of grant references needed to share the buffer
185  * and its pages when frontend allocates the buffer.
186  *
187  * \param buf shared buffer.
188  */
189 static void guest_calc_num_grefs(struct xen_front_pgdir_shbuf *buf)
190 {
191 	/*
192 	 * Number of pages the page directory consumes itself
193 	 * plus grefs for the buffer pages.
194 	 */
195 	buf->num_grefs = get_num_pages_dir(buf) + buf->num_pages;
196 }
197 
198 #define xen_page_to_vaddr(page) \
199 	((uintptr_t)pfn_to_kaddr(page_to_xen_pfn(page)))
200 
201 /**
202  * Unmap the buffer previously mapped with grant references
203  * provided by the backend.
204  *
205  * \param buf shared buffer.
206  * \return zero on success or a negative number on failure.
207  */
208 static int backend_unmap(struct xen_front_pgdir_shbuf *buf)
209 {
210 	struct gnttab_unmap_grant_ref *unmap_ops;
211 	int i, ret;
212 
213 	if (!buf->pages || !buf->backend_map_handles || !buf->grefs)
214 		return 0;
215 
216 	unmap_ops = kcalloc(buf->num_pages, sizeof(*unmap_ops),
217 			    GFP_KERNEL);
218 	if (!unmap_ops)
219 		return -ENOMEM;
220 
221 	for (i = 0; i < buf->num_pages; i++) {
222 		phys_addr_t addr;
223 
224 		addr = xen_page_to_vaddr(buf->pages[i]);
225 		gnttab_set_unmap_op(&unmap_ops[i], addr, GNTMAP_host_map,
226 				    buf->backend_map_handles[i]);
227 	}
228 
229 	ret = gnttab_unmap_refs(unmap_ops, NULL, buf->pages,
230 				buf->num_pages);
231 
232 	for (i = 0; i < buf->num_pages; i++) {
233 		if (unlikely(unmap_ops[i].status != GNTST_okay))
234 			dev_err(&buf->xb_dev->dev,
235 				"Failed to unmap page %d: %d\n",
236 				i, unmap_ops[i].status);
237 	}
238 
239 	if (ret)
240 		dev_err(&buf->xb_dev->dev,
241 			"Failed to unmap grant references, ret %d", ret);
242 
243 	kfree(unmap_ops);
244 	kfree(buf->backend_map_handles);
245 	buf->backend_map_handles = NULL;
246 	return ret;
247 }
248 
249 /**
250  * Map the buffer with grant references provided by the backend.
251  *
252  * \param buf shared buffer.
253  * \return zero on success or a negative number on failure.
254  */
255 static int backend_map(struct xen_front_pgdir_shbuf *buf)
256 {
257 	struct gnttab_map_grant_ref *map_ops = NULL;
258 	unsigned char *ptr;
259 	int ret, cur_gref, cur_dir_page, cur_page, grefs_left;
260 
261 	map_ops = kcalloc(buf->num_pages, sizeof(*map_ops), GFP_KERNEL);
262 	if (!map_ops)
263 		return -ENOMEM;
264 
265 	buf->backend_map_handles = kcalloc(buf->num_pages,
266 					   sizeof(*buf->backend_map_handles),
267 					   GFP_KERNEL);
268 	if (!buf->backend_map_handles) {
269 		kfree(map_ops);
270 		return -ENOMEM;
271 	}
272 
273 	/*
274 	 * Read page directory to get grefs from the backend: for external
275 	 * buffer we only allocate buf->grefs for the page directory,
276 	 * so buf->num_grefs has number of pages in the page directory itself.
277 	 */
278 	ptr = buf->directory;
279 	grefs_left = buf->num_pages;
280 	cur_page = 0;
281 	for (cur_dir_page = 0; cur_dir_page < buf->num_grefs; cur_dir_page++) {
282 		struct xen_page_directory *page_dir =
283 			(struct xen_page_directory *)ptr;
284 		int to_copy = XEN_NUM_GREFS_PER_PAGE;
285 
286 		if (to_copy > grefs_left)
287 			to_copy = grefs_left;
288 
289 		for (cur_gref = 0; cur_gref < to_copy; cur_gref++) {
290 			phys_addr_t addr;
291 
292 			addr = xen_page_to_vaddr(buf->pages[cur_page]);
293 			gnttab_set_map_op(&map_ops[cur_page], addr,
294 					  GNTMAP_host_map,
295 					  page_dir->gref[cur_gref],
296 					  buf->xb_dev->otherend_id);
297 			cur_page++;
298 		}
299 
300 		grefs_left -= to_copy;
301 		ptr += PAGE_SIZE;
302 	}
303 	ret = gnttab_map_refs(map_ops, NULL, buf->pages, buf->num_pages);
304 
305 	/* Save handles even if error, so we can unmap. */
306 	for (cur_page = 0; cur_page < buf->num_pages; cur_page++) {
307 		if (likely(map_ops[cur_page].status == GNTST_okay)) {
308 			buf->backend_map_handles[cur_page] =
309 				map_ops[cur_page].handle;
310 		} else {
311 			buf->backend_map_handles[cur_page] =
312 				INVALID_GRANT_HANDLE;
313 			if (!ret)
314 				ret = -ENXIO;
315 			dev_err(&buf->xb_dev->dev,
316 				"Failed to map page %d: %d\n",
317 				cur_page, map_ops[cur_page].status);
318 		}
319 	}
320 
321 	if (ret) {
322 		dev_err(&buf->xb_dev->dev,
323 			"Failed to map grant references, ret %d", ret);
324 		backend_unmap(buf);
325 	}
326 
327 	kfree(map_ops);
328 	return ret;
329 }
330 
331 /**
332  * Fill page directory with grant references to the pages of the
333  * page directory itself.
334  *
335  * The grant references to the buffer pages are provided by the
336  * backend in this case.
337  *
338  * \param buf shared buffer.
339  */
340 static void backend_fill_page_dir(struct xen_front_pgdir_shbuf *buf)
341 {
342 	struct xen_page_directory *page_dir;
343 	unsigned char *ptr;
344 	int i, num_pages_dir;
345 
346 	ptr = buf->directory;
347 	num_pages_dir = get_num_pages_dir(buf);
348 
349 	/* Fill only grefs for the page directory itself. */
350 	for (i = 0; i < num_pages_dir - 1; i++) {
351 		page_dir = (struct xen_page_directory *)ptr;
352 
353 		page_dir->gref_dir_next_page = buf->grefs[i + 1];
354 		ptr += PAGE_SIZE;
355 	}
356 	/* Last page must say there is no more pages. */
357 	page_dir = (struct xen_page_directory *)ptr;
358 	page_dir->gref_dir_next_page = GRANT_INVALID_REF;
359 }
360 
361 /**
362  * Fill page directory with grant references to the pages of the
363  * page directory and the buffer we share with the backend.
364  *
365  * \param buf shared buffer.
366  */
367 static void guest_fill_page_dir(struct xen_front_pgdir_shbuf *buf)
368 {
369 	unsigned char *ptr;
370 	int cur_gref, grefs_left, to_copy, i, num_pages_dir;
371 
372 	ptr = buf->directory;
373 	num_pages_dir = get_num_pages_dir(buf);
374 
375 	/*
376 	 * While copying, skip grefs at start, they are for pages
377 	 * granted for the page directory itself.
378 	 */
379 	cur_gref = num_pages_dir;
380 	grefs_left = buf->num_pages;
381 	for (i = 0; i < num_pages_dir; i++) {
382 		struct xen_page_directory *page_dir =
383 			(struct xen_page_directory *)ptr;
384 
385 		if (grefs_left <= XEN_NUM_GREFS_PER_PAGE) {
386 			to_copy = grefs_left;
387 			page_dir->gref_dir_next_page = GRANT_INVALID_REF;
388 		} else {
389 			to_copy = XEN_NUM_GREFS_PER_PAGE;
390 			page_dir->gref_dir_next_page = buf->grefs[i + 1];
391 		}
392 		memcpy(&page_dir->gref, &buf->grefs[cur_gref],
393 		       to_copy * sizeof(grant_ref_t));
394 		ptr += PAGE_SIZE;
395 		grefs_left -= to_copy;
396 		cur_gref += to_copy;
397 	}
398 }
399 
400 /**
401  * Grant references to the frontend's buffer pages.
402  *
403  * These will be shared with the backend, so it can
404  * access the buffer's data.
405  *
406  * \param buf shared buffer.
407  * \return zero on success or a negative number on failure.
408  */
409 static int guest_grant_refs_for_buffer(struct xen_front_pgdir_shbuf *buf,
410 				       grant_ref_t *priv_gref_head,
411 				       int gref_idx)
412 {
413 	int i, cur_ref, otherend_id;
414 
415 	otherend_id = buf->xb_dev->otherend_id;
416 	for (i = 0; i < buf->num_pages; i++) {
417 		cur_ref = gnttab_claim_grant_reference(priv_gref_head);
418 		if (cur_ref < 0)
419 			return cur_ref;
420 
421 		gnttab_grant_foreign_access_ref(cur_ref, otherend_id,
422 						xen_page_to_gfn(buf->pages[i]),
423 						0);
424 		buf->grefs[gref_idx++] = cur_ref;
425 	}
426 	return 0;
427 }
428 
429 /**
430  * Grant all the references needed to share the buffer.
431  *
432  * Grant references to the page directory pages and, if
433  * needed, also to the pages of the shared buffer data.
434  *
435  * \param buf shared buffer.
436  * \return zero on success or a negative number on failure.
437  */
438 static int grant_references(struct xen_front_pgdir_shbuf *buf)
439 {
440 	grant_ref_t priv_gref_head;
441 	int ret, i, j, cur_ref;
442 	int otherend_id, num_pages_dir;
443 
444 	ret = gnttab_alloc_grant_references(buf->num_grefs, &priv_gref_head);
445 	if (ret < 0) {
446 		dev_err(&buf->xb_dev->dev,
447 			"Cannot allocate grant references\n");
448 		return ret;
449 	}
450 
451 	otherend_id = buf->xb_dev->otherend_id;
452 	j = 0;
453 	num_pages_dir = get_num_pages_dir(buf);
454 	for (i = 0; i < num_pages_dir; i++) {
455 		unsigned long frame;
456 
457 		cur_ref = gnttab_claim_grant_reference(&priv_gref_head);
458 		if (cur_ref < 0)
459 			return cur_ref;
460 
461 		frame = xen_page_to_gfn(virt_to_page(buf->directory +
462 						     PAGE_SIZE * i));
463 		gnttab_grant_foreign_access_ref(cur_ref, otherend_id, frame, 0);
464 		buf->grefs[j++] = cur_ref;
465 	}
466 
467 	if (buf->ops->grant_refs_for_buffer) {
468 		ret = buf->ops->grant_refs_for_buffer(buf, &priv_gref_head, j);
469 		if (ret)
470 			return ret;
471 	}
472 
473 	gnttab_free_grant_references(priv_gref_head);
474 	return 0;
475 }
476 
477 /**
478  * Allocate all required structures to mange shared buffer.
479  *
480  * \param buf shared buffer.
481  * \return zero on success or a negative number on failure.
482  */
483 static int alloc_storage(struct xen_front_pgdir_shbuf *buf)
484 {
485 	buf->grefs = kcalloc(buf->num_grefs, sizeof(*buf->grefs), GFP_KERNEL);
486 	if (!buf->grefs)
487 		return -ENOMEM;
488 
489 	buf->directory = kcalloc(get_num_pages_dir(buf), PAGE_SIZE, GFP_KERNEL);
490 	if (!buf->directory)
491 		return -ENOMEM;
492 
493 	return 0;
494 }
495 
496 /*
497  * For backend allocated buffers we don't need grant_refs_for_buffer
498  * as those grant references are allocated at backend side.
499  */
500 static const struct xen_front_pgdir_shbuf_ops backend_ops = {
501 	.calc_num_grefs = backend_calc_num_grefs,
502 	.fill_page_dir = backend_fill_page_dir,
503 	.map = backend_map,
504 	.unmap = backend_unmap
505 };
506 
507 /*
508  * For locally granted references we do not need to map/unmap
509  * the references.
510  */
511 static const struct xen_front_pgdir_shbuf_ops local_ops = {
512 	.calc_num_grefs = guest_calc_num_grefs,
513 	.fill_page_dir = guest_fill_page_dir,
514 	.grant_refs_for_buffer = guest_grant_refs_for_buffer,
515 };
516 
517 /**
518  * Allocate a new instance of a shared buffer.
519  *
520  * \param cfg configuration to be used while allocating a new shared buffer.
521  * \return zero on success or a negative number on failure.
522  */
523 int xen_front_pgdir_shbuf_alloc(struct xen_front_pgdir_shbuf_cfg *cfg)
524 {
525 	struct xen_front_pgdir_shbuf *buf = cfg->pgdir;
526 	int ret;
527 
528 	if (cfg->be_alloc)
529 		buf->ops = &backend_ops;
530 	else
531 		buf->ops = &local_ops;
532 	buf->xb_dev = cfg->xb_dev;
533 	buf->num_pages = cfg->num_pages;
534 	buf->pages = cfg->pages;
535 
536 	buf->ops->calc_num_grefs(buf);
537 
538 	ret = alloc_storage(buf);
539 	if (ret)
540 		goto fail;
541 
542 	ret = grant_references(buf);
543 	if (ret)
544 		goto fail;
545 
546 	buf->ops->fill_page_dir(buf);
547 
548 	return 0;
549 
550 fail:
551 	xen_front_pgdir_shbuf_free(buf);
552 	return ret;
553 }
554 EXPORT_SYMBOL_GPL(xen_front_pgdir_shbuf_alloc);
555 
556 MODULE_DESCRIPTION("Xen frontend/backend page directory based "
557 		   "shared buffer handling");
558 MODULE_AUTHOR("Oleksandr Andrushchenko");
559 MODULE_LICENSE("GPL");
560