96848913085f63ba73d66c56925c48c1a4de3686
[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         mutex_lock(&obj->dev->struct_mutex);
542
543         omap_obj->roll = roll;
544
545         /* if we aren't mapped yet, we don't need to do anything */
546         if (omap_obj->block) {
547                 struct page **pages;
548                 ret = get_pages(obj, &pages);
549                 if (ret)
550                         goto fail;
551                 ret = tiler_pin(omap_obj->block, pages, npages, roll, true);
552                 if (ret)
553                         dev_err(obj->dev->dev, "could not repin: %d\n", ret);
554         }
555
556 fail:
557         mutex_unlock(&obj->dev->struct_mutex);
558
559         return ret;
560 }
561
562 /* Get physical address for DMA.. if 'remap' is true, and the buffer is not
563  * already contiguous, remap it to pin in physically contiguous memory.. (ie.
564  * map in TILER)
565  */
566 int omap_gem_get_paddr(struct drm_gem_object *obj,
567                 dma_addr_t *paddr, bool remap)
568 {
569         struct omap_drm_private *priv = obj->dev->dev_private;
570         struct omap_gem_object *omap_obj = to_omap_bo(obj);
571         int ret = 0;
572
573         mutex_lock(&obj->dev->struct_mutex);
574
575         if (remap && is_shmem(obj) && priv->has_dmm) {
576                 if (omap_obj->paddr_cnt == 0) {
577                         struct page **pages;
578                         uint32_t npages = obj->size >> PAGE_SHIFT;
579                         enum tiler_fmt fmt = gem2fmt(omap_obj->flags);
580                         struct tiler_block *block;
581
582                         BUG_ON(omap_obj->block);
583
584                         ret = get_pages(obj, &pages);
585                         if (ret)
586                                 goto fail;
587
588                         if (omap_obj->flags & OMAP_BO_TILED) {
589                                 block = tiler_reserve_2d(fmt,
590                                                 omap_obj->width,
591                                                 omap_obj->height, 0);
592                         } else {
593                                 block = tiler_reserve_1d(obj->size);
594                         }
595
596                         if (IS_ERR(block)) {
597                                 ret = PTR_ERR(block);
598                                 dev_err(obj->dev->dev,
599                                         "could not remap: %d (%d)\n", ret, fmt);
600                                 goto fail;
601                         }
602
603                         /* TODO: enable async refill.. */
604                         ret = tiler_pin(block, pages, npages,
605                                         omap_obj->roll, true);
606                         if (ret) {
607                                 tiler_release(block);
608                                 dev_err(obj->dev->dev,
609                                                 "could not pin: %d\n", ret);
610                                 goto fail;
611                         }
612
613                         omap_obj->paddr = tiler_ssptr(block);
614                         omap_obj->block = block;
615
616                         DBG("got paddr: %08x", omap_obj->paddr);
617                 }
618
619                 omap_obj->paddr_cnt++;
620
621                 *paddr = omap_obj->paddr;
622         } else if (omap_obj->flags & OMAP_BO_DMA) {
623                 *paddr = omap_obj->paddr;
624         } else {
625                 ret = -EINVAL;
626         }
627
628 fail:
629         mutex_unlock(&obj->dev->struct_mutex);
630
631         return ret;
632 }
633
634 /* Release physical address, when DMA is no longer being performed.. this
635  * could potentially unpin and unmap buffers from TILER
636  */
637 int omap_gem_put_paddr(struct drm_gem_object *obj)
638 {
639         struct omap_gem_object *omap_obj = to_omap_bo(obj);
640         int ret = 0;
641
642         mutex_lock(&obj->dev->struct_mutex);
643         if (omap_obj->paddr_cnt > 0) {
644                 omap_obj->paddr_cnt--;
645                 if (omap_obj->paddr_cnt == 0) {
646                         ret = tiler_unpin(omap_obj->block);
647                         if (ret) {
648                                 dev_err(obj->dev->dev,
649                                         "could not unpin pages: %d\n", ret);
650                                 goto fail;
651                         }
652                         ret = tiler_release(omap_obj->block);
653                         if (ret) {
654                                 dev_err(obj->dev->dev,
655                                         "could not release unmap: %d\n", ret);
656                         }
657                         omap_obj->block = NULL;
658                 }
659         }
660 fail:
661         mutex_unlock(&obj->dev->struct_mutex);
662         return ret;
663 }
664
665 /* acquire pages when needed (for example, for DMA where physically
666  * contiguous buffer is not required
667  */
668 static int get_pages(struct drm_gem_object *obj, struct page ***pages)
669 {
670         struct omap_gem_object *omap_obj = to_omap_bo(obj);
671         int ret = 0;
672
673         if (is_shmem(obj) && !omap_obj->pages) {
674                 ret = omap_gem_attach_pages(obj);
675                 if (ret) {
676                         dev_err(obj->dev->dev, "could not attach pages\n");
677                         return ret;
678                 }
679         }
680
681         /* TODO: even phys-contig.. we should have a list of pages? */
682         *pages = omap_obj->pages;
683
684         return 0;
685 }
686
687 int omap_gem_get_pages(struct drm_gem_object *obj, struct page ***pages)
688 {
689         int ret;
690         mutex_lock(&obj->dev->struct_mutex);
691         ret = get_pages(obj, pages);
692         mutex_unlock(&obj->dev->struct_mutex);
693         return ret;
694 }
695
696 /* release pages when DMA no longer being performed */
697 int omap_gem_put_pages(struct drm_gem_object *obj)
698 {
699         /* do something here if we dynamically attach/detach pages.. at
700          * least they would no longer need to be pinned if everyone has
701          * released the pages..
702          */
703         return 0;
704 }
705
706 /* Get kernel virtual address for CPU access.. this more or less only
707  * exists for omap_fbdev.  This should be called with struct_mutex
708  * held.
709  */
710 void *omap_gem_vaddr(struct drm_gem_object *obj)
711 {
712         struct omap_gem_object *omap_obj = to_omap_bo(obj);
713         WARN_ON(! mutex_is_locked(&obj->dev->struct_mutex));
714         if (!omap_obj->vaddr) {
715                 struct page **pages;
716                 int ret = get_pages(obj, &pages);
717                 if (ret)
718                         return ERR_PTR(ret);
719                 omap_obj->vaddr = vmap(pages, obj->size >> PAGE_SHIFT,
720                                 VM_MAP, pgprot_writecombine(PAGE_KERNEL));
721         }
722         return omap_obj->vaddr;
723 }
724
725 /* Buffer Synchronization:
726  */
727
728 struct omap_gem_sync_waiter {
729         struct list_head list;
730         struct omap_gem_object *omap_obj;
731         enum omap_gem_op op;
732         uint32_t read_target, write_target;
733         /* notify called w/ sync_lock held */
734         void (*notify)(void *arg);
735         void *arg;
736 };
737
738 /* list of omap_gem_sync_waiter.. the notify fxn gets called back when
739  * the read and/or write target count is achieved which can call a user
740  * callback (ex. to kick 3d and/or 2d), wakeup blocked task (prep for
741  * cpu access), etc.
742  */
743 static LIST_HEAD(waiters);
744
745 static inline bool is_waiting(struct omap_gem_sync_waiter *waiter)
746 {
747         struct omap_gem_object *omap_obj = waiter->omap_obj;
748         if ((waiter->op & OMAP_GEM_READ) &&
749                         (omap_obj->sync->read_complete < waiter->read_target))
750                 return true;
751         if ((waiter->op & OMAP_GEM_WRITE) &&
752                         (omap_obj->sync->write_complete < waiter->write_target))
753                 return true;
754         return false;
755 }
756
757 /* macro for sync debug.. */
758 #define SYNCDBG 0
759 #define SYNC(fmt, ...) do { if (SYNCDBG) \
760                 printk(KERN_ERR "%s:%d: "fmt"\n", \
761                                 __func__, __LINE__, ##__VA_ARGS__); \
762         } while (0)
763
764
765 static void sync_op_update(void)
766 {
767         struct omap_gem_sync_waiter *waiter, *n;
768         list_for_each_entry_safe(waiter, n, &waiters, list) {
769                 if (!is_waiting(waiter)) {
770                         list_del(&waiter->list);
771                         SYNC("notify: %p", waiter);
772                         waiter->notify(waiter->arg);
773                         kfree(waiter);
774                 }
775         }
776 }
777
778 static inline int sync_op(struct drm_gem_object *obj,
779                 enum omap_gem_op op, bool start)
780 {
781         struct omap_gem_object *omap_obj = to_omap_bo(obj);
782         int ret = 0;
783
784         spin_lock(&sync_lock);
785
786         if (!omap_obj->sync) {
787                 omap_obj->sync = kzalloc(sizeof(*omap_obj->sync), GFP_ATOMIC);
788                 if (!omap_obj->sync) {
789                         ret = -ENOMEM;
790                         goto unlock;
791                 }
792         }
793
794         if (start) {
795                 if (op & OMAP_GEM_READ)
796                         omap_obj->sync->read_pending++;
797                 if (op & OMAP_GEM_WRITE)
798                         omap_obj->sync->write_pending++;
799         } else {
800                 if (op & OMAP_GEM_READ)
801                         omap_obj->sync->read_complete++;
802                 if (op & OMAP_GEM_WRITE)
803                         omap_obj->sync->write_complete++;
804                 sync_op_update();
805         }
806
807 unlock:
808         spin_unlock(&sync_lock);
809
810         return ret;
811 }
812
813 /* it is a bit lame to handle updates in this sort of polling way, but
814  * in case of PVR, the GPU can directly update read/write complete
815  * values, and not really tell us which ones it updated.. this also
816  * means that sync_lock is not quite sufficient.  So we'll need to
817  * do something a bit better when it comes time to add support for
818  * separate 2d hw..
819  */
820 void omap_gem_op_update(void)
821 {
822         spin_lock(&sync_lock);
823         sync_op_update();
824         spin_unlock(&sync_lock);
825 }
826
827 /* mark the start of read and/or write operation */
828 int omap_gem_op_start(struct drm_gem_object *obj, enum omap_gem_op op)
829 {
830         return sync_op(obj, op, true);
831 }
832
833 int omap_gem_op_finish(struct drm_gem_object *obj, enum omap_gem_op op)
834 {
835         return sync_op(obj, op, false);
836 }
837
838 static DECLARE_WAIT_QUEUE_HEAD(sync_event);
839
840 static void sync_notify(void *arg)
841 {
842         struct task_struct **waiter_task = arg;
843         *waiter_task = NULL;
844         wake_up_all(&sync_event);
845 }
846
847 int omap_gem_op_sync(struct drm_gem_object *obj, enum omap_gem_op op)
848 {
849         struct omap_gem_object *omap_obj = to_omap_bo(obj);
850         int ret = 0;
851         if (omap_obj->sync) {
852                 struct task_struct *waiter_task = current;
853                 struct omap_gem_sync_waiter *waiter =
854                                 kzalloc(sizeof(*waiter), GFP_KERNEL);
855
856                 if (!waiter) {
857                         return -ENOMEM;
858                 }
859
860                 waiter->omap_obj = omap_obj;
861                 waiter->op = op;
862                 waiter->read_target = omap_obj->sync->read_pending;
863                 waiter->write_target = omap_obj->sync->write_pending;
864                 waiter->notify = sync_notify;
865                 waiter->arg = &waiter_task;
866
867                 spin_lock(&sync_lock);
868                 if (is_waiting(waiter)) {
869                         SYNC("waited: %p", waiter);
870                         list_add_tail(&waiter->list, &waiters);
871                         spin_unlock(&sync_lock);
872                         ret = wait_event_interruptible(sync_event,
873                                         (waiter_task == NULL));
874                         spin_lock(&sync_lock);
875                         if (waiter_task) {
876                                 SYNC("interrupted: %p", waiter);
877                                 /* we were interrupted */
878                                 list_del(&waiter->list);
879                                 waiter_task = NULL;
880                         } else {
881                                 /* freed in sync_op_update() */
882                                 waiter = NULL;
883                         }
884                 }
885                 spin_unlock(&sync_lock);
886
887                 if (waiter) {
888                         kfree(waiter);
889                 }
890         }
891         return ret;
892 }
893
894 /* call fxn(arg), either synchronously or asynchronously if the op
895  * is currently blocked..  fxn() can be called from any context
896  *
897  * (TODO for now fxn is called back from whichever context calls
898  * omap_gem_op_update().. but this could be better defined later
899  * if needed)
900  *
901  * TODO more code in common w/ _sync()..
902  */
903 int omap_gem_op_async(struct drm_gem_object *obj, enum omap_gem_op op,
904                 void (*fxn)(void *arg), void *arg)
905 {
906         struct omap_gem_object *omap_obj = to_omap_bo(obj);
907         if (omap_obj->sync) {
908                 struct omap_gem_sync_waiter *waiter =
909                                 kzalloc(sizeof(*waiter), GFP_ATOMIC);
910
911                 if (!waiter) {
912                         return -ENOMEM;
913                 }
914
915                 waiter->omap_obj = omap_obj;
916                 waiter->op = op;
917                 waiter->read_target = omap_obj->sync->read_pending;
918                 waiter->write_target = omap_obj->sync->write_pending;
919                 waiter->notify = fxn;
920                 waiter->arg = arg;
921
922                 spin_lock(&sync_lock);
923                 if (is_waiting(waiter)) {
924                         SYNC("waited: %p", waiter);
925                         list_add_tail(&waiter->list, &waiters);
926                         spin_unlock(&sync_lock);
927                         return 0;
928                 }
929
930                 spin_unlock(&sync_lock);
931         }
932
933         /* no waiting.. */
934         fxn(arg);
935
936         return 0;
937 }
938
939 /* special API so PVR can update the buffer to use a sync-object allocated
940  * from it's sync-obj heap.  Only used for a newly allocated (from PVR's
941  * perspective) sync-object, so we overwrite the new syncobj w/ values
942  * from the already allocated syncobj (if there is one)
943  */
944 int omap_gem_set_sync_object(struct drm_gem_object *obj, void *syncobj)
945 {
946         struct omap_gem_object *omap_obj = to_omap_bo(obj);
947         int ret = 0;
948
949         spin_lock(&sync_lock);
950
951         if ((omap_obj->flags & OMAP_BO_EXT_SYNC) && !syncobj) {
952                 /* clearing a previously set syncobj */
953                 syncobj = kzalloc(sizeof(*omap_obj->sync), GFP_ATOMIC);
954                 if (!syncobj) {
955                         ret = -ENOMEM;
956                         goto unlock;
957                 }
958                 memcpy(syncobj, omap_obj->sync, sizeof(*omap_obj->sync));
959                 omap_obj->flags &= ~OMAP_BO_EXT_SYNC;
960                 omap_obj->sync = syncobj;
961         } else if (syncobj && !(omap_obj->flags & OMAP_BO_EXT_SYNC)) {
962                 /* replacing an existing syncobj */
963                 if (omap_obj->sync) {
964                         memcpy(syncobj, omap_obj->sync, sizeof(*omap_obj->sync));
965                         kfree(omap_obj->sync);
966                 }
967                 omap_obj->flags |= OMAP_BO_EXT_SYNC;
968                 omap_obj->sync = syncobj;
969         }
970
971 unlock:
972         spin_unlock(&sync_lock);
973         return ret;
974 }
975
976 int omap_gem_init_object(struct drm_gem_object *obj)
977 {
978         return -EINVAL;          /* unused */
979 }
980
981 /* don't call directly.. called from GEM core when it is time to actually
982  * free the object..
983  */
984 void omap_gem_free_object(struct drm_gem_object *obj)
985 {
986         struct drm_device *dev = obj->dev;
987         struct omap_gem_object *omap_obj = to_omap_bo(obj);
988
989         evict(obj);
990
991         if (obj->map_list.map) {
992                 drm_gem_free_mmap_offset(obj);
993         }
994
995         /* don't free externally allocated backing memory */
996         if (!(omap_obj->flags & OMAP_BO_EXT_MEM)) {
997                 if (omap_obj->pages) {
998                         omap_gem_detach_pages(obj);
999                 }
1000                 if (!is_shmem(obj)) {
1001                         dma_free_writecombine(dev->dev, obj->size,
1002                                         omap_obj->vaddr, omap_obj->paddr);
1003                 } else if (omap_obj->vaddr) {
1004                         vunmap(omap_obj->vaddr);
1005                 }
1006         }
1007
1008         /* don't free externally allocated syncobj */
1009         if (!(omap_obj->flags & OMAP_BO_EXT_SYNC)) {
1010                 kfree(omap_obj->sync);
1011         }
1012
1013         drm_gem_object_release(obj);
1014
1015         kfree(obj);
1016 }
1017
1018 /* convenience method to construct a GEM buffer object, and userspace handle */
1019 int omap_gem_new_handle(struct drm_device *dev, struct drm_file *file,
1020                 union omap_gem_size gsize, uint32_t flags, uint32_t *handle)
1021 {
1022         struct drm_gem_object *obj;
1023         int ret;
1024
1025         obj = omap_gem_new(dev, gsize, flags);
1026         if (!obj)
1027                 return -ENOMEM;
1028
1029         ret = drm_gem_handle_create(file, obj, handle);
1030         if (ret) {
1031                 drm_gem_object_release(obj);
1032                 kfree(obj); /* TODO isn't there a dtor to call? just copying i915 */
1033                 return ret;
1034         }
1035
1036         /* drop reference from allocate - handle holds it now */
1037         drm_gem_object_unreference_unlocked(obj);
1038
1039         return 0;
1040 }
1041
1042 /* GEM buffer object constructor */
1043 struct drm_gem_object *omap_gem_new(struct drm_device *dev,
1044                 union omap_gem_size gsize, uint32_t flags)
1045 {
1046         struct omap_drm_private *priv = dev->dev_private;
1047         struct omap_gem_object *omap_obj;
1048         struct drm_gem_object *obj = NULL;
1049         size_t size;
1050         int ret;
1051
1052         if (flags & OMAP_BO_TILED) {
1053                 if (!usergart) {
1054                         dev_err(dev->dev, "Tiled buffers require DMM\n");
1055                         goto fail;
1056                 }
1057
1058                 /* tiled buffers are always shmem paged backed.. when they are
1059                  * scanned out, they are remapped into DMM/TILER
1060                  */
1061                 flags &= ~OMAP_BO_SCANOUT;
1062
1063                 /* currently don't allow cached buffers.. there is some caching
1064                  * stuff that needs to be handled better
1065                  */
1066                 flags &= ~(OMAP_BO_CACHED|OMAP_BO_UNCACHED);
1067                 flags |= OMAP_BO_WC;
1068
1069                 /* align dimensions to slot boundaries... */
1070                 tiler_align(gem2fmt(flags),
1071                                 &gsize.tiled.width, &gsize.tiled.height);
1072
1073                 /* ...and calculate size based on aligned dimensions */
1074                 size = tiler_size(gem2fmt(flags),
1075                                 gsize.tiled.width, gsize.tiled.height);
1076         } else {
1077                 size = PAGE_ALIGN(gsize.bytes);
1078         }
1079
1080         omap_obj = kzalloc(sizeof(*omap_obj), GFP_KERNEL);
1081         if (!omap_obj) {
1082                 dev_err(dev->dev, "could not allocate GEM object\n");
1083                 goto fail;
1084         }
1085
1086         obj = &omap_obj->base;
1087
1088         if ((flags & OMAP_BO_SCANOUT) && !priv->has_dmm) {
1089                 /* attempt to allocate contiguous memory if we don't
1090                  * have DMM for remappign discontiguous buffers
1091                  */
1092                 omap_obj->vaddr =  dma_alloc_writecombine(dev->dev, size,
1093                                 &omap_obj->paddr, GFP_KERNEL);
1094                 if (omap_obj->vaddr) {
1095                         flags |= OMAP_BO_DMA;
1096                 }
1097         }
1098
1099         omap_obj->flags = flags;
1100
1101         if (flags & OMAP_BO_TILED) {
1102                 omap_obj->width = gsize.tiled.width;
1103                 omap_obj->height = gsize.tiled.height;
1104         }
1105
1106         if (flags & (OMAP_BO_DMA|OMAP_BO_EXT_MEM)) {
1107                 ret = drm_gem_private_object_init(dev, obj, size);
1108         } else {
1109                 ret = drm_gem_object_init(dev, obj, size);
1110         }
1111
1112         if (ret) {
1113                 goto fail;
1114         }
1115
1116         return obj;
1117
1118 fail:
1119         if (obj) {
1120                 omap_gem_free_object(obj);
1121         }
1122         return NULL;
1123 }
1124
1125 /* init/cleanup.. if DMM is used, we need to set some stuff up.. */
1126 void omap_gem_init(struct drm_device *dev)
1127 {
1128         struct omap_drm_private *priv = dev->dev_private;
1129         const enum tiler_fmt fmts[] = {
1130                         TILFMT_8BIT, TILFMT_16BIT, TILFMT_32BIT
1131         };
1132         int i, j, ret;
1133
1134         ret = omap_dmm_init(dev);
1135         if (ret) {
1136                 /* DMM only supported on OMAP4 and later, so this isn't fatal */
1137                 dev_warn(dev->dev, "omap_dmm_init failed, disabling DMM\n");
1138                 return;
1139         }
1140
1141         usergart = kzalloc(3 * sizeof(*usergart), GFP_KERNEL);
1142         if (!usergart) {
1143                 dev_warn(dev->dev, "could not allocate usergart\n");
1144                 return;
1145         }
1146
1147         /* reserve 4k aligned/wide regions for userspace mappings: */
1148         for (i = 0; i < ARRAY_SIZE(fmts); i++) {
1149                 uint16_t h = 1, w = PAGE_SIZE >> i;
1150                 tiler_align(fmts[i], &w, &h);
1151                 /* note: since each region is 1 4kb page wide, and minimum
1152                  * number of rows, the height ends up being the same as the
1153                  * # of pages in the region
1154                  */
1155                 usergart[i].height = h;
1156                 usergart[i].height_shift = ilog2(h);
1157                 usergart[i].stride_pfn = tiler_stride(fmts[i]) >> PAGE_SHIFT;
1158                 usergart[i].slot_shift = ilog2((PAGE_SIZE / h) >> i);
1159                 for (j = 0; j < NUM_USERGART_ENTRIES; j++) {
1160                         struct usergart_entry *entry = &usergart[i].entry[j];
1161                         struct tiler_block *block =
1162                                         tiler_reserve_2d(fmts[i], w, h,
1163                                                         PAGE_SIZE);
1164                         if (IS_ERR(block)) {
1165                                 dev_err(dev->dev,
1166                                                 "reserve failed: %d, %d, %ld\n",
1167                                                 i, j, PTR_ERR(block));
1168                                 return;
1169                         }
1170                         entry->paddr = tiler_ssptr(block);
1171                         entry->block = block;
1172
1173                         DBG("%d:%d: %dx%d: paddr=%08x stride=%d", i, j, w, h,
1174                                         entry->paddr,
1175                                         usergart[i].stride_pfn << PAGE_SHIFT);
1176                 }
1177         }
1178
1179         priv->has_dmm = true;
1180 }
1181
1182 void omap_gem_deinit(struct drm_device *dev)
1183 {
1184         /* I believe we can rely on there being no more outstanding GEM
1185          * objects which could depend on usergart/dmm at this point.
1186          */
1187         omap_dmm_remove();
1188         kfree(usergart);
1189 }