Merge branch 'drm-intel-fixes' into drm-intel-next
[pandora-kernel.git] / drivers / gpu / drm / drm_gem.c
1 /*
2  * Copyright © 2008 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *
26  */
27
28 #include <linux/types.h>
29 #include <linux/slab.h>
30 #include <linux/mm.h>
31 #include <linux/uaccess.h>
32 #include <linux/fs.h>
33 #include <linux/file.h>
34 #include <linux/module.h>
35 #include <linux/mman.h>
36 #include <linux/pagemap.h>
37 #include <linux/shmem_fs.h>
38 #include "drmP.h"
39
40 /** @file drm_gem.c
41  *
42  * This file provides some of the base ioctls and library routines for
43  * the graphics memory manager implemented by each device driver.
44  *
45  * Because various devices have different requirements in terms of
46  * synchronization and migration strategies, implementing that is left up to
47  * the driver, and all that the general API provides should be generic --
48  * allocating objects, reading/writing data with the cpu, freeing objects.
49  * Even there, platform-dependent optimizations for reading/writing data with
50  * the CPU mean we'll likely hook those out to driver-specific calls.  However,
51  * the DRI2 implementation wants to have at least allocate/mmap be generic.
52  *
53  * The goal was to have swap-backed object allocation managed through
54  * struct file.  However, file descriptors as handles to a struct file have
55  * two major failings:
56  * - Process limits prevent more than 1024 or so being used at a time by
57  *   default.
58  * - Inability to allocate high fds will aggravate the X Server's select()
59  *   handling, and likely that of many GL client applications as well.
60  *
61  * This led to a plan of using our own integer IDs (called handles, following
62  * DRM terminology) to mimic fds, and implement the fd syscalls we need as
63  * ioctls.  The objects themselves will still include the struct file so
64  * that we can transition to fds if the required kernel infrastructure shows
65  * up at a later date, and as our interface with shmfs for memory allocation.
66  */
67
68 /*
69  * We make up offsets for buffer objects so we can recognize them at
70  * mmap time.
71  */
72
73 /* pgoff in mmap is an unsigned long, so we need to make sure that
74  * the faked up offset will fit
75  */
76
77 #if BITS_PER_LONG == 64
78 #define DRM_FILE_PAGE_OFFSET_START ((0xFFFFFFFFUL >> PAGE_SHIFT) + 1)
79 #define DRM_FILE_PAGE_OFFSET_SIZE ((0xFFFFFFFFUL >> PAGE_SHIFT) * 16)
80 #else
81 #define DRM_FILE_PAGE_OFFSET_START ((0xFFFFFFFUL >> PAGE_SHIFT) + 1)
82 #define DRM_FILE_PAGE_OFFSET_SIZE ((0xFFFFFFFUL >> PAGE_SHIFT) * 16)
83 #endif
84
85 /**
86  * Initialize the GEM device fields
87  */
88
89 int
90 drm_gem_init(struct drm_device *dev)
91 {
92         struct drm_gem_mm *mm;
93
94         spin_lock_init(&dev->object_name_lock);
95         idr_init(&dev->object_name_idr);
96
97         mm = kzalloc(sizeof(struct drm_gem_mm), GFP_KERNEL);
98         if (!mm) {
99                 DRM_ERROR("out of memory\n");
100                 return -ENOMEM;
101         }
102
103         dev->mm_private = mm;
104
105         if (drm_ht_create(&mm->offset_hash, 12)) {
106                 kfree(mm);
107                 return -ENOMEM;
108         }
109
110         if (drm_mm_init(&mm->offset_manager, DRM_FILE_PAGE_OFFSET_START,
111                         DRM_FILE_PAGE_OFFSET_SIZE)) {
112                 drm_ht_remove(&mm->offset_hash);
113                 kfree(mm);
114                 return -ENOMEM;
115         }
116
117         return 0;
118 }
119
120 void
121 drm_gem_destroy(struct drm_device *dev)
122 {
123         struct drm_gem_mm *mm = dev->mm_private;
124
125         drm_mm_takedown(&mm->offset_manager);
126         drm_ht_remove(&mm->offset_hash);
127         kfree(mm);
128         dev->mm_private = NULL;
129 }
130
131 /**
132  * Initialize an already allocate GEM object of the specified size with
133  * shmfs backing store.
134  */
135 int drm_gem_object_init(struct drm_device *dev,
136                         struct drm_gem_object *obj, size_t size)
137 {
138         BUG_ON((size & (PAGE_SIZE - 1)) != 0);
139
140         obj->dev = dev;
141         obj->filp = shmem_file_setup("drm mm object", size, VM_NORESERVE);
142         if (IS_ERR(obj->filp))
143                 return -ENOMEM;
144
145         kref_init(&obj->refcount);
146         atomic_set(&obj->handle_count, 0);
147         obj->size = size;
148
149         return 0;
150 }
151 EXPORT_SYMBOL(drm_gem_object_init);
152
153 /**
154  * Allocate a GEM object of the specified size with shmfs backing store
155  */
156 struct drm_gem_object *
157 drm_gem_object_alloc(struct drm_device *dev, size_t size)
158 {
159         struct drm_gem_object *obj;
160
161         obj = kzalloc(sizeof(*obj), GFP_KERNEL);
162         if (!obj)
163                 goto free;
164
165         if (drm_gem_object_init(dev, obj, size) != 0)
166                 goto free;
167
168         if (dev->driver->gem_init_object != NULL &&
169             dev->driver->gem_init_object(obj) != 0) {
170                 goto fput;
171         }
172         return obj;
173 fput:
174         /* Object_init mangles the global counters - readjust them. */
175         fput(obj->filp);
176 free:
177         kfree(obj);
178         return NULL;
179 }
180 EXPORT_SYMBOL(drm_gem_object_alloc);
181
182 /**
183  * Removes the mapping from handle to filp for this object.
184  */
185 int
186 drm_gem_handle_delete(struct drm_file *filp, u32 handle)
187 {
188         struct drm_device *dev;
189         struct drm_gem_object *obj;
190
191         /* This is gross. The idr system doesn't let us try a delete and
192          * return an error code.  It just spews if you fail at deleting.
193          * So, we have to grab a lock around finding the object and then
194          * doing the delete on it and dropping the refcount, or the user
195          * could race us to double-decrement the refcount and cause a
196          * use-after-free later.  Given the frequency of our handle lookups,
197          * we may want to use ida for number allocation and a hash table
198          * for the pointers, anyway.
199          */
200         spin_lock(&filp->table_lock);
201
202         /* Check if we currently have a reference on the object */
203         obj = idr_find(&filp->object_idr, handle);
204         if (obj == NULL) {
205                 spin_unlock(&filp->table_lock);
206                 return -EINVAL;
207         }
208         dev = obj->dev;
209
210         /* Release reference and decrement refcount. */
211         idr_remove(&filp->object_idr, handle);
212         spin_unlock(&filp->table_lock);
213
214         if (dev->driver->gem_close_object)
215                 dev->driver->gem_close_object(obj, filp);
216         drm_gem_object_handle_unreference_unlocked(obj);
217
218         return 0;
219 }
220 EXPORT_SYMBOL(drm_gem_handle_delete);
221
222 /**
223  * Create a handle for this object. This adds a handle reference
224  * to the object, which includes a regular reference count. Callers
225  * will likely want to dereference the object afterwards.
226  */
227 int
228 drm_gem_handle_create(struct drm_file *file_priv,
229                        struct drm_gem_object *obj,
230                        u32 *handlep)
231 {
232         struct drm_device *dev = obj->dev;
233         int ret;
234
235         /*
236          * Get the user-visible handle using idr.
237          */
238 again:
239         /* ensure there is space available to allocate a handle */
240         if (idr_pre_get(&file_priv->object_idr, GFP_KERNEL) == 0)
241                 return -ENOMEM;
242
243         /* do the allocation under our spinlock */
244         spin_lock(&file_priv->table_lock);
245         ret = idr_get_new_above(&file_priv->object_idr, obj, 1, (int *)handlep);
246         spin_unlock(&file_priv->table_lock);
247         if (ret == -EAGAIN)
248                 goto again;
249
250         if (ret != 0)
251                 return ret;
252
253         drm_gem_object_handle_reference(obj);
254
255         if (dev->driver->gem_open_object) {
256                 ret = dev->driver->gem_open_object(obj, file_priv);
257                 if (ret) {
258                         drm_gem_handle_delete(file_priv, *handlep);
259                         return ret;
260                 }
261         }
262
263         return 0;
264 }
265 EXPORT_SYMBOL(drm_gem_handle_create);
266
267 /** Returns a reference to the object named by the handle. */
268 struct drm_gem_object *
269 drm_gem_object_lookup(struct drm_device *dev, struct drm_file *filp,
270                       u32 handle)
271 {
272         struct drm_gem_object *obj;
273
274         spin_lock(&filp->table_lock);
275
276         /* Check if we currently have a reference on the object */
277         obj = idr_find(&filp->object_idr, handle);
278         if (obj == NULL) {
279                 spin_unlock(&filp->table_lock);
280                 return NULL;
281         }
282
283         drm_gem_object_reference(obj);
284
285         spin_unlock(&filp->table_lock);
286
287         return obj;
288 }
289 EXPORT_SYMBOL(drm_gem_object_lookup);
290
291 /**
292  * Releases the handle to an mm object.
293  */
294 int
295 drm_gem_close_ioctl(struct drm_device *dev, void *data,
296                     struct drm_file *file_priv)
297 {
298         struct drm_gem_close *args = data;
299         int ret;
300
301         if (!(dev->driver->driver_features & DRIVER_GEM))
302                 return -ENODEV;
303
304         ret = drm_gem_handle_delete(file_priv, args->handle);
305
306         return ret;
307 }
308
309 /**
310  * Create a global name for an object, returning the name.
311  *
312  * Note that the name does not hold a reference; when the object
313  * is freed, the name goes away.
314  */
315 int
316 drm_gem_flink_ioctl(struct drm_device *dev, void *data,
317                     struct drm_file *file_priv)
318 {
319         struct drm_gem_flink *args = data;
320         struct drm_gem_object *obj;
321         int ret;
322
323         if (!(dev->driver->driver_features & DRIVER_GEM))
324                 return -ENODEV;
325
326         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
327         if (obj == NULL)
328                 return -ENOENT;
329
330 again:
331         if (idr_pre_get(&dev->object_name_idr, GFP_KERNEL) == 0) {
332                 ret = -ENOMEM;
333                 goto err;
334         }
335
336         spin_lock(&dev->object_name_lock);
337         if (!obj->name) {
338                 ret = idr_get_new_above(&dev->object_name_idr, obj, 1,
339                                         &obj->name);
340                 args->name = (uint64_t) obj->name;
341                 spin_unlock(&dev->object_name_lock);
342
343                 if (ret == -EAGAIN)
344                         goto again;
345
346                 if (ret != 0)
347                         goto err;
348
349                 /* Allocate a reference for the name table.  */
350                 drm_gem_object_reference(obj);
351         } else {
352                 args->name = (uint64_t) obj->name;
353                 spin_unlock(&dev->object_name_lock);
354                 ret = 0;
355         }
356
357 err:
358         drm_gem_object_unreference_unlocked(obj);
359         return ret;
360 }
361
362 /**
363  * Open an object using the global name, returning a handle and the size.
364  *
365  * This handle (of course) holds a reference to the object, so the object
366  * will not go away until the handle is deleted.
367  */
368 int
369 drm_gem_open_ioctl(struct drm_device *dev, void *data,
370                    struct drm_file *file_priv)
371 {
372         struct drm_gem_open *args = data;
373         struct drm_gem_object *obj;
374         int ret;
375         u32 handle;
376
377         if (!(dev->driver->driver_features & DRIVER_GEM))
378                 return -ENODEV;
379
380         spin_lock(&dev->object_name_lock);
381         obj = idr_find(&dev->object_name_idr, (int) args->name);
382         if (obj)
383                 drm_gem_object_reference(obj);
384         spin_unlock(&dev->object_name_lock);
385         if (!obj)
386                 return -ENOENT;
387
388         ret = drm_gem_handle_create(file_priv, obj, &handle);
389         drm_gem_object_unreference_unlocked(obj);
390         if (ret)
391                 return ret;
392
393         args->handle = handle;
394         args->size = obj->size;
395
396         return 0;
397 }
398
399 /**
400  * Called at device open time, sets up the structure for handling refcounting
401  * of mm objects.
402  */
403 void
404 drm_gem_open(struct drm_device *dev, struct drm_file *file_private)
405 {
406         idr_init(&file_private->object_idr);
407         spin_lock_init(&file_private->table_lock);
408 }
409
410 /**
411  * Called at device close to release the file's
412  * handle references on objects.
413  */
414 static int
415 drm_gem_object_release_handle(int id, void *ptr, void *data)
416 {
417         struct drm_file *file_priv = data;
418         struct drm_gem_object *obj = ptr;
419         struct drm_device *dev = obj->dev;
420
421         if (dev->driver->gem_close_object)
422                 dev->driver->gem_close_object(obj, file_priv);
423
424         drm_gem_object_handle_unreference_unlocked(obj);
425
426         return 0;
427 }
428
429 /**
430  * Called at close time when the filp is going away.
431  *
432  * Releases any remaining references on objects by this filp.
433  */
434 void
435 drm_gem_release(struct drm_device *dev, struct drm_file *file_private)
436 {
437         idr_for_each(&file_private->object_idr,
438                      &drm_gem_object_release_handle, file_private);
439
440         idr_remove_all(&file_private->object_idr);
441         idr_destroy(&file_private->object_idr);
442 }
443
444 void
445 drm_gem_object_release(struct drm_gem_object *obj)
446 {
447         fput(obj->filp);
448 }
449 EXPORT_SYMBOL(drm_gem_object_release);
450
451 /**
452  * Called after the last reference to the object has been lost.
453  * Must be called holding struct_ mutex
454  *
455  * Frees the object
456  */
457 void
458 drm_gem_object_free(struct kref *kref)
459 {
460         struct drm_gem_object *obj = (struct drm_gem_object *) kref;
461         struct drm_device *dev = obj->dev;
462
463         BUG_ON(!mutex_is_locked(&dev->struct_mutex));
464
465         if (dev->driver->gem_free_object != NULL)
466                 dev->driver->gem_free_object(obj);
467 }
468 EXPORT_SYMBOL(drm_gem_object_free);
469
470 static void drm_gem_object_ref_bug(struct kref *list_kref)
471 {
472         BUG();
473 }
474
475 /**
476  * Called after the last handle to the object has been closed
477  *
478  * Removes any name for the object. Note that this must be
479  * called before drm_gem_object_free or we'll be touching
480  * freed memory
481  */
482 void drm_gem_object_handle_free(struct drm_gem_object *obj)
483 {
484         struct drm_device *dev = obj->dev;
485
486         /* Remove any name for this object */
487         spin_lock(&dev->object_name_lock);
488         if (obj->name) {
489                 idr_remove(&dev->object_name_idr, obj->name);
490                 obj->name = 0;
491                 spin_unlock(&dev->object_name_lock);
492                 /*
493                  * The object name held a reference to this object, drop
494                  * that now.
495                 *
496                 * This cannot be the last reference, since the handle holds one too.
497                  */
498                 kref_put(&obj->refcount, drm_gem_object_ref_bug);
499         } else
500                 spin_unlock(&dev->object_name_lock);
501
502 }
503 EXPORT_SYMBOL(drm_gem_object_handle_free);
504
505 void drm_gem_vm_open(struct vm_area_struct *vma)
506 {
507         struct drm_gem_object *obj = vma->vm_private_data;
508
509         drm_gem_object_reference(obj);
510
511         mutex_lock(&obj->dev->struct_mutex);
512         drm_vm_open_locked(vma);
513         mutex_unlock(&obj->dev->struct_mutex);
514 }
515 EXPORT_SYMBOL(drm_gem_vm_open);
516
517 void drm_gem_vm_close(struct vm_area_struct *vma)
518 {
519         struct drm_gem_object *obj = vma->vm_private_data;
520         struct drm_device *dev = obj->dev;
521
522         mutex_lock(&dev->struct_mutex);
523         drm_vm_close_locked(vma);
524         drm_gem_object_unreference(obj);
525         mutex_unlock(&dev->struct_mutex);
526 }
527 EXPORT_SYMBOL(drm_gem_vm_close);
528
529
530 /**
531  * drm_gem_mmap - memory map routine for GEM objects
532  * @filp: DRM file pointer
533  * @vma: VMA for the area to be mapped
534  *
535  * If a driver supports GEM object mapping, mmap calls on the DRM file
536  * descriptor will end up here.
537  *
538  * If we find the object based on the offset passed in (vma->vm_pgoff will
539  * contain the fake offset we created when the GTT map ioctl was called on
540  * the object), we set up the driver fault handler so that any accesses
541  * to the object can be trapped, to perform migration, GTT binding, surface
542  * register allocation, or performance monitoring.
543  */
544 int drm_gem_mmap(struct file *filp, struct vm_area_struct *vma)
545 {
546         struct drm_file *priv = filp->private_data;
547         struct drm_device *dev = priv->minor->dev;
548         struct drm_gem_mm *mm = dev->mm_private;
549         struct drm_local_map *map = NULL;
550         struct drm_gem_object *obj;
551         struct drm_hash_item *hash;
552         int ret = 0;
553
554         mutex_lock(&dev->struct_mutex);
555
556         if (drm_ht_find_item(&mm->offset_hash, vma->vm_pgoff, &hash)) {
557                 mutex_unlock(&dev->struct_mutex);
558                 return drm_mmap(filp, vma);
559         }
560
561         map = drm_hash_entry(hash, struct drm_map_list, hash)->map;
562         if (!map ||
563             ((map->flags & _DRM_RESTRICTED) && !capable(CAP_SYS_ADMIN))) {
564                 ret =  -EPERM;
565                 goto out_unlock;
566         }
567
568         /* Check for valid size. */
569         if (map->size < vma->vm_end - vma->vm_start) {
570                 ret = -EINVAL;
571                 goto out_unlock;
572         }
573
574         obj = map->handle;
575         if (!obj->dev->driver->gem_vm_ops) {
576                 ret = -EINVAL;
577                 goto out_unlock;
578         }
579
580         vma->vm_flags |= VM_RESERVED | VM_IO | VM_PFNMAP | VM_DONTEXPAND;
581         vma->vm_ops = obj->dev->driver->gem_vm_ops;
582         vma->vm_private_data = map->handle;
583         vma->vm_page_prot =  pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
584
585         /* Take a ref for this mapping of the object, so that the fault
586          * handler can dereference the mmap offset's pointer to the object.
587          * This reference is cleaned up by the corresponding vm_close
588          * (which should happen whether the vma was created by this call, or
589          * by a vm_open due to mremap or partial unmap or whatever).
590          */
591         drm_gem_object_reference(obj);
592
593         vma->vm_file = filp;    /* Needed for drm_vm_open() */
594         drm_vm_open_locked(vma);
595
596 out_unlock:
597         mutex_unlock(&dev->struct_mutex);
598
599         return ret;
600 }
601 EXPORT_SYMBOL(drm_gem_mmap);