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