xref: /linux/drivers/dma-buf/udmabuf.c (revision c17ee635fd3a482b2ad2bf5e269755c2eae5f25e)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/cred.h>
3 #include <linux/device.h>
4 #include <linux/dma-buf.h>
5 #include <linux/dma-resv.h>
6 #include <linux/highmem.h>
7 #include <linux/init.h>
8 #include <linux/kernel.h>
9 #include <linux/memfd.h>
10 #include <linux/miscdevice.h>
11 #include <linux/module.h>
12 #include <linux/shmem_fs.h>
13 #include <linux/hugetlb.h>
14 #include <linux/slab.h>
15 #include <linux/udmabuf.h>
16 #include <linux/vmalloc.h>
17 #include <linux/iosys-map.h>
18 
19 static int list_limit = 1024;
20 module_param(list_limit, int, 0644);
21 MODULE_PARM_DESC(list_limit, "udmabuf_create_list->count limit. Default is 1024.");
22 
23 static int size_limit_mb = 64;
24 module_param(size_limit_mb, int, 0644);
25 MODULE_PARM_DESC(size_limit_mb, "Max size of a dmabuf, in megabytes. Default is 64.");
26 
27 struct udmabuf {
28 	pgoff_t pagecount;
29 	struct folio **folios;
30 
31 	/**
32 	 * Unlike folios, pinned_folios is only used for unpin.
33 	 * So, nr_pinned is not the same to pagecount, the pinned_folios
34 	 * only set each folio which already pinned when udmabuf_create.
35 	 * Note that, since a folio may be pinned multiple times, each folio
36 	 * can be added to pinned_folios multiple times, depending on how many
37 	 * times the folio has been pinned when create.
38 	 */
39 	pgoff_t nr_pinned;
40 	struct folio **pinned_folios;
41 
42 	struct sg_table *sg;
43 	struct miscdevice *device;
44 	pgoff_t *offsets;
45 };
46 
47 static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
48 {
49 	struct vm_area_struct *vma = vmf->vma;
50 	struct udmabuf *ubuf = vma->vm_private_data;
51 	pgoff_t pgoff = vmf->pgoff;
52 	unsigned long addr, pfn;
53 	vm_fault_t ret;
54 
55 	if (pgoff >= ubuf->pagecount)
56 		return VM_FAULT_SIGBUS;
57 
58 	pfn = folio_pfn(ubuf->folios[pgoff]);
59 	pfn += ubuf->offsets[pgoff] >> PAGE_SHIFT;
60 
61 	ret = vmf_insert_pfn(vma, vmf->address, pfn);
62 	if (ret & VM_FAULT_ERROR)
63 		return ret;
64 
65 	/* pre fault */
66 	pgoff = vma->vm_pgoff;
67 	addr = vma->vm_start;
68 
69 	for (; addr < vma->vm_end; pgoff++, addr += PAGE_SIZE) {
70 		if (addr == vmf->address)
71 			continue;
72 
73 		if (WARN_ON(pgoff >= ubuf->pagecount))
74 			break;
75 
76 		pfn = folio_pfn(ubuf->folios[pgoff]);
77 		pfn += ubuf->offsets[pgoff] >> PAGE_SHIFT;
78 
79 		/**
80 		 * If the below vmf_insert_pfn() fails, we do not return an
81 		 * error here during this pre-fault step. However, an error
82 		 * will be returned if the failure occurs when the addr is
83 		 * truly accessed.
84 		 */
85 		if (vmf_insert_pfn(vma, addr, pfn) & VM_FAULT_ERROR)
86 			break;
87 	}
88 
89 	return ret;
90 }
91 
92 static const struct vm_operations_struct udmabuf_vm_ops = {
93 	.fault = udmabuf_vm_fault,
94 };
95 
96 static int mmap_udmabuf(struct dma_buf *buf, struct vm_area_struct *vma)
97 {
98 	struct udmabuf *ubuf = buf->priv;
99 
100 	if ((vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) == 0)
101 		return -EINVAL;
102 
103 	vma->vm_ops = &udmabuf_vm_ops;
104 	vma->vm_private_data = ubuf;
105 	vm_flags_set(vma, VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP);
106 	return 0;
107 }
108 
109 static int vmap_udmabuf(struct dma_buf *buf, struct iosys_map *map)
110 {
111 	struct udmabuf *ubuf = buf->priv;
112 	struct page **pages;
113 	void *vaddr;
114 	pgoff_t pg;
115 
116 	dma_resv_assert_held(buf->resv);
117 
118 	pages = kvmalloc_objs(*pages, ubuf->pagecount);
119 	if (!pages)
120 		return -ENOMEM;
121 
122 	for (pg = 0; pg < ubuf->pagecount; pg++)
123 		pages[pg] = folio_page(ubuf->folios[pg],
124 				       ubuf->offsets[pg] >> PAGE_SHIFT);
125 
126 	vaddr = vm_map_ram(pages, ubuf->pagecount, -1);
127 	kvfree(pages);
128 	if (!vaddr)
129 		return -EINVAL;
130 
131 	iosys_map_set_vaddr(map, vaddr);
132 	return 0;
133 }
134 
135 static void vunmap_udmabuf(struct dma_buf *buf, struct iosys_map *map)
136 {
137 	struct udmabuf *ubuf = buf->priv;
138 
139 	dma_resv_assert_held(buf->resv);
140 
141 	vm_unmap_ram(map->vaddr, ubuf->pagecount);
142 }
143 
144 static struct sg_table *get_sg_table(struct device *dev, struct dma_buf *buf,
145 				     enum dma_data_direction direction)
146 {
147 	struct udmabuf *ubuf = buf->priv;
148 	struct sg_table *sg;
149 	struct scatterlist *sgl;
150 	unsigned int i = 0;
151 	int ret;
152 
153 	sg = kzalloc_obj(*sg);
154 	if (!sg)
155 		return ERR_PTR(-ENOMEM);
156 
157 	ret = sg_alloc_table(sg, ubuf->pagecount, GFP_KERNEL);
158 	if (ret < 0)
159 		goto err_alloc;
160 
161 	for_each_sg(sg->sgl, sgl, ubuf->pagecount, i)
162 		sg_set_folio(sgl, ubuf->folios[i], PAGE_SIZE,
163 			     ubuf->offsets[i]);
164 
165 	ret = dma_map_sgtable(dev, sg, direction, 0);
166 	if (ret < 0)
167 		goto err_map;
168 	return sg;
169 
170 err_map:
171 	sg_free_table(sg);
172 err_alloc:
173 	kfree(sg);
174 	return ERR_PTR(ret);
175 }
176 
177 static void put_sg_table(struct device *dev, struct sg_table *sg,
178 			 enum dma_data_direction direction)
179 {
180 	dma_unmap_sgtable(dev, sg, direction, 0);
181 	sg_free_table(sg);
182 	kfree(sg);
183 }
184 
185 static struct sg_table *map_udmabuf(struct dma_buf_attachment *at,
186 				    enum dma_data_direction direction)
187 {
188 	return get_sg_table(at->dev, at->dmabuf, direction);
189 }
190 
191 static void unmap_udmabuf(struct dma_buf_attachment *at,
192 			  struct sg_table *sg,
193 			  enum dma_data_direction direction)
194 {
195 	return put_sg_table(at->dev, sg, direction);
196 }
197 
198 static void unpin_all_folios(struct udmabuf *ubuf)
199 {
200 	pgoff_t i;
201 
202 	for (i = 0; i < ubuf->nr_pinned; ++i)
203 		unpin_folio(ubuf->pinned_folios[i]);
204 
205 	kvfree(ubuf->pinned_folios);
206 }
207 
208 static __always_inline int init_udmabuf(struct udmabuf *ubuf, pgoff_t pgcnt)
209 {
210 	ubuf->folios = kvmalloc_objs(*ubuf->folios, pgcnt);
211 	if (!ubuf->folios)
212 		return -ENOMEM;
213 
214 	ubuf->offsets = kvzalloc_objs(*ubuf->offsets, pgcnt);
215 	if (!ubuf->offsets)
216 		return -ENOMEM;
217 
218 	ubuf->pinned_folios = kvmalloc_objs(*ubuf->pinned_folios, pgcnt);
219 	if (!ubuf->pinned_folios)
220 		return -ENOMEM;
221 
222 	return 0;
223 }
224 
225 static __always_inline void deinit_udmabuf(struct udmabuf *ubuf)
226 {
227 	unpin_all_folios(ubuf);
228 	kvfree(ubuf->offsets);
229 	kvfree(ubuf->folios);
230 }
231 
232 static void release_udmabuf(struct dma_buf *buf)
233 {
234 	struct udmabuf *ubuf = buf->priv;
235 	struct device *dev = ubuf->device->this_device;
236 
237 	if (ubuf->sg)
238 		put_sg_table(dev, ubuf->sg, DMA_BIDIRECTIONAL);
239 
240 	deinit_udmabuf(ubuf);
241 	kfree(ubuf);
242 }
243 
244 static int begin_cpu_udmabuf(struct dma_buf *buf,
245 			     enum dma_data_direction direction)
246 {
247 	struct udmabuf *ubuf = buf->priv;
248 	struct device *dev = ubuf->device->this_device;
249 	int ret = 0;
250 
251 	if (!ubuf->sg) {
252 		ubuf->sg = get_sg_table(dev, buf, direction);
253 		if (IS_ERR(ubuf->sg)) {
254 			ret = PTR_ERR(ubuf->sg);
255 			ubuf->sg = NULL;
256 		}
257 	} else {
258 		dma_sync_sgtable_for_cpu(dev, ubuf->sg, direction);
259 	}
260 
261 	return ret;
262 }
263 
264 static int end_cpu_udmabuf(struct dma_buf *buf,
265 			   enum dma_data_direction direction)
266 {
267 	struct udmabuf *ubuf = buf->priv;
268 	struct device *dev = ubuf->device->this_device;
269 
270 	if (!ubuf->sg)
271 		return -EINVAL;
272 
273 	dma_sync_sgtable_for_device(dev, ubuf->sg, direction);
274 	return 0;
275 }
276 
277 static const struct dma_buf_ops udmabuf_ops = {
278 	.map_dma_buf	   = map_udmabuf,
279 	.unmap_dma_buf	   = unmap_udmabuf,
280 	.release	   = release_udmabuf,
281 	.mmap		   = mmap_udmabuf,
282 	.vmap		   = vmap_udmabuf,
283 	.vunmap		   = vunmap_udmabuf,
284 	.begin_cpu_access  = begin_cpu_udmabuf,
285 	.end_cpu_access    = end_cpu_udmabuf,
286 };
287 
288 #define SEALS_WANTED (F_SEAL_SHRINK)
289 #define SEALS_DENIED (F_SEAL_WRITE|F_SEAL_FUTURE_WRITE)
290 
291 static int check_memfd_seals(struct file *memfd)
292 {
293 	int seals;
294 
295 	if (!shmem_file(memfd) && !is_file_hugepages(memfd))
296 		return -EBADFD;
297 
298 	seals = memfd_fcntl(memfd, F_GET_SEALS, 0);
299 	if (seals == -EINVAL)
300 		return -EBADFD;
301 
302 	if ((seals & SEALS_WANTED) != SEALS_WANTED ||
303 	    (seals & SEALS_DENIED) != 0)
304 		return -EINVAL;
305 
306 	return 0;
307 }
308 
309 static struct dma_buf *export_udmabuf(struct udmabuf *ubuf,
310 				      struct miscdevice *device)
311 {
312 	DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
313 
314 	ubuf->device = device;
315 	exp_info.ops  = &udmabuf_ops;
316 	exp_info.size = ubuf->pagecount << PAGE_SHIFT;
317 	exp_info.priv = ubuf;
318 	exp_info.flags = O_RDWR;
319 
320 	return dma_buf_export(&exp_info);
321 }
322 
323 static long udmabuf_pin_folios(struct udmabuf *ubuf, struct file *memfd,
324 			       loff_t start, loff_t size, struct folio **folios)
325 {
326 	pgoff_t nr_pinned = ubuf->nr_pinned;
327 	pgoff_t upgcnt = ubuf->pagecount;
328 	u32 cur_folio, cur_pgcnt;
329 	pgoff_t pgoff, pgcnt;
330 	long nr_folios;
331 	loff_t end;
332 
333 	pgcnt = size >> PAGE_SHIFT;
334 	end = start + (pgcnt << PAGE_SHIFT) - 1;
335 	nr_folios = memfd_pin_folios(memfd, start, end, folios, pgcnt, &pgoff);
336 	if (nr_folios <= 0)
337 		return nr_folios ? nr_folios : -EINVAL;
338 
339 	cur_pgcnt = 0;
340 	for (cur_folio = 0; cur_folio < nr_folios; ++cur_folio) {
341 		pgoff_t subpgoff = pgoff;
342 		size_t fsize = folio_size(folios[cur_folio]);
343 
344 		ubuf->pinned_folios[nr_pinned++] = folios[cur_folio];
345 
346 		for (; subpgoff < fsize; subpgoff += PAGE_SIZE) {
347 			ubuf->folios[upgcnt] = folios[cur_folio];
348 			ubuf->offsets[upgcnt] = subpgoff;
349 			++upgcnt;
350 
351 			if (++cur_pgcnt >= pgcnt)
352 				goto end;
353 		}
354 
355 		/**
356 		 * In a given range, only the first subpage of the first folio
357 		 * has an offset, that is returned by memfd_pin_folios().
358 		 * The first subpages of other folios (in the range) have an
359 		 * offset of 0.
360 		 */
361 		pgoff = 0;
362 	}
363 end:
364 	ubuf->pagecount = upgcnt;
365 	ubuf->nr_pinned = nr_pinned;
366 	return 0;
367 }
368 
369 static long udmabuf_create(struct miscdevice *device,
370 			   struct udmabuf_create_list *head,
371 			   struct udmabuf_create_item *list)
372 {
373 	unsigned long max_nr_folios = 0;
374 	struct folio **folios = NULL;
375 	pgoff_t pgcnt = 0, pglimit;
376 	struct udmabuf *ubuf;
377 	struct dma_buf *dmabuf;
378 	long ret = -EINVAL;
379 	u32 i, flags;
380 
381 	ubuf = kzalloc(sizeof(*ubuf), GFP_KERNEL);
382 	if (!ubuf)
383 		return -ENOMEM;
384 
385 	pglimit = ((u64)size_limit_mb * 1024 * 1024) >> PAGE_SHIFT;
386 	for (i = 0; i < head->count; i++) {
387 		pgoff_t subpgcnt;
388 
389 		if (!PAGE_ALIGNED(list[i].offset))
390 			goto err_noinit;
391 		if (!PAGE_ALIGNED(list[i].size))
392 			goto err_noinit;
393 
394 		subpgcnt = list[i].size >> PAGE_SHIFT;
395 		pgcnt += subpgcnt;
396 		if (pgcnt > pglimit)
397 			goto err_noinit;
398 
399 		max_nr_folios = max_t(unsigned long, subpgcnt, max_nr_folios);
400 	}
401 
402 	if (!pgcnt)
403 		goto err_noinit;
404 
405 	ret = init_udmabuf(ubuf, pgcnt);
406 	if (ret)
407 		goto err;
408 
409 	folios = kvmalloc_array(max_nr_folios, sizeof(*folios), GFP_KERNEL);
410 	if (!folios) {
411 		ret = -ENOMEM;
412 		goto err;
413 	}
414 
415 	for (i = 0; i < head->count; i++) {
416 		struct file *memfd = fget(list[i].memfd);
417 
418 		if (!memfd) {
419 			ret = -EBADFD;
420 			goto err;
421 		}
422 
423 		/*
424 		 * Take the inode lock to protect against concurrent
425 		 * memfd_add_seals(), which takes this lock in write mode.
426 		 */
427 		inode_lock_shared(file_inode(memfd));
428 		ret = check_memfd_seals(memfd);
429 		if (ret)
430 			goto out_unlock;
431 
432 		ret = udmabuf_pin_folios(ubuf, memfd, list[i].offset,
433 					 list[i].size, folios);
434 out_unlock:
435 		inode_unlock_shared(file_inode(memfd));
436 		fput(memfd);
437 		if (ret)
438 			goto err;
439 	}
440 
441 	flags = head->flags & UDMABUF_FLAGS_CLOEXEC ? O_CLOEXEC : 0;
442 	dmabuf = export_udmabuf(ubuf, device);
443 	if (IS_ERR(dmabuf)) {
444 		ret = PTR_ERR(dmabuf);
445 		goto err;
446 	}
447 	/*
448 	 * Ownership of ubuf is held by the dmabuf from here.
449 	 * If the following dma_buf_fd() fails, dma_buf_put() cleans up both the
450 	 * dmabuf and the ubuf (through udmabuf_ops.release).
451 	 */
452 
453 	ret = dma_buf_fd(dmabuf, flags);
454 	if (ret < 0)
455 		dma_buf_put(dmabuf);
456 
457 	kvfree(folios);
458 	return ret;
459 
460 err:
461 	deinit_udmabuf(ubuf);
462 err_noinit:
463 	kfree(ubuf);
464 	kvfree(folios);
465 	return ret;
466 }
467 
468 static long udmabuf_ioctl_create(struct file *filp, unsigned long arg)
469 {
470 	struct udmabuf_create create;
471 	struct udmabuf_create_list head;
472 	struct udmabuf_create_item list;
473 
474 	if (copy_from_user(&create, (void __user *)arg,
475 			   sizeof(create)))
476 		return -EFAULT;
477 
478 	head.flags  = create.flags;
479 	head.count  = 1;
480 	list.memfd  = create.memfd;
481 	list.offset = create.offset;
482 	list.size   = create.size;
483 
484 	return udmabuf_create(filp->private_data, &head, &list);
485 }
486 
487 static long udmabuf_ioctl_create_list(struct file *filp, unsigned long arg)
488 {
489 	struct udmabuf_create_list head;
490 	struct udmabuf_create_item *list;
491 	int ret = -EINVAL;
492 	u32 lsize;
493 
494 	if (copy_from_user(&head, (void __user *)arg, sizeof(head)))
495 		return -EFAULT;
496 	if (head.count > list_limit)
497 		return -EINVAL;
498 	lsize = sizeof(struct udmabuf_create_item) * head.count;
499 	list = memdup_user((void __user *)(arg + sizeof(head)), lsize);
500 	if (IS_ERR(list))
501 		return PTR_ERR(list);
502 
503 	ret = udmabuf_create(filp->private_data, &head, list);
504 	kfree(list);
505 	return ret;
506 }
507 
508 static long udmabuf_ioctl(struct file *filp, unsigned int ioctl,
509 			  unsigned long arg)
510 {
511 	long ret;
512 
513 	switch (ioctl) {
514 	case UDMABUF_CREATE:
515 		ret = udmabuf_ioctl_create(filp, arg);
516 		break;
517 	case UDMABUF_CREATE_LIST:
518 		ret = udmabuf_ioctl_create_list(filp, arg);
519 		break;
520 	default:
521 		ret = -ENOTTY;
522 		break;
523 	}
524 	return ret;
525 }
526 
527 static const struct file_operations udmabuf_fops = {
528 	.owner		= THIS_MODULE,
529 	.unlocked_ioctl = udmabuf_ioctl,
530 #ifdef CONFIG_COMPAT
531 	.compat_ioctl   = udmabuf_ioctl,
532 #endif
533 };
534 
535 static struct miscdevice udmabuf_misc = {
536 	.minor          = MISC_DYNAMIC_MINOR,
537 	.name           = "udmabuf",
538 	.fops           = &udmabuf_fops,
539 };
540 
541 static int __init udmabuf_dev_init(void)
542 {
543 	int ret;
544 
545 	ret = misc_register(&udmabuf_misc);
546 	if (ret < 0) {
547 		pr_err("Could not initialize udmabuf device\n");
548 		return ret;
549 	}
550 
551 	ret = dma_coerce_mask_and_coherent(udmabuf_misc.this_device,
552 					   DMA_BIT_MASK(64));
553 	if (ret < 0) {
554 		pr_err("Could not setup DMA mask for udmabuf device\n");
555 		misc_deregister(&udmabuf_misc);
556 		return ret;
557 	}
558 
559 	return 0;
560 }
561 
562 static void __exit udmabuf_dev_exit(void)
563 {
564 	misc_deregister(&udmabuf_misc);
565 }
566 
567 module_init(udmabuf_dev_init)
568 module_exit(udmabuf_dev_exit)
569 
570 MODULE_AUTHOR("Gerd Hoffmann <kraxel@redhat.com>");
571