xref: /linux/drivers/gpu/drm/drm_prime.c (revision 5fc2bfddb0ae6c6ebd5e690014abf551c6b29bfd)
1 /*
2  * Copyright © 2012 Red Hat
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *      Dave Airlie <airlied@redhat.com>
25  *      Rob Clark <rob.clark@linaro.org>
26  *
27  */
28 
29 #include <linux/export.h>
30 #include <linux/dma-buf.h>
31 #include <linux/rbtree.h>
32 #include <linux/module.h>
33 
34 #include <drm/drm.h>
35 #include <drm/drm_drv.h>
36 #include <drm/drm_file.h>
37 #include <drm/drm_framebuffer.h>
38 #include <drm/drm_gem.h>
39 #include <drm/drm_prime.h>
40 
41 #include "drm_internal.h"
42 
43 MODULE_IMPORT_NS("DMA_BUF");
44 
45 /**
46  * DOC: overview and lifetime rules
47  *
48  * Similar to GEM global names, PRIME file descriptors are also used to share
49  * buffer objects across processes. They offer additional security: as file
50  * descriptors must be explicitly sent over UNIX domain sockets to be shared
51  * between applications, they can't be guessed like the globally unique GEM
52  * names.
53  *
54  * Drivers that support the PRIME API implement the drm_gem_object_funcs.export
55  * and &drm_driver.gem_prime_import hooks. &dma_buf_ops implementations for
56  * drivers are all individually exported for drivers which need to overwrite
57  * or reimplement some of them.
58  *
59  * Reference Counting for GEM Drivers
60  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
61  *
62  * On the export the &dma_buf holds a reference to the exported buffer object,
63  * usually a &drm_gem_object. It takes this reference in the PRIME_HANDLE_TO_FD
64  * IOCTL, when it first calls &drm_gem_object_funcs.export
65  * and stores the exporting GEM object in the &dma_buf.priv field. This
66  * reference needs to be released when the final reference to the &dma_buf
67  * itself is dropped and its &dma_buf_ops.release function is called.  For
68  * GEM-based drivers, the &dma_buf should be exported using
69  * drm_gem_dmabuf_export() and then released by drm_gem_dmabuf_release().
70  *
71  * Thus the chain of references always flows in one direction, avoiding loops:
72  * importing GEM object -> dma-buf -> exported GEM bo. A further complication
73  * are the lookup caches for import and export. These are required to guarantee
74  * that any given object will always have only one unique userspace handle. This
75  * is required to allow userspace to detect duplicated imports, since some GEM
76  * drivers do fail command submissions if a given buffer object is listed more
77  * than once. These import and export caches in &drm_prime_file_private only
78  * retain a weak reference, which is cleaned up when the corresponding object is
79  * released.
80  *
81  * Self-importing: If userspace is using PRIME as a replacement for flink then
82  * it will get a fd->handle request for a GEM object that it created.  Drivers
83  * should detect this situation and return back the underlying object from the
84  * dma-buf private. For GEM based drivers this is handled in
85  * drm_gem_prime_import() already.
86  */
87 
88 struct drm_prime_member {
89 	struct dma_buf *dma_buf;
90 	uint32_t handle;
91 
92 	struct rb_node dmabuf_rb;
93 	struct rb_node handle_rb;
94 };
95 
96 int drm_prime_add_buf_handle(struct drm_prime_file_private *prime_fpriv,
97 				    struct dma_buf *dma_buf, uint32_t handle)
98 {
99 	struct drm_prime_member *member;
100 	struct rb_node **p, *rb;
101 
102 	member = kmalloc(sizeof(*member), GFP_KERNEL);
103 	if (!member)
104 		return -ENOMEM;
105 
106 	get_dma_buf(dma_buf);
107 	member->dma_buf = dma_buf;
108 	member->handle = handle;
109 
110 	rb = NULL;
111 	p = &prime_fpriv->dmabufs.rb_node;
112 	while (*p) {
113 		struct drm_prime_member *pos;
114 
115 		rb = *p;
116 		pos = rb_entry(rb, struct drm_prime_member, dmabuf_rb);
117 		if (dma_buf > pos->dma_buf)
118 			p = &rb->rb_right;
119 		else
120 			p = &rb->rb_left;
121 	}
122 	rb_link_node(&member->dmabuf_rb, rb, p);
123 	rb_insert_color(&member->dmabuf_rb, &prime_fpriv->dmabufs);
124 
125 	rb = NULL;
126 	p = &prime_fpriv->handles.rb_node;
127 	while (*p) {
128 		struct drm_prime_member *pos;
129 
130 		rb = *p;
131 		pos = rb_entry(rb, struct drm_prime_member, handle_rb);
132 		if (handle > pos->handle)
133 			p = &rb->rb_right;
134 		else
135 			p = &rb->rb_left;
136 	}
137 	rb_link_node(&member->handle_rb, rb, p);
138 	rb_insert_color(&member->handle_rb, &prime_fpriv->handles);
139 
140 	return 0;
141 }
142 
143 static struct dma_buf *drm_prime_lookup_buf_by_handle(struct drm_prime_file_private *prime_fpriv,
144 						      uint32_t handle)
145 {
146 	struct rb_node *rb;
147 
148 	rb = prime_fpriv->handles.rb_node;
149 	while (rb) {
150 		struct drm_prime_member *member;
151 
152 		member = rb_entry(rb, struct drm_prime_member, handle_rb);
153 		if (member->handle == handle)
154 			return member->dma_buf;
155 		else if (member->handle < handle)
156 			rb = rb->rb_right;
157 		else
158 			rb = rb->rb_left;
159 	}
160 
161 	return NULL;
162 }
163 
164 static int drm_prime_lookup_buf_handle(struct drm_prime_file_private *prime_fpriv,
165 				       struct dma_buf *dma_buf,
166 				       uint32_t *handle)
167 {
168 	struct rb_node *rb;
169 
170 	rb = prime_fpriv->dmabufs.rb_node;
171 	while (rb) {
172 		struct drm_prime_member *member;
173 
174 		member = rb_entry(rb, struct drm_prime_member, dmabuf_rb);
175 		if (member->dma_buf == dma_buf) {
176 			*handle = member->handle;
177 			return 0;
178 		} else if (member->dma_buf < dma_buf) {
179 			rb = rb->rb_right;
180 		} else {
181 			rb = rb->rb_left;
182 		}
183 	}
184 
185 	return -ENOENT;
186 }
187 
188 void drm_prime_remove_buf_handle(struct drm_prime_file_private *prime_fpriv,
189 				 uint32_t handle)
190 {
191 	struct rb_node *rb;
192 
193 	rb = prime_fpriv->handles.rb_node;
194 	while (rb) {
195 		struct drm_prime_member *member;
196 
197 		member = rb_entry(rb, struct drm_prime_member, handle_rb);
198 		if (member->handle == handle) {
199 			rb_erase(&member->handle_rb, &prime_fpriv->handles);
200 			rb_erase(&member->dmabuf_rb, &prime_fpriv->dmabufs);
201 
202 			dma_buf_put(member->dma_buf);
203 			kfree(member);
204 			break;
205 		} else if (member->handle < handle) {
206 			rb = rb->rb_right;
207 		} else {
208 			rb = rb->rb_left;
209 		}
210 	}
211 }
212 
213 void drm_prime_init_file_private(struct drm_prime_file_private *prime_fpriv)
214 {
215 	mutex_init(&prime_fpriv->lock);
216 	prime_fpriv->dmabufs = RB_ROOT;
217 	prime_fpriv->handles = RB_ROOT;
218 }
219 
220 void drm_prime_destroy_file_private(struct drm_prime_file_private *prime_fpriv)
221 {
222 	/* by now drm_gem_release should've made sure the list is empty */
223 	WARN_ON(!RB_EMPTY_ROOT(&prime_fpriv->dmabufs));
224 }
225 
226 /**
227  * drm_gem_dmabuf_export - &dma_buf export implementation for GEM
228  * @dev: parent device for the exported dmabuf
229  * @exp_info: the export information used by dma_buf_export()
230  *
231  * This wraps dma_buf_export() for use by generic GEM drivers that are using
232  * drm_gem_dmabuf_release(). In addition to calling dma_buf_export(), we take
233  * a reference to the &drm_device and the exported &drm_gem_object (stored in
234  * &dma_buf_export_info.priv) which is released by drm_gem_dmabuf_release().
235  *
236  * Returns the new dmabuf.
237  */
238 struct dma_buf *drm_gem_dmabuf_export(struct drm_device *dev,
239 				      struct dma_buf_export_info *exp_info)
240 {
241 	struct drm_gem_object *obj = exp_info->priv;
242 	struct dma_buf *dma_buf;
243 
244 	dma_buf = dma_buf_export(exp_info);
245 	if (IS_ERR(dma_buf))
246 		return dma_buf;
247 
248 	drm_dev_get(dev);
249 	drm_gem_object_get(obj);
250 	dma_buf->file->f_mapping = obj->dev->anon_inode->i_mapping;
251 
252 	return dma_buf;
253 }
254 EXPORT_SYMBOL(drm_gem_dmabuf_export);
255 
256 /**
257  * drm_gem_dmabuf_release - &dma_buf release implementation for GEM
258  * @dma_buf: buffer to be released
259  *
260  * Generic release function for dma_bufs exported as PRIME buffers. GEM drivers
261  * must use this in their &dma_buf_ops structure as the release callback.
262  * drm_gem_dmabuf_release() should be used in conjunction with
263  * drm_gem_dmabuf_export().
264  */
265 void drm_gem_dmabuf_release(struct dma_buf *dma_buf)
266 {
267 	struct drm_gem_object *obj = dma_buf->priv;
268 	struct drm_device *dev = obj->dev;
269 
270 	/* drop the reference on the export fd holds */
271 	drm_gem_object_put(obj);
272 
273 	drm_dev_put(dev);
274 }
275 EXPORT_SYMBOL(drm_gem_dmabuf_release);
276 
277 /**
278  * drm_gem_prime_fd_to_handle - PRIME import function for GEM drivers
279  * @dev: drm_device to import into
280  * @file_priv: drm file-private structure
281  * @prime_fd: fd id of the dma-buf which should be imported
282  * @handle: pointer to storage for the handle of the imported buffer object
283  *
284  * This is the PRIME import function which must be used mandatorily by GEM
285  * drivers to ensure correct lifetime management of the underlying GEM object.
286  * The actual importing of GEM object from the dma-buf is done through the
287  * &drm_driver.gem_prime_import driver callback.
288  *
289  * Returns 0 on success or a negative error code on failure.
290  */
291 int drm_gem_prime_fd_to_handle(struct drm_device *dev,
292 			       struct drm_file *file_priv, int prime_fd,
293 			       uint32_t *handle)
294 {
295 	struct dma_buf *dma_buf;
296 	struct drm_gem_object *obj;
297 	int ret;
298 
299 	dma_buf = dma_buf_get(prime_fd);
300 	if (IS_ERR(dma_buf))
301 		return PTR_ERR(dma_buf);
302 
303 	mutex_lock(&file_priv->prime.lock);
304 
305 	ret = drm_prime_lookup_buf_handle(&file_priv->prime,
306 			dma_buf, handle);
307 	if (ret == 0)
308 		goto out_put;
309 
310 	/* never seen this one, need to import */
311 	mutex_lock(&dev->object_name_lock);
312 	if (dev->driver->gem_prime_import)
313 		obj = dev->driver->gem_prime_import(dev, dma_buf);
314 	else
315 		obj = drm_gem_prime_import(dev, dma_buf);
316 	if (IS_ERR(obj)) {
317 		ret = PTR_ERR(obj);
318 		goto out_unlock;
319 	}
320 
321 	if (obj->dma_buf) {
322 		WARN_ON(obj->dma_buf != dma_buf);
323 	} else {
324 		obj->dma_buf = dma_buf;
325 		get_dma_buf(dma_buf);
326 	}
327 
328 	/* _handle_create_tail unconditionally unlocks dev->object_name_lock. */
329 	ret = drm_gem_handle_create_tail(file_priv, obj, handle);
330 	drm_gem_object_put(obj);
331 	if (ret)
332 		goto out_put;
333 
334 	ret = drm_prime_add_buf_handle(&file_priv->prime,
335 			dma_buf, *handle);
336 	mutex_unlock(&file_priv->prime.lock);
337 	if (ret)
338 		goto fail;
339 
340 	dma_buf_put(dma_buf);
341 
342 	return 0;
343 
344 fail:
345 	/* hmm, if driver attached, we are relying on the free-object path
346 	 * to detach.. which seems ok..
347 	 */
348 	drm_gem_handle_delete(file_priv, *handle);
349 	dma_buf_put(dma_buf);
350 	return ret;
351 
352 out_unlock:
353 	mutex_unlock(&dev->object_name_lock);
354 out_put:
355 	mutex_unlock(&file_priv->prime.lock);
356 	dma_buf_put(dma_buf);
357 	return ret;
358 }
359 EXPORT_SYMBOL(drm_gem_prime_fd_to_handle);
360 
361 int drm_prime_fd_to_handle_ioctl(struct drm_device *dev, void *data,
362 				 struct drm_file *file_priv)
363 {
364 	struct drm_prime_handle *args = data;
365 
366 	if (dev->driver->prime_fd_to_handle) {
367 		return dev->driver->prime_fd_to_handle(dev, file_priv, args->fd,
368 						       &args->handle);
369 	}
370 
371 	return drm_gem_prime_fd_to_handle(dev, file_priv, args->fd, &args->handle);
372 }
373 
374 static struct dma_buf *export_and_register_object(struct drm_device *dev,
375 						  struct drm_gem_object *obj,
376 						  uint32_t flags)
377 {
378 	struct dma_buf *dmabuf;
379 
380 	/* prevent races with concurrent gem_close. */
381 	if (obj->handle_count == 0) {
382 		dmabuf = ERR_PTR(-ENOENT);
383 		return dmabuf;
384 	}
385 
386 	if (obj->funcs && obj->funcs->export)
387 		dmabuf = obj->funcs->export(obj, flags);
388 	else
389 		dmabuf = drm_gem_prime_export(obj, flags);
390 	if (IS_ERR(dmabuf)) {
391 		/* normally the created dma-buf takes ownership of the ref,
392 		 * but if that fails then drop the ref
393 		 */
394 		return dmabuf;
395 	}
396 
397 	/*
398 	 * Note that callers do not need to clean up the export cache
399 	 * since the check for obj->handle_count guarantees that someone
400 	 * will clean it up.
401 	 */
402 	obj->dma_buf = dmabuf;
403 	get_dma_buf(obj->dma_buf);
404 
405 	return dmabuf;
406 }
407 
408 /**
409  * drm_gem_prime_handle_to_dmabuf - PRIME export function for GEM drivers
410  * @dev: dev to export the buffer from
411  * @file_priv: drm file-private structure
412  * @handle: buffer handle to export
413  * @flags: flags like DRM_CLOEXEC
414  *
415  * This is the PRIME export function which must be used mandatorily by GEM
416  * drivers to ensure correct lifetime management of the underlying GEM object.
417  * The actual exporting from GEM object to a dma-buf is done through the
418  * &drm_gem_object_funcs.export callback.
419  *
420  * Unlike drm_gem_prime_handle_to_fd(), it returns the struct dma_buf it
421  * has created, without attaching it to any file descriptors.  The difference
422  * between those two is similar to that between anon_inode_getfile() and
423  * anon_inode_getfd(); insertion into descriptor table is something you
424  * can not revert if any cleanup is needed, so the descriptor-returning
425  * variants should only be used when you are past the last failure exit
426  * and the only thing left is passing the new file descriptor to userland.
427  * When all you need is the object itself or when you need to do something
428  * else that might fail, use that one instead.
429  */
430 struct dma_buf *drm_gem_prime_handle_to_dmabuf(struct drm_device *dev,
431 			       struct drm_file *file_priv, uint32_t handle,
432 			       uint32_t flags)
433 {
434 	struct drm_gem_object *obj;
435 	int ret = 0;
436 	struct dma_buf *dmabuf;
437 
438 	mutex_lock(&file_priv->prime.lock);
439 	obj = drm_gem_object_lookup(file_priv, handle);
440 	if (!obj)  {
441 		dmabuf = ERR_PTR(-ENOENT);
442 		goto out_unlock;
443 	}
444 
445 	dmabuf = drm_prime_lookup_buf_by_handle(&file_priv->prime, handle);
446 	if (dmabuf) {
447 		get_dma_buf(dmabuf);
448 		goto out;
449 	}
450 
451 	mutex_lock(&dev->object_name_lock);
452 	/* re-export the original imported/exported object */
453 	if (obj->dma_buf) {
454 		get_dma_buf(obj->dma_buf);
455 		dmabuf = obj->dma_buf;
456 		goto out_have_obj;
457 	}
458 
459 	dmabuf = export_and_register_object(dev, obj, flags);
460 	if (IS_ERR(dmabuf)) {
461 		/* normally the created dma-buf takes ownership of the ref,
462 		 * but if that fails then drop the ref
463 		 */
464 		mutex_unlock(&dev->object_name_lock);
465 		goto out;
466 	}
467 
468 out_have_obj:
469 	/*
470 	 * If we've exported this buffer then cheat and add it to the import list
471 	 * so we get the correct handle back. We must do this under the
472 	 * protection of dev->object_name_lock to ensure that a racing gem close
473 	 * ioctl doesn't miss to remove this buffer handle from the cache.
474 	 */
475 	ret = drm_prime_add_buf_handle(&file_priv->prime,
476 				       dmabuf, handle);
477 	mutex_unlock(&dev->object_name_lock);
478 	if (ret) {
479 		dma_buf_put(dmabuf);
480 		dmabuf = ERR_PTR(ret);
481 	}
482 out:
483 	drm_gem_object_put(obj);
484 out_unlock:
485 	mutex_unlock(&file_priv->prime.lock);
486 	return dmabuf;
487 }
488 EXPORT_SYMBOL(drm_gem_prime_handle_to_dmabuf);
489 
490 /**
491  * drm_gem_prime_handle_to_fd - PRIME export function for GEM drivers
492  * @dev: dev to export the buffer from
493  * @file_priv: drm file-private structure
494  * @handle: buffer handle to export
495  * @flags: flags like DRM_CLOEXEC
496  * @prime_fd: pointer to storage for the fd id of the create dma-buf
497  *
498  * This is the PRIME export function which must be used mandatorily by GEM
499  * drivers to ensure correct lifetime management of the underlying GEM object.
500  * The actual exporting from GEM object to a dma-buf is done through the
501  * &drm_gem_object_funcs.export callback.
502  */
503 int drm_gem_prime_handle_to_fd(struct drm_device *dev,
504 			       struct drm_file *file_priv, uint32_t handle,
505 			       uint32_t flags,
506 			       int *prime_fd)
507 {
508 	struct dma_buf *dmabuf;
509 	int fd = get_unused_fd_flags(flags);
510 
511 	if (fd < 0)
512 		return fd;
513 
514 	dmabuf = drm_gem_prime_handle_to_dmabuf(dev, file_priv, handle, flags);
515 	if (IS_ERR(dmabuf)) {
516 		put_unused_fd(fd);
517 		return PTR_ERR(dmabuf);
518 	}
519 
520 	fd_install(fd, dmabuf->file);
521 	*prime_fd = fd;
522 	return 0;
523 }
524 EXPORT_SYMBOL(drm_gem_prime_handle_to_fd);
525 
526 int drm_prime_handle_to_fd_ioctl(struct drm_device *dev, void *data,
527 				 struct drm_file *file_priv)
528 {
529 	struct drm_prime_handle *args = data;
530 
531 	/* check flags are valid */
532 	if (args->flags & ~(DRM_CLOEXEC | DRM_RDWR))
533 		return -EINVAL;
534 
535 	if (dev->driver->prime_handle_to_fd) {
536 		return dev->driver->prime_handle_to_fd(dev, file_priv,
537 						       args->handle, args->flags,
538 						       &args->fd);
539 	}
540 	return drm_gem_prime_handle_to_fd(dev, file_priv, args->handle,
541 					  args->flags, &args->fd);
542 }
543 
544 /**
545  * DOC: PRIME Helpers
546  *
547  * Drivers can implement &drm_gem_object_funcs.export and
548  * &drm_driver.gem_prime_import in terms of simpler APIs by using the helper
549  * functions drm_gem_prime_export() and drm_gem_prime_import(). These functions
550  * implement dma-buf support in terms of some lower-level helpers, which are
551  * again exported for drivers to use individually:
552  *
553  * Exporting buffers
554  * ~~~~~~~~~~~~~~~~~
555  *
556  * Optional pinning of buffers is handled at dma-buf attach and detach time in
557  * drm_gem_map_attach() and drm_gem_map_detach(). Backing storage itself is
558  * handled by drm_gem_map_dma_buf() and drm_gem_unmap_dma_buf(), which relies on
559  * &drm_gem_object_funcs.get_sg_table. If &drm_gem_object_funcs.get_sg_table is
560  * unimplemented, exports into another device are rejected.
561  *
562  * For kernel-internal access there's drm_gem_dmabuf_vmap() and
563  * drm_gem_dmabuf_vunmap(). Userspace mmap support is provided by
564  * drm_gem_dmabuf_mmap().
565  *
566  * Note that these export helpers can only be used if the underlying backing
567  * storage is fully coherent and either permanently pinned, or it is safe to pin
568  * it indefinitely.
569  *
570  * FIXME: The underlying helper functions are named rather inconsistently.
571  *
572  * Importing buffers
573  * ~~~~~~~~~~~~~~~~~
574  *
575  * Importing dma-bufs using drm_gem_prime_import() relies on
576  * &drm_driver.gem_prime_import_sg_table.
577  *
578  * Note that similarly to the export helpers this permanently pins the
579  * underlying backing storage. Which is ok for scanout, but is not the best
580  * option for sharing lots of buffers for rendering.
581  */
582 
583 /**
584  * drm_gem_map_attach - dma_buf attach implementation for GEM
585  * @dma_buf: buffer to attach device to
586  * @attach: buffer attachment data
587  *
588  * Calls &drm_gem_object_funcs.pin for device specific handling. This can be
589  * used as the &dma_buf_ops.attach callback. Must be used together with
590  * drm_gem_map_detach().
591  *
592  * Returns 0 on success, negative error code on failure.
593  */
594 int drm_gem_map_attach(struct dma_buf *dma_buf,
595 		       struct dma_buf_attachment *attach)
596 {
597 	struct drm_gem_object *obj = dma_buf->priv;
598 	int ret;
599 
600 	/*
601 	 * drm_gem_map_dma_buf() requires obj->get_sg_table(), but drivers
602 	 * that implement their own ->map_dma_buf() do not.
603 	 */
604 	if (dma_buf->ops->map_dma_buf == drm_gem_map_dma_buf &&
605 	    !obj->funcs->get_sg_table)
606 		return -ENOSYS;
607 
608 	if (!obj->funcs->pin)
609 		return 0;
610 
611 	ret = dma_resv_lock(obj->resv, NULL);
612 	if (ret)
613 		return ret;
614 	ret = obj->funcs->pin(obj);
615 	dma_resv_unlock(obj->resv);
616 
617 	return ret;
618 }
619 EXPORT_SYMBOL(drm_gem_map_attach);
620 
621 /**
622  * drm_gem_map_detach - dma_buf detach implementation for GEM
623  * @dma_buf: buffer to detach from
624  * @attach: attachment to be detached
625  *
626  * Calls &drm_gem_object_funcs.pin for device specific handling.  Cleans up
627  * &dma_buf_attachment from drm_gem_map_attach(). This can be used as the
628  * &dma_buf_ops.detach callback.
629  */
630 void drm_gem_map_detach(struct dma_buf *dma_buf,
631 			struct dma_buf_attachment *attach)
632 {
633 	struct drm_gem_object *obj = dma_buf->priv;
634 	int ret;
635 
636 	if (!obj->funcs->unpin)
637 		return;
638 
639 	ret = dma_resv_lock(obj->resv, NULL);
640 	if (drm_WARN_ON(obj->dev, ret))
641 		return;
642 	obj->funcs->unpin(obj);
643 	dma_resv_unlock(obj->resv);
644 }
645 EXPORT_SYMBOL(drm_gem_map_detach);
646 
647 /**
648  * drm_gem_map_dma_buf - map_dma_buf implementation for GEM
649  * @attach: attachment whose scatterlist is to be returned
650  * @dir: direction of DMA transfer
651  *
652  * Calls &drm_gem_object_funcs.get_sg_table and then maps the scatterlist. This
653  * can be used as the &dma_buf_ops.map_dma_buf callback. Should be used together
654  * with drm_gem_unmap_dma_buf().
655  *
656  * Returns:sg_table containing the scatterlist to be returned; returns ERR_PTR
657  * on error. May return -EINTR if it is interrupted by a signal.
658  */
659 struct sg_table *drm_gem_map_dma_buf(struct dma_buf_attachment *attach,
660 				     enum dma_data_direction dir)
661 {
662 	struct drm_gem_object *obj = attach->dmabuf->priv;
663 	struct sg_table *sgt;
664 	int ret;
665 
666 	if (WARN_ON(dir == DMA_NONE))
667 		return ERR_PTR(-EINVAL);
668 
669 	if (WARN_ON(!obj->funcs->get_sg_table))
670 		return ERR_PTR(-ENOSYS);
671 
672 	sgt = obj->funcs->get_sg_table(obj);
673 	if (IS_ERR(sgt))
674 		return sgt;
675 
676 	ret = dma_map_sgtable(attach->dev, sgt, dir,
677 			      DMA_ATTR_SKIP_CPU_SYNC);
678 	if (ret) {
679 		sg_free_table(sgt);
680 		kfree(sgt);
681 		sgt = ERR_PTR(ret);
682 	}
683 
684 	return sgt;
685 }
686 EXPORT_SYMBOL(drm_gem_map_dma_buf);
687 
688 /**
689  * drm_gem_unmap_dma_buf - unmap_dma_buf implementation for GEM
690  * @attach: attachment to unmap buffer from
691  * @sgt: scatterlist info of the buffer to unmap
692  * @dir: direction of DMA transfer
693  *
694  * This can be used as the &dma_buf_ops.unmap_dma_buf callback.
695  */
696 void drm_gem_unmap_dma_buf(struct dma_buf_attachment *attach,
697 			   struct sg_table *sgt,
698 			   enum dma_data_direction dir)
699 {
700 	if (!sgt)
701 		return;
702 
703 	dma_unmap_sgtable(attach->dev, sgt, dir, DMA_ATTR_SKIP_CPU_SYNC);
704 	sg_free_table(sgt);
705 	kfree(sgt);
706 }
707 EXPORT_SYMBOL(drm_gem_unmap_dma_buf);
708 
709 /**
710  * drm_gem_dmabuf_vmap - dma_buf vmap implementation for GEM
711  * @dma_buf: buffer to be mapped
712  * @map: the virtual address of the buffer
713  *
714  * Sets up a kernel virtual mapping. This can be used as the &dma_buf_ops.vmap
715  * callback. Calls into &drm_gem_object_funcs.vmap for device specific handling.
716  * The kernel virtual address is returned in map.
717  *
718  * Returns 0 on success or a negative errno code otherwise.
719  */
720 int drm_gem_dmabuf_vmap(struct dma_buf *dma_buf, struct iosys_map *map)
721 {
722 	struct drm_gem_object *obj = dma_buf->priv;
723 
724 	return drm_gem_vmap_locked(obj, map);
725 }
726 EXPORT_SYMBOL(drm_gem_dmabuf_vmap);
727 
728 /**
729  * drm_gem_dmabuf_vunmap - dma_buf vunmap implementation for GEM
730  * @dma_buf: buffer to be unmapped
731  * @map: the virtual address of the buffer
732  *
733  * Releases a kernel virtual mapping. This can be used as the
734  * &dma_buf_ops.vunmap callback. Calls into &drm_gem_object_funcs.vunmap for device specific handling.
735  */
736 void drm_gem_dmabuf_vunmap(struct dma_buf *dma_buf, struct iosys_map *map)
737 {
738 	struct drm_gem_object *obj = dma_buf->priv;
739 
740 	drm_gem_vunmap_locked(obj, map);
741 }
742 EXPORT_SYMBOL(drm_gem_dmabuf_vunmap);
743 
744 /**
745  * drm_gem_prime_mmap - PRIME mmap function for GEM drivers
746  * @obj: GEM object
747  * @vma: Virtual address range
748  *
749  * This function sets up a userspace mapping for PRIME exported buffers using
750  * the same codepath that is used for regular GEM buffer mapping on the DRM fd.
751  * The fake GEM offset is added to vma->vm_pgoff and &drm_driver->fops->mmap is
752  * called to set up the mapping.
753  */
754 int drm_gem_prime_mmap(struct drm_gem_object *obj, struct vm_area_struct *vma)
755 {
756 	struct drm_file *priv;
757 	struct file *fil;
758 	int ret;
759 
760 	/* Add the fake offset */
761 	vma->vm_pgoff += drm_vma_node_start(&obj->vma_node);
762 
763 	if (obj->funcs && obj->funcs->mmap) {
764 		vma->vm_ops = obj->funcs->vm_ops;
765 
766 		drm_gem_object_get(obj);
767 		ret = obj->funcs->mmap(obj, vma);
768 		if (ret) {
769 			drm_gem_object_put(obj);
770 			return ret;
771 		}
772 		vma->vm_private_data = obj;
773 		return 0;
774 	}
775 
776 	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
777 	fil = kzalloc(sizeof(*fil), GFP_KERNEL);
778 	if (!priv || !fil) {
779 		ret = -ENOMEM;
780 		goto out;
781 	}
782 
783 	/* Used by drm_gem_mmap() to lookup the GEM object */
784 	priv->minor = obj->dev->primary;
785 	fil->private_data = priv;
786 
787 	ret = drm_vma_node_allow(&obj->vma_node, priv);
788 	if (ret)
789 		goto out;
790 
791 	ret = obj->dev->driver->fops->mmap(fil, vma);
792 
793 	drm_vma_node_revoke(&obj->vma_node, priv);
794 out:
795 	kfree(priv);
796 	kfree(fil);
797 
798 	return ret;
799 }
800 EXPORT_SYMBOL(drm_gem_prime_mmap);
801 
802 /**
803  * drm_gem_dmabuf_mmap - dma_buf mmap implementation for GEM
804  * @dma_buf: buffer to be mapped
805  * @vma: virtual address range
806  *
807  * Provides memory mapping for the buffer. This can be used as the
808  * &dma_buf_ops.mmap callback. It just forwards to drm_gem_prime_mmap().
809  *
810  * Returns 0 on success or a negative error code on failure.
811  */
812 int drm_gem_dmabuf_mmap(struct dma_buf *dma_buf, struct vm_area_struct *vma)
813 {
814 	struct drm_gem_object *obj = dma_buf->priv;
815 
816 	return drm_gem_prime_mmap(obj, vma);
817 }
818 EXPORT_SYMBOL(drm_gem_dmabuf_mmap);
819 
820 static const struct dma_buf_ops drm_gem_prime_dmabuf_ops =  {
821 	.attach = drm_gem_map_attach,
822 	.detach = drm_gem_map_detach,
823 	.map_dma_buf = drm_gem_map_dma_buf,
824 	.unmap_dma_buf = drm_gem_unmap_dma_buf,
825 	.release = drm_gem_dmabuf_release,
826 	.mmap = drm_gem_dmabuf_mmap,
827 	.vmap = drm_gem_dmabuf_vmap,
828 	.vunmap = drm_gem_dmabuf_vunmap,
829 };
830 
831 /**
832  * drm_prime_pages_to_sg - converts a page array into an sg list
833  * @dev: DRM device
834  * @pages: pointer to the array of page pointers to convert
835  * @nr_pages: length of the page vector
836  *
837  * This helper creates an sg table object from a set of pages
838  * the driver is responsible for mapping the pages into the
839  * importers address space for use with dma_buf itself.
840  *
841  * This is useful for implementing &drm_gem_object_funcs.get_sg_table.
842  */
843 struct sg_table *drm_prime_pages_to_sg(struct drm_device *dev,
844 				       struct page **pages, unsigned int nr_pages)
845 {
846 	struct sg_table *sg;
847 	size_t max_segment = 0;
848 	int err;
849 
850 	sg = kmalloc(sizeof(struct sg_table), GFP_KERNEL);
851 	if (!sg)
852 		return ERR_PTR(-ENOMEM);
853 
854 	if (dev)
855 		max_segment = dma_max_mapping_size(dev->dev);
856 	if (max_segment == 0)
857 		max_segment = UINT_MAX;
858 	err = sg_alloc_table_from_pages_segment(sg, pages, nr_pages, 0,
859 						(unsigned long)nr_pages << PAGE_SHIFT,
860 						max_segment, GFP_KERNEL);
861 	if (err) {
862 		kfree(sg);
863 		sg = ERR_PTR(err);
864 	}
865 	return sg;
866 }
867 EXPORT_SYMBOL(drm_prime_pages_to_sg);
868 
869 /**
870  * drm_prime_get_contiguous_size - returns the contiguous size of the buffer
871  * @sgt: sg_table describing the buffer to check
872  *
873  * This helper calculates the contiguous size in the DMA address space
874  * of the buffer described by the provided sg_table.
875  *
876  * This is useful for implementing
877  * &drm_gem_object_funcs.gem_prime_import_sg_table.
878  */
879 unsigned long drm_prime_get_contiguous_size(struct sg_table *sgt)
880 {
881 	dma_addr_t expected = sg_dma_address(sgt->sgl);
882 	struct scatterlist *sg;
883 	unsigned long size = 0;
884 	int i;
885 
886 	for_each_sgtable_dma_sg(sgt, sg, i) {
887 		unsigned int len = sg_dma_len(sg);
888 
889 		if (!len)
890 			break;
891 		if (sg_dma_address(sg) != expected)
892 			break;
893 		expected += len;
894 		size += len;
895 	}
896 	return size;
897 }
898 EXPORT_SYMBOL(drm_prime_get_contiguous_size);
899 
900 /**
901  * drm_gem_prime_export - helper library implementation of the export callback
902  * @obj: GEM object to export
903  * @flags: flags like DRM_CLOEXEC and DRM_RDWR
904  *
905  * This is the implementation of the &drm_gem_object_funcs.export functions for GEM drivers
906  * using the PRIME helpers. It is used as the default in
907  * drm_gem_prime_handle_to_fd().
908  */
909 struct dma_buf *drm_gem_prime_export(struct drm_gem_object *obj,
910 				     int flags)
911 {
912 	struct drm_device *dev = obj->dev;
913 	struct dma_buf_export_info exp_info = {
914 		.exp_name = KBUILD_MODNAME, /* white lie for debug */
915 		.owner = dev->driver->fops->owner,
916 		.ops = &drm_gem_prime_dmabuf_ops,
917 		.size = obj->size,
918 		.flags = flags,
919 		.priv = obj,
920 		.resv = obj->resv,
921 	};
922 
923 	return drm_gem_dmabuf_export(dev, &exp_info);
924 }
925 EXPORT_SYMBOL(drm_gem_prime_export);
926 
927 
928 /**
929  * drm_gem_is_prime_exported_dma_buf -
930  * checks if the DMA-BUF was exported from a GEM object belonging to @dev.
931  * @dev: drm_device to check against
932  * @dma_buf: dma-buf object to import
933  *
934  * Return: true if the DMA-BUF was exported from a GEM object belonging
935  * to @dev, false otherwise.
936  */
937 
938 bool drm_gem_is_prime_exported_dma_buf(struct drm_device *dev,
939 				       struct dma_buf *dma_buf)
940 {
941 	struct drm_gem_object *obj = dma_buf->priv;
942 
943 	return (dma_buf->ops == &drm_gem_prime_dmabuf_ops) && (obj->dev == dev);
944 }
945 EXPORT_SYMBOL(drm_gem_is_prime_exported_dma_buf);
946 
947 /**
948  * drm_gem_prime_import_dev - core implementation of the import callback
949  * @dev: drm_device to import into
950  * @dma_buf: dma-buf object to import
951  * @attach_dev: struct device to dma_buf attach
952  *
953  * This is the core of drm_gem_prime_import(). It's designed to be called by
954  * drivers who want to use a different device structure than &drm_device.dev for
955  * attaching via dma_buf. This function calls
956  * &drm_driver.gem_prime_import_sg_table internally.
957  *
958  * Drivers must arrange to call drm_prime_gem_destroy() from their
959  * &drm_gem_object_funcs.free hook when using this function.
960  */
961 struct drm_gem_object *drm_gem_prime_import_dev(struct drm_device *dev,
962 					    struct dma_buf *dma_buf,
963 					    struct device *attach_dev)
964 {
965 	struct dma_buf_attachment *attach;
966 	struct sg_table *sgt;
967 	struct drm_gem_object *obj;
968 	int ret;
969 
970 	if (drm_gem_is_prime_exported_dma_buf(dev, dma_buf)) {
971 		/*
972 		 * Importing dmabuf exported from our own gem increases
973 		 * refcount on gem itself instead of f_count of dmabuf.
974 		 */
975 		obj = dma_buf->priv;
976 		drm_gem_object_get(obj);
977 		return obj;
978 	}
979 
980 	if (!dev->driver->gem_prime_import_sg_table)
981 		return ERR_PTR(-EINVAL);
982 
983 	attach = dma_buf_attach(dma_buf, attach_dev);
984 	if (IS_ERR(attach))
985 		return ERR_CAST(attach);
986 
987 	get_dma_buf(dma_buf);
988 
989 	sgt = dma_buf_map_attachment_unlocked(attach, DMA_BIDIRECTIONAL);
990 	if (IS_ERR(sgt)) {
991 		ret = PTR_ERR(sgt);
992 		goto fail_detach;
993 	}
994 
995 	obj = dev->driver->gem_prime_import_sg_table(dev, attach, sgt);
996 	if (IS_ERR(obj)) {
997 		ret = PTR_ERR(obj);
998 		goto fail_unmap;
999 	}
1000 
1001 	obj->import_attach = attach;
1002 	obj->resv = dma_buf->resv;
1003 
1004 	return obj;
1005 
1006 fail_unmap:
1007 	dma_buf_unmap_attachment_unlocked(attach, sgt, DMA_BIDIRECTIONAL);
1008 fail_detach:
1009 	dma_buf_detach(dma_buf, attach);
1010 	dma_buf_put(dma_buf);
1011 
1012 	return ERR_PTR(ret);
1013 }
1014 EXPORT_SYMBOL(drm_gem_prime_import_dev);
1015 
1016 /**
1017  * drm_gem_prime_import - helper library implementation of the import callback
1018  * @dev: drm_device to import into
1019  * @dma_buf: dma-buf object to import
1020  *
1021  * This is the implementation of the gem_prime_import functions for GEM drivers
1022  * using the PRIME helpers. Drivers can use this as their
1023  * &drm_driver.gem_prime_import implementation. It is used as the default
1024  * implementation in drm_gem_prime_fd_to_handle().
1025  *
1026  * Drivers must arrange to call drm_prime_gem_destroy() from their
1027  * &drm_gem_object_funcs.free hook when using this function.
1028  */
1029 struct drm_gem_object *drm_gem_prime_import(struct drm_device *dev,
1030 					    struct dma_buf *dma_buf)
1031 {
1032 	return drm_gem_prime_import_dev(dev, dma_buf, drm_dev_dma_dev(dev));
1033 }
1034 EXPORT_SYMBOL(drm_gem_prime_import);
1035 
1036 /**
1037  * drm_prime_sg_to_page_array - convert an sg table into a page array
1038  * @sgt: scatter-gather table to convert
1039  * @pages: array of page pointers to store the pages in
1040  * @max_entries: size of the passed-in array
1041  *
1042  * Exports an sg table into an array of pages.
1043  *
1044  * This function is deprecated and strongly discouraged to be used.
1045  * The page array is only useful for page faults and those can corrupt fields
1046  * in the struct page if they are not handled by the exporting driver.
1047  */
1048 int __deprecated drm_prime_sg_to_page_array(struct sg_table *sgt,
1049 					    struct page **pages,
1050 					    int max_entries)
1051 {
1052 	struct sg_page_iter page_iter;
1053 	struct page **p = pages;
1054 
1055 	for_each_sgtable_page(sgt, &page_iter, 0) {
1056 		if (WARN_ON(p - pages >= max_entries))
1057 			return -1;
1058 		*p++ = sg_page_iter_page(&page_iter);
1059 	}
1060 	return 0;
1061 }
1062 EXPORT_SYMBOL(drm_prime_sg_to_page_array);
1063 
1064 /**
1065  * drm_prime_sg_to_dma_addr_array - convert an sg table into a dma addr array
1066  * @sgt: scatter-gather table to convert
1067  * @addrs: array to store the dma bus address of each page
1068  * @max_entries: size of both the passed-in arrays
1069  *
1070  * Exports an sg table into an array of addresses.
1071  *
1072  * Drivers should use this in their &drm_driver.gem_prime_import_sg_table
1073  * implementation.
1074  */
1075 int drm_prime_sg_to_dma_addr_array(struct sg_table *sgt, dma_addr_t *addrs,
1076 				   int max_entries)
1077 {
1078 	struct sg_dma_page_iter dma_iter;
1079 	dma_addr_t *a = addrs;
1080 
1081 	for_each_sgtable_dma_page(sgt, &dma_iter, 0) {
1082 		if (WARN_ON(a - addrs >= max_entries))
1083 			return -1;
1084 		*a++ = sg_page_iter_dma_address(&dma_iter);
1085 	}
1086 	return 0;
1087 }
1088 EXPORT_SYMBOL(drm_prime_sg_to_dma_addr_array);
1089 
1090 /**
1091  * drm_prime_gem_destroy - helper to clean up a PRIME-imported GEM object
1092  * @obj: GEM object which was created from a dma-buf
1093  * @sg: the sg-table which was pinned at import time
1094  *
1095  * This is the cleanup functions which GEM drivers need to call when they use
1096  * drm_gem_prime_import() or drm_gem_prime_import_dev() to import dma-bufs.
1097  */
1098 void drm_prime_gem_destroy(struct drm_gem_object *obj, struct sg_table *sg)
1099 {
1100 	struct dma_buf_attachment *attach;
1101 	struct dma_buf *dma_buf;
1102 
1103 	attach = obj->import_attach;
1104 	if (sg)
1105 		dma_buf_unmap_attachment_unlocked(attach, sg, DMA_BIDIRECTIONAL);
1106 	dma_buf = attach->dmabuf;
1107 	dma_buf_detach(attach->dmabuf, attach);
1108 	/* remove the reference */
1109 	dma_buf_put(dma_buf);
1110 }
1111 EXPORT_SYMBOL(drm_prime_gem_destroy);
1112