xref: /openbmc/linux/drivers/gpu/drm/omapdrm/omap_gem.c (revision 3db55767)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2011 Texas Instruments Incorporated - https://www.ti.com/
4  * Author: Rob Clark <rob.clark@linaro.org>
5  */
6 
7 #include <linux/dma-mapping.h>
8 #include <linux/seq_file.h>
9 #include <linux/shmem_fs.h>
10 #include <linux/spinlock.h>
11 #include <linux/pfn_t.h>
12 
13 #include <drm/drm_prime.h>
14 #include <drm/drm_vma_manager.h>
15 
16 #include "omap_drv.h"
17 #include "omap_dmm_tiler.h"
18 
19 /*
20  * GEM buffer object implementation.
21  */
22 
23 /* note: we use upper 8 bits of flags for driver-internal flags: */
24 #define OMAP_BO_MEM_DMA_API	0x01000000	/* memory allocated with the dma_alloc_* API */
25 #define OMAP_BO_MEM_SHMEM	0x02000000	/* memory allocated through shmem backing */
26 #define OMAP_BO_MEM_DMABUF	0x08000000	/* memory imported from a dmabuf */
27 
28 struct omap_gem_object {
29 	struct drm_gem_object base;
30 
31 	struct list_head mm_list;
32 
33 	u32 flags;
34 
35 	/** width/height for tiled formats (rounded up to slot boundaries) */
36 	u16 width, height;
37 
38 	/** roll applied when mapping to DMM */
39 	u32 roll;
40 
41 	/** protects pin_cnt, block, pages, dma_addrs and vaddr */
42 	struct mutex lock;
43 
44 	/**
45 	 * dma_addr contains the buffer DMA address. It is valid for
46 	 *
47 	 * - buffers allocated through the DMA mapping API (with the
48 	 *   OMAP_BO_MEM_DMA_API flag set)
49 	 *
50 	 * - buffers imported from dmabuf (with the OMAP_BO_MEM_DMABUF flag set)
51 	 *   if they are physically contiguous (when sgt->orig_nents == 1)
52 	 *
53 	 * - buffers mapped through the TILER when pin_cnt is not zero, in which
54 	 *   case the DMA address points to the TILER aperture
55 	 *
56 	 * Physically contiguous buffers have their DMA address equal to the
57 	 * physical address as we don't remap those buffers through the TILER.
58 	 *
59 	 * Buffers mapped to the TILER have their DMA address pointing to the
60 	 * TILER aperture. As TILER mappings are refcounted (through pin_cnt)
61 	 * the DMA address must be accessed through omap_gem_pin() to ensure
62 	 * that the mapping won't disappear unexpectedly. References must be
63 	 * released with omap_gem_unpin().
64 	 */
65 	dma_addr_t dma_addr;
66 
67 	/**
68 	 * # of users
69 	 */
70 	refcount_t pin_cnt;
71 
72 	/**
73 	 * If the buffer has been imported from a dmabuf the OMAP_DB_DMABUF flag
74 	 * is set and the sgt field is valid.
75 	 */
76 	struct sg_table *sgt;
77 
78 	/**
79 	 * tiler block used when buffer is remapped in DMM/TILER.
80 	 */
81 	struct tiler_block *block;
82 
83 	/**
84 	 * Array of backing pages, if allocated.  Note that pages are never
85 	 * allocated for buffers originally allocated from contiguous memory
86 	 */
87 	struct page **pages;
88 
89 	/** addresses corresponding to pages in above array */
90 	dma_addr_t *dma_addrs;
91 
92 	/**
93 	 * Virtual address, if mapped.
94 	 */
95 	void *vaddr;
96 };
97 
98 #define to_omap_bo(x) container_of(x, struct omap_gem_object, base)
99 
100 /* To deal with userspace mmap'ings of 2d tiled buffers, which (a) are
101  * not necessarily pinned in TILER all the time, and (b) when they are
102  * they are not necessarily page aligned, we reserve one or more small
103  * regions in each of the 2d containers to use as a user-GART where we
104  * can create a second page-aligned mapping of parts of the buffer
105  * being accessed from userspace.
106  *
107  * Note that we could optimize slightly when we know that multiple
108  * tiler containers are backed by the same PAT.. but I'll leave that
109  * for later..
110  */
111 #define NUM_USERGART_ENTRIES 2
112 struct omap_drm_usergart_entry {
113 	struct tiler_block *block;	/* the reserved tiler block */
114 	dma_addr_t dma_addr;
115 	struct drm_gem_object *obj;	/* the current pinned obj */
116 	pgoff_t obj_pgoff;		/* page offset of obj currently
117 					   mapped in */
118 };
119 
120 struct omap_drm_usergart {
121 	struct omap_drm_usergart_entry entry[NUM_USERGART_ENTRIES];
122 	int height;				/* height in rows */
123 	int height_shift;		/* ilog2(height in rows) */
124 	int slot_shift;			/* ilog2(width per slot) */
125 	int stride_pfn;			/* stride in pages */
126 	int last;				/* index of last used entry */
127 };
128 
129 /* -----------------------------------------------------------------------------
130  * Helpers
131  */
132 
133 /** get mmap offset */
134 u64 omap_gem_mmap_offset(struct drm_gem_object *obj)
135 {
136 	struct drm_device *dev = obj->dev;
137 	int ret;
138 	size_t size;
139 
140 	/* Make it mmapable */
141 	size = omap_gem_mmap_size(obj);
142 	ret = drm_gem_create_mmap_offset_size(obj, size);
143 	if (ret) {
144 		dev_err(dev->dev, "could not allocate mmap offset\n");
145 		return 0;
146 	}
147 
148 	return drm_vma_node_offset_addr(&obj->vma_node);
149 }
150 
151 static bool omap_gem_is_contiguous(struct omap_gem_object *omap_obj)
152 {
153 	if (omap_obj->flags & OMAP_BO_MEM_DMA_API)
154 		return true;
155 
156 	if ((omap_obj->flags & OMAP_BO_MEM_DMABUF) && omap_obj->sgt->nents == 1)
157 		return true;
158 
159 	return false;
160 }
161 
162 /* -----------------------------------------------------------------------------
163  * Eviction
164  */
165 
166 static void omap_gem_evict_entry(struct drm_gem_object *obj,
167 		enum tiler_fmt fmt, struct omap_drm_usergart_entry *entry)
168 {
169 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
170 	struct omap_drm_private *priv = obj->dev->dev_private;
171 	int n = priv->usergart[fmt].height;
172 	size_t size = PAGE_SIZE * n;
173 	loff_t off = omap_gem_mmap_offset(obj) +
174 			(entry->obj_pgoff << PAGE_SHIFT);
175 	const int m = DIV_ROUND_UP(omap_obj->width << fmt, PAGE_SIZE);
176 
177 	if (m > 1) {
178 		int i;
179 		/* if stride > than PAGE_SIZE then sparse mapping: */
180 		for (i = n; i > 0; i--) {
181 			unmap_mapping_range(obj->dev->anon_inode->i_mapping,
182 					    off, PAGE_SIZE, 1);
183 			off += PAGE_SIZE * m;
184 		}
185 	} else {
186 		unmap_mapping_range(obj->dev->anon_inode->i_mapping,
187 				    off, size, 1);
188 	}
189 
190 	entry->obj = NULL;
191 }
192 
193 /* Evict a buffer from usergart, if it is mapped there */
194 static void omap_gem_evict(struct drm_gem_object *obj)
195 {
196 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
197 	struct omap_drm_private *priv = obj->dev->dev_private;
198 
199 	if (omap_obj->flags & OMAP_BO_TILED_MASK) {
200 		enum tiler_fmt fmt = gem2fmt(omap_obj->flags);
201 		int i;
202 
203 		for (i = 0; i < NUM_USERGART_ENTRIES; i++) {
204 			struct omap_drm_usergart_entry *entry =
205 				&priv->usergart[fmt].entry[i];
206 
207 			if (entry->obj == obj)
208 				omap_gem_evict_entry(obj, fmt, entry);
209 		}
210 	}
211 }
212 
213 /* -----------------------------------------------------------------------------
214  * Page Management
215  */
216 
217 /*
218  * Ensure backing pages are allocated. Must be called with the omap_obj.lock
219  * held.
220  */
221 static int omap_gem_attach_pages(struct drm_gem_object *obj)
222 {
223 	struct drm_device *dev = obj->dev;
224 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
225 	struct page **pages;
226 	int npages = obj->size >> PAGE_SHIFT;
227 	int i, ret;
228 	dma_addr_t *addrs;
229 
230 	lockdep_assert_held(&omap_obj->lock);
231 
232 	/*
233 	 * If not using shmem (in which case backing pages don't need to be
234 	 * allocated) or if pages are already allocated we're done.
235 	 */
236 	if (!(omap_obj->flags & OMAP_BO_MEM_SHMEM) || omap_obj->pages)
237 		return 0;
238 
239 	pages = drm_gem_get_pages(obj);
240 	if (IS_ERR(pages)) {
241 		dev_err(obj->dev->dev, "could not get pages: %ld\n", PTR_ERR(pages));
242 		return PTR_ERR(pages);
243 	}
244 
245 	/* for non-cached buffers, ensure the new pages are clean because
246 	 * DSS, GPU, etc. are not cache coherent:
247 	 */
248 	if (omap_obj->flags & (OMAP_BO_WC|OMAP_BO_UNCACHED)) {
249 		addrs = kmalloc_array(npages, sizeof(*addrs), GFP_KERNEL);
250 		if (!addrs) {
251 			ret = -ENOMEM;
252 			goto free_pages;
253 		}
254 
255 		for (i = 0; i < npages; i++) {
256 			addrs[i] = dma_map_page(dev->dev, pages[i],
257 					0, PAGE_SIZE, DMA_TO_DEVICE);
258 
259 			if (dma_mapping_error(dev->dev, addrs[i])) {
260 				dev_warn(dev->dev,
261 					"%s: failed to map page\n", __func__);
262 
263 				for (i = i - 1; i >= 0; --i) {
264 					dma_unmap_page(dev->dev, addrs[i],
265 						PAGE_SIZE, DMA_TO_DEVICE);
266 				}
267 
268 				ret = -ENOMEM;
269 				goto free_addrs;
270 			}
271 		}
272 	} else {
273 		addrs = kcalloc(npages, sizeof(*addrs), GFP_KERNEL);
274 		if (!addrs) {
275 			ret = -ENOMEM;
276 			goto free_pages;
277 		}
278 	}
279 
280 	omap_obj->dma_addrs = addrs;
281 	omap_obj->pages = pages;
282 
283 	return 0;
284 
285 free_addrs:
286 	kfree(addrs);
287 free_pages:
288 	drm_gem_put_pages(obj, pages, true, false);
289 
290 	return ret;
291 }
292 
293 /* Release backing pages. Must be called with the omap_obj.lock held. */
294 static void omap_gem_detach_pages(struct drm_gem_object *obj)
295 {
296 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
297 	unsigned int npages = obj->size >> PAGE_SHIFT;
298 	unsigned int i;
299 
300 	lockdep_assert_held(&omap_obj->lock);
301 
302 	for (i = 0; i < npages; i++) {
303 		if (omap_obj->dma_addrs[i])
304 			dma_unmap_page(obj->dev->dev, omap_obj->dma_addrs[i],
305 				       PAGE_SIZE, DMA_TO_DEVICE);
306 	}
307 
308 	kfree(omap_obj->dma_addrs);
309 	omap_obj->dma_addrs = NULL;
310 
311 	drm_gem_put_pages(obj, omap_obj->pages, true, false);
312 	omap_obj->pages = NULL;
313 }
314 
315 /* get buffer flags */
316 u32 omap_gem_flags(struct drm_gem_object *obj)
317 {
318 	return to_omap_bo(obj)->flags;
319 }
320 
321 /** get mmap size */
322 size_t omap_gem_mmap_size(struct drm_gem_object *obj)
323 {
324 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
325 	size_t size = obj->size;
326 
327 	if (omap_obj->flags & OMAP_BO_TILED_MASK) {
328 		/* for tiled buffers, the virtual size has stride rounded up
329 		 * to 4kb.. (to hide the fact that row n+1 might start 16kb or
330 		 * 32kb later!).  But we don't back the entire buffer with
331 		 * pages, only the valid picture part.. so need to adjust for
332 		 * this in the size used to mmap and generate mmap offset
333 		 */
334 		size = tiler_vsize(gem2fmt(omap_obj->flags),
335 				omap_obj->width, omap_obj->height);
336 	}
337 
338 	return size;
339 }
340 
341 /* -----------------------------------------------------------------------------
342  * Fault Handling
343  */
344 
345 /* Normal handling for the case of faulting in non-tiled buffers */
346 static vm_fault_t omap_gem_fault_1d(struct drm_gem_object *obj,
347 		struct vm_area_struct *vma, struct vm_fault *vmf)
348 {
349 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
350 	unsigned long pfn;
351 	pgoff_t pgoff;
352 
353 	/* We don't use vmf->pgoff since that has the fake offset: */
354 	pgoff = (vmf->address - vma->vm_start) >> PAGE_SHIFT;
355 
356 	if (omap_obj->pages) {
357 		omap_gem_cpu_sync_page(obj, pgoff);
358 		pfn = page_to_pfn(omap_obj->pages[pgoff]);
359 	} else {
360 		BUG_ON(!omap_gem_is_contiguous(omap_obj));
361 		pfn = (omap_obj->dma_addr >> PAGE_SHIFT) + pgoff;
362 	}
363 
364 	VERB("Inserting %p pfn %lx, pa %lx", (void *)vmf->address,
365 			pfn, pfn << PAGE_SHIFT);
366 
367 	return vmf_insert_mixed(vma, vmf->address,
368 			__pfn_to_pfn_t(pfn, PFN_DEV));
369 }
370 
371 /* Special handling for the case of faulting in 2d tiled buffers */
372 static vm_fault_t omap_gem_fault_2d(struct drm_gem_object *obj,
373 		struct vm_area_struct *vma, struct vm_fault *vmf)
374 {
375 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
376 	struct omap_drm_private *priv = obj->dev->dev_private;
377 	struct omap_drm_usergart_entry *entry;
378 	enum tiler_fmt fmt = gem2fmt(omap_obj->flags);
379 	struct page *pages[64];  /* XXX is this too much to have on stack? */
380 	unsigned long pfn;
381 	pgoff_t pgoff, base_pgoff;
382 	unsigned long vaddr;
383 	int i, err, slots;
384 	vm_fault_t ret = VM_FAULT_NOPAGE;
385 
386 	/*
387 	 * Note the height of the slot is also equal to the number of pages
388 	 * that need to be mapped in to fill 4kb wide CPU page.  If the slot
389 	 * height is 64, then 64 pages fill a 4kb wide by 64 row region.
390 	 */
391 	const int n = priv->usergart[fmt].height;
392 	const int n_shift = priv->usergart[fmt].height_shift;
393 
394 	/*
395 	 * If buffer width in bytes > PAGE_SIZE then the virtual stride is
396 	 * rounded up to next multiple of PAGE_SIZE.. this need to be taken
397 	 * into account in some of the math, so figure out virtual stride
398 	 * in pages
399 	 */
400 	const int m = DIV_ROUND_UP(omap_obj->width << fmt, PAGE_SIZE);
401 
402 	/* We don't use vmf->pgoff since that has the fake offset: */
403 	pgoff = (vmf->address - vma->vm_start) >> PAGE_SHIFT;
404 
405 	/*
406 	 * Actual address we start mapping at is rounded down to previous slot
407 	 * boundary in the y direction:
408 	 */
409 	base_pgoff = round_down(pgoff, m << n_shift);
410 
411 	/* figure out buffer width in slots */
412 	slots = omap_obj->width >> priv->usergart[fmt].slot_shift;
413 
414 	vaddr = vmf->address - ((pgoff - base_pgoff) << PAGE_SHIFT);
415 
416 	entry = &priv->usergart[fmt].entry[priv->usergart[fmt].last];
417 
418 	/* evict previous buffer using this usergart entry, if any: */
419 	if (entry->obj)
420 		omap_gem_evict_entry(entry->obj, fmt, entry);
421 
422 	entry->obj = obj;
423 	entry->obj_pgoff = base_pgoff;
424 
425 	/* now convert base_pgoff to phys offset from virt offset: */
426 	base_pgoff = (base_pgoff >> n_shift) * slots;
427 
428 	/* for wider-than 4k.. figure out which part of the slot-row we want: */
429 	if (m > 1) {
430 		int off = pgoff % m;
431 		entry->obj_pgoff += off;
432 		base_pgoff /= m;
433 		slots = min(slots - (off << n_shift), n);
434 		base_pgoff += off << n_shift;
435 		vaddr += off << PAGE_SHIFT;
436 	}
437 
438 	/*
439 	 * Map in pages. Beyond the valid pixel part of the buffer, we set
440 	 * pages[i] to NULL to get a dummy page mapped in.. if someone
441 	 * reads/writes it they will get random/undefined content, but at
442 	 * least it won't be corrupting whatever other random page used to
443 	 * be mapped in, or other undefined behavior.
444 	 */
445 	memcpy(pages, &omap_obj->pages[base_pgoff],
446 			sizeof(struct page *) * slots);
447 	memset(pages + slots, 0,
448 			sizeof(struct page *) * (n - slots));
449 
450 	err = tiler_pin(entry->block, pages, ARRAY_SIZE(pages), 0, true);
451 	if (err) {
452 		ret = vmf_error(err);
453 		dev_err(obj->dev->dev, "failed to pin: %d\n", err);
454 		return ret;
455 	}
456 
457 	pfn = entry->dma_addr >> PAGE_SHIFT;
458 
459 	VERB("Inserting %p pfn %lx, pa %lx", (void *)vmf->address,
460 			pfn, pfn << PAGE_SHIFT);
461 
462 	for (i = n; i > 0; i--) {
463 		ret = vmf_insert_mixed(vma,
464 			vaddr, __pfn_to_pfn_t(pfn, PFN_DEV));
465 		if (ret & VM_FAULT_ERROR)
466 			break;
467 		pfn += priv->usergart[fmt].stride_pfn;
468 		vaddr += PAGE_SIZE * m;
469 	}
470 
471 	/* simple round-robin: */
472 	priv->usergart[fmt].last = (priv->usergart[fmt].last + 1)
473 				 % NUM_USERGART_ENTRIES;
474 
475 	return ret;
476 }
477 
478 /**
479  * omap_gem_fault		-	pagefault handler for GEM objects
480  * @vmf: fault detail
481  *
482  * Invoked when a fault occurs on an mmap of a GEM managed area. GEM
483  * does most of the work for us including the actual map/unmap calls
484  * but we need to do the actual page work.
485  *
486  * The VMA was set up by GEM. In doing so it also ensured that the
487  * vma->vm_private_data points to the GEM object that is backing this
488  * mapping.
489  */
490 static vm_fault_t omap_gem_fault(struct vm_fault *vmf)
491 {
492 	struct vm_area_struct *vma = vmf->vma;
493 	struct drm_gem_object *obj = vma->vm_private_data;
494 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
495 	int err;
496 	vm_fault_t ret;
497 
498 	/* Make sure we don't parallel update on a fault, nor move or remove
499 	 * something from beneath our feet
500 	 */
501 	mutex_lock(&omap_obj->lock);
502 
503 	/* if a shmem backed object, make sure we have pages attached now */
504 	err = omap_gem_attach_pages(obj);
505 	if (err) {
506 		ret = vmf_error(err);
507 		goto fail;
508 	}
509 
510 	/* where should we do corresponding put_pages().. we are mapping
511 	 * the original page, rather than thru a GART, so we can't rely
512 	 * on eviction to trigger this.  But munmap() or all mappings should
513 	 * probably trigger put_pages()?
514 	 */
515 
516 	if (omap_obj->flags & OMAP_BO_TILED_MASK)
517 		ret = omap_gem_fault_2d(obj, vma, vmf);
518 	else
519 		ret = omap_gem_fault_1d(obj, vma, vmf);
520 
521 
522 fail:
523 	mutex_unlock(&omap_obj->lock);
524 	return ret;
525 }
526 
527 /** We override mainly to fix up some of the vm mapping flags.. */
528 int omap_gem_mmap(struct file *filp, struct vm_area_struct *vma)
529 {
530 	int ret;
531 
532 	ret = drm_gem_mmap(filp, vma);
533 	if (ret) {
534 		DBG("mmap failed: %d", ret);
535 		return ret;
536 	}
537 
538 	return omap_gem_mmap_obj(vma->vm_private_data, vma);
539 }
540 
541 int omap_gem_mmap_obj(struct drm_gem_object *obj,
542 		struct vm_area_struct *vma)
543 {
544 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
545 
546 	vm_flags_mod(vma, VM_MIXEDMAP, VM_PFNMAP);
547 
548 	if (omap_obj->flags & OMAP_BO_WC) {
549 		vma->vm_page_prot = pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
550 	} else if (omap_obj->flags & OMAP_BO_UNCACHED) {
551 		vma->vm_page_prot = pgprot_noncached(vm_get_page_prot(vma->vm_flags));
552 	} else {
553 		/*
554 		 * We do have some private objects, at least for scanout buffers
555 		 * on hardware without DMM/TILER.  But these are allocated write-
556 		 * combine
557 		 */
558 		if (WARN_ON(!obj->filp))
559 			return -EINVAL;
560 
561 		/*
562 		 * Shunt off cached objs to shmem file so they have their own
563 		 * address_space (so unmap_mapping_range does what we want,
564 		 * in particular in the case of mmap'd dmabufs)
565 		 */
566 		vma->vm_pgoff = 0;
567 		vma_set_file(vma, obj->filp);
568 
569 		vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
570 	}
571 
572 	return 0;
573 }
574 
575 /* -----------------------------------------------------------------------------
576  * Dumb Buffers
577  */
578 
579 /**
580  * omap_gem_dumb_create	-	create a dumb buffer
581  * @file: our client file
582  * @dev: our device
583  * @args: the requested arguments copied from userspace
584  *
585  * Allocate a buffer suitable for use for a frame buffer of the
586  * form described by user space. Give userspace a handle by which
587  * to reference it.
588  */
589 int omap_gem_dumb_create(struct drm_file *file, struct drm_device *dev,
590 		struct drm_mode_create_dumb *args)
591 {
592 	union omap_gem_size gsize;
593 
594 	args->pitch = DIV_ROUND_UP(args->width * args->bpp, 8);
595 
596 	args->size = PAGE_ALIGN(args->pitch * args->height);
597 
598 	gsize = (union omap_gem_size){
599 		.bytes = args->size,
600 	};
601 
602 	return omap_gem_new_handle(dev, file, gsize,
603 			OMAP_BO_SCANOUT | OMAP_BO_WC, &args->handle);
604 }
605 
606 /**
607  * omap_gem_dumb_map_offset - create an offset for a dumb buffer
608  * @file: our drm client file
609  * @dev: drm device
610  * @handle: GEM handle to the object (from dumb_create)
611  * @offset: memory map offset placeholder
612  *
613  * Do the necessary setup to allow the mapping of the frame buffer
614  * into user memory. We don't have to do much here at the moment.
615  */
616 int omap_gem_dumb_map_offset(struct drm_file *file, struct drm_device *dev,
617 		u32 handle, u64 *offset)
618 {
619 	struct drm_gem_object *obj;
620 	int ret = 0;
621 
622 	/* GEM does all our handle to object mapping */
623 	obj = drm_gem_object_lookup(file, handle);
624 	if (obj == NULL) {
625 		ret = -ENOENT;
626 		goto fail;
627 	}
628 
629 	*offset = omap_gem_mmap_offset(obj);
630 
631 	drm_gem_object_put(obj);
632 
633 fail:
634 	return ret;
635 }
636 
637 #ifdef CONFIG_DRM_FBDEV_EMULATION
638 /* Set scrolling position.  This allows us to implement fast scrolling
639  * for console.
640  *
641  * Call only from non-atomic contexts.
642  */
643 int omap_gem_roll(struct drm_gem_object *obj, u32 roll)
644 {
645 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
646 	u32 npages = obj->size >> PAGE_SHIFT;
647 	int ret = 0;
648 
649 	if (roll > npages) {
650 		dev_err(obj->dev->dev, "invalid roll: %d\n", roll);
651 		return -EINVAL;
652 	}
653 
654 	omap_obj->roll = roll;
655 
656 	mutex_lock(&omap_obj->lock);
657 
658 	/* if we aren't mapped yet, we don't need to do anything */
659 	if (omap_obj->block) {
660 		ret = omap_gem_attach_pages(obj);
661 		if (ret)
662 			goto fail;
663 
664 		ret = tiler_pin(omap_obj->block, omap_obj->pages, npages,
665 				roll, true);
666 		if (ret)
667 			dev_err(obj->dev->dev, "could not repin: %d\n", ret);
668 	}
669 
670 fail:
671 	mutex_unlock(&omap_obj->lock);
672 
673 	return ret;
674 }
675 #endif
676 
677 /* -----------------------------------------------------------------------------
678  * Memory Management & DMA Sync
679  */
680 
681 /*
682  * shmem buffers that are mapped cached are not coherent.
683  *
684  * We keep track of dirty pages using page faulting to perform cache management.
685  * When a page is mapped to the CPU in read/write mode the device can't access
686  * it and omap_obj->dma_addrs[i] is NULL. When a page is mapped to the device
687  * the omap_obj->dma_addrs[i] is set to the DMA address, and the page is
688  * unmapped from the CPU.
689  */
690 static inline bool omap_gem_is_cached_coherent(struct drm_gem_object *obj)
691 {
692 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
693 
694 	return !((omap_obj->flags & OMAP_BO_MEM_SHMEM) &&
695 		((omap_obj->flags & OMAP_BO_CACHE_MASK) == OMAP_BO_CACHED));
696 }
697 
698 /* Sync the buffer for CPU access.. note pages should already be
699  * attached, ie. omap_gem_get_pages()
700  */
701 void omap_gem_cpu_sync_page(struct drm_gem_object *obj, int pgoff)
702 {
703 	struct drm_device *dev = obj->dev;
704 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
705 
706 	if (omap_gem_is_cached_coherent(obj))
707 		return;
708 
709 	if (omap_obj->dma_addrs[pgoff]) {
710 		dma_unmap_page(dev->dev, omap_obj->dma_addrs[pgoff],
711 				PAGE_SIZE, DMA_TO_DEVICE);
712 		omap_obj->dma_addrs[pgoff] = 0;
713 	}
714 }
715 
716 /* sync the buffer for DMA access */
717 void omap_gem_dma_sync_buffer(struct drm_gem_object *obj,
718 		enum dma_data_direction dir)
719 {
720 	struct drm_device *dev = obj->dev;
721 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
722 	int i, npages = obj->size >> PAGE_SHIFT;
723 	struct page **pages = omap_obj->pages;
724 	bool dirty = false;
725 
726 	if (omap_gem_is_cached_coherent(obj))
727 		return;
728 
729 	for (i = 0; i < npages; i++) {
730 		if (!omap_obj->dma_addrs[i]) {
731 			dma_addr_t addr;
732 
733 			addr = dma_map_page(dev->dev, pages[i], 0,
734 					    PAGE_SIZE, dir);
735 			if (dma_mapping_error(dev->dev, addr)) {
736 				dev_warn(dev->dev, "%s: failed to map page\n",
737 					__func__);
738 				break;
739 			}
740 
741 			dirty = true;
742 			omap_obj->dma_addrs[i] = addr;
743 		}
744 	}
745 
746 	if (dirty) {
747 		unmap_mapping_range(obj->filp->f_mapping, 0,
748 				    omap_gem_mmap_size(obj), 1);
749 	}
750 }
751 
752 static int omap_gem_pin_tiler(struct drm_gem_object *obj)
753 {
754 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
755 	u32 npages = obj->size >> PAGE_SHIFT;
756 	enum tiler_fmt fmt = gem2fmt(omap_obj->flags);
757 	struct tiler_block *block;
758 	int ret;
759 
760 	BUG_ON(omap_obj->block);
761 
762 	if (omap_obj->flags & OMAP_BO_TILED_MASK) {
763 		block = tiler_reserve_2d(fmt, omap_obj->width, omap_obj->height,
764 					 PAGE_SIZE);
765 	} else {
766 		block = tiler_reserve_1d(obj->size);
767 	}
768 
769 	if (IS_ERR(block)) {
770 		ret = PTR_ERR(block);
771 		dev_err(obj->dev->dev, "could not remap: %d (%d)\n", ret, fmt);
772 		goto fail;
773 	}
774 
775 	/* TODO: enable async refill.. */
776 	ret = tiler_pin(block, omap_obj->pages, npages, omap_obj->roll, true);
777 	if (ret) {
778 		tiler_release(block);
779 		dev_err(obj->dev->dev, "could not pin: %d\n", ret);
780 		goto fail;
781 	}
782 
783 	omap_obj->dma_addr = tiler_ssptr(block);
784 	omap_obj->block = block;
785 
786 	DBG("got dma address: %pad", &omap_obj->dma_addr);
787 
788 fail:
789 	return ret;
790 }
791 
792 /**
793  * omap_gem_pin() - Pin a GEM object in memory
794  * @obj: the GEM object
795  * @dma_addr: the DMA address
796  *
797  * Pin the given GEM object in memory and fill the dma_addr pointer with the
798  * object's DMA address. If the buffer is not physically contiguous it will be
799  * remapped through the TILER to provide a contiguous view.
800  *
801  * Pins are reference-counted, calling this function multiple times is allowed
802  * as long the corresponding omap_gem_unpin() calls are balanced.
803  *
804  * Return 0 on success or a negative error code otherwise.
805  */
806 int omap_gem_pin(struct drm_gem_object *obj, dma_addr_t *dma_addr)
807 {
808 	struct omap_drm_private *priv = obj->dev->dev_private;
809 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
810 	int ret = 0;
811 
812 	mutex_lock(&omap_obj->lock);
813 
814 	if (!omap_gem_is_contiguous(omap_obj)) {
815 		if (refcount_read(&omap_obj->pin_cnt) == 0) {
816 
817 			refcount_set(&omap_obj->pin_cnt, 1);
818 
819 			ret = omap_gem_attach_pages(obj);
820 			if (ret)
821 				goto fail;
822 
823 			if (omap_obj->flags & OMAP_BO_SCANOUT) {
824 				if (priv->has_dmm) {
825 					ret = omap_gem_pin_tiler(obj);
826 					if (ret)
827 						goto fail;
828 				}
829 			}
830 		} else {
831 			refcount_inc(&omap_obj->pin_cnt);
832 		}
833 	}
834 
835 	if (dma_addr)
836 		*dma_addr = omap_obj->dma_addr;
837 
838 fail:
839 	mutex_unlock(&omap_obj->lock);
840 
841 	return ret;
842 }
843 
844 /**
845  * omap_gem_unpin_locked() - Unpin a GEM object from memory
846  * @obj: the GEM object
847  *
848  * omap_gem_unpin() without locking.
849  */
850 static void omap_gem_unpin_locked(struct drm_gem_object *obj)
851 {
852 	struct omap_drm_private *priv = obj->dev->dev_private;
853 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
854 	int ret;
855 
856 	if (omap_gem_is_contiguous(omap_obj))
857 		return;
858 
859 	if (refcount_dec_and_test(&omap_obj->pin_cnt)) {
860 		if (omap_obj->sgt) {
861 			sg_free_table(omap_obj->sgt);
862 			kfree(omap_obj->sgt);
863 			omap_obj->sgt = NULL;
864 		}
865 		if (!(omap_obj->flags & OMAP_BO_SCANOUT))
866 			return;
867 		if (priv->has_dmm) {
868 			ret = tiler_unpin(omap_obj->block);
869 			if (ret) {
870 				dev_err(obj->dev->dev,
871 					"could not unpin pages: %d\n", ret);
872 			}
873 			ret = tiler_release(omap_obj->block);
874 			if (ret) {
875 				dev_err(obj->dev->dev,
876 					"could not release unmap: %d\n", ret);
877 			}
878 			omap_obj->dma_addr = 0;
879 			omap_obj->block = NULL;
880 		}
881 	}
882 }
883 
884 /**
885  * omap_gem_unpin() - Unpin a GEM object from memory
886  * @obj: the GEM object
887  *
888  * Unpin the given GEM object previously pinned with omap_gem_pin(). Pins are
889  * reference-counted, the actual unpin will only be performed when the number
890  * of calls to this function matches the number of calls to omap_gem_pin().
891  */
892 void omap_gem_unpin(struct drm_gem_object *obj)
893 {
894 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
895 
896 	mutex_lock(&omap_obj->lock);
897 	omap_gem_unpin_locked(obj);
898 	mutex_unlock(&omap_obj->lock);
899 }
900 
901 /* Get rotated scanout address (only valid if already pinned), at the
902  * specified orientation and x,y offset from top-left corner of buffer
903  * (only valid for tiled 2d buffers)
904  */
905 int omap_gem_rotated_dma_addr(struct drm_gem_object *obj, u32 orient,
906 		int x, int y, dma_addr_t *dma_addr)
907 {
908 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
909 	int ret = -EINVAL;
910 
911 	mutex_lock(&omap_obj->lock);
912 
913 	if ((refcount_read(&omap_obj->pin_cnt) > 0) && omap_obj->block &&
914 			(omap_obj->flags & OMAP_BO_TILED_MASK)) {
915 		*dma_addr = tiler_tsptr(omap_obj->block, orient, x, y);
916 		ret = 0;
917 	}
918 
919 	mutex_unlock(&omap_obj->lock);
920 
921 	return ret;
922 }
923 
924 /* Get tiler stride for the buffer (only valid for 2d tiled buffers) */
925 int omap_gem_tiled_stride(struct drm_gem_object *obj, u32 orient)
926 {
927 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
928 	int ret = -EINVAL;
929 	if (omap_obj->flags & OMAP_BO_TILED_MASK)
930 		ret = tiler_stride(gem2fmt(omap_obj->flags), orient);
931 	return ret;
932 }
933 
934 /* if !remap, and we don't have pages backing, then fail, rather than
935  * increasing the pin count (which we don't really do yet anyways,
936  * because we don't support swapping pages back out).  And 'remap'
937  * might not be quite the right name, but I wanted to keep it working
938  * similarly to omap_gem_pin().  Note though that mutex is not
939  * aquired if !remap (because this can be called in atomic ctxt),
940  * but probably omap_gem_unpin() should be changed to work in the
941  * same way.  If !remap, a matching omap_gem_put_pages() call is not
942  * required (and should not be made).
943  */
944 int omap_gem_get_pages(struct drm_gem_object *obj, struct page ***pages,
945 		bool remap)
946 {
947 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
948 	int ret = 0;
949 
950 	mutex_lock(&omap_obj->lock);
951 
952 	if (remap) {
953 		ret = omap_gem_attach_pages(obj);
954 		if (ret)
955 			goto unlock;
956 	}
957 
958 	if (!omap_obj->pages) {
959 		ret = -ENOMEM;
960 		goto unlock;
961 	}
962 
963 	*pages = omap_obj->pages;
964 
965 unlock:
966 	mutex_unlock(&omap_obj->lock);
967 
968 	return ret;
969 }
970 
971 /* release pages when DMA no longer being performed */
972 int omap_gem_put_pages(struct drm_gem_object *obj)
973 {
974 	/* do something here if we dynamically attach/detach pages.. at
975 	 * least they would no longer need to be pinned if everyone has
976 	 * released the pages..
977 	 */
978 	return 0;
979 }
980 
981 struct sg_table *omap_gem_get_sg(struct drm_gem_object *obj,
982 		enum dma_data_direction dir)
983 {
984 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
985 	dma_addr_t addr;
986 	struct sg_table *sgt;
987 	struct scatterlist *sg;
988 	unsigned int count, len, stride, i;
989 	int ret;
990 
991 	ret = omap_gem_pin(obj, &addr);
992 	if (ret)
993 		return ERR_PTR(ret);
994 
995 	mutex_lock(&omap_obj->lock);
996 
997 	sgt = omap_obj->sgt;
998 	if (sgt)
999 		goto out;
1000 
1001 	sgt = kzalloc(sizeof(*sgt), GFP_KERNEL);
1002 	if (!sgt) {
1003 		ret = -ENOMEM;
1004 		goto err_unpin;
1005 	}
1006 
1007 	if (addr) {
1008 		if (omap_obj->flags & OMAP_BO_TILED_MASK) {
1009 			enum tiler_fmt fmt = gem2fmt(omap_obj->flags);
1010 
1011 			len = omap_obj->width << (int)fmt;
1012 			count = omap_obj->height;
1013 			stride = tiler_stride(fmt, 0);
1014 		} else {
1015 			len = obj->size;
1016 			count = 1;
1017 			stride = 0;
1018 		}
1019 	} else {
1020 		count = obj->size >> PAGE_SHIFT;
1021 	}
1022 
1023 	ret = sg_alloc_table(sgt, count, GFP_KERNEL);
1024 	if (ret)
1025 		goto err_free;
1026 
1027 	/* this must be after omap_gem_pin() to ensure we have pages attached */
1028 	omap_gem_dma_sync_buffer(obj, dir);
1029 
1030 	if (addr) {
1031 		for_each_sg(sgt->sgl, sg, count, i) {
1032 			sg_set_page(sg, phys_to_page(addr), len,
1033 				offset_in_page(addr));
1034 			sg_dma_address(sg) = addr;
1035 			sg_dma_len(sg) = len;
1036 
1037 			addr += stride;
1038 		}
1039 	} else {
1040 		for_each_sg(sgt->sgl, sg, count, i) {
1041 			sg_set_page(sg, omap_obj->pages[i], PAGE_SIZE, 0);
1042 			sg_dma_address(sg) = omap_obj->dma_addrs[i];
1043 			sg_dma_len(sg) =  PAGE_SIZE;
1044 		}
1045 	}
1046 
1047 	omap_obj->sgt = sgt;
1048 out:
1049 	mutex_unlock(&omap_obj->lock);
1050 	return sgt;
1051 
1052 err_free:
1053 	kfree(sgt);
1054 err_unpin:
1055 	mutex_unlock(&omap_obj->lock);
1056 	omap_gem_unpin(obj);
1057 	return ERR_PTR(ret);
1058 }
1059 
1060 void omap_gem_put_sg(struct drm_gem_object *obj, struct sg_table *sgt)
1061 {
1062 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
1063 
1064 	if (WARN_ON(omap_obj->sgt != sgt))
1065 		return;
1066 
1067 	omap_gem_unpin(obj);
1068 }
1069 
1070 #ifdef CONFIG_DRM_FBDEV_EMULATION
1071 /*
1072  * Get kernel virtual address for CPU access.. this more or less only
1073  * exists for omap_fbdev.
1074  */
1075 void *omap_gem_vaddr(struct drm_gem_object *obj)
1076 {
1077 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
1078 	void *vaddr;
1079 	int ret;
1080 
1081 	mutex_lock(&omap_obj->lock);
1082 
1083 	if (!omap_obj->vaddr) {
1084 		ret = omap_gem_attach_pages(obj);
1085 		if (ret) {
1086 			vaddr = ERR_PTR(ret);
1087 			goto unlock;
1088 		}
1089 
1090 		omap_obj->vaddr = vmap(omap_obj->pages, obj->size >> PAGE_SHIFT,
1091 				VM_MAP, pgprot_writecombine(PAGE_KERNEL));
1092 	}
1093 
1094 	vaddr = omap_obj->vaddr;
1095 
1096 unlock:
1097 	mutex_unlock(&omap_obj->lock);
1098 	return vaddr;
1099 }
1100 #endif
1101 
1102 /* -----------------------------------------------------------------------------
1103  * Power Management
1104  */
1105 
1106 #ifdef CONFIG_PM
1107 /* re-pin objects in DMM in resume path: */
1108 int omap_gem_resume(struct drm_device *dev)
1109 {
1110 	struct omap_drm_private *priv = dev->dev_private;
1111 	struct omap_gem_object *omap_obj;
1112 	int ret = 0;
1113 
1114 	mutex_lock(&priv->list_lock);
1115 	list_for_each_entry(omap_obj, &priv->obj_list, mm_list) {
1116 		if (omap_obj->block) {
1117 			struct drm_gem_object *obj = &omap_obj->base;
1118 			u32 npages = obj->size >> PAGE_SHIFT;
1119 
1120 			WARN_ON(!omap_obj->pages);  /* this can't happen */
1121 			ret = tiler_pin(omap_obj->block,
1122 					omap_obj->pages, npages,
1123 					omap_obj->roll, true);
1124 			if (ret) {
1125 				dev_err(dev->dev, "could not repin: %d\n", ret);
1126 				goto done;
1127 			}
1128 		}
1129 	}
1130 
1131 done:
1132 	mutex_unlock(&priv->list_lock);
1133 	return ret;
1134 }
1135 #endif
1136 
1137 /* -----------------------------------------------------------------------------
1138  * DebugFS
1139  */
1140 
1141 #ifdef CONFIG_DEBUG_FS
1142 void omap_gem_describe(struct drm_gem_object *obj, struct seq_file *m)
1143 {
1144 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
1145 	u64 off;
1146 
1147 	off = drm_vma_node_start(&obj->vma_node);
1148 
1149 	mutex_lock(&omap_obj->lock);
1150 
1151 	seq_printf(m, "%08x: %2d (%2d) %08llx %pad (%2d) %p %4d",
1152 			omap_obj->flags, obj->name, kref_read(&obj->refcount),
1153 			off, &omap_obj->dma_addr,
1154 			refcount_read(&omap_obj->pin_cnt),
1155 			omap_obj->vaddr, omap_obj->roll);
1156 
1157 	if (omap_obj->flags & OMAP_BO_TILED_MASK) {
1158 		seq_printf(m, " %dx%d", omap_obj->width, omap_obj->height);
1159 		if (omap_obj->block) {
1160 			struct tcm_area *area = &omap_obj->block->area;
1161 			seq_printf(m, " (%dx%d, %dx%d)",
1162 					area->p0.x, area->p0.y,
1163 					area->p1.x, area->p1.y);
1164 		}
1165 	} else {
1166 		seq_printf(m, " %zu", obj->size);
1167 	}
1168 
1169 	mutex_unlock(&omap_obj->lock);
1170 
1171 	seq_printf(m, "\n");
1172 }
1173 
1174 void omap_gem_describe_objects(struct list_head *list, struct seq_file *m)
1175 {
1176 	struct omap_gem_object *omap_obj;
1177 	int count = 0;
1178 	size_t size = 0;
1179 
1180 	list_for_each_entry(omap_obj, list, mm_list) {
1181 		struct drm_gem_object *obj = &omap_obj->base;
1182 		seq_printf(m, "   ");
1183 		omap_gem_describe(obj, m);
1184 		count++;
1185 		size += obj->size;
1186 	}
1187 
1188 	seq_printf(m, "Total %d objects, %zu bytes\n", count, size);
1189 }
1190 #endif
1191 
1192 /* -----------------------------------------------------------------------------
1193  * Constructor & Destructor
1194  */
1195 
1196 static void omap_gem_free_object(struct drm_gem_object *obj)
1197 {
1198 	struct drm_device *dev = obj->dev;
1199 	struct omap_drm_private *priv = dev->dev_private;
1200 	struct omap_gem_object *omap_obj = to_omap_bo(obj);
1201 
1202 	omap_gem_evict(obj);
1203 
1204 	mutex_lock(&priv->list_lock);
1205 	list_del(&omap_obj->mm_list);
1206 	mutex_unlock(&priv->list_lock);
1207 
1208 	/*
1209 	 * We own the sole reference to the object at this point, but to keep
1210 	 * lockdep happy, we must still take the omap_obj_lock to call
1211 	 * omap_gem_detach_pages(). This should hardly make any difference as
1212 	 * there can't be any lock contention.
1213 	 */
1214 	mutex_lock(&omap_obj->lock);
1215 
1216 	/* The object should not be pinned. */
1217 	WARN_ON(refcount_read(&omap_obj->pin_cnt) > 0);
1218 
1219 	if (omap_obj->pages) {
1220 		if (omap_obj->flags & OMAP_BO_MEM_DMABUF)
1221 			kfree(omap_obj->pages);
1222 		else
1223 			omap_gem_detach_pages(obj);
1224 	}
1225 
1226 	if (omap_obj->flags & OMAP_BO_MEM_DMA_API) {
1227 		dma_free_wc(dev->dev, obj->size, omap_obj->vaddr,
1228 			    omap_obj->dma_addr);
1229 	} else if (omap_obj->vaddr) {
1230 		vunmap(omap_obj->vaddr);
1231 	} else if (obj->import_attach) {
1232 		drm_prime_gem_destroy(obj, omap_obj->sgt);
1233 	}
1234 
1235 	mutex_unlock(&omap_obj->lock);
1236 
1237 	drm_gem_object_release(obj);
1238 
1239 	mutex_destroy(&omap_obj->lock);
1240 
1241 	kfree(omap_obj);
1242 }
1243 
1244 static bool omap_gem_validate_flags(struct drm_device *dev, u32 flags)
1245 {
1246 	struct omap_drm_private *priv = dev->dev_private;
1247 
1248 	switch (flags & OMAP_BO_CACHE_MASK) {
1249 	case OMAP_BO_CACHED:
1250 	case OMAP_BO_WC:
1251 	case OMAP_BO_CACHE_MASK:
1252 		break;
1253 
1254 	default:
1255 		return false;
1256 	}
1257 
1258 	if (flags & OMAP_BO_TILED_MASK) {
1259 		if (!priv->usergart)
1260 			return false;
1261 
1262 		switch (flags & OMAP_BO_TILED_MASK) {
1263 		case OMAP_BO_TILED_8:
1264 		case OMAP_BO_TILED_16:
1265 		case OMAP_BO_TILED_32:
1266 			break;
1267 
1268 		default:
1269 			return false;
1270 		}
1271 	}
1272 
1273 	return true;
1274 }
1275 
1276 static const struct vm_operations_struct omap_gem_vm_ops = {
1277 	.fault = omap_gem_fault,
1278 	.open = drm_gem_vm_open,
1279 	.close = drm_gem_vm_close,
1280 };
1281 
1282 static const struct drm_gem_object_funcs omap_gem_object_funcs = {
1283 	.free = omap_gem_free_object,
1284 	.export = omap_gem_prime_export,
1285 	.vm_ops = &omap_gem_vm_ops,
1286 };
1287 
1288 /* GEM buffer object constructor */
1289 struct drm_gem_object *omap_gem_new(struct drm_device *dev,
1290 		union omap_gem_size gsize, u32 flags)
1291 {
1292 	struct omap_drm_private *priv = dev->dev_private;
1293 	struct omap_gem_object *omap_obj;
1294 	struct drm_gem_object *obj;
1295 	struct address_space *mapping;
1296 	size_t size;
1297 	int ret;
1298 
1299 	if (!omap_gem_validate_flags(dev, flags))
1300 		return NULL;
1301 
1302 	/* Validate the flags and compute the memory and cache flags. */
1303 	if (flags & OMAP_BO_TILED_MASK) {
1304 		/*
1305 		 * Tiled buffers are always shmem paged backed. When they are
1306 		 * scanned out, they are remapped into DMM/TILER.
1307 		 */
1308 		flags |= OMAP_BO_MEM_SHMEM;
1309 
1310 		/*
1311 		 * Currently don't allow cached buffers. There is some caching
1312 		 * stuff that needs to be handled better.
1313 		 */
1314 		flags &= ~(OMAP_BO_CACHED|OMAP_BO_WC|OMAP_BO_UNCACHED);
1315 		flags |= tiler_get_cpu_cache_flags();
1316 	} else if ((flags & OMAP_BO_SCANOUT) && !priv->has_dmm) {
1317 		/*
1318 		 * If we don't have DMM, we must allocate scanout buffers
1319 		 * from contiguous DMA memory.
1320 		 */
1321 		flags |= OMAP_BO_MEM_DMA_API;
1322 	} else if (!(flags & OMAP_BO_MEM_DMABUF)) {
1323 		/*
1324 		 * All other buffers not backed by dma_buf are shmem-backed.
1325 		 */
1326 		flags |= OMAP_BO_MEM_SHMEM;
1327 	}
1328 
1329 	/* Allocate the initialize the OMAP GEM object. */
1330 	omap_obj = kzalloc(sizeof(*omap_obj), GFP_KERNEL);
1331 	if (!omap_obj)
1332 		return NULL;
1333 
1334 	obj = &omap_obj->base;
1335 	omap_obj->flags = flags;
1336 	mutex_init(&omap_obj->lock);
1337 
1338 	if (flags & OMAP_BO_TILED_MASK) {
1339 		/*
1340 		 * For tiled buffers align dimensions to slot boundaries and
1341 		 * calculate size based on aligned dimensions.
1342 		 */
1343 		tiler_align(gem2fmt(flags), &gsize.tiled.width,
1344 			    &gsize.tiled.height);
1345 
1346 		size = tiler_size(gem2fmt(flags), gsize.tiled.width,
1347 				  gsize.tiled.height);
1348 
1349 		omap_obj->width = gsize.tiled.width;
1350 		omap_obj->height = gsize.tiled.height;
1351 	} else {
1352 		size = PAGE_ALIGN(gsize.bytes);
1353 	}
1354 
1355 	obj->funcs = &omap_gem_object_funcs;
1356 
1357 	/* Initialize the GEM object. */
1358 	if (!(flags & OMAP_BO_MEM_SHMEM)) {
1359 		drm_gem_private_object_init(dev, obj, size);
1360 	} else {
1361 		ret = drm_gem_object_init(dev, obj, size);
1362 		if (ret)
1363 			goto err_free;
1364 
1365 		mapping = obj->filp->f_mapping;
1366 		mapping_set_gfp_mask(mapping, GFP_USER | __GFP_DMA32);
1367 	}
1368 
1369 	/* Allocate memory if needed. */
1370 	if (flags & OMAP_BO_MEM_DMA_API) {
1371 		omap_obj->vaddr = dma_alloc_wc(dev->dev, size,
1372 					       &omap_obj->dma_addr,
1373 					       GFP_KERNEL);
1374 		if (!omap_obj->vaddr)
1375 			goto err_release;
1376 	}
1377 
1378 	mutex_lock(&priv->list_lock);
1379 	list_add(&omap_obj->mm_list, &priv->obj_list);
1380 	mutex_unlock(&priv->list_lock);
1381 
1382 	return obj;
1383 
1384 err_release:
1385 	drm_gem_object_release(obj);
1386 err_free:
1387 	kfree(omap_obj);
1388 	return NULL;
1389 }
1390 
1391 struct drm_gem_object *omap_gem_new_dmabuf(struct drm_device *dev, size_t size,
1392 					   struct sg_table *sgt)
1393 {
1394 	struct omap_drm_private *priv = dev->dev_private;
1395 	struct omap_gem_object *omap_obj;
1396 	struct drm_gem_object *obj;
1397 	union omap_gem_size gsize;
1398 
1399 	/* Without a DMM only physically contiguous buffers can be supported. */
1400 	if (sgt->orig_nents != 1 && !priv->has_dmm)
1401 		return ERR_PTR(-EINVAL);
1402 
1403 	gsize.bytes = PAGE_ALIGN(size);
1404 	obj = omap_gem_new(dev, gsize, OMAP_BO_MEM_DMABUF | OMAP_BO_WC);
1405 	if (!obj)
1406 		return ERR_PTR(-ENOMEM);
1407 
1408 	omap_obj = to_omap_bo(obj);
1409 
1410 	mutex_lock(&omap_obj->lock);
1411 
1412 	omap_obj->sgt = sgt;
1413 
1414 	if (sgt->orig_nents == 1) {
1415 		omap_obj->dma_addr = sg_dma_address(sgt->sgl);
1416 	} else {
1417 		/* Create pages list from sgt */
1418 		struct page **pages;
1419 		unsigned int npages;
1420 		unsigned int ret;
1421 
1422 		npages = DIV_ROUND_UP(size, PAGE_SIZE);
1423 		pages = kcalloc(npages, sizeof(*pages), GFP_KERNEL);
1424 		if (!pages) {
1425 			omap_gem_free_object(obj);
1426 			obj = ERR_PTR(-ENOMEM);
1427 			goto done;
1428 		}
1429 
1430 		omap_obj->pages = pages;
1431 		ret = drm_prime_sg_to_page_array(sgt, pages, npages);
1432 		if (ret) {
1433 			omap_gem_free_object(obj);
1434 			obj = ERR_PTR(-ENOMEM);
1435 			goto done;
1436 		}
1437 	}
1438 
1439 done:
1440 	mutex_unlock(&omap_obj->lock);
1441 	return obj;
1442 }
1443 
1444 /* convenience method to construct a GEM buffer object, and userspace handle */
1445 int omap_gem_new_handle(struct drm_device *dev, struct drm_file *file,
1446 		union omap_gem_size gsize, u32 flags, u32 *handle)
1447 {
1448 	struct drm_gem_object *obj;
1449 	int ret;
1450 
1451 	obj = omap_gem_new(dev, gsize, flags);
1452 	if (!obj)
1453 		return -ENOMEM;
1454 
1455 	ret = drm_gem_handle_create(file, obj, handle);
1456 	if (ret) {
1457 		omap_gem_free_object(obj);
1458 		return ret;
1459 	}
1460 
1461 	/* drop reference from allocate - handle holds it now */
1462 	drm_gem_object_put(obj);
1463 
1464 	return 0;
1465 }
1466 
1467 /* -----------------------------------------------------------------------------
1468  * Init & Cleanup
1469  */
1470 
1471 /* If DMM is used, we need to set some stuff up.. */
1472 void omap_gem_init(struct drm_device *dev)
1473 {
1474 	struct omap_drm_private *priv = dev->dev_private;
1475 	struct omap_drm_usergart *usergart;
1476 	const enum tiler_fmt fmts[] = {
1477 			TILFMT_8BIT, TILFMT_16BIT, TILFMT_32BIT
1478 	};
1479 	int i, j;
1480 
1481 	if (!dmm_is_available()) {
1482 		/* DMM only supported on OMAP4 and later, so this isn't fatal */
1483 		dev_warn(dev->dev, "DMM not available, disable DMM support\n");
1484 		return;
1485 	}
1486 
1487 	usergart = kcalloc(3, sizeof(*usergart), GFP_KERNEL);
1488 	if (!usergart)
1489 		return;
1490 
1491 	/* reserve 4k aligned/wide regions for userspace mappings: */
1492 	for (i = 0; i < ARRAY_SIZE(fmts); i++) {
1493 		u16 h = 1, w = PAGE_SIZE >> i;
1494 
1495 		tiler_align(fmts[i], &w, &h);
1496 		/* note: since each region is 1 4kb page wide, and minimum
1497 		 * number of rows, the height ends up being the same as the
1498 		 * # of pages in the region
1499 		 */
1500 		usergart[i].height = h;
1501 		usergart[i].height_shift = ilog2(h);
1502 		usergart[i].stride_pfn = tiler_stride(fmts[i], 0) >> PAGE_SHIFT;
1503 		usergart[i].slot_shift = ilog2((PAGE_SIZE / h) >> i);
1504 		for (j = 0; j < NUM_USERGART_ENTRIES; j++) {
1505 			struct omap_drm_usergart_entry *entry;
1506 			struct tiler_block *block;
1507 
1508 			entry = &usergart[i].entry[j];
1509 			block = tiler_reserve_2d(fmts[i], w, h, PAGE_SIZE);
1510 			if (IS_ERR(block)) {
1511 				dev_err(dev->dev,
1512 						"reserve failed: %d, %d, %ld\n",
1513 						i, j, PTR_ERR(block));
1514 				return;
1515 			}
1516 			entry->dma_addr = tiler_ssptr(block);
1517 			entry->block = block;
1518 
1519 			DBG("%d:%d: %dx%d: dma_addr=%pad stride=%d", i, j, w, h,
1520 					&entry->dma_addr,
1521 					usergart[i].stride_pfn << PAGE_SHIFT);
1522 		}
1523 	}
1524 
1525 	priv->usergart = usergart;
1526 	priv->has_dmm = true;
1527 }
1528 
1529 void omap_gem_deinit(struct drm_device *dev)
1530 {
1531 	struct omap_drm_private *priv = dev->dev_private;
1532 
1533 	/* I believe we can rely on there being no more outstanding GEM
1534 	 * objects which could depend on usergart/dmm at this point.
1535 	 */
1536 	kfree(priv->usergart);
1537 }
1538