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