xref: /linux/drivers/dma-buf/dma-buf.c (revision a8bdd9310cc9b47d9ea851f6f5fb699aaa4930d6)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Framework for buffer objects that can be shared across devices/subsystems.
4  *
5  * Copyright(C) 2011 Linaro Limited. All rights reserved.
6  * Author: Sumit Semwal <sumit.semwal@ti.com>
7  *
8  * Many thanks to linaro-mm-sig list, and specially
9  * Arnd Bergmann <arnd@arndb.de>, Rob Clark <rob@ti.com> and
10  * Daniel Vetter <daniel@ffwll.ch> for their support in creation and
11  * refining of this idea.
12  */
13 
14 #include <linux/fs.h>
15 #include <linux/slab.h>
16 #include <linux/dma-buf.h>
17 #include <linux/dma-fence.h>
18 #include <linux/dma-fence-unwrap.h>
19 #include <linux/anon_inodes.h>
20 #include <linux/export.h>
21 #include <linux/debugfs.h>
22 #include <linux/list.h>
23 #include <linux/module.h>
24 #include <linux/mutex.h>
25 #include <linux/seq_file.h>
26 #include <linux/sync_file.h>
27 #include <linux/poll.h>
28 #include <linux/dma-resv.h>
29 #include <linux/mm.h>
30 #include <linux/mount.h>
31 #include <linux/pseudo_fs.h>
32 
33 #include <uapi/linux/dma-buf.h>
34 #include <uapi/linux/magic.h>
35 
36 #define CREATE_TRACE_POINTS
37 #include <trace/events/dma_buf.h>
38 
39 /*
40  * dmabuf->name must be accessed with holding dmabuf->name_lock.
41  * we need to take the lock around the tracepoint call itself where
42  * it is called in the code.
43  *
44  * Note: FUNC##_enabled() is a static branch that will only
45  *       be set when the trace event is enabled.
46  */
47 #define DMA_BUF_TRACE(FUNC, ...)					\
48 	do {								\
49 		if (FUNC##_enabled()) {					\
50 			guard(spinlock)(&dmabuf->name_lock);		\
51 			FUNC(__VA_ARGS__);				\
52 		} else if (IS_ENABLED(CONFIG_LOCKDEP)) {		\
53 			/* Expose this lock when lockdep is enabled */	\
54 			guard(spinlock)(&dmabuf->name_lock);		\
55 		}							\
56 	} while (0)
57 
58 /* Wrapper to hide the sg_table page link from the importer */
59 struct dma_buf_sg_table_wrapper {
60 	struct sg_table *original;
61 	struct sg_table wrapper;
62 };
63 
64 static inline int is_dma_buf_file(struct file *);
65 
66 static DEFINE_MUTEX(dmabuf_list_mutex);
67 static LIST_HEAD(dmabuf_list);
68 
69 static void __dma_buf_list_add(struct dma_buf *dmabuf)
70 {
71 	mutex_lock(&dmabuf_list_mutex);
72 	list_add(&dmabuf->list_node, &dmabuf_list);
73 	mutex_unlock(&dmabuf_list_mutex);
74 }
75 
76 static void __dma_buf_list_del(struct dma_buf *dmabuf)
77 {
78 	if (!dmabuf)
79 		return;
80 
81 	mutex_lock(&dmabuf_list_mutex);
82 	list_del(&dmabuf->list_node);
83 	mutex_unlock(&dmabuf_list_mutex);
84 }
85 
86 /**
87  * dma_buf_iter_begin - begin iteration through global list of all DMA buffers
88  *
89  * Returns the first buffer in the global list of DMA-bufs that's not in the
90  * process of being destroyed. Increments that buffer's reference count to
91  * prevent buffer destruction. Callers must release the reference, either by
92  * continuing iteration with dma_buf_iter_next(), or with dma_buf_put().
93  *
94  * Return:
95  * * First buffer from global list, with refcount elevated
96  * * NULL if no active buffers are present
97  */
98 struct dma_buf *dma_buf_iter_begin(void)
99 {
100 	struct dma_buf *ret = NULL, *dmabuf;
101 
102 	/*
103 	 * The list mutex does not protect a dmabuf's refcount, so it can be
104 	 * zeroed while we are iterating. We cannot call get_dma_buf() since the
105 	 * caller may not already own a reference to the buffer.
106 	 */
107 	mutex_lock(&dmabuf_list_mutex);
108 	list_for_each_entry(dmabuf, &dmabuf_list, list_node) {
109 		if (file_ref_get(&dmabuf->file->f_ref)) {
110 			ret = dmabuf;
111 			break;
112 		}
113 	}
114 	mutex_unlock(&dmabuf_list_mutex);
115 	return ret;
116 }
117 
118 /**
119  * dma_buf_iter_next - continue iteration through global list of all DMA buffers
120  * @dmabuf:	[in]	pointer to dma_buf
121  *
122  * Decrements the reference count on the provided buffer. Returns the next
123  * buffer from the remainder of the global list of DMA-bufs with its reference
124  * count incremented. Callers must release the reference, either by continuing
125  * iteration with dma_buf_iter_next(), or with dma_buf_put().
126  *
127  * Return:
128  * * Next buffer from global list, with refcount elevated
129  * * NULL if no additional active buffers are present
130  */
131 struct dma_buf *dma_buf_iter_next(struct dma_buf *dmabuf)
132 {
133 	struct dma_buf *ret = NULL;
134 
135 	/*
136 	 * The list mutex does not protect a dmabuf's refcount, so it can be
137 	 * zeroed while we are iterating. We cannot call get_dma_buf() since the
138 	 * caller may not already own a reference to the buffer.
139 	 */
140 	mutex_lock(&dmabuf_list_mutex);
141 	dma_buf_put(dmabuf);
142 	list_for_each_entry_continue(dmabuf, &dmabuf_list, list_node) {
143 		if (file_ref_get(&dmabuf->file->f_ref)) {
144 			ret = dmabuf;
145 			break;
146 		}
147 	}
148 	mutex_unlock(&dmabuf_list_mutex);
149 	return ret;
150 }
151 
152 static char *dmabuffs_dname(struct dentry *dentry, char *buffer, int buflen)
153 {
154 	struct dma_buf *dmabuf;
155 	char name[DMA_BUF_NAME_LEN];
156 	ssize_t ret = 0;
157 
158 	dmabuf = dentry->d_fsdata;
159 	spin_lock(&dmabuf->name_lock);
160 	if (dmabuf->name)
161 		ret = strscpy(name, dmabuf->name, sizeof(name));
162 	spin_unlock(&dmabuf->name_lock);
163 
164 	return dynamic_dname(buffer, buflen, "/%s:%s",
165 			     dentry->d_name.name, ret > 0 ? name : "");
166 }
167 
168 static void dma_buf_release(struct dentry *dentry)
169 {
170 	struct dma_buf *dmabuf;
171 
172 	dmabuf = dentry->d_fsdata;
173 	if (unlikely(!dmabuf))
174 		return;
175 
176 	BUG_ON(dmabuf->vmapping_counter);
177 
178 	/*
179 	 * If you hit this BUG() it could mean:
180 	 * * There's a file reference imbalance in dma_buf_poll / dma_buf_poll_cb or somewhere else
181 	 * * dmabuf->cb_in/out.active are non-0 despite no pending fence callback
182 	 */
183 	BUG_ON(dmabuf->cb_in.active || dmabuf->cb_out.active);
184 
185 	dmabuf->ops->release(dmabuf);
186 
187 	if (dmabuf->resv == (struct dma_resv *)&dmabuf[1])
188 		dma_resv_fini(dmabuf->resv);
189 
190 	WARN_ON(!list_empty(&dmabuf->attachments));
191 	module_put(dmabuf->owner);
192 	kfree(dmabuf->name);
193 	kfree(dmabuf);
194 }
195 
196 static int dma_buf_file_release(struct inode *inode, struct file *file)
197 {
198 	if (!is_dma_buf_file(file))
199 		return -EINVAL;
200 
201 	__dma_buf_list_del(file->private_data);
202 
203 	return 0;
204 }
205 
206 static const struct dentry_operations dma_buf_dentry_ops = {
207 	.d_dname = dmabuffs_dname,
208 	.d_release = dma_buf_release,
209 };
210 
211 static struct vfsmount *dma_buf_mnt;
212 
213 static int dma_buf_fs_init_context(struct fs_context *fc)
214 {
215 	struct pseudo_fs_context *ctx;
216 
217 	ctx = init_pseudo(fc, DMA_BUF_MAGIC);
218 	if (!ctx)
219 		return -ENOMEM;
220 	ctx->dops = &dma_buf_dentry_ops;
221 	return 0;
222 }
223 
224 static struct file_system_type dma_buf_fs_type = {
225 	.name = "dmabuf",
226 	.init_fs_context = dma_buf_fs_init_context,
227 	.kill_sb = kill_anon_super,
228 };
229 
230 static int dma_buf_mmap_internal(struct file *file, struct vm_area_struct *vma)
231 {
232 	struct dma_buf *dmabuf;
233 
234 	if (!is_dma_buf_file(file))
235 		return -EINVAL;
236 
237 	dmabuf = file->private_data;
238 
239 	/* check if buffer supports mmap */
240 	if (!dmabuf->ops->mmap)
241 		return -EINVAL;
242 
243 	/* check for overflowing the buffer's size */
244 	if (vma->vm_pgoff + vma_pages(vma) >
245 	    dmabuf->size >> PAGE_SHIFT)
246 		return -EINVAL;
247 
248 	DMA_BUF_TRACE(trace_dma_buf_mmap_internal, dmabuf);
249 
250 	return dmabuf->ops->mmap(dmabuf, vma);
251 }
252 
253 static loff_t dma_buf_llseek(struct file *file, loff_t offset, int whence)
254 {
255 	struct dma_buf *dmabuf;
256 	loff_t base;
257 
258 	if (!is_dma_buf_file(file))
259 		return -EBADF;
260 
261 	dmabuf = file->private_data;
262 
263 	/* only support discovering the end of the buffer,
264 	 * but also allow SEEK_SET to maintain the idiomatic
265 	 * SEEK_END(0), SEEK_CUR(0) pattern.
266 	 */
267 	if (whence == SEEK_END)
268 		base = dmabuf->size;
269 	else if (whence == SEEK_SET)
270 		base = 0;
271 	else
272 		return -EINVAL;
273 
274 	if (offset != 0)
275 		return -EINVAL;
276 
277 	return base + offset;
278 }
279 
280 /**
281  * DOC: implicit fence polling
282  *
283  * To support cross-device and cross-driver synchronization of buffer access
284  * implicit fences (represented internally in the kernel with &struct dma_fence)
285  * can be attached to a &dma_buf. The glue for that and a few related things are
286  * provided in the &dma_resv structure.
287  *
288  * Userspace can query the state of these implicitly tracked fences using poll()
289  * and related system calls:
290  *
291  * - Checking for EPOLLIN, i.e. read access, can be use to query the state of the
292  *   most recent write or exclusive fence.
293  *
294  * - Checking for EPOLLOUT, i.e. write access, can be used to query the state of
295  *   all attached fences, shared and exclusive ones.
296  *
297  * Note that this only signals the completion of the respective fences, i.e. the
298  * DMA transfers are complete. Cache flushing and any other necessary
299  * preparations before CPU access can begin still need to happen.
300  *
301  * As an alternative to poll(), the set of fences on DMA buffer can be
302  * exported as a &sync_file using &dma_buf_sync_file_export.
303  */
304 
305 static void dma_buf_poll_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
306 {
307 	struct dma_buf_poll_cb_t *dcb = (struct dma_buf_poll_cb_t *)cb;
308 	struct dma_buf *dmabuf = container_of(dcb->poll, struct dma_buf, poll);
309 	unsigned long flags;
310 
311 	spin_lock_irqsave(&dcb->poll->lock, flags);
312 	wake_up_locked_poll(dcb->poll, dcb->active);
313 	dcb->active = 0;
314 	spin_unlock_irqrestore(&dcb->poll->lock, flags);
315 	dma_fence_put(fence);
316 	/* Paired with get_file in dma_buf_poll */
317 	fput(dmabuf->file);
318 }
319 
320 static bool dma_buf_poll_add_cb(struct dma_resv *resv, bool write,
321 				struct dma_buf_poll_cb_t *dcb)
322 {
323 	struct dma_resv_iter cursor;
324 	struct dma_fence *fence;
325 	int r;
326 
327 	dma_resv_for_each_fence(&cursor, resv, dma_resv_usage_rw(write),
328 				fence) {
329 		dma_fence_get(fence);
330 		r = dma_fence_add_callback(fence, &dcb->cb, dma_buf_poll_cb);
331 		if (!r)
332 			return true;
333 		dma_fence_put(fence);
334 	}
335 
336 	return false;
337 }
338 
339 static __poll_t dma_buf_poll(struct file *file, poll_table *poll)
340 {
341 	struct dma_buf *dmabuf;
342 	struct dma_resv *resv;
343 	__poll_t events;
344 
345 	dmabuf = file->private_data;
346 	if (!dmabuf || !dmabuf->resv)
347 		return EPOLLERR;
348 
349 	resv = dmabuf->resv;
350 
351 	poll_wait(file, &dmabuf->poll, poll);
352 
353 	events = poll_requested_events(poll) & (EPOLLIN | EPOLLOUT);
354 	if (!events)
355 		return 0;
356 
357 	dma_resv_lock(resv, NULL);
358 
359 	if (events & EPOLLOUT) {
360 		struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_out;
361 
362 		/* Check that callback isn't busy */
363 		spin_lock_irq(&dmabuf->poll.lock);
364 		if (dcb->active)
365 			events &= ~EPOLLOUT;
366 		else
367 			dcb->active = EPOLLOUT;
368 		spin_unlock_irq(&dmabuf->poll.lock);
369 
370 		if (events & EPOLLOUT) {
371 			/* Paired with fput in dma_buf_poll_cb */
372 			get_file(dmabuf->file);
373 
374 			if (!dma_buf_poll_add_cb(resv, true, dcb))
375 				/* No callback queued, wake up any other waiters */
376 				dma_buf_poll_cb(NULL, &dcb->cb);
377 			else
378 				events &= ~EPOLLOUT;
379 		}
380 	}
381 
382 	if (events & EPOLLIN) {
383 		struct dma_buf_poll_cb_t *dcb = &dmabuf->cb_in;
384 
385 		/* Check that callback isn't busy */
386 		spin_lock_irq(&dmabuf->poll.lock);
387 		if (dcb->active)
388 			events &= ~EPOLLIN;
389 		else
390 			dcb->active = EPOLLIN;
391 		spin_unlock_irq(&dmabuf->poll.lock);
392 
393 		if (events & EPOLLIN) {
394 			/* Paired with fput in dma_buf_poll_cb */
395 			get_file(dmabuf->file);
396 
397 			if (!dma_buf_poll_add_cb(resv, false, dcb))
398 				/* No callback queued, wake up any other waiters */
399 				dma_buf_poll_cb(NULL, &dcb->cb);
400 			else
401 				events &= ~EPOLLIN;
402 		}
403 	}
404 
405 	dma_resv_unlock(resv);
406 	return events;
407 }
408 
409 /**
410  * dma_buf_set_name - Set a name to a specific dma_buf to track the usage.
411  * It could support changing the name of the dma-buf if the same
412  * piece of memory is used for multiple purpose between different devices.
413  *
414  * @dmabuf: [in]     dmabuf buffer that will be renamed.
415  * @buf:    [in]     A piece of userspace memory that contains the name of
416  *                   the dma-buf.
417  *
418  * Returns 0 on success. If the dma-buf buffer is already attached to
419  * devices, return -EBUSY.
420  *
421  */
422 static long dma_buf_set_name(struct dma_buf *dmabuf, const char __user *buf)
423 {
424 	char *name = strndup_user(buf, DMA_BUF_NAME_LEN);
425 
426 	if (IS_ERR(name))
427 		return PTR_ERR(name);
428 
429 	spin_lock(&dmabuf->name_lock);
430 	kfree(dmabuf->name);
431 	dmabuf->name = name;
432 	spin_unlock(&dmabuf->name_lock);
433 
434 	return 0;
435 }
436 
437 #if IS_ENABLED(CONFIG_SYNC_FILE)
438 static long dma_buf_export_sync_file(struct dma_buf *dmabuf,
439 				     void __user *user_data)
440 {
441 	struct dma_buf_export_sync_file arg;
442 	enum dma_resv_usage usage;
443 	struct dma_fence *fence = NULL;
444 	struct sync_file *sync_file;
445 	int fd, ret;
446 
447 	if (copy_from_user(&arg, user_data, sizeof(arg)))
448 		return -EFAULT;
449 
450 	if (arg.flags & ~DMA_BUF_SYNC_RW)
451 		return -EINVAL;
452 
453 	if ((arg.flags & DMA_BUF_SYNC_RW) == 0)
454 		return -EINVAL;
455 
456 	fd = get_unused_fd_flags(O_CLOEXEC);
457 	if (fd < 0)
458 		return fd;
459 
460 	usage = dma_resv_usage_rw(arg.flags & DMA_BUF_SYNC_WRITE);
461 	ret = dma_resv_get_singleton(dmabuf->resv, usage, &fence);
462 	if (ret)
463 		goto err_put_fd;
464 
465 	if (!fence)
466 		fence = dma_fence_get_stub();
467 
468 	sync_file = sync_file_create(fence);
469 
470 	dma_fence_put(fence);
471 
472 	if (!sync_file) {
473 		ret = -ENOMEM;
474 		goto err_put_fd;
475 	}
476 
477 	arg.fd = fd;
478 	if (copy_to_user(user_data, &arg, sizeof(arg))) {
479 		ret = -EFAULT;
480 		goto err_put_file;
481 	}
482 
483 	fd_install(fd, sync_file->file);
484 
485 	return 0;
486 
487 err_put_file:
488 	fput(sync_file->file);
489 err_put_fd:
490 	put_unused_fd(fd);
491 	return ret;
492 }
493 
494 static long dma_buf_import_sync_file(struct dma_buf *dmabuf,
495 				     const void __user *user_data)
496 {
497 	struct dma_buf_import_sync_file arg;
498 	struct dma_fence *fence, *f;
499 	enum dma_resv_usage usage;
500 	struct dma_fence_unwrap iter;
501 	unsigned int num_fences;
502 	int ret = 0;
503 
504 	if (copy_from_user(&arg, user_data, sizeof(arg)))
505 		return -EFAULT;
506 
507 	if (arg.flags & ~DMA_BUF_SYNC_RW)
508 		return -EINVAL;
509 
510 	if ((arg.flags & DMA_BUF_SYNC_RW) == 0)
511 		return -EINVAL;
512 
513 	fence = sync_file_get_fence(arg.fd);
514 	if (!fence)
515 		return -EINVAL;
516 
517 	usage = (arg.flags & DMA_BUF_SYNC_WRITE) ? DMA_RESV_USAGE_WRITE :
518 						   DMA_RESV_USAGE_READ;
519 
520 	num_fences = 0;
521 	dma_fence_unwrap_for_each(f, &iter, fence)
522 		++num_fences;
523 
524 	if (num_fences > 0) {
525 		dma_resv_lock(dmabuf->resv, NULL);
526 
527 		ret = dma_resv_reserve_fences(dmabuf->resv, num_fences);
528 		if (!ret) {
529 			dma_fence_unwrap_for_each(f, &iter, fence)
530 				dma_resv_add_fence(dmabuf->resv, f, usage);
531 		}
532 
533 		dma_resv_unlock(dmabuf->resv);
534 	}
535 
536 	dma_fence_put(fence);
537 
538 	return ret;
539 }
540 #endif
541 
542 static long dma_buf_ioctl(struct file *file,
543 			  unsigned int cmd, unsigned long arg)
544 {
545 	struct dma_buf *dmabuf;
546 	struct dma_buf_sync sync;
547 	enum dma_data_direction direction;
548 	int ret;
549 
550 	dmabuf = file->private_data;
551 
552 	switch (cmd) {
553 	case DMA_BUF_IOCTL_SYNC:
554 		if (copy_from_user(&sync, (void __user *) arg, sizeof(sync)))
555 			return -EFAULT;
556 
557 		if (sync.flags & ~DMA_BUF_SYNC_VALID_FLAGS_MASK)
558 			return -EINVAL;
559 
560 		switch (sync.flags & DMA_BUF_SYNC_RW) {
561 		case DMA_BUF_SYNC_READ:
562 			direction = DMA_FROM_DEVICE;
563 			break;
564 		case DMA_BUF_SYNC_WRITE:
565 			direction = DMA_TO_DEVICE;
566 			break;
567 		case DMA_BUF_SYNC_RW:
568 			direction = DMA_BIDIRECTIONAL;
569 			break;
570 		default:
571 			return -EINVAL;
572 		}
573 
574 		if (sync.flags & DMA_BUF_SYNC_END)
575 			ret = dma_buf_end_cpu_access(dmabuf, direction);
576 		else
577 			ret = dma_buf_begin_cpu_access(dmabuf, direction);
578 
579 		return ret;
580 
581 	case DMA_BUF_SET_NAME_A:
582 	case DMA_BUF_SET_NAME_B:
583 		return dma_buf_set_name(dmabuf, (const char __user *)arg);
584 
585 #if IS_ENABLED(CONFIG_SYNC_FILE)
586 	case DMA_BUF_IOCTL_EXPORT_SYNC_FILE:
587 		return dma_buf_export_sync_file(dmabuf, (void __user *)arg);
588 	case DMA_BUF_IOCTL_IMPORT_SYNC_FILE:
589 		return dma_buf_import_sync_file(dmabuf, (const void __user *)arg);
590 #endif
591 
592 	default:
593 		return -ENOTTY;
594 	}
595 }
596 
597 static void dma_buf_show_fdinfo(struct seq_file *m, struct file *file)
598 {
599 	struct dma_buf *dmabuf = file->private_data;
600 
601 	seq_printf(m, "size:\t%zu\n", dmabuf->size);
602 	/* Don't count the temporary reference taken inside procfs seq_show */
603 	seq_printf(m, "count:\t%ld\n", file_count(dmabuf->file) - 1);
604 	seq_printf(m, "exp_name:\t%s\n", dmabuf->exp_name);
605 	spin_lock(&dmabuf->name_lock);
606 	if (dmabuf->name)
607 		seq_printf(m, "name:\t%s\n", dmabuf->name);
608 	spin_unlock(&dmabuf->name_lock);
609 }
610 
611 static const struct file_operations dma_buf_fops = {
612 	.release	= dma_buf_file_release,
613 	.mmap		= dma_buf_mmap_internal,
614 	.llseek		= dma_buf_llseek,
615 	.poll		= dma_buf_poll,
616 	.unlocked_ioctl	= dma_buf_ioctl,
617 	.compat_ioctl	= compat_ptr_ioctl,
618 	.show_fdinfo	= dma_buf_show_fdinfo,
619 };
620 
621 /*
622  * is_dma_buf_file - Check if struct file* is associated with dma_buf
623  */
624 static inline int is_dma_buf_file(struct file *file)
625 {
626 	return file->f_op == &dma_buf_fops;
627 }
628 
629 static struct file *dma_buf_getfile(size_t size, int flags)
630 {
631 	static atomic64_t dmabuf_inode = ATOMIC64_INIT(0);
632 	struct inode *inode = alloc_anon_inode(dma_buf_mnt->mnt_sb);
633 	struct file *file;
634 
635 	if (IS_ERR(inode))
636 		return ERR_CAST(inode);
637 
638 	inode->i_size = size;
639 	inode_set_bytes(inode, size);
640 
641 	/*
642 	 * The ->i_ino acquired from get_next_ino() is not unique thus
643 	 * not suitable for using it as dentry name by dmabuf stats.
644 	 * Override ->i_ino with the unique and dmabuffs specific
645 	 * value.
646 	 */
647 	inode->i_ino = atomic64_inc_return(&dmabuf_inode);
648 	flags &= O_ACCMODE | O_NONBLOCK;
649 	file = alloc_file_pseudo(inode, dma_buf_mnt, "dmabuf",
650 				 flags, &dma_buf_fops);
651 	if (IS_ERR(file))
652 		goto err_alloc_file;
653 
654 	return file;
655 
656 err_alloc_file:
657 	iput(inode);
658 	return file;
659 }
660 
661 /**
662  * DOC: dma buf device access
663  *
664  * For device DMA access to a shared DMA buffer the usual sequence of operations
665  * is fairly simple:
666  *
667  * 1. The exporter defines his exporter instance using
668  *    DEFINE_DMA_BUF_EXPORT_INFO() and calls dma_buf_export() to wrap a private
669  *    buffer object into a &dma_buf. It then exports that &dma_buf to userspace
670  *    as a file descriptor by calling dma_buf_fd().
671  *
672  * 2. Userspace passes this file-descriptors to all drivers it wants this buffer
673  *    to share with: First the file descriptor is converted to a &dma_buf using
674  *    dma_buf_get(). Then the buffer is attached to the device using
675  *    dma_buf_attach().
676  *
677  *    Up to this stage the exporter is still free to migrate or reallocate the
678  *    backing storage.
679  *
680  * 3. Once the buffer is attached to all devices userspace can initiate DMA
681  *    access to the shared buffer. In the kernel this is done by calling
682  *    dma_buf_map_attachment() and dma_buf_unmap_attachment().
683  *
684  * 4. Once a driver is done with a shared buffer it needs to call
685  *    dma_buf_detach() (after cleaning up any mappings) and then release the
686  *    reference acquired with dma_buf_get() by calling dma_buf_put().
687  *
688  * For the detailed semantics exporters are expected to implement see
689  * &dma_buf_ops.
690  */
691 
692 /**
693  * dma_buf_export - Creates a new dma_buf, and associates an anon file
694  * with this buffer, so it can be exported.
695  * Also connect the allocator specific data and ops to the buffer.
696  * Additionally, provide a name string for exporter; useful in debugging.
697  *
698  * @exp_info:	[in]	holds all the export related information provided
699  *			by the exporter. see &struct dma_buf_export_info
700  *			for further details.
701  *
702  * Returns, on success, a newly created struct dma_buf object, which wraps the
703  * supplied private data and operations for struct dma_buf_ops. On either
704  * missing ops, or error in allocating struct dma_buf, will return negative
705  * error.
706  *
707  * For most cases the easiest way to create @exp_info is through the
708  * %DEFINE_DMA_BUF_EXPORT_INFO macro.
709  */
710 struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
711 {
712 	struct dma_buf *dmabuf;
713 	struct dma_resv *resv = exp_info->resv;
714 	struct file *file;
715 	size_t alloc_size = sizeof(struct dma_buf);
716 	int ret;
717 
718 	if (WARN_ON(!exp_info->priv || !exp_info->ops
719 		    || !exp_info->ops->map_dma_buf
720 		    || !exp_info->ops->unmap_dma_buf
721 		    || !exp_info->ops->release))
722 		return ERR_PTR(-EINVAL);
723 
724 	if (WARN_ON(!exp_info->ops->pin != !exp_info->ops->unpin))
725 		return ERR_PTR(-EINVAL);
726 
727 	if (!try_module_get(exp_info->owner))
728 		return ERR_PTR(-ENOENT);
729 
730 	file = dma_buf_getfile(exp_info->size, exp_info->flags);
731 	if (IS_ERR(file)) {
732 		ret = PTR_ERR(file);
733 		goto err_module;
734 	}
735 
736 	if (!exp_info->resv)
737 		alloc_size += sizeof(struct dma_resv);
738 	else
739 		/* prevent &dma_buf[1] == dma_buf->resv */
740 		alloc_size += 1;
741 	dmabuf = kzalloc(alloc_size, GFP_KERNEL);
742 	if (!dmabuf) {
743 		ret = -ENOMEM;
744 		goto err_file;
745 	}
746 
747 	dmabuf->priv = exp_info->priv;
748 	dmabuf->ops = exp_info->ops;
749 	dmabuf->size = exp_info->size;
750 	dmabuf->exp_name = exp_info->exp_name;
751 	dmabuf->owner = exp_info->owner;
752 	spin_lock_init(&dmabuf->name_lock);
753 	init_waitqueue_head(&dmabuf->poll);
754 	dmabuf->cb_in.poll = dmabuf->cb_out.poll = &dmabuf->poll;
755 	dmabuf->cb_in.active = dmabuf->cb_out.active = 0;
756 	INIT_LIST_HEAD(&dmabuf->attachments);
757 
758 	if (!resv) {
759 		dmabuf->resv = (struct dma_resv *)&dmabuf[1];
760 		dma_resv_init(dmabuf->resv);
761 	} else {
762 		dmabuf->resv = resv;
763 	}
764 
765 	file->private_data = dmabuf;
766 	file->f_path.dentry->d_fsdata = dmabuf;
767 	dmabuf->file = file;
768 
769 	__dma_buf_list_add(dmabuf);
770 
771 	DMA_BUF_TRACE(trace_dma_buf_export, dmabuf);
772 
773 	return dmabuf;
774 
775 err_file:
776 	fput(file);
777 err_module:
778 	module_put(exp_info->owner);
779 	return ERR_PTR(ret);
780 }
781 EXPORT_SYMBOL_NS_GPL(dma_buf_export, "DMA_BUF");
782 
783 /**
784  * dma_buf_fd - returns a file descriptor for the given struct dma_buf
785  * @dmabuf:	[in]	pointer to dma_buf for which fd is required.
786  * @flags:      [in]    flags to give to fd
787  *
788  * On success, returns an associated 'fd'. Else, returns error.
789  */
790 int dma_buf_fd(struct dma_buf *dmabuf, int flags)
791 {
792 	int fd;
793 
794 	if (!dmabuf || !dmabuf->file)
795 		return -EINVAL;
796 
797 	fd = FD_ADD(flags, dmabuf->file);
798 	if (fd >= 0)
799 		DMA_BUF_TRACE(trace_dma_buf_fd, dmabuf, fd);
800 
801 	return fd;
802 }
803 EXPORT_SYMBOL_NS_GPL(dma_buf_fd, "DMA_BUF");
804 
805 /**
806  * dma_buf_get - returns the struct dma_buf related to an fd
807  * @fd:	[in]	fd associated with the struct dma_buf to be returned
808  *
809  * On success, returns the struct dma_buf associated with an fd; uses
810  * file's refcounting done by fget to increase refcount. returns ERR_PTR
811  * otherwise.
812  */
813 struct dma_buf *dma_buf_get(int fd)
814 {
815 	struct file *file;
816 	struct dma_buf *dmabuf;
817 
818 	file = fget(fd);
819 
820 	if (!file)
821 		return ERR_PTR(-EBADF);
822 
823 	if (!is_dma_buf_file(file)) {
824 		fput(file);
825 		return ERR_PTR(-EINVAL);
826 	}
827 
828 	dmabuf = file->private_data;
829 
830 	DMA_BUF_TRACE(trace_dma_buf_get, dmabuf, fd);
831 
832 	return dmabuf;
833 }
834 EXPORT_SYMBOL_NS_GPL(dma_buf_get, "DMA_BUF");
835 
836 /**
837  * dma_buf_put - decreases refcount of the buffer
838  * @dmabuf:	[in]	buffer to reduce refcount of
839  *
840  * Uses file's refcounting done implicitly by fput().
841  *
842  * If, as a result of this call, the refcount becomes 0, the 'release' file
843  * operation related to this fd is called. It calls &dma_buf_ops.release vfunc
844  * in turn, and frees the memory allocated for dmabuf when exported.
845  */
846 void dma_buf_put(struct dma_buf *dmabuf)
847 {
848 	if (WARN_ON(!dmabuf || !dmabuf->file))
849 		return;
850 
851 	fput(dmabuf->file);
852 
853 	DMA_BUF_TRACE(trace_dma_buf_put, dmabuf);
854 }
855 EXPORT_SYMBOL_NS_GPL(dma_buf_put, "DMA_BUF");
856 
857 static int dma_buf_wrap_sg_table(struct sg_table **sg_table)
858 {
859 	struct scatterlist *to_sg, *from_sg;
860 	struct sg_table *from = *sg_table;
861 	struct dma_buf_sg_table_wrapper *to;
862 	int i, ret;
863 
864 	if (!IS_ENABLED(CONFIG_DMABUF_DEBUG))
865 		return 0;
866 
867 	/*
868 	 * To catch abuse of the underlying struct page by importers copy the
869 	 * sg_table without copying the page_link and give only the copy back to
870 	 * the importer.
871 	 */
872 	to = kzalloc(sizeof(*to), GFP_KERNEL);
873 	if (!to)
874 		return -ENOMEM;
875 
876 	ret = sg_alloc_table(&to->wrapper, from->nents, GFP_KERNEL);
877 	if (ret)
878 		goto free_to;
879 
880 	to_sg = to->wrapper.sgl;
881 	for_each_sgtable_dma_sg(from, from_sg, i) {
882 		to_sg->offset = 0;
883 		to_sg->length = 0;
884 		sg_assign_page(to_sg, NULL);
885 		sg_dma_address(to_sg) = sg_dma_address(from_sg);
886 		sg_dma_len(to_sg) = sg_dma_len(from_sg);
887 		to_sg = sg_next(to_sg);
888 	}
889 
890 	to->original = from;
891 	*sg_table = &to->wrapper;
892 	return 0;
893 
894 free_to:
895 	kfree(to);
896 	return ret;
897 }
898 
899 static void dma_buf_unwrap_sg_table(struct sg_table **sg_table)
900 {
901 	struct dma_buf_sg_table_wrapper *copy;
902 
903 	if (!IS_ENABLED(CONFIG_DMABUF_DEBUG))
904 		return;
905 
906 	copy = container_of(*sg_table, typeof(*copy), wrapper);
907 	*sg_table = copy->original;
908 	sg_free_table(&copy->wrapper);
909 	kfree(copy);
910 }
911 
912 static inline bool
913 dma_buf_attachment_is_dynamic(struct dma_buf_attachment *attach)
914 {
915 	return !!attach->importer_ops;
916 }
917 
918 static bool
919 dma_buf_pin_on_map(struct dma_buf_attachment *attach)
920 {
921 	return attach->dmabuf->ops->pin &&
922 		(!dma_buf_attachment_is_dynamic(attach) ||
923 		 !IS_ENABLED(CONFIG_DMABUF_MOVE_NOTIFY));
924 }
925 
926 /**
927  * DOC: locking convention
928  *
929  * In order to avoid deadlock situations between dma-buf exports and importers,
930  * all dma-buf API users must follow the common dma-buf locking convention.
931  *
932  * Convention for importers
933  *
934  * 1. Importers must hold the dma-buf reservation lock when calling these
935  *    functions:
936  *
937  *     - dma_buf_pin()
938  *     - dma_buf_unpin()
939  *     - dma_buf_map_attachment()
940  *     - dma_buf_unmap_attachment()
941  *     - dma_buf_vmap()
942  *     - dma_buf_vunmap()
943  *
944  * 2. Importers must not hold the dma-buf reservation lock when calling these
945  *    functions:
946  *
947  *     - dma_buf_attach()
948  *     - dma_buf_dynamic_attach()
949  *     - dma_buf_detach()
950  *     - dma_buf_export()
951  *     - dma_buf_fd()
952  *     - dma_buf_get()
953  *     - dma_buf_put()
954  *     - dma_buf_mmap()
955  *     - dma_buf_begin_cpu_access()
956  *     - dma_buf_end_cpu_access()
957  *     - dma_buf_map_attachment_unlocked()
958  *     - dma_buf_unmap_attachment_unlocked()
959  *     - dma_buf_vmap_unlocked()
960  *     - dma_buf_vunmap_unlocked()
961  *
962  * Convention for exporters
963  *
964  * 1. These &dma_buf_ops callbacks are invoked with unlocked dma-buf
965  *    reservation and exporter can take the lock:
966  *
967  *     - &dma_buf_ops.attach()
968  *     - &dma_buf_ops.detach()
969  *     - &dma_buf_ops.release()
970  *     - &dma_buf_ops.begin_cpu_access()
971  *     - &dma_buf_ops.end_cpu_access()
972  *     - &dma_buf_ops.mmap()
973  *
974  * 2. These &dma_buf_ops callbacks are invoked with locked dma-buf
975  *    reservation and exporter can't take the lock:
976  *
977  *     - &dma_buf_ops.pin()
978  *     - &dma_buf_ops.unpin()
979  *     - &dma_buf_ops.map_dma_buf()
980  *     - &dma_buf_ops.unmap_dma_buf()
981  *     - &dma_buf_ops.vmap()
982  *     - &dma_buf_ops.vunmap()
983  *
984  * 3. Exporters must hold the dma-buf reservation lock when calling these
985  *    functions:
986  *
987  *     - dma_buf_move_notify()
988  */
989 
990 /**
991  * dma_buf_dynamic_attach - Add the device to dma_buf's attachments list
992  * @dmabuf:		[in]	buffer to attach device to.
993  * @dev:		[in]	device to be attached.
994  * @importer_ops:	[in]	importer operations for the attachment
995  * @importer_priv:	[in]	importer private pointer for the attachment
996  *
997  * Returns struct dma_buf_attachment pointer for this attachment. Attachments
998  * must be cleaned up by calling dma_buf_detach().
999  *
1000  * Optionally this calls &dma_buf_ops.attach to allow device-specific attach
1001  * functionality.
1002  *
1003  * Returns:
1004  *
1005  * A pointer to newly created &dma_buf_attachment on success, or a negative
1006  * error code wrapped into a pointer on failure.
1007  *
1008  * Note that this can fail if the backing storage of @dmabuf is in a place not
1009  * accessible to @dev, and cannot be moved to a more suitable place. This is
1010  * indicated with the error code -EBUSY.
1011  */
1012 struct dma_buf_attachment *
1013 dma_buf_dynamic_attach(struct dma_buf *dmabuf, struct device *dev,
1014 		       const struct dma_buf_attach_ops *importer_ops,
1015 		       void *importer_priv)
1016 {
1017 	struct dma_buf_attachment *attach;
1018 	int ret;
1019 
1020 	if (WARN_ON(!dmabuf || !dev))
1021 		return ERR_PTR(-EINVAL);
1022 
1023 	if (WARN_ON(importer_ops && !importer_ops->move_notify))
1024 		return ERR_PTR(-EINVAL);
1025 
1026 	attach = kzalloc(sizeof(*attach), GFP_KERNEL);
1027 	if (!attach)
1028 		return ERR_PTR(-ENOMEM);
1029 
1030 	attach->dev = dev;
1031 	attach->dmabuf = dmabuf;
1032 	if (importer_ops)
1033 		attach->peer2peer = importer_ops->allow_peer2peer;
1034 	attach->importer_ops = importer_ops;
1035 	attach->importer_priv = importer_priv;
1036 
1037 	if (dmabuf->ops->attach) {
1038 		ret = dmabuf->ops->attach(dmabuf, attach);
1039 		if (ret)
1040 			goto err_attach;
1041 	}
1042 	dma_resv_lock(dmabuf->resv, NULL);
1043 	list_add(&attach->node, &dmabuf->attachments);
1044 	dma_resv_unlock(dmabuf->resv);
1045 
1046 	DMA_BUF_TRACE(trace_dma_buf_dynamic_attach, dmabuf, attach,
1047 		dma_buf_attachment_is_dynamic(attach), dev);
1048 
1049 	return attach;
1050 
1051 err_attach:
1052 	kfree(attach);
1053 	return ERR_PTR(ret);
1054 }
1055 EXPORT_SYMBOL_NS_GPL(dma_buf_dynamic_attach, "DMA_BUF");
1056 
1057 /**
1058  * dma_buf_attach - Wrapper for dma_buf_dynamic_attach
1059  * @dmabuf:	[in]	buffer to attach device to.
1060  * @dev:	[in]	device to be attached.
1061  *
1062  * Wrapper to call dma_buf_dynamic_attach() for drivers which still use a static
1063  * mapping.
1064  */
1065 struct dma_buf_attachment *dma_buf_attach(struct dma_buf *dmabuf,
1066 					  struct device *dev)
1067 {
1068 	return dma_buf_dynamic_attach(dmabuf, dev, NULL, NULL);
1069 }
1070 EXPORT_SYMBOL_NS_GPL(dma_buf_attach, "DMA_BUF");
1071 
1072 /**
1073  * dma_buf_detach - Remove the given attachment from dmabuf's attachments list
1074  * @dmabuf:	[in]	buffer to detach from.
1075  * @attach:	[in]	attachment to be detached; is free'd after this call.
1076  *
1077  * Clean up a device attachment obtained by calling dma_buf_attach().
1078  *
1079  * Optionally this calls &dma_buf_ops.detach for device-specific detach.
1080  */
1081 void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
1082 {
1083 	if (WARN_ON(!dmabuf || !attach || dmabuf != attach->dmabuf))
1084 		return;
1085 
1086 	dma_resv_lock(dmabuf->resv, NULL);
1087 	list_del(&attach->node);
1088 	dma_resv_unlock(dmabuf->resv);
1089 
1090 	if (dmabuf->ops->detach)
1091 		dmabuf->ops->detach(dmabuf, attach);
1092 
1093 	DMA_BUF_TRACE(trace_dma_buf_detach, dmabuf, attach,
1094 		dma_buf_attachment_is_dynamic(attach), attach->dev);
1095 
1096 	kfree(attach);
1097 }
1098 EXPORT_SYMBOL_NS_GPL(dma_buf_detach, "DMA_BUF");
1099 
1100 /**
1101  * dma_buf_pin - Lock down the DMA-buf
1102  * @attach:	[in]	attachment which should be pinned
1103  *
1104  * Only dynamic importers (who set up @attach with dma_buf_dynamic_attach()) may
1105  * call this, and only for limited use cases like scanout and not for temporary
1106  * pin operations. It is not permitted to allow userspace to pin arbitrary
1107  * amounts of buffers through this interface.
1108  *
1109  * Buffers must be unpinned by calling dma_buf_unpin().
1110  *
1111  * Returns:
1112  * 0 on success, negative error code on failure.
1113  */
1114 int dma_buf_pin(struct dma_buf_attachment *attach)
1115 {
1116 	struct dma_buf *dmabuf = attach->dmabuf;
1117 	int ret = 0;
1118 
1119 	WARN_ON(!attach->importer_ops);
1120 
1121 	dma_resv_assert_held(dmabuf->resv);
1122 
1123 	if (dmabuf->ops->pin)
1124 		ret = dmabuf->ops->pin(attach);
1125 
1126 	return ret;
1127 }
1128 EXPORT_SYMBOL_NS_GPL(dma_buf_pin, "DMA_BUF");
1129 
1130 /**
1131  * dma_buf_unpin - Unpin a DMA-buf
1132  * @attach:	[in]	attachment which should be unpinned
1133  *
1134  * This unpins a buffer pinned by dma_buf_pin() and allows the exporter to move
1135  * any mapping of @attach again and inform the importer through
1136  * &dma_buf_attach_ops.move_notify.
1137  */
1138 void dma_buf_unpin(struct dma_buf_attachment *attach)
1139 {
1140 	struct dma_buf *dmabuf = attach->dmabuf;
1141 
1142 	WARN_ON(!attach->importer_ops);
1143 
1144 	dma_resv_assert_held(dmabuf->resv);
1145 
1146 	if (dmabuf->ops->unpin)
1147 		dmabuf->ops->unpin(attach);
1148 }
1149 EXPORT_SYMBOL_NS_GPL(dma_buf_unpin, "DMA_BUF");
1150 
1151 /**
1152  * dma_buf_map_attachment - Returns the scatterlist table of the attachment;
1153  * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
1154  * dma_buf_ops.
1155  * @attach:	[in]	attachment whose scatterlist is to be returned
1156  * @direction:	[in]	direction of DMA transfer
1157  *
1158  * Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
1159  * on error. May return -EINTR if it is interrupted by a signal.
1160  *
1161  * On success, the DMA addresses and lengths in the returned scatterlist are
1162  * PAGE_SIZE aligned.
1163  *
1164  * A mapping must be unmapped by using dma_buf_unmap_attachment(). Note that
1165  * the underlying backing storage is pinned for as long as a mapping exists,
1166  * therefore users/importers should not hold onto a mapping for undue amounts of
1167  * time.
1168  *
1169  * Important: Dynamic importers must wait for the exclusive fence of the struct
1170  * dma_resv attached to the DMA-BUF first.
1171  */
1172 struct sg_table *dma_buf_map_attachment(struct dma_buf_attachment *attach,
1173 					enum dma_data_direction direction)
1174 {
1175 	struct sg_table *sg_table;
1176 	signed long ret;
1177 
1178 	might_sleep();
1179 
1180 	if (WARN_ON(!attach || !attach->dmabuf))
1181 		return ERR_PTR(-EINVAL);
1182 
1183 	dma_resv_assert_held(attach->dmabuf->resv);
1184 
1185 	if (dma_buf_pin_on_map(attach)) {
1186 		ret = attach->dmabuf->ops->pin(attach);
1187 		/*
1188 		 * Catch exporters making buffers inaccessible even when
1189 		 * attachments preventing that exist.
1190 		 */
1191 		WARN_ON_ONCE(ret == -EBUSY);
1192 		if (ret)
1193 			return ERR_PTR(ret);
1194 	}
1195 
1196 	sg_table = attach->dmabuf->ops->map_dma_buf(attach, direction);
1197 	if (!sg_table)
1198 		sg_table = ERR_PTR(-ENOMEM);
1199 	if (IS_ERR(sg_table))
1200 		goto error_unpin;
1201 
1202 	/*
1203 	 * Importers with static attachments don't wait for fences.
1204 	 */
1205 	if (!dma_buf_attachment_is_dynamic(attach)) {
1206 		ret = dma_resv_wait_timeout(attach->dmabuf->resv,
1207 					    DMA_RESV_USAGE_KERNEL, true,
1208 					    MAX_SCHEDULE_TIMEOUT);
1209 		if (ret < 0)
1210 			goto error_unmap;
1211 	}
1212 	ret = dma_buf_wrap_sg_table(&sg_table);
1213 	if (ret)
1214 		goto error_unmap;
1215 
1216 	if (IS_ENABLED(CONFIG_DMA_API_DEBUG)) {
1217 		struct scatterlist *sg;
1218 		u64 addr;
1219 		int len;
1220 		int i;
1221 
1222 		for_each_sgtable_dma_sg(sg_table, sg, i) {
1223 			addr = sg_dma_address(sg);
1224 			len = sg_dma_len(sg);
1225 			if (!PAGE_ALIGNED(addr) || !PAGE_ALIGNED(len)) {
1226 				pr_debug("%s: addr %llx or len %x is not page aligned!\n",
1227 					 __func__, addr, len);
1228 				break;
1229 			}
1230 		}
1231 	}
1232 	return sg_table;
1233 
1234 error_unmap:
1235 	attach->dmabuf->ops->unmap_dma_buf(attach, sg_table, direction);
1236 	sg_table = ERR_PTR(ret);
1237 
1238 error_unpin:
1239 	if (dma_buf_pin_on_map(attach))
1240 		attach->dmabuf->ops->unpin(attach);
1241 
1242 	return sg_table;
1243 }
1244 EXPORT_SYMBOL_NS_GPL(dma_buf_map_attachment, "DMA_BUF");
1245 
1246 /**
1247  * dma_buf_map_attachment_unlocked - Returns the scatterlist table of the attachment;
1248  * mapped into _device_ address space. Is a wrapper for map_dma_buf() of the
1249  * dma_buf_ops.
1250  * @attach:	[in]	attachment whose scatterlist is to be returned
1251  * @direction:	[in]	direction of DMA transfer
1252  *
1253  * Unlocked variant of dma_buf_map_attachment().
1254  */
1255 struct sg_table *
1256 dma_buf_map_attachment_unlocked(struct dma_buf_attachment *attach,
1257 				enum dma_data_direction direction)
1258 {
1259 	struct sg_table *sg_table;
1260 
1261 	might_sleep();
1262 
1263 	if (WARN_ON(!attach || !attach->dmabuf))
1264 		return ERR_PTR(-EINVAL);
1265 
1266 	dma_resv_lock(attach->dmabuf->resv, NULL);
1267 	sg_table = dma_buf_map_attachment(attach, direction);
1268 	dma_resv_unlock(attach->dmabuf->resv);
1269 
1270 	return sg_table;
1271 }
1272 EXPORT_SYMBOL_NS_GPL(dma_buf_map_attachment_unlocked, "DMA_BUF");
1273 
1274 /**
1275  * dma_buf_unmap_attachment - unmaps and decreases usecount of the buffer;might
1276  * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
1277  * dma_buf_ops.
1278  * @attach:	[in]	attachment to unmap buffer from
1279  * @sg_table:	[in]	scatterlist info of the buffer to unmap
1280  * @direction:  [in]    direction of DMA transfer
1281  *
1282  * This unmaps a DMA mapping for @attached obtained by dma_buf_map_attachment().
1283  */
1284 void dma_buf_unmap_attachment(struct dma_buf_attachment *attach,
1285 				struct sg_table *sg_table,
1286 				enum dma_data_direction direction)
1287 {
1288 	might_sleep();
1289 
1290 	if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
1291 		return;
1292 
1293 	dma_resv_assert_held(attach->dmabuf->resv);
1294 
1295 	dma_buf_unwrap_sg_table(&sg_table);
1296 	attach->dmabuf->ops->unmap_dma_buf(attach, sg_table, direction);
1297 
1298 	if (dma_buf_pin_on_map(attach))
1299 		attach->dmabuf->ops->unpin(attach);
1300 }
1301 EXPORT_SYMBOL_NS_GPL(dma_buf_unmap_attachment, "DMA_BUF");
1302 
1303 /**
1304  * dma_buf_unmap_attachment_unlocked - unmaps and decreases usecount of the buffer;might
1305  * deallocate the scatterlist associated. Is a wrapper for unmap_dma_buf() of
1306  * dma_buf_ops.
1307  * @attach:	[in]	attachment to unmap buffer from
1308  * @sg_table:	[in]	scatterlist info of the buffer to unmap
1309  * @direction:	[in]	direction of DMA transfer
1310  *
1311  * Unlocked variant of dma_buf_unmap_attachment().
1312  */
1313 void dma_buf_unmap_attachment_unlocked(struct dma_buf_attachment *attach,
1314 				       struct sg_table *sg_table,
1315 				       enum dma_data_direction direction)
1316 {
1317 	might_sleep();
1318 
1319 	if (WARN_ON(!attach || !attach->dmabuf || !sg_table))
1320 		return;
1321 
1322 	dma_resv_lock(attach->dmabuf->resv, NULL);
1323 	dma_buf_unmap_attachment(attach, sg_table, direction);
1324 	dma_resv_unlock(attach->dmabuf->resv);
1325 }
1326 EXPORT_SYMBOL_NS_GPL(dma_buf_unmap_attachment_unlocked, "DMA_BUF");
1327 
1328 /**
1329  * dma_buf_move_notify - notify attachments that DMA-buf is moving
1330  *
1331  * @dmabuf:	[in]	buffer which is moving
1332  *
1333  * Informs all attachments that they need to destroy and recreate all their
1334  * mappings.
1335  */
1336 void dma_buf_move_notify(struct dma_buf *dmabuf)
1337 {
1338 	struct dma_buf_attachment *attach;
1339 
1340 	dma_resv_assert_held(dmabuf->resv);
1341 
1342 	list_for_each_entry(attach, &dmabuf->attachments, node)
1343 		if (attach->importer_ops)
1344 			attach->importer_ops->move_notify(attach);
1345 }
1346 EXPORT_SYMBOL_NS_GPL(dma_buf_move_notify, "DMA_BUF");
1347 
1348 /**
1349  * DOC: cpu access
1350  *
1351  * There are multiple reasons for supporting CPU access to a dma buffer object:
1352  *
1353  * - Fallback operations in the kernel, for example when a device is connected
1354  *   over USB and the kernel needs to shuffle the data around first before
1355  *   sending it away. Cache coherency is handled by bracketing any transactions
1356  *   with calls to dma_buf_begin_cpu_access() and dma_buf_end_cpu_access()
1357  *   access.
1358  *
1359  *   Since for most kernel internal dma-buf accesses need the entire buffer, a
1360  *   vmap interface is introduced. Note that on very old 32-bit architectures
1361  *   vmalloc space might be limited and result in vmap calls failing.
1362  *
1363  *   Interfaces:
1364  *
1365  *   .. code-block:: c
1366  *
1367  *     void *dma_buf_vmap(struct dma_buf *dmabuf, struct iosys_map *map)
1368  *     void dma_buf_vunmap(struct dma_buf *dmabuf, struct iosys_map *map)
1369  *
1370  *   The vmap call can fail if there is no vmap support in the exporter, or if
1371  *   it runs out of vmalloc space. Note that the dma-buf layer keeps a reference
1372  *   count for all vmap access and calls down into the exporter's vmap function
1373  *   only when no vmapping exists, and only unmaps it once. Protection against
1374  *   concurrent vmap/vunmap calls is provided by taking the &dma_buf.lock mutex.
1375  *
1376  * - For full compatibility on the importer side with existing userspace
1377  *   interfaces, which might already support mmap'ing buffers. This is needed in
1378  *   many processing pipelines (e.g. feeding a software rendered image into a
1379  *   hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
1380  *   framework already supported this and for DMA buffer file descriptors to
1381  *   replace ION buffers mmap support was needed.
1382  *
1383  *   There is no special interfaces, userspace simply calls mmap on the dma-buf
1384  *   fd. But like for CPU access there's a need to bracket the actual access,
1385  *   which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
1386  *   DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
1387  *   be restarted.
1388  *
1389  *   Some systems might need some sort of cache coherency management e.g. when
1390  *   CPU and GPU domains are being accessed through dma-buf at the same time.
1391  *   To circumvent this problem there are begin/end coherency markers, that
1392  *   forward directly to existing dma-buf device drivers vfunc hooks. Userspace
1393  *   can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
1394  *   sequence would be used like following:
1395  *
1396  *     - mmap dma-buf fd
1397  *     - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
1398  *       to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
1399  *       want (with the new data being consumed by say the GPU or the scanout
1400  *       device)
1401  *     - munmap once you don't need the buffer any more
1402  *
1403  *    For correctness and optimal performance, it is always required to use
1404  *    SYNC_START and SYNC_END before and after, respectively, when accessing the
1405  *    mapped address. Userspace cannot rely on coherent access, even when there
1406  *    are systems where it just works without calling these ioctls.
1407  *
1408  * - And as a CPU fallback in userspace processing pipelines.
1409  *
1410  *   Similar to the motivation for kernel cpu access it is again important that
1411  *   the userspace code of a given importing subsystem can use the same
1412  *   interfaces with a imported dma-buf buffer object as with a native buffer
1413  *   object. This is especially important for drm where the userspace part of
1414  *   contemporary OpenGL, X, and other drivers is huge, and reworking them to
1415  *   use a different way to mmap a buffer rather invasive.
1416  *
1417  *   The assumption in the current dma-buf interfaces is that redirecting the
1418  *   initial mmap is all that's needed. A survey of some of the existing
1419  *   subsystems shows that no driver seems to do any nefarious thing like
1420  *   syncing up with outstanding asynchronous processing on the device or
1421  *   allocating special resources at fault time. So hopefully this is good
1422  *   enough, since adding interfaces to intercept pagefaults and allow pte
1423  *   shootdowns would increase the complexity quite a bit.
1424  *
1425  *   Interface:
1426  *
1427  *   .. code-block:: c
1428  *
1429  *     int dma_buf_mmap(struct dma_buf *, struct vm_area_struct *, unsigned long);
1430  *
1431  *   If the importing subsystem simply provides a special-purpose mmap call to
1432  *   set up a mapping in userspace, calling do_mmap with &dma_buf.file will
1433  *   equally achieve that for a dma-buf object.
1434  */
1435 
1436 static int __dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
1437 				      enum dma_data_direction direction)
1438 {
1439 	bool write = (direction == DMA_BIDIRECTIONAL ||
1440 		      direction == DMA_TO_DEVICE);
1441 	struct dma_resv *resv = dmabuf->resv;
1442 	long ret;
1443 
1444 	/* Wait on any implicit rendering fences */
1445 	ret = dma_resv_wait_timeout(resv, dma_resv_usage_rw(write),
1446 				    true, MAX_SCHEDULE_TIMEOUT);
1447 	if (ret < 0)
1448 		return ret;
1449 
1450 	return 0;
1451 }
1452 
1453 /**
1454  * dma_buf_begin_cpu_access - Must be called before accessing a dma_buf from the
1455  * cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific
1456  * preparations. Coherency is only guaranteed in the specified range for the
1457  * specified access direction.
1458  * @dmabuf:	[in]	buffer to prepare cpu access for.
1459  * @direction:	[in]	direction of access.
1460  *
1461  * After the cpu access is complete the caller should call
1462  * dma_buf_end_cpu_access(). Only when cpu access is bracketed by both calls is
1463  * it guaranteed to be coherent with other DMA access.
1464  *
1465  * This function will also wait for any DMA transactions tracked through
1466  * implicit synchronization in &dma_buf.resv. For DMA transactions with explicit
1467  * synchronization this function will only ensure cache coherency, callers must
1468  * ensure synchronization with such DMA transactions on their own.
1469  *
1470  * Can return negative error values, returns 0 on success.
1471  */
1472 int dma_buf_begin_cpu_access(struct dma_buf *dmabuf,
1473 			     enum dma_data_direction direction)
1474 {
1475 	int ret = 0;
1476 
1477 	if (WARN_ON(!dmabuf))
1478 		return -EINVAL;
1479 
1480 	might_lock(&dmabuf->resv->lock.base);
1481 
1482 	if (dmabuf->ops->begin_cpu_access)
1483 		ret = dmabuf->ops->begin_cpu_access(dmabuf, direction);
1484 
1485 	/* Ensure that all fences are waited upon - but we first allow
1486 	 * the native handler the chance to do so more efficiently if it
1487 	 * chooses. A double invocation here will be reasonably cheap no-op.
1488 	 */
1489 	if (ret == 0)
1490 		ret = __dma_buf_begin_cpu_access(dmabuf, direction);
1491 
1492 	return ret;
1493 }
1494 EXPORT_SYMBOL_NS_GPL(dma_buf_begin_cpu_access, "DMA_BUF");
1495 
1496 /**
1497  * dma_buf_end_cpu_access - Must be called after accessing a dma_buf from the
1498  * cpu in the kernel context. Calls end_cpu_access to allow exporter-specific
1499  * actions. Coherency is only guaranteed in the specified range for the
1500  * specified access direction.
1501  * @dmabuf:	[in]	buffer to complete cpu access for.
1502  * @direction:	[in]	direction of access.
1503  *
1504  * This terminates CPU access started with dma_buf_begin_cpu_access().
1505  *
1506  * Can return negative error values, returns 0 on success.
1507  */
1508 int dma_buf_end_cpu_access(struct dma_buf *dmabuf,
1509 			   enum dma_data_direction direction)
1510 {
1511 	int ret = 0;
1512 
1513 	WARN_ON(!dmabuf);
1514 
1515 	might_lock(&dmabuf->resv->lock.base);
1516 
1517 	if (dmabuf->ops->end_cpu_access)
1518 		ret = dmabuf->ops->end_cpu_access(dmabuf, direction);
1519 
1520 	return ret;
1521 }
1522 EXPORT_SYMBOL_NS_GPL(dma_buf_end_cpu_access, "DMA_BUF");
1523 
1524 
1525 /**
1526  * dma_buf_mmap - Setup up a userspace mmap with the given vma
1527  * @dmabuf:	[in]	buffer that should back the vma
1528  * @vma:	[in]	vma for the mmap
1529  * @pgoff:	[in]	offset in pages where this mmap should start within the
1530  *			dma-buf buffer.
1531  *
1532  * This function adjusts the passed in vma so that it points at the file of the
1533  * dma_buf operation. It also adjusts the starting pgoff and does bounds
1534  * checking on the size of the vma. Then it calls the exporters mmap function to
1535  * set up the mapping.
1536  *
1537  * Can return negative error values, returns 0 on success.
1538  */
1539 int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma,
1540 		 unsigned long pgoff)
1541 {
1542 	if (WARN_ON(!dmabuf || !vma))
1543 		return -EINVAL;
1544 
1545 	/* check if buffer supports mmap */
1546 	if (!dmabuf->ops->mmap)
1547 		return -EINVAL;
1548 
1549 	/* check for offset overflow */
1550 	if (pgoff + vma_pages(vma) < pgoff)
1551 		return -EOVERFLOW;
1552 
1553 	/* check for overflowing the buffer's size */
1554 	if (pgoff + vma_pages(vma) >
1555 	    dmabuf->size >> PAGE_SHIFT)
1556 		return -EINVAL;
1557 
1558 	/* readjust the vma */
1559 	vma_set_file(vma, dmabuf->file);
1560 	vma->vm_pgoff = pgoff;
1561 
1562 	DMA_BUF_TRACE(trace_dma_buf_mmap, dmabuf);
1563 
1564 	return dmabuf->ops->mmap(dmabuf, vma);
1565 }
1566 EXPORT_SYMBOL_NS_GPL(dma_buf_mmap, "DMA_BUF");
1567 
1568 /**
1569  * dma_buf_vmap - Create virtual mapping for the buffer object into kernel
1570  * address space. Same restrictions as for vmap and friends apply.
1571  * @dmabuf:	[in]	buffer to vmap
1572  * @map:	[out]	returns the vmap pointer
1573  *
1574  * This call may fail due to lack of virtual mapping address space.
1575  * These calls are optional in drivers. The intended use for them
1576  * is for mapping objects linear in kernel space for high use objects.
1577  *
1578  * To ensure coherency users must call dma_buf_begin_cpu_access() and
1579  * dma_buf_end_cpu_access() around any cpu access performed through this
1580  * mapping.
1581  *
1582  * Returns 0 on success, or a negative errno code otherwise.
1583  */
1584 int dma_buf_vmap(struct dma_buf *dmabuf, struct iosys_map *map)
1585 {
1586 	struct iosys_map ptr;
1587 	int ret;
1588 
1589 	iosys_map_clear(map);
1590 
1591 	if (WARN_ON(!dmabuf))
1592 		return -EINVAL;
1593 
1594 	dma_resv_assert_held(dmabuf->resv);
1595 
1596 	if (!dmabuf->ops->vmap)
1597 		return -EINVAL;
1598 
1599 	if (dmabuf->vmapping_counter) {
1600 		dmabuf->vmapping_counter++;
1601 		BUG_ON(iosys_map_is_null(&dmabuf->vmap_ptr));
1602 		*map = dmabuf->vmap_ptr;
1603 		return 0;
1604 	}
1605 
1606 	BUG_ON(iosys_map_is_set(&dmabuf->vmap_ptr));
1607 
1608 	ret = dmabuf->ops->vmap(dmabuf, &ptr);
1609 	if (WARN_ON_ONCE(ret))
1610 		return ret;
1611 
1612 	dmabuf->vmap_ptr = ptr;
1613 	dmabuf->vmapping_counter = 1;
1614 
1615 	*map = dmabuf->vmap_ptr;
1616 
1617 	return 0;
1618 }
1619 EXPORT_SYMBOL_NS_GPL(dma_buf_vmap, "DMA_BUF");
1620 
1621 /**
1622  * dma_buf_vmap_unlocked - Create virtual mapping for the buffer object into kernel
1623  * address space. Same restrictions as for vmap and friends apply.
1624  * @dmabuf:	[in]	buffer to vmap
1625  * @map:	[out]	returns the vmap pointer
1626  *
1627  * Unlocked version of dma_buf_vmap()
1628  *
1629  * Returns 0 on success, or a negative errno code otherwise.
1630  */
1631 int dma_buf_vmap_unlocked(struct dma_buf *dmabuf, struct iosys_map *map)
1632 {
1633 	int ret;
1634 
1635 	iosys_map_clear(map);
1636 
1637 	if (WARN_ON(!dmabuf))
1638 		return -EINVAL;
1639 
1640 	dma_resv_lock(dmabuf->resv, NULL);
1641 	ret = dma_buf_vmap(dmabuf, map);
1642 	dma_resv_unlock(dmabuf->resv);
1643 
1644 	return ret;
1645 }
1646 EXPORT_SYMBOL_NS_GPL(dma_buf_vmap_unlocked, "DMA_BUF");
1647 
1648 /**
1649  * dma_buf_vunmap - Unmap a vmap obtained by dma_buf_vmap.
1650  * @dmabuf:	[in]	buffer to vunmap
1651  * @map:	[in]	vmap pointer to vunmap
1652  */
1653 void dma_buf_vunmap(struct dma_buf *dmabuf, struct iosys_map *map)
1654 {
1655 	if (WARN_ON(!dmabuf))
1656 		return;
1657 
1658 	dma_resv_assert_held(dmabuf->resv);
1659 
1660 	BUG_ON(iosys_map_is_null(&dmabuf->vmap_ptr));
1661 	BUG_ON(dmabuf->vmapping_counter == 0);
1662 	BUG_ON(!iosys_map_is_equal(&dmabuf->vmap_ptr, map));
1663 
1664 	if (--dmabuf->vmapping_counter == 0) {
1665 		if (dmabuf->ops->vunmap)
1666 			dmabuf->ops->vunmap(dmabuf, map);
1667 		iosys_map_clear(&dmabuf->vmap_ptr);
1668 	}
1669 }
1670 EXPORT_SYMBOL_NS_GPL(dma_buf_vunmap, "DMA_BUF");
1671 
1672 /**
1673  * dma_buf_vunmap_unlocked - Unmap a vmap obtained by dma_buf_vmap.
1674  * @dmabuf:	[in]	buffer to vunmap
1675  * @map:	[in]	vmap pointer to vunmap
1676  */
1677 void dma_buf_vunmap_unlocked(struct dma_buf *dmabuf, struct iosys_map *map)
1678 {
1679 	if (WARN_ON(!dmabuf))
1680 		return;
1681 
1682 	dma_resv_lock(dmabuf->resv, NULL);
1683 	dma_buf_vunmap(dmabuf, map);
1684 	dma_resv_unlock(dmabuf->resv);
1685 }
1686 EXPORT_SYMBOL_NS_GPL(dma_buf_vunmap_unlocked, "DMA_BUF");
1687 
1688 #ifdef CONFIG_DEBUG_FS
1689 static int dma_buf_debug_show(struct seq_file *s, void *unused)
1690 {
1691 	struct dma_buf *buf_obj;
1692 	struct dma_buf_attachment *attach_obj;
1693 	int count = 0, attach_count;
1694 	size_t size = 0;
1695 	int ret;
1696 
1697 	ret = mutex_lock_interruptible(&dmabuf_list_mutex);
1698 
1699 	if (ret)
1700 		return ret;
1701 
1702 	seq_puts(s, "\nDma-buf Objects:\n");
1703 	seq_printf(s, "%-8s\t%-8s\t%-8s\t%-8s\texp_name\t%-8s\tname\n",
1704 		   "size", "flags", "mode", "count", "ino");
1705 
1706 	list_for_each_entry(buf_obj, &dmabuf_list, list_node) {
1707 
1708 		ret = dma_resv_lock_interruptible(buf_obj->resv, NULL);
1709 		if (ret)
1710 			goto error_unlock;
1711 
1712 
1713 		spin_lock(&buf_obj->name_lock);
1714 		seq_printf(s, "%08zu\t%08x\t%08x\t%08ld\t%s\t%08lu\t%s\n",
1715 				buf_obj->size,
1716 				buf_obj->file->f_flags, buf_obj->file->f_mode,
1717 				file_count(buf_obj->file),
1718 				buf_obj->exp_name,
1719 				file_inode(buf_obj->file)->i_ino,
1720 				buf_obj->name ?: "<none>");
1721 		spin_unlock(&buf_obj->name_lock);
1722 
1723 		dma_resv_describe(buf_obj->resv, s);
1724 
1725 		seq_puts(s, "\tAttached Devices:\n");
1726 		attach_count = 0;
1727 
1728 		list_for_each_entry(attach_obj, &buf_obj->attachments, node) {
1729 			seq_printf(s, "\t%s\n", dev_name(attach_obj->dev));
1730 			attach_count++;
1731 		}
1732 		dma_resv_unlock(buf_obj->resv);
1733 
1734 		seq_printf(s, "Total %d devices attached\n\n",
1735 				attach_count);
1736 
1737 		count++;
1738 		size += buf_obj->size;
1739 	}
1740 
1741 	seq_printf(s, "\nTotal %d objects, %zu bytes\n", count, size);
1742 
1743 	mutex_unlock(&dmabuf_list_mutex);
1744 	return 0;
1745 
1746 error_unlock:
1747 	mutex_unlock(&dmabuf_list_mutex);
1748 	return ret;
1749 }
1750 
1751 DEFINE_SHOW_ATTRIBUTE(dma_buf_debug);
1752 
1753 static struct dentry *dma_buf_debugfs_dir;
1754 
1755 static int dma_buf_init_debugfs(void)
1756 {
1757 	struct dentry *d;
1758 	int err = 0;
1759 
1760 	d = debugfs_create_dir("dma_buf", NULL);
1761 	if (IS_ERR(d))
1762 		return PTR_ERR(d);
1763 
1764 	dma_buf_debugfs_dir = d;
1765 
1766 	d = debugfs_create_file("bufinfo", 0444, dma_buf_debugfs_dir,
1767 				NULL, &dma_buf_debug_fops);
1768 	if (IS_ERR(d)) {
1769 		pr_debug("dma_buf: debugfs: failed to create node bufinfo\n");
1770 		debugfs_remove_recursive(dma_buf_debugfs_dir);
1771 		dma_buf_debugfs_dir = NULL;
1772 		err = PTR_ERR(d);
1773 	}
1774 
1775 	return err;
1776 }
1777 
1778 static void dma_buf_uninit_debugfs(void)
1779 {
1780 	debugfs_remove_recursive(dma_buf_debugfs_dir);
1781 }
1782 #else
1783 static inline int dma_buf_init_debugfs(void)
1784 {
1785 	return 0;
1786 }
1787 static inline void dma_buf_uninit_debugfs(void)
1788 {
1789 }
1790 #endif
1791 
1792 static int __init dma_buf_init(void)
1793 {
1794 	dma_buf_mnt = kern_mount(&dma_buf_fs_type);
1795 	if (IS_ERR(dma_buf_mnt))
1796 		return PTR_ERR(dma_buf_mnt);
1797 
1798 	dma_buf_init_debugfs();
1799 	return 0;
1800 }
1801 subsys_initcall(dma_buf_init);
1802 
1803 static void __exit dma_buf_deinit(void)
1804 {
1805 	dma_buf_uninit_debugfs();
1806 	kern_unmount(dma_buf_mnt);
1807 }
1808 __exitcall(dma_buf_deinit);
1809