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 
drm_prime_add_buf_handle(struct drm_prime_file_private * prime_fpriv,struct dma_buf * dma_buf,uint32_t handle)96 static 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 
drm_prime_lookup_buf_by_handle(struct drm_prime_file_private * prime_fpriv,uint32_t handle)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 
drm_prime_lookup_buf_handle(struct drm_prime_file_private * prime_fpriv,struct dma_buf * dma_buf,uint32_t * handle)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 
drm_prime_remove_buf_handle(struct drm_prime_file_private * prime_fpriv,uint32_t handle)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 	mutex_lock(&prime_fpriv->lock);
194 
195 	rb = prime_fpriv->handles.rb_node;
196 	while (rb) {
197 		struct drm_prime_member *member;
198 
199 		member = rb_entry(rb, struct drm_prime_member, handle_rb);
200 		if (member->handle == handle) {
201 			rb_erase(&member->handle_rb, &prime_fpriv->handles);
202 			rb_erase(&member->dmabuf_rb, &prime_fpriv->dmabufs);
203 
204 			dma_buf_put(member->dma_buf);
205 			kfree(member);
206 			break;
207 		} else if (member->handle < handle) {
208 			rb = rb->rb_right;
209 		} else {
210 			rb = rb->rb_left;
211 		}
212 	}
213 
214 	mutex_unlock(&prime_fpriv->lock);
215 }
216 
drm_prime_init_file_private(struct drm_prime_file_private * prime_fpriv)217 void drm_prime_init_file_private(struct drm_prime_file_private *prime_fpriv)
218 {
219 	rw_init(&prime_fpriv->lock, "primlk");
220 	prime_fpriv->dmabufs = RB_ROOT;
221 	prime_fpriv->handles = RB_ROOT;
222 }
223 
drm_prime_destroy_file_private(struct drm_prime_file_private * prime_fpriv)224 void drm_prime_destroy_file_private(struct drm_prime_file_private *prime_fpriv)
225 {
226 	/* by now drm_gem_release should've made sure the list is empty */
227 	WARN_ON(!RB_EMPTY_ROOT(&prime_fpriv->dmabufs));
228 }
229 
230 /**
231  * drm_gem_dmabuf_export - &dma_buf export implementation for GEM
232  * @dev: parent device for the exported dmabuf
233  * @exp_info: the export information used by dma_buf_export()
234  *
235  * This wraps dma_buf_export() for use by generic GEM drivers that are using
236  * drm_gem_dmabuf_release(). In addition to calling dma_buf_export(), we take
237  * a reference to the &drm_device and the exported &drm_gem_object (stored in
238  * &dma_buf_export_info.priv) which is released by drm_gem_dmabuf_release().
239  *
240  * Returns the new dmabuf.
241  */
drm_gem_dmabuf_export(struct drm_device * dev,struct dma_buf_export_info * exp_info)242 struct dma_buf *drm_gem_dmabuf_export(struct drm_device *dev,
243 				      struct dma_buf_export_info *exp_info)
244 {
245 	struct drm_gem_object *obj = exp_info->priv;
246 	struct dma_buf *dma_buf;
247 
248 	dma_buf = dma_buf_export(exp_info);
249 	if (IS_ERR(dma_buf))
250 		return dma_buf;
251 
252 	drm_dev_get(dev);
253 	drm_gem_object_get(obj);
254 #ifdef __linux__
255 	dma_buf->file->f_mapping = obj->dev->anon_inode->i_mapping;
256 #endif
257 
258 	return dma_buf;
259 }
260 EXPORT_SYMBOL(drm_gem_dmabuf_export);
261 
262 /**
263  * drm_gem_dmabuf_release - &dma_buf release implementation for GEM
264  * @dma_buf: buffer to be released
265  *
266  * Generic release function for dma_bufs exported as PRIME buffers. GEM drivers
267  * must use this in their &dma_buf_ops structure as the release callback.
268  * drm_gem_dmabuf_release() should be used in conjunction with
269  * drm_gem_dmabuf_export().
270  */
drm_gem_dmabuf_release(struct dma_buf * dma_buf)271 void drm_gem_dmabuf_release(struct dma_buf *dma_buf)
272 {
273 	struct drm_gem_object *obj = dma_buf->priv;
274 	struct drm_device *dev = obj->dev;
275 
276 	/* drop the reference on the export fd holds */
277 	drm_gem_object_put(obj);
278 
279 	drm_dev_put(dev);
280 }
281 EXPORT_SYMBOL(drm_gem_dmabuf_release);
282 
283 /**
284  * drm_gem_prime_fd_to_handle - PRIME import function for GEM drivers
285  * @dev: drm_device to import into
286  * @file_priv: drm file-private structure
287  * @prime_fd: fd id of the dma-buf which should be imported
288  * @handle: pointer to storage for the handle of the imported buffer object
289  *
290  * This is the PRIME import function which must be used mandatorily by GEM
291  * drivers to ensure correct lifetime management of the underlying GEM object.
292  * The actual importing of GEM object from the dma-buf is done through the
293  * &drm_driver.gem_prime_import driver callback.
294  *
295  * Returns 0 on success or a negative error code on failure.
296  */
drm_gem_prime_fd_to_handle(struct drm_device * dev,struct drm_file * file_priv,int prime_fd,uint32_t * handle)297 int drm_gem_prime_fd_to_handle(struct drm_device *dev,
298 			       struct drm_file *file_priv, int prime_fd,
299 			       uint32_t *handle)
300 {
301 	struct dma_buf *dma_buf;
302 	struct drm_gem_object *obj;
303 	int ret;
304 
305 	dma_buf = dma_buf_get(prime_fd);
306 	if (IS_ERR(dma_buf))
307 		return PTR_ERR(dma_buf);
308 
309 	mutex_lock(&file_priv->prime.lock);
310 
311 	ret = drm_prime_lookup_buf_handle(&file_priv->prime,
312 			dma_buf, handle);
313 	if (ret == 0)
314 		goto out_put;
315 
316 	/* never seen this one, need to import */
317 	mutex_lock(&dev->object_name_lock);
318 	if (dev->driver->gem_prime_import)
319 		obj = dev->driver->gem_prime_import(dev, dma_buf);
320 	else
321 		obj = drm_gem_prime_import(dev, dma_buf);
322 	if (IS_ERR(obj)) {
323 		ret = PTR_ERR(obj);
324 		goto out_unlock;
325 	}
326 
327 	if (obj->dma_buf) {
328 		WARN_ON(obj->dma_buf != dma_buf);
329 	} else {
330 		obj->dma_buf = dma_buf;
331 		get_dma_buf(dma_buf);
332 	}
333 
334 	/* _handle_create_tail unconditionally unlocks dev->object_name_lock. */
335 	ret = drm_gem_handle_create_tail(file_priv, obj, handle);
336 	drm_gem_object_put(obj);
337 	if (ret)
338 		goto out_put;
339 
340 	ret = drm_prime_add_buf_handle(&file_priv->prime,
341 			dma_buf, *handle);
342 	mutex_unlock(&file_priv->prime.lock);
343 	if (ret)
344 		goto fail;
345 
346 	dma_buf_put(dma_buf);
347 
348 	return 0;
349 
350 fail:
351 	/* hmm, if driver attached, we are relying on the free-object path
352 	 * to detach.. which seems ok..
353 	 */
354 	drm_gem_handle_delete(file_priv, *handle);
355 	dma_buf_put(dma_buf);
356 	return ret;
357 
358 out_unlock:
359 	mutex_unlock(&dev->object_name_lock);
360 out_put:
361 	mutex_unlock(&file_priv->prime.lock);
362 	dma_buf_put(dma_buf);
363 	return ret;
364 }
365 EXPORT_SYMBOL(drm_gem_prime_fd_to_handle);
366 
drm_prime_fd_to_handle_ioctl(struct drm_device * dev,void * data,struct drm_file * file_priv)367 int drm_prime_fd_to_handle_ioctl(struct drm_device *dev, void *data,
368 				 struct drm_file *file_priv)
369 {
370 	struct drm_prime_handle *args = data;
371 
372 	if (dev->driver->prime_fd_to_handle) {
373 		return dev->driver->prime_fd_to_handle(dev, file_priv, args->fd,
374 						       &args->handle);
375 	}
376 
377 	return drm_gem_prime_fd_to_handle(dev, file_priv, args->fd, &args->handle);
378 }
379 
export_and_register_object(struct drm_device * dev,struct drm_gem_object * obj,uint32_t flags)380 static struct dma_buf *export_and_register_object(struct drm_device *dev,
381 						  struct drm_gem_object *obj,
382 						  uint32_t flags)
383 {
384 	struct dma_buf *dmabuf;
385 
386 	/* prevent races with concurrent gem_close. */
387 	if (obj->handle_count == 0) {
388 		dmabuf = ERR_PTR(-ENOENT);
389 		return dmabuf;
390 	}
391 
392 	if (obj->funcs && obj->funcs->export)
393 		dmabuf = obj->funcs->export(obj, flags);
394 	else
395 		dmabuf = drm_gem_prime_export(obj, flags);
396 	if (IS_ERR(dmabuf)) {
397 		/* normally the created dma-buf takes ownership of the ref,
398 		 * but if that fails then drop the ref
399 		 */
400 		return dmabuf;
401 	}
402 
403 	/*
404 	 * Note that callers do not need to clean up the export cache
405 	 * since the check for obj->handle_count guarantees that someone
406 	 * will clean it up.
407 	 */
408 	obj->dma_buf = dmabuf;
409 	get_dma_buf(obj->dma_buf);
410 
411 	return dmabuf;
412 }
413 
414 /**
415  * drm_gem_prime_handle_to_dmabuf - PRIME export function for GEM drivers
416  * @dev: dev to export the buffer from
417  * @file_priv: drm file-private structure
418  * @handle: buffer handle to export
419  * @flags: flags like DRM_CLOEXEC
420  *
421  * This is the PRIME export function which must be used mandatorily by GEM
422  * drivers to ensure correct lifetime management of the underlying GEM object.
423  * The actual exporting from GEM object to a dma-buf is done through the
424  * &drm_gem_object_funcs.export callback.
425  *
426  * Unlike drm_gem_prime_handle_to_fd(), it returns the struct dma_buf it
427  * has created, without attaching it to any file descriptors.  The difference
428  * between those two is similar to that between anon_inode_getfile() and
429  * anon_inode_getfd(); insertion into descriptor table is something you
430  * can not revert if any cleanup is needed, so the descriptor-returning
431  * variants should only be used when you are past the last failure exit
432  * and the only thing left is passing the new file descriptor to userland.
433  * When all you need is the object itself or when you need to do something
434  * else that might fail, use that one instead.
435  */
drm_gem_prime_handle_to_dmabuf(struct drm_device * dev,struct drm_file * file_priv,uint32_t handle,uint32_t flags)436 struct dma_buf *drm_gem_prime_handle_to_dmabuf(struct drm_device *dev,
437 			       struct drm_file *file_priv, uint32_t handle,
438 			       uint32_t flags)
439 {
440 	struct drm_gem_object *obj;
441 	int ret = 0;
442 	struct dma_buf *dmabuf;
443 
444 	mutex_lock(&file_priv->prime.lock);
445 	obj = drm_gem_object_lookup(file_priv, handle);
446 	if (!obj)  {
447 		dmabuf = ERR_PTR(-ENOENT);
448 		goto out_unlock;
449 	}
450 
451 	dmabuf = drm_prime_lookup_buf_by_handle(&file_priv->prime, handle);
452 	if (dmabuf) {
453 		get_dma_buf(dmabuf);
454 		goto out;
455 	}
456 
457 	mutex_lock(&dev->object_name_lock);
458 #ifdef notyet
459 	/* re-export the original imported object */
460 	if (obj->import_attach) {
461 		dmabuf = obj->import_attach->dmabuf;
462 		get_dma_buf(dmabuf);
463 		goto out_have_obj;
464 	}
465 #endif
466 
467 	if (obj->dma_buf) {
468 		get_dma_buf(obj->dma_buf);
469 		dmabuf = obj->dma_buf;
470 		goto out_have_obj;
471 	}
472 
473 	dmabuf = export_and_register_object(dev, obj, flags);
474 	if (IS_ERR(dmabuf)) {
475 		/* normally the created dma-buf takes ownership of the ref,
476 		 * but if that fails then drop the ref
477 		 */
478 		mutex_unlock(&dev->object_name_lock);
479 		goto out;
480 	}
481 
482 out_have_obj:
483 	/*
484 	 * If we've exported this buffer then cheat and add it to the import list
485 	 * so we get the correct handle back. We must do this under the
486 	 * protection of dev->object_name_lock to ensure that a racing gem close
487 	 * ioctl doesn't miss to remove this buffer handle from the cache.
488 	 */
489 	ret = drm_prime_add_buf_handle(&file_priv->prime,
490 				       dmabuf, handle);
491 	mutex_unlock(&dev->object_name_lock);
492 	if (ret) {
493 		dma_buf_put(dmabuf);
494 		dmabuf = ERR_PTR(ret);
495 	}
496 out:
497 	drm_gem_object_put(obj);
498 out_unlock:
499 	mutex_unlock(&file_priv->prime.lock);
500 	return dmabuf;
501 }
502 EXPORT_SYMBOL(drm_gem_prime_handle_to_dmabuf);
503 
504 /**
505  * drm_gem_prime_handle_to_fd - PRIME export function for GEM drivers
506  * @dev: dev to export the buffer from
507  * @file_priv: drm file-private structure
508  * @handle: buffer handle to export
509  * @flags: flags like DRM_CLOEXEC
510  * @prime_fd: pointer to storage for the fd id of the create dma-buf
511  *
512  * This is the PRIME export function which must be used mandatorily by GEM
513  * drivers to ensure correct lifetime management of the underlying GEM object.
514  * The actual exporting from GEM object to a dma-buf is done through the
515  * &drm_gem_object_funcs.export callback.
516  */
drm_gem_prime_handle_to_fd(struct drm_device * dev,struct drm_file * file_priv,uint32_t handle,uint32_t flags,int * prime_fd)517 int drm_gem_prime_handle_to_fd(struct drm_device *dev,
518 			       struct drm_file *file_priv, uint32_t handle,
519 			       uint32_t flags,
520 			       int *prime_fd)
521 {
522 	struct dma_buf *dmabuf;
523 	int fd = get_unused_fd_flags(flags);
524 
525 	if (fd < 0)
526 		return fd;
527 
528 	dmabuf = drm_gem_prime_handle_to_dmabuf(dev, file_priv, handle, flags);
529 	if (IS_ERR(dmabuf)) {
530 		put_unused_fd(fd);
531 		return PTR_ERR(dmabuf);
532 	}
533 
534 	fd_install(fd, dmabuf->file);
535 	*prime_fd = fd;
536 	return 0;
537 }
538 EXPORT_SYMBOL(drm_gem_prime_handle_to_fd);
539 
drm_prime_handle_to_fd_ioctl(struct drm_device * dev,void * data,struct drm_file * file_priv)540 int drm_prime_handle_to_fd_ioctl(struct drm_device *dev, void *data,
541 				 struct drm_file *file_priv)
542 {
543 	struct drm_prime_handle *args = data;
544 
545 	/* check flags are valid */
546 	if (args->flags & ~(DRM_CLOEXEC | DRM_RDWR))
547 		return -EINVAL;
548 
549 	if (dev->driver->prime_handle_to_fd) {
550 		return dev->driver->prime_handle_to_fd(dev, file_priv,
551 						       args->handle, args->flags,
552 						       &args->fd);
553 	}
554 	return drm_gem_prime_handle_to_fd(dev, file_priv, args->handle,
555 					  args->flags, &args->fd);
556 }
557 
558 /**
559  * DOC: PRIME Helpers
560  *
561  * Drivers can implement &drm_gem_object_funcs.export and
562  * &drm_driver.gem_prime_import in terms of simpler APIs by using the helper
563  * functions drm_gem_prime_export() and drm_gem_prime_import(). These functions
564  * implement dma-buf support in terms of some lower-level helpers, which are
565  * again exported for drivers to use individually:
566  *
567  * Exporting buffers
568  * ~~~~~~~~~~~~~~~~~
569  *
570  * Optional pinning of buffers is handled at dma-buf attach and detach time in
571  * drm_gem_map_attach() and drm_gem_map_detach(). Backing storage itself is
572  * handled by drm_gem_map_dma_buf() and drm_gem_unmap_dma_buf(), which relies on
573  * &drm_gem_object_funcs.get_sg_table. If &drm_gem_object_funcs.get_sg_table is
574  * unimplemented, exports into another device are rejected.
575  *
576  * For kernel-internal access there's drm_gem_dmabuf_vmap() and
577  * drm_gem_dmabuf_vunmap(). Userspace mmap support is provided by
578  * drm_gem_dmabuf_mmap().
579  *
580  * Note that these export helpers can only be used if the underlying backing
581  * storage is fully coherent and either permanently pinned, or it is safe to pin
582  * it indefinitely.
583  *
584  * FIXME: The underlying helper functions are named rather inconsistently.
585  *
586  * Importing buffers
587  * ~~~~~~~~~~~~~~~~~
588  *
589  * Importing dma-bufs using drm_gem_prime_import() relies on
590  * &drm_driver.gem_prime_import_sg_table.
591  *
592  * Note that similarly to the export helpers this permanently pins the
593  * underlying backing storage. Which is ok for scanout, but is not the best
594  * option for sharing lots of buffers for rendering.
595  */
596 
597 /**
598  * drm_gem_map_attach - dma_buf attach implementation for GEM
599  * @dma_buf: buffer to attach device to
600  * @attach: buffer attachment data
601  *
602  * Calls &drm_gem_object_funcs.pin for device specific handling. This can be
603  * used as the &dma_buf_ops.attach callback. Must be used together with
604  * drm_gem_map_detach().
605  *
606  * Returns 0 on success, negative error code on failure.
607  */
drm_gem_map_attach(struct dma_buf * dma_buf,struct dma_buf_attachment * attach)608 int drm_gem_map_attach(struct dma_buf *dma_buf,
609 		       struct dma_buf_attachment *attach)
610 {
611 	struct drm_gem_object *obj = dma_buf->priv;
612 
613 	/*
614 	 * drm_gem_map_dma_buf() requires obj->get_sg_table(), but drivers
615 	 * that implement their own ->map_dma_buf() do not.
616 	 */
617 #ifdef notyet
618 	if (dma_buf->ops->map_dma_buf == drm_gem_map_dma_buf &&
619 	    !obj->funcs->get_sg_table)
620 #else
621 	if (!obj->funcs->get_sg_table)
622 #endif
623 		return -ENOSYS;
624 
625 	return drm_gem_pin(obj);
626 }
627 EXPORT_SYMBOL(drm_gem_map_attach);
628 
629 /**
630  * drm_gem_map_detach - dma_buf detach implementation for GEM
631  * @dma_buf: buffer to detach from
632  * @attach: attachment to be detached
633  *
634  * Calls &drm_gem_object_funcs.pin for device specific handling.  Cleans up
635  * &dma_buf_attachment from drm_gem_map_attach(). This can be used as the
636  * &dma_buf_ops.detach callback.
637  */
drm_gem_map_detach(struct dma_buf * dma_buf,struct dma_buf_attachment * attach)638 void drm_gem_map_detach(struct dma_buf *dma_buf,
639 			struct dma_buf_attachment *attach)
640 {
641 	struct drm_gem_object *obj = dma_buf->priv;
642 
643 	drm_gem_unpin(obj);
644 }
645 EXPORT_SYMBOL(drm_gem_map_detach);
646 
647 #ifdef notyet
648 
649 /**
650  * drm_gem_map_dma_buf - map_dma_buf implementation for GEM
651  * @attach: attachment whose scatterlist is to be returned
652  * @dir: direction of DMA transfer
653  *
654  * Calls &drm_gem_object_funcs.get_sg_table and then maps the scatterlist. This
655  * can be used as the &dma_buf_ops.map_dma_buf callback. Should be used together
656  * with drm_gem_unmap_dma_buf().
657  *
658  * Returns:sg_table containing the scatterlist to be returned; returns ERR_PTR
659  * on error. May return -EINTR if it is interrupted by a signal.
660  */
drm_gem_map_dma_buf(struct dma_buf_attachment * attach,enum dma_data_direction dir)661 struct sg_table *drm_gem_map_dma_buf(struct dma_buf_attachment *attach,
662 				     enum dma_data_direction dir)
663 {
664 	struct drm_gem_object *obj = attach->dmabuf->priv;
665 	struct sg_table *sgt;
666 	int ret;
667 
668 	if (WARN_ON(dir == DMA_NONE))
669 		return ERR_PTR(-EINVAL);
670 
671 	if (WARN_ON(!obj->funcs->get_sg_table))
672 		return ERR_PTR(-ENOSYS);
673 
674 	sgt = obj->funcs->get_sg_table(obj);
675 	if (IS_ERR(sgt))
676 		return sgt;
677 
678 	ret = dma_map_sgtable(attach->dev, sgt, dir,
679 			      DMA_ATTR_SKIP_CPU_SYNC);
680 	if (ret) {
681 		sg_free_table(sgt);
682 		kfree(sgt);
683 		sgt = ERR_PTR(ret);
684 	}
685 
686 	return sgt;
687 }
688 EXPORT_SYMBOL(drm_gem_map_dma_buf);
689 
690 /**
691  * drm_gem_unmap_dma_buf - unmap_dma_buf implementation for GEM
692  * @attach: attachment to unmap buffer from
693  * @sgt: scatterlist info of the buffer to unmap
694  * @dir: direction of DMA transfer
695  *
696  * This can be used as the &dma_buf_ops.unmap_dma_buf callback.
697  */
drm_gem_unmap_dma_buf(struct dma_buf_attachment * attach,struct sg_table * sgt,enum dma_data_direction dir)698 void drm_gem_unmap_dma_buf(struct dma_buf_attachment *attach,
699 			   struct sg_table *sgt,
700 			   enum dma_data_direction dir)
701 {
702 	if (!sgt)
703 		return;
704 
705 	dma_unmap_sgtable(attach->dev, sgt, dir, DMA_ATTR_SKIP_CPU_SYNC);
706 	sg_free_table(sgt);
707 	kfree(sgt);
708 }
709 EXPORT_SYMBOL(drm_gem_unmap_dma_buf);
710 
711 #endif /* notyet */
712 
713 /**
714  * drm_gem_dmabuf_vmap - dma_buf vmap implementation for GEM
715  * @dma_buf: buffer to be mapped
716  * @map: the virtual address of the buffer
717  *
718  * Sets up a kernel virtual mapping. This can be used as the &dma_buf_ops.vmap
719  * callback. Calls into &drm_gem_object_funcs.vmap for device specific handling.
720  * The kernel virtual address is returned in map.
721  *
722  * Returns 0 on success or a negative errno code otherwise.
723  */
drm_gem_dmabuf_vmap(struct dma_buf * dma_buf,struct iosys_map * map)724 int drm_gem_dmabuf_vmap(struct dma_buf *dma_buf, struct iosys_map *map)
725 {
726 	struct drm_gem_object *obj = dma_buf->priv;
727 
728 	return drm_gem_vmap(obj, map);
729 }
730 EXPORT_SYMBOL(drm_gem_dmabuf_vmap);
731 
732 /**
733  * drm_gem_dmabuf_vunmap - dma_buf vunmap implementation for GEM
734  * @dma_buf: buffer to be unmapped
735  * @map: the virtual address of the buffer
736  *
737  * Releases a kernel virtual mapping. This can be used as the
738  * &dma_buf_ops.vunmap callback. Calls into &drm_gem_object_funcs.vunmap for device specific handling.
739  */
drm_gem_dmabuf_vunmap(struct dma_buf * dma_buf,struct iosys_map * map)740 void drm_gem_dmabuf_vunmap(struct dma_buf *dma_buf, struct iosys_map *map)
741 {
742 	struct drm_gem_object *obj = dma_buf->priv;
743 
744 	drm_gem_vunmap(obj, map);
745 }
746 EXPORT_SYMBOL(drm_gem_dmabuf_vunmap);
747 
748 #ifdef __linux__
749 /**
750  * drm_gem_prime_mmap - PRIME mmap function for GEM drivers
751  * @obj: GEM object
752  * @vma: Virtual address range
753  *
754  * This function sets up a userspace mapping for PRIME exported buffers using
755  * the same codepath that is used for regular GEM buffer mapping on the DRM fd.
756  * The fake GEM offset is added to vma->vm_pgoff and &drm_driver->fops->mmap is
757  * called to set up the mapping.
758  */
drm_gem_prime_mmap(struct drm_gem_object * obj,struct vm_area_struct * vma)759 int drm_gem_prime_mmap(struct drm_gem_object *obj, struct vm_area_struct *vma)
760 {
761 	struct drm_file *priv;
762 	struct file *fil;
763 	int ret;
764 
765 	/* Add the fake offset */
766 	vma->vm_pgoff += drm_vma_node_start(&obj->vma_node);
767 
768 	if (obj->funcs && obj->funcs->mmap) {
769 		vma->vm_ops = obj->funcs->vm_ops;
770 
771 		drm_gem_object_get(obj);
772 		ret = obj->funcs->mmap(obj, vma);
773 		if (ret) {
774 			drm_gem_object_put(obj);
775 			return ret;
776 		}
777 		vma->vm_private_data = obj;
778 		return 0;
779 	}
780 
781 	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
782 	fil = kzalloc(sizeof(*fil), GFP_KERNEL);
783 	if (!priv || !fil) {
784 		ret = -ENOMEM;
785 		goto out;
786 	}
787 
788 	/* Used by drm_gem_mmap() to lookup the GEM object */
789 	priv->minor = obj->dev->primary;
790 	fil->private_data = priv;
791 
792 	ret = drm_vma_node_allow(&obj->vma_node, priv);
793 	if (ret)
794 		goto out;
795 
796 	ret = obj->dev->driver->fops->mmap(fil, vma);
797 
798 	drm_vma_node_revoke(&obj->vma_node, priv);
799 out:
800 	kfree(priv);
801 	kfree(fil);
802 
803 	return ret;
804 }
805 EXPORT_SYMBOL(drm_gem_prime_mmap);
806 #else
807 struct uvm_object *
drm_gem_prime_mmap(struct file * filp,vm_prot_t accessprot,voff_t off,vsize_t size)808 drm_gem_prime_mmap(struct file *filp, vm_prot_t accessprot, voff_t off,
809     vsize_t size)
810 {
811 	STUB();
812 	return NULL;
813 }
814 #endif
815 
816 #ifdef notyet
817 
818 /**
819  * drm_gem_dmabuf_mmap - dma_buf mmap implementation for GEM
820  * @dma_buf: buffer to be mapped
821  * @vma: virtual address range
822  *
823  * Provides memory mapping for the buffer. This can be used as the
824  * &dma_buf_ops.mmap callback. It just forwards to drm_gem_prime_mmap().
825  *
826  * Returns 0 on success or a negative error code on failure.
827  */
drm_gem_dmabuf_mmap(struct dma_buf * dma_buf,struct vm_area_struct * vma)828 int drm_gem_dmabuf_mmap(struct dma_buf *dma_buf, struct vm_area_struct *vma)
829 {
830 	struct drm_gem_object *obj = dma_buf->priv;
831 
832 	return drm_gem_prime_mmap(obj, vma);
833 }
834 EXPORT_SYMBOL(drm_gem_dmabuf_mmap);
835 
836 #endif /* notyet */
837 
838 static const struct dma_buf_ops drm_gem_prime_dmabuf_ops =  {
839 #ifdef notyet
840 	.cache_sgt_mapping = true,
841 	.attach = drm_gem_map_attach,
842 	.detach = drm_gem_map_detach,
843 	.map_dma_buf = drm_gem_map_dma_buf,
844 	.unmap_dma_buf = drm_gem_unmap_dma_buf,
845 #endif
846 	.release = drm_gem_dmabuf_release,
847 #ifdef notyet
848 	.mmap = drm_gem_dmabuf_mmap,
849 	.vmap = drm_gem_dmabuf_vmap,
850 	.vunmap = drm_gem_dmabuf_vunmap,
851 #endif
852 };
853 
854 /**
855  * drm_prime_pages_to_sg - converts a page array into an sg list
856  * @dev: DRM device
857  * @pages: pointer to the array of page pointers to convert
858  * @nr_pages: length of the page vector
859  *
860  * This helper creates an sg table object from a set of pages
861  * the driver is responsible for mapping the pages into the
862  * importers address space for use with dma_buf itself.
863  *
864  * This is useful for implementing &drm_gem_object_funcs.get_sg_table.
865  */
drm_prime_pages_to_sg(struct drm_device * dev,struct vm_page ** pages,unsigned int nr_pages)866 struct sg_table *drm_prime_pages_to_sg(struct drm_device *dev,
867 				       struct vm_page **pages, unsigned int nr_pages)
868 {
869 	STUB();
870 	return NULL;
871 #ifdef notyet
872 	struct sg_table *sg;
873 	size_t max_segment = 0;
874 	int err;
875 
876 	sg = kmalloc(sizeof(struct sg_table), GFP_KERNEL);
877 	if (!sg)
878 		return ERR_PTR(-ENOMEM);
879 
880 	if (dev)
881 		max_segment = dma_max_mapping_size(dev->dev);
882 	if (max_segment == 0)
883 		max_segment = UINT_MAX;
884 	err = sg_alloc_table_from_pages_segment(sg, pages, nr_pages, 0,
885 						(unsigned long)nr_pages << PAGE_SHIFT,
886 						max_segment, GFP_KERNEL);
887 	if (err) {
888 		kfree(sg);
889 		sg = ERR_PTR(err);
890 	}
891 	return sg;
892 #endif
893 }
894 EXPORT_SYMBOL(drm_prime_pages_to_sg);
895 
896 /**
897  * drm_prime_get_contiguous_size - returns the contiguous size of the buffer
898  * @sgt: sg_table describing the buffer to check
899  *
900  * This helper calculates the contiguous size in the DMA address space
901  * of the buffer described by the provided sg_table.
902  *
903  * This is useful for implementing
904  * &drm_gem_object_funcs.gem_prime_import_sg_table.
905  */
drm_prime_get_contiguous_size(struct sg_table * sgt)906 unsigned long drm_prime_get_contiguous_size(struct sg_table *sgt)
907 {
908 	STUB();
909 	return 0;
910 #ifdef notyet
911 	dma_addr_t expected = sg_dma_address(sgt->sgl);
912 	struct scatterlist *sg;
913 	unsigned long size = 0;
914 	int i;
915 
916 	for_each_sgtable_dma_sg(sgt, sg, i) {
917 		unsigned int len = sg_dma_len(sg);
918 
919 		if (!len)
920 			break;
921 		if (sg_dma_address(sg) != expected)
922 			break;
923 		expected += len;
924 		size += len;
925 	}
926 	return size;
927 #endif
928 }
929 EXPORT_SYMBOL(drm_prime_get_contiguous_size);
930 
931 /**
932  * drm_gem_prime_export - helper library implementation of the export callback
933  * @obj: GEM object to export
934  * @flags: flags like DRM_CLOEXEC and DRM_RDWR
935  *
936  * This is the implementation of the &drm_gem_object_funcs.export functions for GEM drivers
937  * using the PRIME helpers. It is used as the default in
938  * drm_gem_prime_handle_to_fd().
939  */
drm_gem_prime_export(struct drm_gem_object * obj,int flags)940 struct dma_buf *drm_gem_prime_export(struct drm_gem_object *obj,
941 				     int flags)
942 {
943 	struct drm_device *dev = obj->dev;
944 	struct dma_buf_export_info exp_info = {
945 #ifdef __linux__
946 		.exp_name = KBUILD_MODNAME, /* white lie for debug */
947 		.owner = dev->driver->fops->owner,
948 #endif
949 		.ops = &drm_gem_prime_dmabuf_ops,
950 		.size = obj->size,
951 		.flags = flags,
952 		.priv = obj,
953 		.resv = obj->resv,
954 	};
955 
956 	return drm_gem_dmabuf_export(dev, &exp_info);
957 }
958 EXPORT_SYMBOL(drm_gem_prime_export);
959 
960 /**
961  * drm_gem_prime_import_dev - core implementation of the import callback
962  * @dev: drm_device to import into
963  * @dma_buf: dma-buf object to import
964  * @attach_dev: struct device to dma_buf attach
965  *
966  * This is the core of drm_gem_prime_import(). It's designed to be called by
967  * drivers who want to use a different device structure than &drm_device.dev for
968  * attaching via dma_buf. This function calls
969  * &drm_driver.gem_prime_import_sg_table internally.
970  *
971  * Drivers must arrange to call drm_prime_gem_destroy() from their
972  * &drm_gem_object_funcs.free hook when using this function.
973  */
drm_gem_prime_import_dev(struct drm_device * dev,struct dma_buf * dma_buf,struct device * attach_dev)974 struct drm_gem_object *drm_gem_prime_import_dev(struct drm_device *dev,
975 					    struct dma_buf *dma_buf,
976 					    struct device *attach_dev)
977 {
978 	struct dma_buf_attachment *attach;
979 #ifdef notyet
980 	struct sg_table *sgt;
981 #endif
982 	struct drm_gem_object *obj;
983 	int ret;
984 
985 	if (dma_buf->ops == &drm_gem_prime_dmabuf_ops) {
986 		obj = dma_buf->priv;
987 		if (obj->dev == dev) {
988 			/*
989 			 * Importing dmabuf exported from our own gem increases
990 			 * refcount on gem itself instead of f_count of dmabuf.
991 			 */
992 			drm_gem_object_get(obj);
993 			return obj;
994 		}
995 	}
996 
997 #ifdef notyet
998 	if (!dev->driver->gem_prime_import_sg_table)
999 		return ERR_PTR(-EINVAL);
1000 #endif
1001 
1002 	attach = dma_buf_attach(dma_buf, attach_dev);
1003 	if (IS_ERR(attach))
1004 		return ERR_CAST(attach);
1005 
1006 #ifdef notyet
1007 	get_dma_buf(dma_buf);
1008 
1009 	sgt = dma_buf_map_attachment_unlocked(attach, DMA_BIDIRECTIONAL);
1010 	if (IS_ERR(sgt)) {
1011 		ret = PTR_ERR(sgt);
1012 		goto fail_detach;
1013 	}
1014 
1015 	obj = dev->driver->gem_prime_import_sg_table(dev, attach, sgt);
1016 	if (IS_ERR(obj)) {
1017 		ret = PTR_ERR(obj);
1018 		goto fail_unmap;
1019 	}
1020 
1021 	obj->import_attach = attach;
1022 	obj->resv = dma_buf->resv;
1023 
1024 	return obj;
1025 
1026 fail_unmap:
1027 	dma_buf_unmap_attachment_unlocked(attach, sgt, DMA_BIDIRECTIONAL);
1028 fail_detach:
1029 	dma_buf_detach(dma_buf, attach);
1030 	dma_buf_put(dma_buf);
1031 
1032 	return ERR_PTR(ret);
1033 #else
1034 	ret = 0;
1035 	panic(__func__);
1036 #endif
1037 }
1038 EXPORT_SYMBOL(drm_gem_prime_import_dev);
1039 
1040 /**
1041  * drm_gem_prime_import - helper library implementation of the import callback
1042  * @dev: drm_device to import into
1043  * @dma_buf: dma-buf object to import
1044  *
1045  * This is the implementation of the gem_prime_import functions for GEM drivers
1046  * using the PRIME helpers. Drivers can use this as their
1047  * &drm_driver.gem_prime_import implementation. It is used as the default
1048  * implementation in drm_gem_prime_fd_to_handle().
1049  *
1050  * Drivers must arrange to call drm_prime_gem_destroy() from their
1051  * &drm_gem_object_funcs.free hook when using this function.
1052  */
drm_gem_prime_import(struct drm_device * dev,struct dma_buf * dma_buf)1053 struct drm_gem_object *drm_gem_prime_import(struct drm_device *dev,
1054 					    struct dma_buf *dma_buf)
1055 {
1056 	return drm_gem_prime_import_dev(dev, dma_buf, dev->dev);
1057 }
1058 EXPORT_SYMBOL(drm_gem_prime_import);
1059 
1060 /**
1061  * drm_prime_sg_to_page_array - convert an sg table into a page array
1062  * @sgt: scatter-gather table to convert
1063  * @pages: array of page pointers to store the pages in
1064  * @max_entries: size of the passed-in array
1065  *
1066  * Exports an sg table into an array of pages.
1067  *
1068  * This function is deprecated and strongly discouraged to be used.
1069  * The page array is only useful for page faults and those can corrupt fields
1070  * in the struct page if they are not handled by the exporting driver.
1071  */
drm_prime_sg_to_page_array(struct sg_table * sgt,struct vm_page ** pages,int max_entries)1072 int __deprecated drm_prime_sg_to_page_array(struct sg_table *sgt,
1073 					    struct vm_page **pages,
1074 					    int max_entries)
1075 {
1076 	STUB();
1077 	return -ENOSYS;
1078 #ifdef notyet
1079 	struct sg_page_iter page_iter;
1080 	struct vm_page **p = pages;
1081 
1082 	for_each_sgtable_page(sgt, &page_iter, 0) {
1083 		if (WARN_ON(p - pages >= max_entries))
1084 			return -1;
1085 		*p++ = sg_page_iter_page(&page_iter);
1086 	}
1087 	return 0;
1088 #endif
1089 }
1090 EXPORT_SYMBOL(drm_prime_sg_to_page_array);
1091 
1092 /**
1093  * drm_prime_sg_to_dma_addr_array - convert an sg table into a dma addr array
1094  * @sgt: scatter-gather table to convert
1095  * @addrs: array to store the dma bus address of each page
1096  * @max_entries: size of both the passed-in arrays
1097  *
1098  * Exports an sg table into an array of addresses.
1099  *
1100  * Drivers should use this in their &drm_driver.gem_prime_import_sg_table
1101  * implementation.
1102  */
drm_prime_sg_to_dma_addr_array(struct sg_table * sgt,dma_addr_t * addrs,int max_entries)1103 int drm_prime_sg_to_dma_addr_array(struct sg_table *sgt, dma_addr_t *addrs,
1104 				   int max_entries)
1105 {
1106 	STUB();
1107 	return -ENOSYS;
1108 #ifdef notyet
1109 	struct sg_dma_page_iter dma_iter;
1110 	dma_addr_t *a = addrs;
1111 
1112 	for_each_sgtable_dma_page(sgt, &dma_iter, 0) {
1113 		if (WARN_ON(a - addrs >= max_entries))
1114 			return -1;
1115 		*a++ = sg_page_iter_dma_address(&dma_iter);
1116 	}
1117 	return 0;
1118 #endif
1119 }
1120 EXPORT_SYMBOL(drm_prime_sg_to_dma_addr_array);
1121 
1122 /**
1123  * drm_prime_gem_destroy - helper to clean up a PRIME-imported GEM object
1124  * @obj: GEM object which was created from a dma-buf
1125  * @sg: the sg-table which was pinned at import time
1126  *
1127  * This is the cleanup functions which GEM drivers need to call when they use
1128  * drm_gem_prime_import() or drm_gem_prime_import_dev() to import dma-bufs.
1129  */
drm_prime_gem_destroy(struct drm_gem_object * obj,struct sg_table * sg)1130 void drm_prime_gem_destroy(struct drm_gem_object *obj, struct sg_table *sg)
1131 {
1132 	STUB();
1133 #ifdef notyet
1134 	struct dma_buf_attachment *attach;
1135 	struct dma_buf *dma_buf;
1136 
1137 	attach = obj->import_attach;
1138 	if (sg)
1139 		dma_buf_unmap_attachment_unlocked(attach, sg, DMA_BIDIRECTIONAL);
1140 	dma_buf = attach->dmabuf;
1141 	dma_buf_detach(attach->dmabuf, attach);
1142 	/* remove the reference */
1143 	dma_buf_put(dma_buf);
1144 #endif
1145 }
1146 EXPORT_SYMBOL(drm_prime_gem_destroy);
1147