xref: /openbsd/sys/dev/pci/drm/drm_prime.c (revision 274d7c50)
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 <drm/drm_prime.h>
33 #include <drm/drm_gem.h>
34 #include <drm/drmP.h>
35 
36 #include "drm_internal.h"
37 
38 /*
39  * DMA-BUF/GEM Object references and lifetime overview:
40  *
41  * On the export the dma_buf holds a reference to the exporting GEM
42  * object. It takes this reference in handle_to_fd_ioctl, when it
43  * first calls .prime_export and stores the exporting GEM object in
44  * the dma_buf priv. This reference needs to be released when the
45  * final reference to the &dma_buf itself is dropped and its
46  * &dma_buf_ops.release function is called. For GEM-based drivers,
47  * the dma_buf should be exported using drm_gem_dmabuf_export() and
48  * then released by drm_gem_dmabuf_release().
49  *
50  * On the import the importing GEM object holds a reference to the
51  * dma_buf (which in turn holds a ref to the exporting GEM object).
52  * It takes that reference in the fd_to_handle ioctl.
53  * It calls dma_buf_get, creates an attachment to it and stores the
54  * attachment in the GEM object. When this attachment is destroyed
55  * when the imported object is destroyed, we remove the attachment
56  * and drop the reference to the dma_buf.
57  *
58  * When all the references to the &dma_buf are dropped, i.e. when
59  * userspace has closed both handles to the imported GEM object (through the
60  * FD_TO_HANDLE IOCTL) and closed the file descriptor of the exported
61  * (through the HANDLE_TO_FD IOCTL) dma_buf, and all kernel-internal references
62  * are also gone, then the dma_buf gets destroyed.  This can also happen as a
63  * part of the clean up procedure in the drm_release() function if userspace
64  * fails to properly clean up.  Note that both the kernel and userspace (by
65  * keeeping the PRIME file descriptors open) can hold references onto a
66  * &dma_buf.
67  *
68  * Thus the chain of references always flows in one direction
69  * (avoiding loops): importing_gem -> dmabuf -> exporting_gem
70  *
71  * Self-importing: if userspace is using PRIME as a replacement for flink
72  * then it will get a fd->handle request for a GEM object that it created.
73  * Drivers should detect this situation and return back the gem object
74  * from the dma-buf private.  Prime will do this automatically for drivers that
75  * use the drm_gem_prime_{import,export} helpers.
76  *
77  * GEM struct &dma_buf_ops symbols are now exported. They can be resued by
78  * drivers which implement GEM interface.
79  */
80 
81 struct drm_prime_member {
82 	struct dma_buf *dma_buf;
83 	uint32_t handle;
84 
85 	struct rb_node dmabuf_rb;
86 	struct rb_node handle_rb;
87 };
88 
89 #ifdef notyet
90 struct drm_prime_attachment {
91 	struct sg_table *sgt;
92 	enum dma_data_direction dir;
93 };
94 #endif
95 
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 
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 /**
189  * drm_gem_map_attach - dma_buf attach implementation for GEM
190  * @dma_buf: buffer to attach device to
191  * @attach: buffer attachment data
192  *
193  * Allocates &drm_prime_attachment and calls &drm_driver.gem_prime_pin for
194  * device specific attachment. This can be used as the &dma_buf_ops.attach
195  * callback.
196  *
197  * Returns 0 on success, negative error code on failure.
198  */
199 
200 #ifdef notyet
201 
202 int drm_gem_map_attach(struct dma_buf *dma_buf,
203 		       struct dma_buf_attachment *attach)
204 {
205 	struct drm_prime_attachment *prime_attach;
206 	struct drm_gem_object *obj = dma_buf->priv;
207 	struct drm_device *dev = obj->dev;
208 
209 	prime_attach = kzalloc(sizeof(*prime_attach), GFP_KERNEL);
210 	if (!prime_attach)
211 		return -ENOMEM;
212 
213 	prime_attach->dir = DMA_NONE;
214 	attach->priv = prime_attach;
215 
216 	if (!dev->driver->gem_prime_pin)
217 		return 0;
218 
219 	return dev->driver->gem_prime_pin(obj);
220 }
221 EXPORT_SYMBOL(drm_gem_map_attach);
222 
223 /**
224  * drm_gem_map_detach - dma_buf detach implementation for GEM
225  * @dma_buf: buffer to detach from
226  * @attach: attachment to be detached
227  *
228  * Cleans up &dma_buf_attachment. This can be used as the &dma_buf_ops.detach
229  * callback.
230  */
231 void drm_gem_map_detach(struct dma_buf *dma_buf,
232 			struct dma_buf_attachment *attach)
233 {
234 	struct drm_prime_attachment *prime_attach = attach->priv;
235 	struct drm_gem_object *obj = dma_buf->priv;
236 	struct drm_device *dev = obj->dev;
237 
238 	if (prime_attach) {
239 		struct sg_table *sgt = prime_attach->sgt;
240 
241 		if (sgt) {
242 			if (prime_attach->dir != DMA_NONE)
243 				dma_unmap_sg_attrs(attach->dev, sgt->sgl,
244 						   sgt->nents,
245 						   prime_attach->dir,
246 						   DMA_ATTR_SKIP_CPU_SYNC);
247 			sg_free_table(sgt);
248 		}
249 
250 		kfree(sgt);
251 		kfree(prime_attach);
252 		attach->priv = NULL;
253 	}
254 
255 	if (dev->driver->gem_prime_unpin)
256 		dev->driver->gem_prime_unpin(obj);
257 }
258 EXPORT_SYMBOL(drm_gem_map_detach);
259 
260 #endif
261 
262 void drm_prime_remove_buf_handle_locked(struct drm_prime_file_private *prime_fpriv,
263 					struct dma_buf *dma_buf)
264 {
265 	struct rb_node *rb;
266 
267 	rb = prime_fpriv->dmabufs.rb_node;
268 	while (rb) {
269 		struct drm_prime_member *member;
270 
271 		member = rb_entry(rb, struct drm_prime_member, dmabuf_rb);
272 		if (member->dma_buf == dma_buf) {
273 			rb_erase(&member->handle_rb, &prime_fpriv->handles);
274 			rb_erase(&member->dmabuf_rb, &prime_fpriv->dmabufs);
275 
276 			dma_buf_put(dma_buf);
277 			kfree(member);
278 			return;
279 		} else if (member->dma_buf < dma_buf) {
280 			rb = rb->rb_right;
281 		} else {
282 			rb = rb->rb_left;
283 		}
284 	}
285 }
286 
287 /**
288  * drm_gem_map_dma_buf - map_dma_buf implementation for GEM
289  * @attach: attachment whose scatterlist is to be returned
290  * @dir: direction of DMA transfer
291  *
292  * Calls &drm_driver.gem_prime_get_sg_table and then maps the scatterlist. This
293  * can be used as the &dma_buf_ops.map_dma_buf callback.
294  *
295  * Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
296  * on error. May return -EINTR if it is interrupted by a signal.
297  */
298 
299 #ifdef notyet
300 
301 struct sg_table *drm_gem_map_dma_buf(struct dma_buf_attachment *attach,
302 				     enum dma_data_direction dir)
303 {
304 	struct drm_prime_attachment *prime_attach = attach->priv;
305 	struct drm_gem_object *obj = attach->dmabuf->priv;
306 	struct sg_table *sgt;
307 
308 	if (WARN_ON(dir == DMA_NONE || !prime_attach))
309 		return ERR_PTR(-EINVAL);
310 
311 	/* return the cached mapping when possible */
312 	if (prime_attach->dir == dir)
313 		return prime_attach->sgt;
314 
315 	/*
316 	 * two mappings with different directions for the same attachment are
317 	 * not allowed
318 	 */
319 	if (WARN_ON(prime_attach->dir != DMA_NONE))
320 		return ERR_PTR(-EBUSY);
321 
322 	sgt = obj->dev->driver->gem_prime_get_sg_table(obj);
323 
324 	if (!IS_ERR(sgt)) {
325 		if (!dma_map_sg_attrs(attach->dev, sgt->sgl, sgt->nents, dir,
326 				      DMA_ATTR_SKIP_CPU_SYNC)) {
327 			sg_free_table(sgt);
328 			kfree(sgt);
329 			sgt = ERR_PTR(-ENOMEM);
330 		} else {
331 			prime_attach->sgt = sgt;
332 			prime_attach->dir = dir;
333 		}
334 	}
335 
336 	return sgt;
337 }
338 EXPORT_SYMBOL(drm_gem_map_dma_buf);
339 
340 /**
341  * drm_gem_unmap_dma_buf - unmap_dma_buf implementation for GEM
342  * @attach: attachment to unmap buffer from
343  * @sgt: scatterlist info of the buffer to unmap
344  * @dir: direction of DMA transfer
345  *
346  * Not implemented. The unmap is done at drm_gem_map_detach().  This can be
347  * used as the &dma_buf_ops.unmap_dma_buf callback.
348  */
349 void drm_gem_unmap_dma_buf(struct dma_buf_attachment *attach,
350 			   struct sg_table *sgt,
351 			   enum dma_data_direction dir)
352 {
353 	/* nothing to be done here */
354 }
355 EXPORT_SYMBOL(drm_gem_unmap_dma_buf);
356 
357 #endif
358 
359 /**
360  * drm_gem_dmabuf_export - dma_buf export implementation for GEM
361  * @dev: parent device for the exported dmabuf
362  * @exp_info: the export information used by dma_buf_export()
363  *
364  * This wraps dma_buf_export() for use by generic GEM drivers that are using
365  * drm_gem_dmabuf_release(). In addition to calling dma_buf_export(), we take
366  * a reference to the &drm_device and the exported &drm_gem_object (stored in
367  * &dma_buf_export_info.priv) which is released by drm_gem_dmabuf_release().
368  *
369  * Returns the new dmabuf.
370  */
371 struct dma_buf *drm_gem_dmabuf_export(struct drm_device *dev,
372 				      struct dma_buf_export_info *exp_info)
373 {
374 	struct dma_buf *dma_buf;
375 
376 	dma_buf = dma_buf_export(exp_info);
377 	if (IS_ERR(dma_buf))
378 		return dma_buf;
379 
380 	drm_dev_get(dev);
381 	drm_gem_object_get(exp_info->priv);
382 
383 	return dma_buf;
384 }
385 EXPORT_SYMBOL(drm_gem_dmabuf_export);
386 
387 /**
388  * drm_gem_dmabuf_release - dma_buf release implementation for GEM
389  * @dma_buf: buffer to be released
390  *
391  * Generic release function for dma_bufs exported as PRIME buffers. GEM drivers
392  * must use this in their dma_buf ops structure as the release callback.
393  * drm_gem_dmabuf_release() should be used in conjunction with
394  * drm_gem_dmabuf_export().
395  */
396 void drm_gem_dmabuf_release(struct dma_buf *dma_buf)
397 {
398 	struct drm_gem_object *obj = dma_buf->priv;
399 	struct drm_device *dev = obj->dev;
400 
401 	/* drop the reference on the export fd holds */
402 	drm_gem_object_put_unlocked(obj);
403 
404 	drm_dev_put(dev);
405 }
406 EXPORT_SYMBOL(drm_gem_dmabuf_release);
407 
408 /**
409  * drm_gem_dmabuf_vmap - dma_buf vmap implementation for GEM
410  * @dma_buf: buffer to be mapped
411  *
412  * Sets up a kernel virtual mapping. This can be used as the &dma_buf_ops.vmap
413  * callback.
414  *
415  * Returns the kernel virtual address.
416  */
417 
418 #ifdef notyet
419 
420 void *drm_gem_dmabuf_vmap(struct dma_buf *dma_buf)
421 {
422 	struct drm_gem_object *obj = dma_buf->priv;
423 	struct drm_device *dev = obj->dev;
424 
425 	if (dev->driver->gem_prime_vmap)
426 		return dev->driver->gem_prime_vmap(obj);
427 	else
428 		return NULL;
429 }
430 EXPORT_SYMBOL(drm_gem_dmabuf_vmap);
431 
432 /**
433  * drm_gem_dmabuf_vunmap - dma_buf vunmap implementation for GEM
434  * @dma_buf: buffer to be unmapped
435  * @vaddr: the virtual address of the buffer
436  *
437  * Releases a kernel virtual mapping. This can be used as the
438  * &dma_buf_ops.vunmap callback.
439  */
440 void drm_gem_dmabuf_vunmap(struct dma_buf *dma_buf, void *vaddr)
441 {
442 	struct drm_gem_object *obj = dma_buf->priv;
443 	struct drm_device *dev = obj->dev;
444 
445 	if (dev->driver->gem_prime_vunmap)
446 		dev->driver->gem_prime_vunmap(obj, vaddr);
447 }
448 EXPORT_SYMBOL(drm_gem_dmabuf_vunmap);
449 
450 /**
451  * drm_gem_dmabuf_kmap - map implementation for GEM
452  * @dma_buf: buffer to be mapped
453  * @page_num: page number within the buffer
454  *
455  * Not implemented. This can be used as the &dma_buf_ops.map callback.
456  */
457 void *drm_gem_dmabuf_kmap(struct dma_buf *dma_buf, unsigned long page_num)
458 {
459 	return NULL;
460 }
461 EXPORT_SYMBOL(drm_gem_dmabuf_kmap);
462 
463 /**
464  * drm_gem_dmabuf_kunmap - unmap implementation for GEM
465  * @dma_buf: buffer to be unmapped
466  * @page_num: page number within the buffer
467  * @addr: virtual address of the buffer
468  *
469  * Not implemented. This can be used as the &dma_buf_ops.unmap callback.
470  */
471 void drm_gem_dmabuf_kunmap(struct dma_buf *dma_buf, unsigned long page_num,
472 			   void *addr)
473 {
474 
475 }
476 EXPORT_SYMBOL(drm_gem_dmabuf_kunmap);
477 
478 /**
479  * drm_gem_dmabuf_mmap - dma_buf mmap implementation for GEM
480  * @dma_buf: buffer to be mapped
481  * @vma: virtual address range
482  *
483  * Provides memory mapping for the buffer. This can be used as the
484  * &dma_buf_ops.mmap callback.
485  *
486  * Returns 0 on success or a negative error code on failure.
487  */
488 int drm_gem_dmabuf_mmap(struct dma_buf *dma_buf, struct vm_area_struct *vma)
489 {
490 	struct drm_gem_object *obj = dma_buf->priv;
491 	struct drm_device *dev = obj->dev;
492 
493 	if (!dev->driver->gem_prime_mmap)
494 		return -ENOSYS;
495 
496 	return dev->driver->gem_prime_mmap(obj, vma);
497 }
498 EXPORT_SYMBOL(drm_gem_dmabuf_mmap);
499 
500 #endif
501 
502 static const struct dma_buf_ops drm_gem_prime_dmabuf_ops =  {
503 #ifdef notyet
504 	.attach = drm_gem_map_attach,
505 	.detach = drm_gem_map_detach,
506 	.map_dma_buf = drm_gem_map_dma_buf,
507 	.unmap_dma_buf = drm_gem_unmap_dma_buf,
508 #endif
509 	.release = drm_gem_dmabuf_release,
510 #ifdef notyet
511 	.map = drm_gem_dmabuf_kmap,
512 	.unmap = drm_gem_dmabuf_kunmap,
513 	.mmap = drm_gem_dmabuf_mmap,
514 	.vmap = drm_gem_dmabuf_vmap,
515 	.vunmap = drm_gem_dmabuf_vunmap,
516 #endif
517 };
518 
519 /**
520  * DOC: PRIME Helpers
521  *
522  * Drivers can implement @gem_prime_export and @gem_prime_import in terms of
523  * simpler APIs by using the helper functions @drm_gem_prime_export and
524  * @drm_gem_prime_import.  These functions implement dma-buf support in terms of
525  * six lower-level driver callbacks:
526  *
527  * Export callbacks:
528  *
529  *  * @gem_prime_pin (optional): prepare a GEM object for exporting
530  *  * @gem_prime_get_sg_table: provide a scatter/gather table of pinned pages
531  *  * @gem_prime_vmap: vmap a buffer exported by your driver
532  *  * @gem_prime_vunmap: vunmap a buffer exported by your driver
533  *  * @gem_prime_mmap (optional): mmap a buffer exported by your driver
534  *
535  * Import callback:
536  *
537  *  * @gem_prime_import_sg_table (import): produce a GEM object from another
538  *    driver's scatter/gather table
539  */
540 
541 /**
542  * drm_gem_prime_export - helper library implementation of the export callback
543  * @dev: drm_device to export from
544  * @obj: GEM object to export
545  * @flags: flags like DRM_CLOEXEC and DRM_RDWR
546  *
547  * This is the implementation of the gem_prime_export functions for GEM drivers
548  * using the PRIME helpers.
549  */
550 struct dma_buf *drm_gem_prime_export(struct drm_device *dev,
551 				     struct drm_gem_object *obj,
552 				     int flags)
553 {
554 	struct dma_buf_export_info exp_info = {
555 #ifdef __linux__
556 		.exp_name = KBUILD_MODNAME, /* white lie for debug */
557 		.owner = dev->driver->fops->owner,
558 #endif
559 		.ops = &drm_gem_prime_dmabuf_ops,
560 		.size = obj->size,
561 		.flags = flags,
562 		.priv = obj,
563 	};
564 
565 	if (dev->driver->gem_prime_res_obj)
566 		exp_info.resv = dev->driver->gem_prime_res_obj(obj);
567 
568 	return drm_gem_dmabuf_export(dev, &exp_info);
569 }
570 EXPORT_SYMBOL(drm_gem_prime_export);
571 
572 static struct dma_buf *export_and_register_object(struct drm_device *dev,
573 						  struct drm_gem_object *obj,
574 						  uint32_t flags)
575 {
576 	struct dma_buf *dmabuf;
577 
578 	/* prevent races with concurrent gem_close. */
579 	if (obj->handle_count == 0) {
580 		dmabuf = ERR_PTR(-ENOENT);
581 		return dmabuf;
582 	}
583 
584 	dmabuf = dev->driver->gem_prime_export(dev, obj, flags);
585 	if (IS_ERR(dmabuf)) {
586 		/* normally the created dma-buf takes ownership of the ref,
587 		 * but if that fails then drop the ref
588 		 */
589 		return dmabuf;
590 	}
591 
592 	/*
593 	 * Note that callers do not need to clean up the export cache
594 	 * since the check for obj->handle_count guarantees that someone
595 	 * will clean it up.
596 	 */
597 	obj->dma_buf = dmabuf;
598 	get_dma_buf(obj->dma_buf);
599 
600 	return dmabuf;
601 }
602 
603 /**
604  * drm_gem_prime_handle_to_fd - PRIME export function for GEM drivers
605  * @dev: dev to export the buffer from
606  * @file_priv: drm file-private structure
607  * @handle: buffer handle to export
608  * @flags: flags like DRM_CLOEXEC
609  * @prime_fd: pointer to storage for the fd id of the create dma-buf
610  *
611  * This is the PRIME export function which must be used mandatorily by GEM
612  * drivers to ensure correct lifetime management of the underlying GEM object.
613  * The actual exporting from GEM object to a dma-buf is done through the
614  * gem_prime_export driver callback.
615  */
616 int drm_gem_prime_handle_to_fd(struct drm_device *dev,
617 			       struct drm_file *file_priv, uint32_t handle,
618 			       uint32_t flags,
619 			       int *prime_fd)
620 {
621 	struct drm_gem_object *obj;
622 	int ret = 0;
623 	struct dma_buf *dmabuf;
624 
625 	mutex_lock(&file_priv->prime.lock);
626 	obj = drm_gem_object_lookup(file_priv, handle);
627 	if (!obj)  {
628 		ret = -ENOENT;
629 		goto out_unlock;
630 	}
631 
632 	dmabuf = drm_prime_lookup_buf_by_handle(&file_priv->prime, handle);
633 	if (dmabuf) {
634 		get_dma_buf(dmabuf);
635 		goto out_have_handle;
636 	}
637 
638 	mutex_lock(&dev->object_name_lock);
639 #ifdef notyet
640 	/* re-export the original imported object */
641 	if (obj->import_attach) {
642 		dmabuf = obj->import_attach->dmabuf;
643 		get_dma_buf(dmabuf);
644 		goto out_have_obj;
645 	}
646 #endif
647 
648 	if (obj->dma_buf) {
649 		get_dma_buf(obj->dma_buf);
650 		dmabuf = obj->dma_buf;
651 		goto out_have_obj;
652 	}
653 
654 	dmabuf = export_and_register_object(dev, obj, flags);
655 	if (IS_ERR(dmabuf)) {
656 		/* normally the created dma-buf takes ownership of the ref,
657 		 * but if that fails then drop the ref
658 		 */
659 		ret = PTR_ERR(dmabuf);
660 		mutex_unlock(&dev->object_name_lock);
661 		goto out;
662 	}
663 
664 out_have_obj:
665 	/*
666 	 * If we've exported this buffer then cheat and add it to the import list
667 	 * so we get the correct handle back. We must do this under the
668 	 * protection of dev->object_name_lock to ensure that a racing gem close
669 	 * ioctl doesn't miss to remove this buffer handle from the cache.
670 	 */
671 	ret = drm_prime_add_buf_handle(&file_priv->prime,
672 				       dmabuf, handle);
673 	mutex_unlock(&dev->object_name_lock);
674 	if (ret)
675 		goto fail_put_dmabuf;
676 
677 out_have_handle:
678 	ret = dma_buf_fd(dmabuf, flags);
679 	/*
680 	 * We must _not_ remove the buffer from the handle cache since the newly
681 	 * created dma buf is already linked in the global obj->dma_buf pointer,
682 	 * and that is invariant as long as a userspace gem handle exists.
683 	 * Closing the handle will clean out the cache anyway, so we don't leak.
684 	 */
685 	if (ret < 0) {
686 		goto fail_put_dmabuf;
687 	} else {
688 		*prime_fd = ret;
689 		ret = 0;
690 	}
691 
692 	goto out;
693 
694 fail_put_dmabuf:
695 	dma_buf_put(dmabuf);
696 out:
697 	drm_gem_object_put_unlocked(obj);
698 out_unlock:
699 	mutex_unlock(&file_priv->prime.lock);
700 
701 	return ret;
702 }
703 EXPORT_SYMBOL(drm_gem_prime_handle_to_fd);
704 
705 /**
706  * drm_gem_prime_import_dev - core implementation of the import callback
707  * @dev: drm_device to import into
708  * @dma_buf: dma-buf object to import
709  * @attach_dev: struct device to dma_buf attach
710  *
711  * This is the core of drm_gem_prime_import. It's designed to be called by
712  * drivers who want to use a different device structure than dev->dev for
713  * attaching via dma_buf.
714  */
715 struct drm_gem_object *drm_gem_prime_import_dev(struct drm_device *dev,
716 					    struct dma_buf *dma_buf,
717 					    struct device *attach_dev)
718 {
719 	struct dma_buf_attachment *attach;
720 #ifdef notyet
721 	struct sg_table *sgt;
722 #endif
723 	struct drm_gem_object *obj;
724 	int ret;
725 
726 	if (dma_buf->ops == &drm_gem_prime_dmabuf_ops) {
727 		obj = dma_buf->priv;
728 		if (obj->dev == dev) {
729 			/*
730 			 * Importing dmabuf exported from out own gem increases
731 			 * refcount on gem itself instead of f_count of dmabuf.
732 			 */
733 			drm_gem_object_get(obj);
734 			return obj;
735 		}
736 	}
737 
738 #ifdef notyet
739 	if (!dev->driver->gem_prime_import_sg_table)
740 		return ERR_PTR(-EINVAL);
741 #endif
742 
743 	attach = dma_buf_attach(dma_buf, attach_dev);
744 	if (IS_ERR(attach))
745 		return ERR_CAST(attach);
746 
747 #ifdef notyet
748 	get_dma_buf(dma_buf);
749 
750 	sgt = dma_buf_map_attachment(attach, DMA_BIDIRECTIONAL);
751 	if (IS_ERR(sgt)) {
752 		ret = PTR_ERR(sgt);
753 		goto fail_detach;
754 	}
755 
756 	obj = dev->driver->gem_prime_import_sg_table(dev, attach, sgt);
757 	if (IS_ERR(obj)) {
758 		ret = PTR_ERR(obj);
759 		goto fail_unmap;
760 	}
761 
762 	obj->import_attach = attach;
763 
764 	return obj;
765 
766 fail_unmap:
767 	dma_buf_unmap_attachment(attach, sgt, DMA_BIDIRECTIONAL);
768 fail_detach:
769 	dma_buf_detach(dma_buf, attach);
770 	dma_buf_put(dma_buf);
771 
772 	return ERR_PTR(ret);
773 #else
774 	ret = 0;
775 	panic(__func__);
776 #endif
777 }
778 EXPORT_SYMBOL(drm_gem_prime_import_dev);
779 
780 /**
781  * drm_gem_prime_import - helper library implementation of the import callback
782  * @dev: drm_device to import into
783  * @dma_buf: dma-buf object to import
784  *
785  * This is the implementation of the gem_prime_import functions for GEM drivers
786  * using the PRIME helpers.
787  */
788 struct drm_gem_object *drm_gem_prime_import(struct drm_device *dev,
789 					    struct dma_buf *dma_buf)
790 {
791 	return drm_gem_prime_import_dev(dev, dma_buf, dev->dev);
792 }
793 EXPORT_SYMBOL(drm_gem_prime_import);
794 
795 /**
796  * drm_gem_prime_fd_to_handle - PRIME import function for GEM drivers
797  * @dev: dev to export the buffer from
798  * @file_priv: drm file-private structure
799  * @prime_fd: fd id of the dma-buf which should be imported
800  * @handle: pointer to storage for the handle of the imported buffer object
801  *
802  * This is the PRIME import function which must be used mandatorily by GEM
803  * drivers to ensure correct lifetime management of the underlying GEM object.
804  * The actual importing of GEM object from the dma-buf is done through the
805  * gem_import_export driver callback.
806  */
807 int drm_gem_prime_fd_to_handle(struct drm_device *dev,
808 			       struct drm_file *file_priv, int prime_fd,
809 			       uint32_t *handle)
810 {
811 	struct dma_buf *dma_buf;
812 	struct drm_gem_object *obj;
813 	int ret;
814 
815 	dma_buf = dma_buf_get(prime_fd);
816 	if (IS_ERR(dma_buf))
817 		return PTR_ERR(dma_buf);
818 
819 	mutex_lock(&file_priv->prime.lock);
820 
821 	ret = drm_prime_lookup_buf_handle(&file_priv->prime,
822 			dma_buf, handle);
823 	if (ret == 0)
824 		goto out_put;
825 
826 	/* never seen this one, need to import */
827 	mutex_lock(&dev->object_name_lock);
828 	obj = dev->driver->gem_prime_import(dev, dma_buf);
829 	if (IS_ERR(obj)) {
830 		ret = PTR_ERR(obj);
831 		goto out_unlock;
832 	}
833 
834 	if (obj->dma_buf) {
835 		WARN_ON(obj->dma_buf != dma_buf);
836 	} else {
837 		obj->dma_buf = dma_buf;
838 		get_dma_buf(dma_buf);
839 	}
840 
841 	/* _handle_create_tail unconditionally unlocks dev->object_name_lock. */
842 	ret = drm_gem_handle_create_tail(file_priv, obj, handle);
843 	drm_gem_object_put_unlocked(obj);
844 	if (ret)
845 		goto out_put;
846 
847 	ret = drm_prime_add_buf_handle(&file_priv->prime,
848 			dma_buf, *handle);
849 	mutex_unlock(&file_priv->prime.lock);
850 	if (ret)
851 		goto fail;
852 
853 	dma_buf_put(dma_buf);
854 
855 	return 0;
856 
857 fail:
858 	/* hmm, if driver attached, we are relying on the free-object path
859 	 * to detach.. which seems ok..
860 	 */
861 	drm_gem_handle_delete(file_priv, *handle);
862 	dma_buf_put(dma_buf);
863 	return ret;
864 
865 out_unlock:
866 	mutex_unlock(&dev->object_name_lock);
867 out_put:
868 	mutex_unlock(&file_priv->prime.lock);
869 	dma_buf_put(dma_buf);
870 	return ret;
871 }
872 EXPORT_SYMBOL(drm_gem_prime_fd_to_handle);
873 
874 int drm_prime_handle_to_fd_ioctl(struct drm_device *dev, void *data,
875 				 struct drm_file *file_priv)
876 {
877 	struct drm_prime_handle *args = data;
878 
879 	if (!drm_core_check_feature(dev, DRIVER_PRIME))
880 		return -EINVAL;
881 
882 	if (!dev->driver->prime_handle_to_fd)
883 		return -ENOSYS;
884 
885 	/* check flags are valid */
886 	if (args->flags & ~(DRM_CLOEXEC | DRM_RDWR))
887 		return -EINVAL;
888 
889 	return dev->driver->prime_handle_to_fd(dev, file_priv,
890 			args->handle, args->flags, &args->fd);
891 }
892 
893 int drm_prime_fd_to_handle_ioctl(struct drm_device *dev, void *data,
894 				 struct drm_file *file_priv)
895 {
896 	struct drm_prime_handle *args = data;
897 
898 	if (!drm_core_check_feature(dev, DRIVER_PRIME))
899 		return -EINVAL;
900 
901 	if (!dev->driver->prime_fd_to_handle)
902 		return -ENOSYS;
903 
904 	return dev->driver->prime_fd_to_handle(dev, file_priv,
905 			args->fd, &args->handle);
906 }
907 
908 #ifdef notyet
909 
910 /**
911  * drm_prime_pages_to_sg - converts a page array into an sg list
912  * @pages: pointer to the array of page pointers to convert
913  * @nr_pages: length of the page vector
914  *
915  * This helper creates an sg table object from a set of pages
916  * the driver is responsible for mapping the pages into the
917  * importers address space for use with dma_buf itself.
918  */
919 struct sg_table *drm_prime_pages_to_sg(struct page **pages, unsigned int nr_pages)
920 {
921 	struct sg_table *sg = NULL;
922 	int ret;
923 
924 	sg = kmalloc(sizeof(struct sg_table), GFP_KERNEL);
925 	if (!sg) {
926 		ret = -ENOMEM;
927 		goto out;
928 	}
929 
930 	ret = sg_alloc_table_from_pages(sg, pages, nr_pages, 0,
931 				nr_pages << PAGE_SHIFT, GFP_KERNEL);
932 	if (ret)
933 		goto out;
934 
935 	return sg;
936 out:
937 	kfree(sg);
938 	return ERR_PTR(ret);
939 }
940 EXPORT_SYMBOL(drm_prime_pages_to_sg);
941 
942 /**
943  * drm_prime_sg_to_page_addr_arrays - convert an sg table into a page array
944  * @sgt: scatter-gather table to convert
945  * @pages: optional array of page pointers to store the page array in
946  * @addrs: optional array to store the dma bus address of each page
947  * @max_entries: size of both the passed-in arrays
948  *
949  * Exports an sg table into an array of pages and addresses. This is currently
950  * required by the TTM driver in order to do correct fault handling.
951  */
952 int drm_prime_sg_to_page_addr_arrays(struct sg_table *sgt, struct page **pages,
953 				     dma_addr_t *addrs, int max_entries)
954 {
955 	unsigned count;
956 	struct scatterlist *sg;
957 	struct page *page;
958 	u32 len, index;
959 	dma_addr_t addr;
960 
961 	index = 0;
962 	for_each_sg(sgt->sgl, sg, sgt->nents, count) {
963 		len = sg->length;
964 		page = sg_page(sg);
965 		addr = sg_dma_address(sg);
966 
967 		while (len > 0) {
968 			if (WARN_ON(index >= max_entries))
969 				return -1;
970 			if (pages)
971 				pages[index] = page;
972 			if (addrs)
973 				addrs[index] = addr;
974 
975 			page++;
976 			addr += PAGE_SIZE;
977 			len -= PAGE_SIZE;
978 			index++;
979 		}
980 	}
981 	return 0;
982 }
983 EXPORT_SYMBOL(drm_prime_sg_to_page_addr_arrays);
984 
985 #endif
986 
987 /**
988  * drm_prime_gem_destroy - helper to clean up a PRIME-imported GEM object
989  * @obj: GEM object which was created from a dma-buf
990  * @sg: the sg-table which was pinned at import time
991  *
992  * This is the cleanup functions which GEM drivers need to call when they use
993  * @drm_gem_prime_import to import dma-bufs.
994  */
995 void drm_prime_gem_destroy(struct drm_gem_object *obj, struct sg_table *sg)
996 {
997 #ifdef notyet
998 	struct dma_buf_attachment *attach;
999 	struct dma_buf *dma_buf;
1000 	attach = obj->import_attach;
1001 	if (sg)
1002 		dma_buf_unmap_attachment(attach, sg, DMA_BIDIRECTIONAL);
1003 	dma_buf = attach->dmabuf;
1004 	dma_buf_detach(attach->dmabuf, attach);
1005 	/* remove the reference */
1006 	dma_buf_put(dma_buf);
1007 #endif
1008 }
1009 EXPORT_SYMBOL(drm_prime_gem_destroy);
1010 
1011 void drm_prime_init_file_private(struct drm_prime_file_private *prime_fpriv)
1012 {
1013 	rw_init(&prime_fpriv->lock, "primlk");
1014 	prime_fpriv->dmabufs = RB_ROOT;
1015 	prime_fpriv->handles = RB_ROOT;
1016 }
1017 
1018 void drm_prime_destroy_file_private(struct drm_prime_file_private *prime_fpriv)
1019 {
1020 	/* by now drm_gem_release should've made sure the list is empty */
1021 	WARN_ON(!RB_EMPTY_ROOT(&prime_fpriv->dmabufs));
1022 }
1023