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