staging: drm/omap: mmap of tiled buffers with stride >4kb
[firefly-linux-kernel-4.4.55.git] / drivers / staging / omapdrm / omap_gem.c
1 /*
2  * drivers/staging/omapdrm/omap_gem.c
3  *
4  * Copyright (C) 2011 Texas Instruments
5  * Author: Rob Clark <rob.clark@linaro.org>
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License version 2 as published by
9  * the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20
21 #include <linux/spinlock.h>
22 #include <linux/shmem_fs.h>
23
24 #include "omap_drv.h"
25 #include "omap_dmm_tiler.h"
26
27 /* remove these once drm core helpers are merged */
28 struct page ** _drm_gem_get_pages(struct drm_gem_object *obj, gfp_t gfpmask);
29 void _drm_gem_put_pages(struct drm_gem_object *obj, struct page **pages,
30                 bool dirty, bool accessed);
31 int _drm_gem_create_mmap_offset_size(struct drm_gem_object *obj, size_t size);
32
33 /*
34  * GEM buffer object implementation.
35  */
36
37 #define to_omap_bo(x) container_of(x, struct omap_gem_object, base)
38
39 /* note: we use upper 8 bits of flags for driver-internal flags: */
40 #define OMAP_BO_DMA                     0x01000000      /* actually is physically contiguous */
41 #define OMAP_BO_EXT_SYNC        0x02000000      /* externally allocated sync object */
42 #define OMAP_BO_EXT_MEM         0x04000000      /* externally allocated memory */
43
44
45 struct omap_gem_object {
46         struct drm_gem_object base;
47
48         struct list_head mm_list;
49
50         uint32_t flags;
51
52         /** width/height for tiled formats (rounded up to slot boundaries) */
53         uint16_t width, height;
54
55         /** roll applied when mapping to DMM */
56         uint32_t roll;
57
58         /**
59          * If buffer is allocated physically contiguous, the OMAP_BO_DMA flag
60          * is set and the paddr is valid.  Also if the buffer is remapped in
61          * TILER and paddr_cnt > 0, then paddr is valid.  But if you are using
62          * the physical address and OMAP_BO_DMA is not set, then you should
63          * be going thru omap_gem_{get,put}_paddr() to ensure the mapping is
64          * not removed from under your feet.
65          *
66          * Note that OMAP_BO_SCANOUT is a hint from userspace that DMA capable
67          * buffer is requested, but doesn't mean that it is.  Use the
68          * OMAP_BO_DMA flag to determine if the buffer has a DMA capable
69          * physical address.
70          */
71         dma_addr_t paddr;
72
73         /**
74          * # of users of paddr
75          */
76         uint32_t paddr_cnt;
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 *addrs;
91
92         /**
93          * Virtual address, if mapped.
94          */
95         void *vaddr;
96
97         /**
98          * sync-object allocated on demand (if needed)
99          *
100          * Per-buffer sync-object for tracking pending and completed hw/dma
101          * read and write operations.  The layout in memory is dictated by
102          * the SGX firmware, which uses this information to stall the command
103          * stream if a surface is not ready yet.
104          *
105          * Note that when buffer is used by SGX, the sync-object needs to be
106          * allocated from a special heap of sync-objects.  This way many sync
107          * objects can be packed in a page, and not waste GPU virtual address
108          * space.  Because of this we have to have a omap_gem_set_sync_object()
109          * API to allow replacement of the syncobj after it has (potentially)
110          * already been allocated.  A bit ugly but I haven't thought of a
111          * better alternative.
112          */
113         struct {
114                 uint32_t write_pending;
115                 uint32_t write_complete;
116                 uint32_t read_pending;
117                 uint32_t read_complete;
118         } *sync;
119 };
120
121 static int get_pages(struct drm_gem_object *obj, struct page ***pages);
122 static uint64_t mmap_offset(struct drm_gem_object *obj);
123
124 /* To deal with userspace mmap'ings of 2d tiled buffers, which (a) are
125  * not necessarily pinned in TILER all the time, and (b) when they are
126  * they are not necessarily page aligned, we reserve one or more small
127  * regions in each of the 2d containers to use as a user-GART where we
128  * can create a second page-aligned mapping of parts of the buffer
129  * being accessed from userspace.
130  *
131  * Note that we could optimize slightly when we know that multiple
132  * tiler containers are backed by the same PAT.. but I'll leave that
133  * for later..
134  */
135 #define NUM_USERGART_ENTRIES 2
136 struct usergart_entry {
137         struct tiler_block *block;      /* the reserved tiler block */
138         dma_addr_t paddr;
139         struct drm_gem_object *obj;     /* the current pinned obj */
140         pgoff_t obj_pgoff;              /* page offset of obj currently
141                                            mapped in */
142 };
143 static struct {
144         struct usergart_entry entry[NUM_USERGART_ENTRIES];
145         int height;                             /* height in rows */
146         int height_shift;               /* ilog2(height in rows) */
147         int slot_shift;                 /* ilog2(width per slot) */
148         int stride_pfn;                 /* stride in pages */
149         int last;                               /* index of last used entry */
150 } *usergart;
151
152 static void evict_entry(struct drm_gem_object *obj,
153                 enum tiler_fmt fmt, struct usergart_entry *entry)
154 {
155         if (obj->dev->dev_mapping) {
156                 struct omap_gem_object *omap_obj = to_omap_bo(obj);
157                 int n = usergart[fmt].height;
158                 size_t size = PAGE_SIZE * n;
159                 loff_t off = mmap_offset(obj) +
160                                 (entry->obj_pgoff << PAGE_SHIFT);
161                 const int m = 1 + ((omap_obj->width << fmt) / PAGE_SIZE);
162                 if (m > 1) {
163                         int i;
164                         /* if stride > than PAGE_SIZE then sparse mapping: */
165                         for (i = n; i > 0; i--) {
166                                 unmap_mapping_range(obj->dev->dev_mapping,
167                                                 off, PAGE_SIZE, 1);
168                                 off += PAGE_SIZE * m;
169                         }
170                 } else {
171                         unmap_mapping_range(obj->dev->dev_mapping, off, size, 1);
172                 }
173         }
174
175         entry->obj = NULL;
176 }
177
178 /* Evict a buffer from usergart, if it is mapped there */
179 static void evict(struct drm_gem_object *obj)
180 {
181         struct omap_gem_object *omap_obj = to_omap_bo(obj);
182
183         if (omap_obj->flags & OMAP_BO_TILED) {
184                 enum tiler_fmt fmt = gem2fmt(omap_obj->flags);
185                 int i;
186
187                 if (!usergart)
188                         return;
189
190                 for (i = 0; i < NUM_USERGART_ENTRIES; i++) {
191                         struct usergart_entry *entry = &usergart[fmt].entry[i];
192                         if (entry->obj == obj)
193                                 evict_entry(obj, fmt, entry);
194                 }
195         }
196 }
197
198 /* GEM objects can either be allocated from contiguous memory (in which
199  * case obj->filp==NULL), or w/ shmem backing (obj->filp!=NULL).  But non
200  * contiguous buffers can be remapped in TILER/DMM if they need to be
201  * contiguous... but we don't do this all the time to reduce pressure
202  * on TILER/DMM space when we know at allocation time that the buffer
203  * will need to be scanned out.
204  */
205 static inline bool is_shmem(struct drm_gem_object *obj)
206 {
207         return obj->filp != NULL;
208 }
209
210 static DEFINE_SPINLOCK(sync_lock);
211
212 /** ensure backing pages are allocated */
213 static int omap_gem_attach_pages(struct drm_gem_object *obj)
214 {
215         struct omap_gem_object *omap_obj = to_omap_bo(obj);
216         struct page **pages;
217
218         WARN_ON(omap_obj->pages);
219
220         /* TODO: __GFP_DMA32 .. but somehow GFP_HIGHMEM is coming from the
221          * mapping_gfp_mask(mapping) which conflicts w/ GFP_DMA32.. probably
222          * we actually want CMA memory for it all anyways..
223          */
224         pages = _drm_gem_get_pages(obj, GFP_KERNEL);
225         if (IS_ERR(pages)) {
226                 dev_err(obj->dev->dev, "could not get pages: %ld\n", PTR_ERR(pages));
227                 return PTR_ERR(pages);
228         }
229
230         /* for non-cached buffers, ensure the new pages are clean because
231          * DSS, GPU, etc. are not cache coherent:
232          */
233         if (omap_obj->flags & (OMAP_BO_WC|OMAP_BO_UNCACHED)) {
234                 int i, npages = obj->size >> PAGE_SHIFT;
235                 dma_addr_t *addrs = kmalloc(npages * sizeof(addrs), GFP_KERNEL);
236                 for (i = 0; i < npages; i++) {
237                         addrs[i] = dma_map_page(obj->dev->dev, pages[i],
238                                         0, PAGE_SIZE, DMA_BIDIRECTIONAL);
239                 }
240                 omap_obj->addrs = addrs;
241         }
242
243         omap_obj->pages = pages;
244         return 0;
245 }
246
247 /** release backing pages */
248 static void omap_gem_detach_pages(struct drm_gem_object *obj)
249 {
250         struct omap_gem_object *omap_obj = to_omap_bo(obj);
251
252         /* for non-cached buffers, ensure the new pages are clean because
253          * DSS, GPU, etc. are not cache coherent:
254          */
255         if (omap_obj->flags & (OMAP_BO_WC|OMAP_BO_UNCACHED)) {
256                 int i, npages = obj->size >> PAGE_SHIFT;
257                 for (i = 0; i < npages; i++) {
258                         dma_unmap_page(obj->dev->dev, omap_obj->addrs[i],
259                                         PAGE_SIZE, DMA_BIDIRECTIONAL);
260                 }
261                 kfree(omap_obj->addrs);
262                 omap_obj->addrs = NULL;
263         }
264
265         _drm_gem_put_pages(obj, omap_obj->pages, true, false);
266         omap_obj->pages = NULL;
267 }
268
269 /** get mmap offset */
270 static uint64_t mmap_offset(struct drm_gem_object *obj)
271 {
272         struct drm_device *dev = obj->dev;
273
274         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
275
276         if (!obj->map_list.map) {
277                 /* Make it mmapable */
278                 size_t size = omap_gem_mmap_size(obj);
279                 int ret = _drm_gem_create_mmap_offset_size(obj, size);
280
281                 if (ret) {
282                         dev_err(dev->dev, "could not allocate mmap offset\n");
283                         return 0;
284                 }
285         }
286
287         return (uint64_t)obj->map_list.hash.key << PAGE_SHIFT;
288 }
289
290 uint64_t omap_gem_mmap_offset(struct drm_gem_object *obj)
291 {
292         uint64_t offset;
293         mutex_lock(&obj->dev->struct_mutex);
294         offset = mmap_offset(obj);
295         mutex_unlock(&obj->dev->struct_mutex);
296         return offset;
297 }
298
299 /** get mmap size */
300 size_t omap_gem_mmap_size(struct drm_gem_object *obj)
301 {
302         struct omap_gem_object *omap_obj = to_omap_bo(obj);
303         size_t size = obj->size;
304
305         if (omap_obj->flags & OMAP_BO_TILED) {
306                 /* for tiled buffers, the virtual size has stride rounded up
307                  * to 4kb.. (to hide the fact that row n+1 might start 16kb or
308                  * 32kb later!).  But we don't back the entire buffer with
309                  * pages, only the valid picture part.. so need to adjust for
310                  * this in the size used to mmap and generate mmap offset
311                  */
312                 size = tiler_vsize(gem2fmt(omap_obj->flags),
313                                 omap_obj->width, omap_obj->height);
314         }
315
316         return size;
317 }
318
319
320 /* Normal handling for the case of faulting in non-tiled buffers */
321 static int fault_1d(struct drm_gem_object *obj,
322                 struct vm_area_struct *vma, struct vm_fault *vmf)
323 {
324         struct omap_gem_object *omap_obj = to_omap_bo(obj);
325         unsigned long pfn;
326         pgoff_t pgoff;
327
328         /* We don't use vmf->pgoff since that has the fake offset: */
329         pgoff = ((unsigned long)vmf->virtual_address -
330                         vma->vm_start) >> PAGE_SHIFT;
331
332         if (omap_obj->pages) {
333                 pfn = page_to_pfn(omap_obj->pages[pgoff]);
334         } else {
335                 BUG_ON(!(omap_obj->flags & OMAP_BO_DMA));
336                 pfn = (omap_obj->paddr >> PAGE_SHIFT) + pgoff;
337         }
338
339         VERB("Inserting %p pfn %lx, pa %lx", vmf->virtual_address,
340                         pfn, pfn << PAGE_SHIFT);
341
342         return vm_insert_mixed(vma, (unsigned long)vmf->virtual_address, pfn);
343 }
344
345 /* Special handling for the case of faulting in 2d tiled buffers */
346 static int fault_2d(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         struct usergart_entry *entry;
351         enum tiler_fmt fmt = gem2fmt(omap_obj->flags);
352         struct page *pages[64];  /* XXX is this too much to have on stack? */
353         unsigned long pfn;
354         pgoff_t pgoff, base_pgoff;
355         void __user *vaddr;
356         int i, ret, slots;
357
358         /*
359          * Note the height of the slot is also equal to the number of pages
360          * that need to be mapped in to fill 4kb wide CPU page.  If the slot
361          * height is 64, then 64 pages fill a 4kb wide by 64 row region.
362          */
363         const int n = usergart[fmt].height;
364         const int n_shift = usergart[fmt].height_shift;
365
366         /*
367          * If buffer width in bytes > PAGE_SIZE then the virtual stride is
368          * rounded up to next multiple of PAGE_SIZE.. this need to be taken
369          * into account in some of the math, so figure out virtual stride
370          * in pages
371          */
372         const int m = 1 + ((omap_obj->width << fmt) / PAGE_SIZE);
373
374         /* We don't use vmf->pgoff since that has the fake offset: */
375         pgoff = ((unsigned long)vmf->virtual_address -
376                         vma->vm_start) >> PAGE_SHIFT;
377
378         /*
379          * Actual address we start mapping at is rounded down to previous slot
380          * boundary in the y direction:
381          */
382         base_pgoff = round_down(pgoff, m << n_shift);
383
384         /* figure out buffer width in slots */
385         slots = omap_obj->width >> usergart[fmt].slot_shift;
386
387         vaddr = vmf->virtual_address - ((pgoff - base_pgoff) << PAGE_SHIFT);
388
389         entry = &usergart[fmt].entry[usergart[fmt].last];
390
391         /* evict previous buffer using this usergart entry, if any: */
392         if (entry->obj)
393                 evict_entry(entry->obj, fmt, entry);
394
395         entry->obj = obj;
396         entry->obj_pgoff = base_pgoff;
397
398         /* now convert base_pgoff to phys offset from virt offset: */
399         base_pgoff = (base_pgoff >> n_shift) * slots;
400
401         /* for wider-than 4k.. figure out which part of the slot-row we want: */
402         if (m > 1) {
403                 int off = pgoff % m;
404                 entry->obj_pgoff += off;
405                 base_pgoff /= m;
406                 slots = min(slots - (off << n_shift), n);
407                 base_pgoff += off << n_shift;
408                 vaddr += off << PAGE_SHIFT;
409         }
410
411         /*
412          * Map in pages. Beyond the valid pixel part of the buffer, we set
413          * pages[i] to NULL to get a dummy page mapped in.. if someone
414          * reads/writes it they will get random/undefined content, but at
415          * least it won't be corrupting whatever other random page used to
416          * be mapped in, or other undefined behavior.
417          */
418         memcpy(pages, &omap_obj->pages[base_pgoff],
419                         sizeof(struct page *) * slots);
420         memset(pages + slots, 0,
421                         sizeof(struct page *) * (n - slots));
422
423         ret = tiler_pin(entry->block, pages, ARRAY_SIZE(pages), 0, true);
424         if (ret) {
425                 dev_err(obj->dev->dev, "failed to pin: %d\n", ret);
426                 return ret;
427         }
428
429         pfn = entry->paddr >> PAGE_SHIFT;
430
431         VERB("Inserting %p pfn %lx, pa %lx", vmf->virtual_address,
432                         pfn, pfn << PAGE_SHIFT);
433
434         for (i = n; i > 0; i--) {
435                 vm_insert_mixed(vma, (unsigned long)vaddr, pfn);
436                 pfn += usergart[fmt].stride_pfn;
437                 vaddr += PAGE_SIZE * m;
438         }
439
440         /* simple round-robin: */
441         usergart[fmt].last = (usergart[fmt].last + 1) % NUM_USERGART_ENTRIES;
442
443         return 0;
444 }
445
446 /**
447  * omap_gem_fault               -       pagefault handler for GEM objects
448  * @vma: the VMA of the GEM object
449  * @vmf: fault detail
450  *
451  * Invoked when a fault occurs on an mmap of a GEM managed area. GEM
452  * does most of the work for us including the actual map/unmap calls
453  * but we need to do the actual page work.
454  *
455  * The VMA was set up by GEM. In doing so it also ensured that the
456  * vma->vm_private_data points to the GEM object that is backing this
457  * mapping.
458  */
459 int omap_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
460 {
461         struct drm_gem_object *obj = vma->vm_private_data;
462         struct omap_gem_object *omap_obj = to_omap_bo(obj);
463         struct drm_device *dev = obj->dev;
464         struct page **pages;
465         int ret;
466
467         /* Make sure we don't parallel update on a fault, nor move or remove
468          * something from beneath our feet
469          */
470         mutex_lock(&dev->struct_mutex);
471
472         /* if a shmem backed object, make sure we have pages attached now */
473         ret = get_pages(obj, &pages);
474         if (ret) {
475                 goto fail;
476         }
477
478         /* where should we do corresponding put_pages().. we are mapping
479          * the original page, rather than thru a GART, so we can't rely
480          * on eviction to trigger this.  But munmap() or all mappings should
481          * probably trigger put_pages()?
482          */
483
484         if (omap_obj->flags & OMAP_BO_TILED)
485                 ret = fault_2d(obj, vma, vmf);
486         else
487                 ret = fault_1d(obj, vma, vmf);
488
489
490 fail:
491         mutex_unlock(&dev->struct_mutex);
492         switch (ret) {
493         case 0:
494         case -ERESTARTSYS:
495         case -EINTR:
496                 return VM_FAULT_NOPAGE;
497         case -ENOMEM:
498                 return VM_FAULT_OOM;
499         default:
500                 return VM_FAULT_SIGBUS;
501         }
502 }
503
504 /** We override mainly to fix up some of the vm mapping flags.. */
505 int omap_gem_mmap(struct file *filp, struct vm_area_struct *vma)
506 {
507         struct omap_gem_object *omap_obj;
508         int ret;
509
510         ret = drm_gem_mmap(filp, vma);
511         if (ret) {
512                 DBG("mmap failed: %d", ret);
513                 return ret;
514         }
515
516         /* after drm_gem_mmap(), it is safe to access the obj */
517         omap_obj = to_omap_bo(vma->vm_private_data);
518
519         vma->vm_flags &= ~VM_PFNMAP;
520         vma->vm_flags |= VM_MIXEDMAP;
521
522         if (omap_obj->flags & OMAP_BO_WC) {
523                 vma->vm_page_prot = pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
524         } else if (omap_obj->flags & OMAP_BO_UNCACHED) {
525                 vma->vm_page_prot = pgprot_noncached(vm_get_page_prot(vma->vm_flags));
526         } else {
527                 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
528         }
529
530         return ret;
531 }
532
533 /**
534  * omap_gem_dumb_create -       create a dumb buffer
535  * @drm_file: our client file
536  * @dev: our device
537  * @args: the requested arguments copied from userspace
538  *
539  * Allocate a buffer suitable for use for a frame buffer of the
540  * form described by user space. Give userspace a handle by which
541  * to reference it.
542  */
543 int omap_gem_dumb_create(struct drm_file *file, struct drm_device *dev,
544                 struct drm_mode_create_dumb *args)
545 {
546         union omap_gem_size gsize;
547
548         /* in case someone tries to feed us a completely bogus stride: */
549         args->pitch = align_pitch(args->pitch, args->width, args->bpp);
550         args->size = PAGE_ALIGN(args->pitch * args->height);
551
552         gsize = (union omap_gem_size){
553                 .bytes = args->size,
554         };
555
556         return omap_gem_new_handle(dev, file, gsize,
557                         OMAP_BO_SCANOUT | OMAP_BO_WC, &args->handle);
558 }
559
560 /**
561  * omap_gem_dumb_destroy        -       destroy a dumb buffer
562  * @file: client file
563  * @dev: our DRM device
564  * @handle: the object handle
565  *
566  * Destroy a handle that was created via omap_gem_dumb_create.
567  */
568 int omap_gem_dumb_destroy(struct drm_file *file, struct drm_device *dev,
569                 uint32_t handle)
570 {
571         /* No special work needed, drop the reference and see what falls out */
572         return drm_gem_handle_delete(file, handle);
573 }
574
575 /**
576  * omap_gem_dumb_map    -       buffer mapping for dumb interface
577  * @file: our drm client file
578  * @dev: drm device
579  * @handle: GEM handle to the object (from dumb_create)
580  *
581  * Do the necessary setup to allow the mapping of the frame buffer
582  * into user memory. We don't have to do much here at the moment.
583  */
584 int omap_gem_dumb_map_offset(struct drm_file *file, struct drm_device *dev,
585                 uint32_t handle, uint64_t *offset)
586 {
587         struct drm_gem_object *obj;
588         int ret = 0;
589
590         /* GEM does all our handle to object mapping */
591         obj = drm_gem_object_lookup(dev, file, handle);
592         if (obj == NULL) {
593                 ret = -ENOENT;
594                 goto fail;
595         }
596
597         *offset = omap_gem_mmap_offset(obj);
598
599         drm_gem_object_unreference_unlocked(obj);
600
601 fail:
602         return ret;
603 }
604
605 /* Set scrolling position.  This allows us to implement fast scrolling
606  * for console.
607  *
608  * Call only from non-atomic contexts.
609  */
610 int omap_gem_roll(struct drm_gem_object *obj, uint32_t roll)
611 {
612         struct omap_gem_object *omap_obj = to_omap_bo(obj);
613         uint32_t npages = obj->size >> PAGE_SHIFT;
614         int ret = 0;
615
616         if (roll > npages) {
617                 dev_err(obj->dev->dev, "invalid roll: %d\n", roll);
618                 return -EINVAL;
619         }
620
621         omap_obj->roll = roll;
622
623         mutex_lock(&obj->dev->struct_mutex);
624
625         /* if we aren't mapped yet, we don't need to do anything */
626         if (omap_obj->block) {
627                 struct page **pages;
628                 ret = get_pages(obj, &pages);
629                 if (ret)
630                         goto fail;
631                 ret = tiler_pin(omap_obj->block, pages, npages, roll, true);
632                 if (ret)
633                         dev_err(obj->dev->dev, "could not repin: %d\n", ret);
634         }
635
636 fail:
637         mutex_unlock(&obj->dev->struct_mutex);
638
639         return ret;
640 }
641
642 /* Get physical address for DMA.. if 'remap' is true, and the buffer is not
643  * already contiguous, remap it to pin in physically contiguous memory.. (ie.
644  * map in TILER)
645  */
646 int omap_gem_get_paddr(struct drm_gem_object *obj,
647                 dma_addr_t *paddr, bool remap)
648 {
649         struct omap_drm_private *priv = obj->dev->dev_private;
650         struct omap_gem_object *omap_obj = to_omap_bo(obj);
651         int ret = 0;
652
653         mutex_lock(&obj->dev->struct_mutex);
654
655         if (remap && is_shmem(obj) && priv->has_dmm) {
656                 if (omap_obj->paddr_cnt == 0) {
657                         struct page **pages;
658                         uint32_t npages = obj->size >> PAGE_SHIFT;
659                         enum tiler_fmt fmt = gem2fmt(omap_obj->flags);
660                         struct tiler_block *block;
661
662                         BUG_ON(omap_obj->block);
663
664                         ret = get_pages(obj, &pages);
665                         if (ret)
666                                 goto fail;
667
668                         if (omap_obj->flags & OMAP_BO_TILED) {
669                                 block = tiler_reserve_2d(fmt,
670                                                 omap_obj->width,
671                                                 omap_obj->height, 0);
672                         } else {
673                                 block = tiler_reserve_1d(obj->size);
674                         }
675
676                         if (IS_ERR(block)) {
677                                 ret = PTR_ERR(block);
678                                 dev_err(obj->dev->dev,
679                                         "could not remap: %d (%d)\n", ret, fmt);
680                                 goto fail;
681                         }
682
683                         /* TODO: enable async refill.. */
684                         ret = tiler_pin(block, pages, npages,
685                                         omap_obj->roll, true);
686                         if (ret) {
687                                 tiler_release(block);
688                                 dev_err(obj->dev->dev,
689                                                 "could not pin: %d\n", ret);
690                                 goto fail;
691                         }
692
693                         omap_obj->paddr = tiler_ssptr(block);
694                         omap_obj->block = block;
695
696                         DBG("got paddr: %08x", omap_obj->paddr);
697                 }
698
699                 omap_obj->paddr_cnt++;
700
701                 *paddr = omap_obj->paddr;
702         } else if (omap_obj->flags & OMAP_BO_DMA) {
703                 *paddr = omap_obj->paddr;
704         } else {
705                 ret = -EINVAL;
706         }
707
708 fail:
709         mutex_unlock(&obj->dev->struct_mutex);
710
711         return ret;
712 }
713
714 /* Release physical address, when DMA is no longer being performed.. this
715  * could potentially unpin and unmap buffers from TILER
716  */
717 int omap_gem_put_paddr(struct drm_gem_object *obj)
718 {
719         struct omap_gem_object *omap_obj = to_omap_bo(obj);
720         int ret = 0;
721
722         mutex_lock(&obj->dev->struct_mutex);
723         if (omap_obj->paddr_cnt > 0) {
724                 omap_obj->paddr_cnt--;
725                 if (omap_obj->paddr_cnt == 0) {
726                         ret = tiler_unpin(omap_obj->block);
727                         if (ret) {
728                                 dev_err(obj->dev->dev,
729                                         "could not unpin pages: %d\n", ret);
730                                 goto fail;
731                         }
732                         ret = tiler_release(omap_obj->block);
733                         if (ret) {
734                                 dev_err(obj->dev->dev,
735                                         "could not release unmap: %d\n", ret);
736                         }
737                         omap_obj->block = NULL;
738                 }
739         }
740 fail:
741         mutex_unlock(&obj->dev->struct_mutex);
742         return ret;
743 }
744
745 /* acquire pages when needed (for example, for DMA where physically
746  * contiguous buffer is not required
747  */
748 static int get_pages(struct drm_gem_object *obj, struct page ***pages)
749 {
750         struct omap_gem_object *omap_obj = to_omap_bo(obj);
751         int ret = 0;
752
753         if (is_shmem(obj) && !omap_obj->pages) {
754                 ret = omap_gem_attach_pages(obj);
755                 if (ret) {
756                         dev_err(obj->dev->dev, "could not attach pages\n");
757                         return ret;
758                 }
759         }
760
761         /* TODO: even phys-contig.. we should have a list of pages? */
762         *pages = omap_obj->pages;
763
764         return 0;
765 }
766
767 int omap_gem_get_pages(struct drm_gem_object *obj, struct page ***pages)
768 {
769         int ret;
770         mutex_lock(&obj->dev->struct_mutex);
771         ret = get_pages(obj, pages);
772         mutex_unlock(&obj->dev->struct_mutex);
773         return ret;
774 }
775
776 /* release pages when DMA no longer being performed */
777 int omap_gem_put_pages(struct drm_gem_object *obj)
778 {
779         /* do something here if we dynamically attach/detach pages.. at
780          * least they would no longer need to be pinned if everyone has
781          * released the pages..
782          */
783         return 0;
784 }
785
786 /* Get kernel virtual address for CPU access.. this more or less only
787  * exists for omap_fbdev.  This should be called with struct_mutex
788  * held.
789  */
790 void *omap_gem_vaddr(struct drm_gem_object *obj)
791 {
792         struct omap_gem_object *omap_obj = to_omap_bo(obj);
793         WARN_ON(! mutex_is_locked(&obj->dev->struct_mutex));
794         if (!omap_obj->vaddr) {
795                 struct page **pages;
796                 int ret = get_pages(obj, &pages);
797                 if (ret)
798                         return ERR_PTR(ret);
799                 omap_obj->vaddr = vmap(pages, obj->size >> PAGE_SHIFT,
800                                 VM_MAP, pgprot_writecombine(PAGE_KERNEL));
801         }
802         return omap_obj->vaddr;
803 }
804
805 #ifdef CONFIG_DEBUG_FS
806 void omap_gem_describe(struct drm_gem_object *obj, struct seq_file *m)
807 {
808         struct drm_device *dev = obj->dev;
809         struct omap_gem_object *omap_obj = to_omap_bo(obj);
810         uint64_t off = 0;
811
812         WARN_ON(! mutex_is_locked(&dev->struct_mutex));
813
814         if (obj->map_list.map)
815                 off = (uint64_t)obj->map_list.hash.key;
816
817         seq_printf(m, "%08x: %2d (%2d) %08llx %08Zx (%2d) %p %4d",
818                         omap_obj->flags, obj->name, obj->refcount.refcount.counter,
819                         off, omap_obj->paddr, omap_obj->paddr_cnt,
820                         omap_obj->vaddr, omap_obj->roll);
821
822         if (omap_obj->flags & OMAP_BO_TILED) {
823                 seq_printf(m, " %dx%d", omap_obj->width, omap_obj->height);
824                 if (omap_obj->block) {
825                         struct tcm_area *area = &omap_obj->block->area;
826                         seq_printf(m, " (%dx%d, %dx%d)",
827                                         area->p0.x, area->p0.y,
828                                         area->p1.x, area->p1.y);
829                 }
830         } else {
831                 seq_printf(m, " %d", obj->size);
832         }
833
834         seq_printf(m, "\n");
835 }
836
837 void omap_gem_describe_objects(struct list_head *list, struct seq_file *m)
838 {
839         struct omap_gem_object *omap_obj;
840         int count = 0;
841         size_t size = 0;
842
843         list_for_each_entry(omap_obj, list, mm_list) {
844                 struct drm_gem_object *obj = &omap_obj->base;
845                 seq_printf(m, "   ");
846                 omap_gem_describe(obj, m);
847                 count++;
848                 size += obj->size;
849         }
850
851         seq_printf(m, "Total %d objects, %zu bytes\n", count, size);
852 }
853 #endif
854
855 /* Buffer Synchronization:
856  */
857
858 struct omap_gem_sync_waiter {
859         struct list_head list;
860         struct omap_gem_object *omap_obj;
861         enum omap_gem_op op;
862         uint32_t read_target, write_target;
863         /* notify called w/ sync_lock held */
864         void (*notify)(void *arg);
865         void *arg;
866 };
867
868 /* list of omap_gem_sync_waiter.. the notify fxn gets called back when
869  * the read and/or write target count is achieved which can call a user
870  * callback (ex. to kick 3d and/or 2d), wakeup blocked task (prep for
871  * cpu access), etc.
872  */
873 static LIST_HEAD(waiters);
874
875 static inline bool is_waiting(struct omap_gem_sync_waiter *waiter)
876 {
877         struct omap_gem_object *omap_obj = waiter->omap_obj;
878         if ((waiter->op & OMAP_GEM_READ) &&
879                         (omap_obj->sync->read_complete < waiter->read_target))
880                 return true;
881         if ((waiter->op & OMAP_GEM_WRITE) &&
882                         (omap_obj->sync->write_complete < waiter->write_target))
883                 return true;
884         return false;
885 }
886
887 /* macro for sync debug.. */
888 #define SYNCDBG 0
889 #define SYNC(fmt, ...) do { if (SYNCDBG) \
890                 printk(KERN_ERR "%s:%d: "fmt"\n", \
891                                 __func__, __LINE__, ##__VA_ARGS__); \
892         } while (0)
893
894
895 static void sync_op_update(void)
896 {
897         struct omap_gem_sync_waiter *waiter, *n;
898         list_for_each_entry_safe(waiter, n, &waiters, list) {
899                 if (!is_waiting(waiter)) {
900                         list_del(&waiter->list);
901                         SYNC("notify: %p", waiter);
902                         waiter->notify(waiter->arg);
903                         kfree(waiter);
904                 }
905         }
906 }
907
908 static inline int sync_op(struct drm_gem_object *obj,
909                 enum omap_gem_op op, bool start)
910 {
911         struct omap_gem_object *omap_obj = to_omap_bo(obj);
912         int ret = 0;
913
914         spin_lock(&sync_lock);
915
916         if (!omap_obj->sync) {
917                 omap_obj->sync = kzalloc(sizeof(*omap_obj->sync), GFP_ATOMIC);
918                 if (!omap_obj->sync) {
919                         ret = -ENOMEM;
920                         goto unlock;
921                 }
922         }
923
924         if (start) {
925                 if (op & OMAP_GEM_READ)
926                         omap_obj->sync->read_pending++;
927                 if (op & OMAP_GEM_WRITE)
928                         omap_obj->sync->write_pending++;
929         } else {
930                 if (op & OMAP_GEM_READ)
931                         omap_obj->sync->read_complete++;
932                 if (op & OMAP_GEM_WRITE)
933                         omap_obj->sync->write_complete++;
934                 sync_op_update();
935         }
936
937 unlock:
938         spin_unlock(&sync_lock);
939
940         return ret;
941 }
942
943 /* it is a bit lame to handle updates in this sort of polling way, but
944  * in case of PVR, the GPU can directly update read/write complete
945  * values, and not really tell us which ones it updated.. this also
946  * means that sync_lock is not quite sufficient.  So we'll need to
947  * do something a bit better when it comes time to add support for
948  * separate 2d hw..
949  */
950 void omap_gem_op_update(void)
951 {
952         spin_lock(&sync_lock);
953         sync_op_update();
954         spin_unlock(&sync_lock);
955 }
956
957 /* mark the start of read and/or write operation */
958 int omap_gem_op_start(struct drm_gem_object *obj, enum omap_gem_op op)
959 {
960         return sync_op(obj, op, true);
961 }
962
963 int omap_gem_op_finish(struct drm_gem_object *obj, enum omap_gem_op op)
964 {
965         return sync_op(obj, op, false);
966 }
967
968 static DECLARE_WAIT_QUEUE_HEAD(sync_event);
969
970 static void sync_notify(void *arg)
971 {
972         struct task_struct **waiter_task = arg;
973         *waiter_task = NULL;
974         wake_up_all(&sync_event);
975 }
976
977 int omap_gem_op_sync(struct drm_gem_object *obj, enum omap_gem_op op)
978 {
979         struct omap_gem_object *omap_obj = to_omap_bo(obj);
980         int ret = 0;
981         if (omap_obj->sync) {
982                 struct task_struct *waiter_task = current;
983                 struct omap_gem_sync_waiter *waiter =
984                                 kzalloc(sizeof(*waiter), GFP_KERNEL);
985
986                 if (!waiter) {
987                         return -ENOMEM;
988                 }
989
990                 waiter->omap_obj = omap_obj;
991                 waiter->op = op;
992                 waiter->read_target = omap_obj->sync->read_pending;
993                 waiter->write_target = omap_obj->sync->write_pending;
994                 waiter->notify = sync_notify;
995                 waiter->arg = &waiter_task;
996
997                 spin_lock(&sync_lock);
998                 if (is_waiting(waiter)) {
999                         SYNC("waited: %p", waiter);
1000                         list_add_tail(&waiter->list, &waiters);
1001                         spin_unlock(&sync_lock);
1002                         ret = wait_event_interruptible(sync_event,
1003                                         (waiter_task == NULL));
1004                         spin_lock(&sync_lock);
1005                         if (waiter_task) {
1006                                 SYNC("interrupted: %p", waiter);
1007                                 /* we were interrupted */
1008                                 list_del(&waiter->list);
1009                                 waiter_task = NULL;
1010                         } else {
1011                                 /* freed in sync_op_update() */
1012                                 waiter = NULL;
1013                         }
1014                 }
1015                 spin_unlock(&sync_lock);
1016
1017                 if (waiter) {
1018                         kfree(waiter);
1019                 }
1020         }
1021         return ret;
1022 }
1023
1024 /* call fxn(arg), either synchronously or asynchronously if the op
1025  * is currently blocked..  fxn() can be called from any context
1026  *
1027  * (TODO for now fxn is called back from whichever context calls
1028  * omap_gem_op_update().. but this could be better defined later
1029  * if needed)
1030  *
1031  * TODO more code in common w/ _sync()..
1032  */
1033 int omap_gem_op_async(struct drm_gem_object *obj, enum omap_gem_op op,
1034                 void (*fxn)(void *arg), void *arg)
1035 {
1036         struct omap_gem_object *omap_obj = to_omap_bo(obj);
1037         if (omap_obj->sync) {
1038                 struct omap_gem_sync_waiter *waiter =
1039                                 kzalloc(sizeof(*waiter), GFP_ATOMIC);
1040
1041                 if (!waiter) {
1042                         return -ENOMEM;
1043                 }
1044
1045                 waiter->omap_obj = omap_obj;
1046                 waiter->op = op;
1047                 waiter->read_target = omap_obj->sync->read_pending;
1048                 waiter->write_target = omap_obj->sync->write_pending;
1049                 waiter->notify = fxn;
1050                 waiter->arg = arg;
1051
1052                 spin_lock(&sync_lock);
1053                 if (is_waiting(waiter)) {
1054                         SYNC("waited: %p", waiter);
1055                         list_add_tail(&waiter->list, &waiters);
1056                         spin_unlock(&sync_lock);
1057                         return 0;
1058                 }
1059
1060                 spin_unlock(&sync_lock);
1061         }
1062
1063         /* no waiting.. */
1064         fxn(arg);
1065
1066         return 0;
1067 }
1068
1069 /* special API so PVR can update the buffer to use a sync-object allocated
1070  * from it's sync-obj heap.  Only used for a newly allocated (from PVR's
1071  * perspective) sync-object, so we overwrite the new syncobj w/ values
1072  * from the already allocated syncobj (if there is one)
1073  */
1074 int omap_gem_set_sync_object(struct drm_gem_object *obj, void *syncobj)
1075 {
1076         struct omap_gem_object *omap_obj = to_omap_bo(obj);
1077         int ret = 0;
1078
1079         spin_lock(&sync_lock);
1080
1081         if ((omap_obj->flags & OMAP_BO_EXT_SYNC) && !syncobj) {
1082                 /* clearing a previously set syncobj */
1083                 syncobj = kzalloc(sizeof(*omap_obj->sync), GFP_ATOMIC);
1084                 if (!syncobj) {
1085                         ret = -ENOMEM;
1086                         goto unlock;
1087                 }
1088                 memcpy(syncobj, omap_obj->sync, sizeof(*omap_obj->sync));
1089                 omap_obj->flags &= ~OMAP_BO_EXT_SYNC;
1090                 omap_obj->sync = syncobj;
1091         } else if (syncobj && !(omap_obj->flags & OMAP_BO_EXT_SYNC)) {
1092                 /* replacing an existing syncobj */
1093                 if (omap_obj->sync) {
1094                         memcpy(syncobj, omap_obj->sync, sizeof(*omap_obj->sync));
1095                         kfree(omap_obj->sync);
1096                 }
1097                 omap_obj->flags |= OMAP_BO_EXT_SYNC;
1098                 omap_obj->sync = syncobj;
1099         }
1100
1101 unlock:
1102         spin_unlock(&sync_lock);
1103         return ret;
1104 }
1105
1106 int omap_gem_init_object(struct drm_gem_object *obj)
1107 {
1108         return -EINVAL;          /* unused */
1109 }
1110
1111 /* don't call directly.. called from GEM core when it is time to actually
1112  * free the object..
1113  */
1114 void omap_gem_free_object(struct drm_gem_object *obj)
1115 {
1116         struct drm_device *dev = obj->dev;
1117         struct omap_gem_object *omap_obj = to_omap_bo(obj);
1118
1119         evict(obj);
1120
1121         WARN_ON(!mutex_is_locked(&dev->struct_mutex));
1122
1123         list_del(&omap_obj->mm_list);
1124
1125         if (obj->map_list.map) {
1126                 drm_gem_free_mmap_offset(obj);
1127         }
1128
1129         /* this means the object is still pinned.. which really should
1130          * not happen.  I think..
1131          */
1132         WARN_ON(omap_obj->paddr_cnt > 0);
1133
1134         /* don't free externally allocated backing memory */
1135         if (!(omap_obj->flags & OMAP_BO_EXT_MEM)) {
1136                 if (omap_obj->pages) {
1137                         omap_gem_detach_pages(obj);
1138                 }
1139                 if (!is_shmem(obj)) {
1140                         dma_free_writecombine(dev->dev, obj->size,
1141                                         omap_obj->vaddr, omap_obj->paddr);
1142                 } else if (omap_obj->vaddr) {
1143                         vunmap(omap_obj->vaddr);
1144                 }
1145         }
1146
1147         /* don't free externally allocated syncobj */
1148         if (!(omap_obj->flags & OMAP_BO_EXT_SYNC)) {
1149                 kfree(omap_obj->sync);
1150         }
1151
1152         drm_gem_object_release(obj);
1153
1154         kfree(obj);
1155 }
1156
1157 /* convenience method to construct a GEM buffer object, and userspace handle */
1158 int omap_gem_new_handle(struct drm_device *dev, struct drm_file *file,
1159                 union omap_gem_size gsize, uint32_t flags, uint32_t *handle)
1160 {
1161         struct drm_gem_object *obj;
1162         int ret;
1163
1164         obj = omap_gem_new(dev, gsize, flags);
1165         if (!obj)
1166                 return -ENOMEM;
1167
1168         ret = drm_gem_handle_create(file, obj, handle);
1169         if (ret) {
1170                 drm_gem_object_release(obj);
1171                 kfree(obj); /* TODO isn't there a dtor to call? just copying i915 */
1172                 return ret;
1173         }
1174
1175         /* drop reference from allocate - handle holds it now */
1176         drm_gem_object_unreference_unlocked(obj);
1177
1178         return 0;
1179 }
1180
1181 /* GEM buffer object constructor */
1182 struct drm_gem_object *omap_gem_new(struct drm_device *dev,
1183                 union omap_gem_size gsize, uint32_t flags)
1184 {
1185         struct omap_drm_private *priv = dev->dev_private;
1186         struct omap_gem_object *omap_obj;
1187         struct drm_gem_object *obj = NULL;
1188         size_t size;
1189         int ret;
1190
1191         if (flags & OMAP_BO_TILED) {
1192                 if (!usergart) {
1193                         dev_err(dev->dev, "Tiled buffers require DMM\n");
1194                         goto fail;
1195                 }
1196
1197                 /* tiled buffers are always shmem paged backed.. when they are
1198                  * scanned out, they are remapped into DMM/TILER
1199                  */
1200                 flags &= ~OMAP_BO_SCANOUT;
1201
1202                 /* currently don't allow cached buffers.. there is some caching
1203                  * stuff that needs to be handled better
1204                  */
1205                 flags &= ~(OMAP_BO_CACHED|OMAP_BO_UNCACHED);
1206                 flags |= OMAP_BO_WC;
1207
1208                 /* align dimensions to slot boundaries... */
1209                 tiler_align(gem2fmt(flags),
1210                                 &gsize.tiled.width, &gsize.tiled.height);
1211
1212                 /* ...and calculate size based on aligned dimensions */
1213                 size = tiler_size(gem2fmt(flags),
1214                                 gsize.tiled.width, gsize.tiled.height);
1215         } else {
1216                 size = PAGE_ALIGN(gsize.bytes);
1217         }
1218
1219         omap_obj = kzalloc(sizeof(*omap_obj), GFP_KERNEL);
1220         if (!omap_obj) {
1221                 dev_err(dev->dev, "could not allocate GEM object\n");
1222                 goto fail;
1223         }
1224
1225         list_add(&omap_obj->mm_list, &priv->obj_list);
1226
1227         obj = &omap_obj->base;
1228
1229         if ((flags & OMAP_BO_SCANOUT) && !priv->has_dmm) {
1230                 /* attempt to allocate contiguous memory if we don't
1231                  * have DMM for remappign discontiguous buffers
1232                  */
1233                 omap_obj->vaddr =  dma_alloc_writecombine(dev->dev, size,
1234                                 &omap_obj->paddr, GFP_KERNEL);
1235                 if (omap_obj->vaddr) {
1236                         flags |= OMAP_BO_DMA;
1237                 }
1238         }
1239
1240         omap_obj->flags = flags;
1241
1242         if (flags & OMAP_BO_TILED) {
1243                 omap_obj->width = gsize.tiled.width;
1244                 omap_obj->height = gsize.tiled.height;
1245         }
1246
1247         if (flags & (OMAP_BO_DMA|OMAP_BO_EXT_MEM)) {
1248                 ret = drm_gem_private_object_init(dev, obj, size);
1249         } else {
1250                 ret = drm_gem_object_init(dev, obj, size);
1251         }
1252
1253         if (ret) {
1254                 goto fail;
1255         }
1256
1257         return obj;
1258
1259 fail:
1260         if (obj) {
1261                 omap_gem_free_object(obj);
1262         }
1263         return NULL;
1264 }
1265
1266 /* init/cleanup.. if DMM is used, we need to set some stuff up.. */
1267 void omap_gem_init(struct drm_device *dev)
1268 {
1269         struct omap_drm_private *priv = dev->dev_private;
1270         const enum tiler_fmt fmts[] = {
1271                         TILFMT_8BIT, TILFMT_16BIT, TILFMT_32BIT
1272         };
1273         int i, j;
1274
1275         if (!dmm_is_initialized()) {
1276                 /* DMM only supported on OMAP4 and later, so this isn't fatal */
1277                 dev_warn(dev->dev, "DMM not available, disable DMM support\n");
1278                 return;
1279         }
1280
1281         usergart = kzalloc(3 * sizeof(*usergart), GFP_KERNEL);
1282         if (!usergart) {
1283                 dev_warn(dev->dev, "could not allocate usergart\n");
1284                 return;
1285         }
1286
1287         /* reserve 4k aligned/wide regions for userspace mappings: */
1288         for (i = 0; i < ARRAY_SIZE(fmts); i++) {
1289                 uint16_t h = 1, w = PAGE_SIZE >> i;
1290                 tiler_align(fmts[i], &w, &h);
1291                 /* note: since each region is 1 4kb page wide, and minimum
1292                  * number of rows, the height ends up being the same as the
1293                  * # of pages in the region
1294                  */
1295                 usergart[i].height = h;
1296                 usergart[i].height_shift = ilog2(h);
1297                 usergart[i].stride_pfn = tiler_stride(fmts[i]) >> PAGE_SHIFT;
1298                 usergart[i].slot_shift = ilog2((PAGE_SIZE / h) >> i);
1299                 for (j = 0; j < NUM_USERGART_ENTRIES; j++) {
1300                         struct usergart_entry *entry = &usergart[i].entry[j];
1301                         struct tiler_block *block =
1302                                         tiler_reserve_2d(fmts[i], w, h,
1303                                                         PAGE_SIZE);
1304                         if (IS_ERR(block)) {
1305                                 dev_err(dev->dev,
1306                                                 "reserve failed: %d, %d, %ld\n",
1307                                                 i, j, PTR_ERR(block));
1308                                 return;
1309                         }
1310                         entry->paddr = tiler_ssptr(block);
1311                         entry->block = block;
1312
1313                         DBG("%d:%d: %dx%d: paddr=%08x stride=%d", i, j, w, h,
1314                                         entry->paddr,
1315                                         usergart[i].stride_pfn << PAGE_SHIFT);
1316                 }
1317         }
1318
1319         priv->has_dmm = true;
1320 }
1321
1322 void omap_gem_deinit(struct drm_device *dev)
1323 {
1324         /* I believe we can rely on there being no more outstanding GEM
1325          * objects which could depend on usergart/dmm at this point.
1326          */
1327         kfree(usergart);
1328 }