Merge branch 'master' of git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6
[linux-2.6] / drivers / gpu / drm / i915 / i915_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 "drmP.h"
29 #include "drm.h"
30 #include "i915_drm.h"
31 #include "i915_drv.h"
32 #include <linux/swap.h>
33 #include <linux/pci.h>
34
35 #define I915_GEM_GPU_DOMAINS    (~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
36
37 static void
38 i915_gem_object_set_to_gpu_domain(struct drm_gem_object *obj,
39                                   uint32_t read_domains,
40                                   uint32_t write_domain);
41 static void i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj);
42 static void i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj);
43 static void i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj);
44 static int i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj,
45                                              int write);
46 static int i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
47                                                      uint64_t offset,
48                                                      uint64_t size);
49 static void i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj);
50 static int i915_gem_object_get_page_list(struct drm_gem_object *obj);
51 static void i915_gem_object_free_page_list(struct drm_gem_object *obj);
52 static int i915_gem_object_wait_rendering(struct drm_gem_object *obj);
53 static int i915_gem_object_bind_to_gtt(struct drm_gem_object *obj,
54                                            unsigned alignment);
55 static void i915_gem_object_get_fence_reg(struct drm_gem_object *obj);
56 static void i915_gem_clear_fence_reg(struct drm_gem_object *obj);
57 static int i915_gem_evict_something(struct drm_device *dev);
58
59 int i915_gem_do_init(struct drm_device *dev, unsigned long start,
60                      unsigned long end)
61 {
62         drm_i915_private_t *dev_priv = dev->dev_private;
63
64         if (start >= end ||
65             (start & (PAGE_SIZE - 1)) != 0 ||
66             (end & (PAGE_SIZE - 1)) != 0) {
67                 return -EINVAL;
68         }
69
70         drm_mm_init(&dev_priv->mm.gtt_space, start,
71                     end - start);
72
73         dev->gtt_total = (uint32_t) (end - start);
74
75         return 0;
76 }
77
78 int
79 i915_gem_init_ioctl(struct drm_device *dev, void *data,
80                     struct drm_file *file_priv)
81 {
82         struct drm_i915_gem_init *args = data;
83         int ret;
84
85         mutex_lock(&dev->struct_mutex);
86         ret = i915_gem_do_init(dev, args->gtt_start, args->gtt_end);
87         mutex_unlock(&dev->struct_mutex);
88
89         return ret;
90 }
91
92 int
93 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
94                             struct drm_file *file_priv)
95 {
96         struct drm_i915_gem_get_aperture *args = data;
97
98         if (!(dev->driver->driver_features & DRIVER_GEM))
99                 return -ENODEV;
100
101         args->aper_size = dev->gtt_total;
102         args->aper_available_size = (args->aper_size -
103                                      atomic_read(&dev->pin_memory));
104
105         return 0;
106 }
107
108
109 /**
110  * Creates a new mm object and returns a handle to it.
111  */
112 int
113 i915_gem_create_ioctl(struct drm_device *dev, void *data,
114                       struct drm_file *file_priv)
115 {
116         struct drm_i915_gem_create *args = data;
117         struct drm_gem_object *obj;
118         int handle, ret;
119
120         args->size = roundup(args->size, PAGE_SIZE);
121
122         /* Allocate the new object */
123         obj = drm_gem_object_alloc(dev, args->size);
124         if (obj == NULL)
125                 return -ENOMEM;
126
127         ret = drm_gem_handle_create(file_priv, obj, &handle);
128         mutex_lock(&dev->struct_mutex);
129         drm_gem_object_handle_unreference(obj);
130         mutex_unlock(&dev->struct_mutex);
131
132         if (ret)
133                 return ret;
134
135         args->handle = handle;
136
137         return 0;
138 }
139
140 /**
141  * Reads data from the object referenced by handle.
142  *
143  * On error, the contents of *data are undefined.
144  */
145 int
146 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
147                      struct drm_file *file_priv)
148 {
149         struct drm_i915_gem_pread *args = data;
150         struct drm_gem_object *obj;
151         struct drm_i915_gem_object *obj_priv;
152         ssize_t read;
153         loff_t offset;
154         int ret;
155
156         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
157         if (obj == NULL)
158                 return -EBADF;
159         obj_priv = obj->driver_private;
160
161         /* Bounds check source.
162          *
163          * XXX: This could use review for overflow issues...
164          */
165         if (args->offset > obj->size || args->size > obj->size ||
166             args->offset + args->size > obj->size) {
167                 drm_gem_object_unreference(obj);
168                 return -EINVAL;
169         }
170
171         mutex_lock(&dev->struct_mutex);
172
173         ret = i915_gem_object_set_cpu_read_domain_range(obj, args->offset,
174                                                         args->size);
175         if (ret != 0) {
176                 drm_gem_object_unreference(obj);
177                 mutex_unlock(&dev->struct_mutex);
178                 return ret;
179         }
180
181         offset = args->offset;
182
183         read = vfs_read(obj->filp, (char __user *)(uintptr_t)args->data_ptr,
184                         args->size, &offset);
185         if (read != args->size) {
186                 drm_gem_object_unreference(obj);
187                 mutex_unlock(&dev->struct_mutex);
188                 if (read < 0)
189                         return read;
190                 else
191                         return -EINVAL;
192         }
193
194         drm_gem_object_unreference(obj);
195         mutex_unlock(&dev->struct_mutex);
196
197         return 0;
198 }
199
200 /* This is the fast write path which cannot handle
201  * page faults in the source data
202  */
203
204 static inline int
205 fast_user_write(struct io_mapping *mapping,
206                 loff_t page_base, int page_offset,
207                 char __user *user_data,
208                 int length)
209 {
210         char *vaddr_atomic;
211         unsigned long unwritten;
212
213         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
214         unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
215                                                       user_data, length);
216         io_mapping_unmap_atomic(vaddr_atomic);
217         if (unwritten)
218                 return -EFAULT;
219         return 0;
220 }
221
222 /* Here's the write path which can sleep for
223  * page faults
224  */
225
226 static inline int
227 slow_user_write(struct io_mapping *mapping,
228                 loff_t page_base, int page_offset,
229                 char __user *user_data,
230                 int length)
231 {
232         char __iomem *vaddr;
233         unsigned long unwritten;
234
235         vaddr = io_mapping_map_wc(mapping, page_base);
236         if (vaddr == NULL)
237                 return -EFAULT;
238         unwritten = __copy_from_user(vaddr + page_offset,
239                                      user_data, length);
240         io_mapping_unmap(vaddr);
241         if (unwritten)
242                 return -EFAULT;
243         return 0;
244 }
245
246 static int
247 i915_gem_gtt_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
248                     struct drm_i915_gem_pwrite *args,
249                     struct drm_file *file_priv)
250 {
251         struct drm_i915_gem_object *obj_priv = obj->driver_private;
252         drm_i915_private_t *dev_priv = dev->dev_private;
253         ssize_t remain;
254         loff_t offset, page_base;
255         char __user *user_data;
256         int page_offset, page_length;
257         int ret;
258
259         user_data = (char __user *) (uintptr_t) args->data_ptr;
260         remain = args->size;
261         if (!access_ok(VERIFY_READ, user_data, remain))
262                 return -EFAULT;
263
264
265         mutex_lock(&dev->struct_mutex);
266         ret = i915_gem_object_pin(obj, 0);
267         if (ret) {
268                 mutex_unlock(&dev->struct_mutex);
269                 return ret;
270         }
271         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
272         if (ret)
273                 goto fail;
274
275         obj_priv = obj->driver_private;
276         offset = obj_priv->gtt_offset + args->offset;
277         obj_priv->dirty = 1;
278
279         while (remain > 0) {
280                 /* Operation in this page
281                  *
282                  * page_base = page offset within aperture
283                  * page_offset = offset within page
284                  * page_length = bytes to copy for this page
285                  */
286                 page_base = (offset & ~(PAGE_SIZE-1));
287                 page_offset = offset & (PAGE_SIZE-1);
288                 page_length = remain;
289                 if ((page_offset + remain) > PAGE_SIZE)
290                         page_length = PAGE_SIZE - page_offset;
291
292                 ret = fast_user_write (dev_priv->mm.gtt_mapping, page_base,
293                                        page_offset, user_data, page_length);
294
295                 /* If we get a fault while copying data, then (presumably) our
296                  * source page isn't available. In this case, use the
297                  * non-atomic function
298                  */
299                 if (ret) {
300                         ret = slow_user_write (dev_priv->mm.gtt_mapping,
301                                                page_base, page_offset,
302                                                user_data, page_length);
303                         if (ret)
304                                 goto fail;
305                 }
306
307                 remain -= page_length;
308                 user_data += page_length;
309                 offset += page_length;
310         }
311
312 fail:
313         i915_gem_object_unpin(obj);
314         mutex_unlock(&dev->struct_mutex);
315
316         return ret;
317 }
318
319 static int
320 i915_gem_shmem_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
321                       struct drm_i915_gem_pwrite *args,
322                       struct drm_file *file_priv)
323 {
324         int ret;
325         loff_t offset;
326         ssize_t written;
327
328         mutex_lock(&dev->struct_mutex);
329
330         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
331         if (ret) {
332                 mutex_unlock(&dev->struct_mutex);
333                 return ret;
334         }
335
336         offset = args->offset;
337
338         written = vfs_write(obj->filp,
339                             (char __user *)(uintptr_t) args->data_ptr,
340                             args->size, &offset);
341         if (written != args->size) {
342                 mutex_unlock(&dev->struct_mutex);
343                 if (written < 0)
344                         return written;
345                 else
346                         return -EINVAL;
347         }
348
349         mutex_unlock(&dev->struct_mutex);
350
351         return 0;
352 }
353
354 /**
355  * Writes data to the object referenced by handle.
356  *
357  * On error, the contents of the buffer that were to be modified are undefined.
358  */
359 int
360 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
361                       struct drm_file *file_priv)
362 {
363         struct drm_i915_gem_pwrite *args = data;
364         struct drm_gem_object *obj;
365         struct drm_i915_gem_object *obj_priv;
366         int ret = 0;
367
368         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
369         if (obj == NULL)
370                 return -EBADF;
371         obj_priv = obj->driver_private;
372
373         /* Bounds check destination.
374          *
375          * XXX: This could use review for overflow issues...
376          */
377         if (args->offset > obj->size || args->size > obj->size ||
378             args->offset + args->size > obj->size) {
379                 drm_gem_object_unreference(obj);
380                 return -EINVAL;
381         }
382
383         /* We can only do the GTT pwrite on untiled buffers, as otherwise
384          * it would end up going through the fenced access, and we'll get
385          * different detiling behavior between reading and writing.
386          * pread/pwrite currently are reading and writing from the CPU
387          * perspective, requiring manual detiling by the client.
388          */
389         if (obj_priv->tiling_mode == I915_TILING_NONE &&
390             dev->gtt_total != 0)
391                 ret = i915_gem_gtt_pwrite(dev, obj, args, file_priv);
392         else
393                 ret = i915_gem_shmem_pwrite(dev, obj, args, file_priv);
394
395 #if WATCH_PWRITE
396         if (ret)
397                 DRM_INFO("pwrite failed %d\n", ret);
398 #endif
399
400         drm_gem_object_unreference(obj);
401
402         return ret;
403 }
404
405 /**
406  * Called when user space prepares to use an object with the CPU, either
407  * through the mmap ioctl's mapping or a GTT mapping.
408  */
409 int
410 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
411                           struct drm_file *file_priv)
412 {
413         struct drm_i915_gem_set_domain *args = data;
414         struct drm_gem_object *obj;
415         uint32_t read_domains = args->read_domains;
416         uint32_t write_domain = args->write_domain;
417         int ret;
418
419         if (!(dev->driver->driver_features & DRIVER_GEM))
420                 return -ENODEV;
421
422         /* Only handle setting domains to types used by the CPU. */
423         if (write_domain & ~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
424                 return -EINVAL;
425
426         if (read_domains & ~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
427                 return -EINVAL;
428
429         /* Having something in the write domain implies it's in the read
430          * domain, and only that read domain.  Enforce that in the request.
431          */
432         if (write_domain != 0 && read_domains != write_domain)
433                 return -EINVAL;
434
435         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
436         if (obj == NULL)
437                 return -EBADF;
438
439         mutex_lock(&dev->struct_mutex);
440 #if WATCH_BUF
441         DRM_INFO("set_domain_ioctl %p(%d), %08x %08x\n",
442                  obj, obj->size, read_domains, write_domain);
443 #endif
444         if (read_domains & I915_GEM_DOMAIN_GTT) {
445                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
446
447                 /* Silently promote "you're not bound, there was nothing to do"
448                  * to success, since the client was just asking us to
449                  * make sure everything was done.
450                  */
451                 if (ret == -EINVAL)
452                         ret = 0;
453         } else {
454                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
455         }
456
457         drm_gem_object_unreference(obj);
458         mutex_unlock(&dev->struct_mutex);
459         return ret;
460 }
461
462 /**
463  * Called when user space has done writes to this buffer
464  */
465 int
466 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
467                       struct drm_file *file_priv)
468 {
469         struct drm_i915_gem_sw_finish *args = data;
470         struct drm_gem_object *obj;
471         struct drm_i915_gem_object *obj_priv;
472         int ret = 0;
473
474         if (!(dev->driver->driver_features & DRIVER_GEM))
475                 return -ENODEV;
476
477         mutex_lock(&dev->struct_mutex);
478         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
479         if (obj == NULL) {
480                 mutex_unlock(&dev->struct_mutex);
481                 return -EBADF;
482         }
483
484 #if WATCH_BUF
485         DRM_INFO("%s: sw_finish %d (%p %d)\n",
486                  __func__, args->handle, obj, obj->size);
487 #endif
488         obj_priv = obj->driver_private;
489
490         /* Pinned buffers may be scanout, so flush the cache */
491         if (obj_priv->pin_count)
492                 i915_gem_object_flush_cpu_write_domain(obj);
493
494         drm_gem_object_unreference(obj);
495         mutex_unlock(&dev->struct_mutex);
496         return ret;
497 }
498
499 /**
500  * Maps the contents of an object, returning the address it is mapped
501  * into.
502  *
503  * While the mapping holds a reference on the contents of the object, it doesn't
504  * imply a ref on the object itself.
505  */
506 int
507 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
508                    struct drm_file *file_priv)
509 {
510         struct drm_i915_gem_mmap *args = data;
511         struct drm_gem_object *obj;
512         loff_t offset;
513         unsigned long addr;
514
515         if (!(dev->driver->driver_features & DRIVER_GEM))
516                 return -ENODEV;
517
518         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
519         if (obj == NULL)
520                 return -EBADF;
521
522         offset = args->offset;
523
524         down_write(&current->mm->mmap_sem);
525         addr = do_mmap(obj->filp, 0, args->size,
526                        PROT_READ | PROT_WRITE, MAP_SHARED,
527                        args->offset);
528         up_write(&current->mm->mmap_sem);
529         mutex_lock(&dev->struct_mutex);
530         drm_gem_object_unreference(obj);
531         mutex_unlock(&dev->struct_mutex);
532         if (IS_ERR((void *)addr))
533                 return addr;
534
535         args->addr_ptr = (uint64_t) addr;
536
537         return 0;
538 }
539
540 /**
541  * i915_gem_fault - fault a page into the GTT
542  * vma: VMA in question
543  * vmf: fault info
544  *
545  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
546  * from userspace.  The fault handler takes care of binding the object to
547  * the GTT (if needed), allocating and programming a fence register (again,
548  * only if needed based on whether the old reg is still valid or the object
549  * is tiled) and inserting a new PTE into the faulting process.
550  *
551  * Note that the faulting process may involve evicting existing objects
552  * from the GTT and/or fence registers to make room.  So performance may
553  * suffer if the GTT working set is large or there are few fence registers
554  * left.
555  */
556 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
557 {
558         struct drm_gem_object *obj = vma->vm_private_data;
559         struct drm_device *dev = obj->dev;
560         struct drm_i915_private *dev_priv = dev->dev_private;
561         struct drm_i915_gem_object *obj_priv = obj->driver_private;
562         pgoff_t page_offset;
563         unsigned long pfn;
564         int ret = 0;
565
566         /* We don't use vmf->pgoff since that has the fake offset */
567         page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
568                 PAGE_SHIFT;
569
570         /* Now bind it into the GTT if needed */
571         mutex_lock(&dev->struct_mutex);
572         if (!obj_priv->gtt_space) {
573                 ret = i915_gem_object_bind_to_gtt(obj, obj_priv->gtt_alignment);
574                 if (ret) {
575                         mutex_unlock(&dev->struct_mutex);
576                         return VM_FAULT_SIGBUS;
577                 }
578                 list_add(&obj_priv->list, &dev_priv->mm.inactive_list);
579         }
580
581         /* Need a new fence register? */
582         if (obj_priv->fence_reg == I915_FENCE_REG_NONE &&
583             obj_priv->tiling_mode != I915_TILING_NONE)
584                 i915_gem_object_get_fence_reg(obj);
585
586         pfn = ((dev->agp->base + obj_priv->gtt_offset) >> PAGE_SHIFT) +
587                 page_offset;
588
589         /* Finally, remap it using the new GTT offset */
590         ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
591
592         mutex_unlock(&dev->struct_mutex);
593
594         switch (ret) {
595         case -ENOMEM:
596         case -EAGAIN:
597                 return VM_FAULT_OOM;
598         case -EFAULT:
599         case -EBUSY:
600                 DRM_ERROR("can't insert pfn??  fault or busy...\n");
601                 return VM_FAULT_SIGBUS;
602         default:
603                 return VM_FAULT_NOPAGE;
604         }
605 }
606
607 /**
608  * i915_gem_create_mmap_offset - create a fake mmap offset for an object
609  * @obj: obj in question
610  *
611  * GEM memory mapping works by handing back to userspace a fake mmap offset
612  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
613  * up the object based on the offset and sets up the various memory mapping
614  * structures.
615  *
616  * This routine allocates and attaches a fake offset for @obj.
617  */
618 static int
619 i915_gem_create_mmap_offset(struct drm_gem_object *obj)
620 {
621         struct drm_device *dev = obj->dev;
622         struct drm_gem_mm *mm = dev->mm_private;
623         struct drm_i915_gem_object *obj_priv = obj->driver_private;
624         struct drm_map_list *list;
625         struct drm_map *map;
626         int ret = 0;
627
628         /* Set the object up for mmap'ing */
629         list = &obj->map_list;
630         list->map = drm_calloc(1, sizeof(struct drm_map_list),
631                                DRM_MEM_DRIVER);
632         if (!list->map)
633                 return -ENOMEM;
634
635         map = list->map;
636         map->type = _DRM_GEM;
637         map->size = obj->size;
638         map->handle = obj;
639
640         /* Get a DRM GEM mmap offset allocated... */
641         list->file_offset_node = drm_mm_search_free(&mm->offset_manager,
642                                                     obj->size / PAGE_SIZE, 0, 0);
643         if (!list->file_offset_node) {
644                 DRM_ERROR("failed to allocate offset for bo %d\n", obj->name);
645                 ret = -ENOMEM;
646                 goto out_free_list;
647         }
648
649         list->file_offset_node = drm_mm_get_block(list->file_offset_node,
650                                                   obj->size / PAGE_SIZE, 0);
651         if (!list->file_offset_node) {
652                 ret = -ENOMEM;
653                 goto out_free_list;
654         }
655
656         list->hash.key = list->file_offset_node->start;
657         if (drm_ht_insert_item(&mm->offset_hash, &list->hash)) {
658                 DRM_ERROR("failed to add to map hash\n");
659                 goto out_free_mm;
660         }
661
662         /* By now we should be all set, any drm_mmap request on the offset
663          * below will get to our mmap & fault handler */
664         obj_priv->mmap_offset = ((uint64_t) list->hash.key) << PAGE_SHIFT;
665
666         return 0;
667
668 out_free_mm:
669         drm_mm_put_block(list->file_offset_node);
670 out_free_list:
671         drm_free(list->map, sizeof(struct drm_map_list), DRM_MEM_DRIVER);
672
673         return ret;
674 }
675
676 /**
677  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
678  * @obj: object to check
679  *
680  * Return the required GTT alignment for an object, taking into account
681  * potential fence register mapping if needed.
682  */
683 static uint32_t
684 i915_gem_get_gtt_alignment(struct drm_gem_object *obj)
685 {
686         struct drm_device *dev = obj->dev;
687         struct drm_i915_gem_object *obj_priv = obj->driver_private;
688         int start, i;
689
690         /*
691          * Minimum alignment is 4k (GTT page size), but might be greater
692          * if a fence register is needed for the object.
693          */
694         if (IS_I965G(dev) || obj_priv->tiling_mode == I915_TILING_NONE)
695                 return 4096;
696
697         /*
698          * Previous chips need to be aligned to the size of the smallest
699          * fence register that can contain the object.
700          */
701         if (IS_I9XX(dev))
702                 start = 1024*1024;
703         else
704                 start = 512*1024;
705
706         for (i = start; i < obj->size; i <<= 1)
707                 ;
708
709         return i;
710 }
711
712 /**
713  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
714  * @dev: DRM device
715  * @data: GTT mapping ioctl data
716  * @file_priv: GEM object info
717  *
718  * Simply returns the fake offset to userspace so it can mmap it.
719  * The mmap call will end up in drm_gem_mmap(), which will set things
720  * up so we can get faults in the handler above.
721  *
722  * The fault handler will take care of binding the object into the GTT
723  * (since it may have been evicted to make room for something), allocating
724  * a fence register, and mapping the appropriate aperture address into
725  * userspace.
726  */
727 int
728 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
729                         struct drm_file *file_priv)
730 {
731         struct drm_i915_gem_mmap_gtt *args = data;
732         struct drm_i915_private *dev_priv = dev->dev_private;
733         struct drm_gem_object *obj;
734         struct drm_i915_gem_object *obj_priv;
735         int ret;
736
737         if (!(dev->driver->driver_features & DRIVER_GEM))
738                 return -ENODEV;
739
740         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
741         if (obj == NULL)
742                 return -EBADF;
743
744         mutex_lock(&dev->struct_mutex);
745
746         obj_priv = obj->driver_private;
747
748         if (!obj_priv->mmap_offset) {
749                 ret = i915_gem_create_mmap_offset(obj);
750                 if (ret)
751                         return ret;
752         }
753
754         args->offset = obj_priv->mmap_offset;
755
756         obj_priv->gtt_alignment = i915_gem_get_gtt_alignment(obj);
757
758         /* Make sure the alignment is correct for fence regs etc */
759         if (obj_priv->agp_mem &&
760             (obj_priv->gtt_offset & (obj_priv->gtt_alignment - 1))) {
761                 drm_gem_object_unreference(obj);
762                 mutex_unlock(&dev->struct_mutex);
763                 return -EINVAL;
764         }
765
766         /*
767          * Pull it into the GTT so that we have a page list (makes the
768          * initial fault faster and any subsequent flushing possible).
769          */
770         if (!obj_priv->agp_mem) {
771                 ret = i915_gem_object_bind_to_gtt(obj, obj_priv->gtt_alignment);
772                 if (ret) {
773                         drm_gem_object_unreference(obj);
774                         mutex_unlock(&dev->struct_mutex);
775                         return ret;
776                 }
777                 list_add(&obj_priv->list, &dev_priv->mm.inactive_list);
778         }
779
780         drm_gem_object_unreference(obj);
781         mutex_unlock(&dev->struct_mutex);
782
783         return 0;
784 }
785
786 static void
787 i915_gem_object_free_page_list(struct drm_gem_object *obj)
788 {
789         struct drm_i915_gem_object *obj_priv = obj->driver_private;
790         int page_count = obj->size / PAGE_SIZE;
791         int i;
792
793         if (obj_priv->page_list == NULL)
794                 return;
795
796
797         for (i = 0; i < page_count; i++)
798                 if (obj_priv->page_list[i] != NULL) {
799                         if (obj_priv->dirty)
800                                 set_page_dirty(obj_priv->page_list[i]);
801                         mark_page_accessed(obj_priv->page_list[i]);
802                         page_cache_release(obj_priv->page_list[i]);
803                 }
804         obj_priv->dirty = 0;
805
806         drm_free(obj_priv->page_list,
807                  page_count * sizeof(struct page *),
808                  DRM_MEM_DRIVER);
809         obj_priv->page_list = NULL;
810 }
811
812 static void
813 i915_gem_object_move_to_active(struct drm_gem_object *obj, uint32_t seqno)
814 {
815         struct drm_device *dev = obj->dev;
816         drm_i915_private_t *dev_priv = dev->dev_private;
817         struct drm_i915_gem_object *obj_priv = obj->driver_private;
818
819         /* Add a reference if we're newly entering the active list. */
820         if (!obj_priv->active) {
821                 drm_gem_object_reference(obj);
822                 obj_priv->active = 1;
823         }
824         /* Move from whatever list we were on to the tail of execution. */
825         list_move_tail(&obj_priv->list,
826                        &dev_priv->mm.active_list);
827         obj_priv->last_rendering_seqno = seqno;
828 }
829
830 static void
831 i915_gem_object_move_to_flushing(struct drm_gem_object *obj)
832 {
833         struct drm_device *dev = obj->dev;
834         drm_i915_private_t *dev_priv = dev->dev_private;
835         struct drm_i915_gem_object *obj_priv = obj->driver_private;
836
837         BUG_ON(!obj_priv->active);
838         list_move_tail(&obj_priv->list, &dev_priv->mm.flushing_list);
839         obj_priv->last_rendering_seqno = 0;
840 }
841
842 static void
843 i915_gem_object_move_to_inactive(struct drm_gem_object *obj)
844 {
845         struct drm_device *dev = obj->dev;
846         drm_i915_private_t *dev_priv = dev->dev_private;
847         struct drm_i915_gem_object *obj_priv = obj->driver_private;
848
849         i915_verify_inactive(dev, __FILE__, __LINE__);
850         if (obj_priv->pin_count != 0)
851                 list_del_init(&obj_priv->list);
852         else
853                 list_move_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
854
855         obj_priv->last_rendering_seqno = 0;
856         if (obj_priv->active) {
857                 obj_priv->active = 0;
858                 drm_gem_object_unreference(obj);
859         }
860         i915_verify_inactive(dev, __FILE__, __LINE__);
861 }
862
863 /**
864  * Creates a new sequence number, emitting a write of it to the status page
865  * plus an interrupt, which will trigger i915_user_interrupt_handler.
866  *
867  * Must be called with struct_lock held.
868  *
869  * Returned sequence numbers are nonzero on success.
870  */
871 static uint32_t
872 i915_add_request(struct drm_device *dev, uint32_t flush_domains)
873 {
874         drm_i915_private_t *dev_priv = dev->dev_private;
875         struct drm_i915_gem_request *request;
876         uint32_t seqno;
877         int was_empty;
878         RING_LOCALS;
879
880         request = drm_calloc(1, sizeof(*request), DRM_MEM_DRIVER);
881         if (request == NULL)
882                 return 0;
883
884         /* Grab the seqno we're going to make this request be, and bump the
885          * next (skipping 0 so it can be the reserved no-seqno value).
886          */
887         seqno = dev_priv->mm.next_gem_seqno;
888         dev_priv->mm.next_gem_seqno++;
889         if (dev_priv->mm.next_gem_seqno == 0)
890                 dev_priv->mm.next_gem_seqno++;
891
892         BEGIN_LP_RING(4);
893         OUT_RING(MI_STORE_DWORD_INDEX);
894         OUT_RING(I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT);
895         OUT_RING(seqno);
896
897         OUT_RING(MI_USER_INTERRUPT);
898         ADVANCE_LP_RING();
899
900         DRM_DEBUG("%d\n", seqno);
901
902         request->seqno = seqno;
903         request->emitted_jiffies = jiffies;
904         was_empty = list_empty(&dev_priv->mm.request_list);
905         list_add_tail(&request->list, &dev_priv->mm.request_list);
906
907         /* Associate any objects on the flushing list matching the write
908          * domain we're flushing with our flush.
909          */
910         if (flush_domains != 0) {
911                 struct drm_i915_gem_object *obj_priv, *next;
912
913                 list_for_each_entry_safe(obj_priv, next,
914                                          &dev_priv->mm.flushing_list, list) {
915                         struct drm_gem_object *obj = obj_priv->obj;
916
917                         if ((obj->write_domain & flush_domains) ==
918                             obj->write_domain) {
919                                 obj->write_domain = 0;
920                                 i915_gem_object_move_to_active(obj, seqno);
921                         }
922                 }
923
924         }
925
926         if (was_empty && !dev_priv->mm.suspended)
927                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
928         return seqno;
929 }
930
931 /**
932  * Command execution barrier
933  *
934  * Ensures that all commands in the ring are finished
935  * before signalling the CPU
936  */
937 static uint32_t
938 i915_retire_commands(struct drm_device *dev)
939 {
940         drm_i915_private_t *dev_priv = dev->dev_private;
941         uint32_t cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
942         uint32_t flush_domains = 0;
943         RING_LOCALS;
944
945         /* The sampler always gets flushed on i965 (sigh) */
946         if (IS_I965G(dev))
947                 flush_domains |= I915_GEM_DOMAIN_SAMPLER;
948         BEGIN_LP_RING(2);
949         OUT_RING(cmd);
950         OUT_RING(0); /* noop */
951         ADVANCE_LP_RING();
952         return flush_domains;
953 }
954
955 /**
956  * Moves buffers associated only with the given active seqno from the active
957  * to inactive list, potentially freeing them.
958  */
959 static void
960 i915_gem_retire_request(struct drm_device *dev,
961                         struct drm_i915_gem_request *request)
962 {
963         drm_i915_private_t *dev_priv = dev->dev_private;
964
965         /* Move any buffers on the active list that are no longer referenced
966          * by the ringbuffer to the flushing/inactive lists as appropriate.
967          */
968         while (!list_empty(&dev_priv->mm.active_list)) {
969                 struct drm_gem_object *obj;
970                 struct drm_i915_gem_object *obj_priv;
971
972                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
973                                             struct drm_i915_gem_object,
974                                             list);
975                 obj = obj_priv->obj;
976
977                 /* If the seqno being retired doesn't match the oldest in the
978                  * list, then the oldest in the list must still be newer than
979                  * this seqno.
980                  */
981                 if (obj_priv->last_rendering_seqno != request->seqno)
982                         return;
983
984 #if WATCH_LRU
985                 DRM_INFO("%s: retire %d moves to inactive list %p\n",
986                          __func__, request->seqno, obj);
987 #endif
988
989                 if (obj->write_domain != 0)
990                         i915_gem_object_move_to_flushing(obj);
991                 else
992                         i915_gem_object_move_to_inactive(obj);
993         }
994 }
995
996 /**
997  * Returns true if seq1 is later than seq2.
998  */
999 static int
1000 i915_seqno_passed(uint32_t seq1, uint32_t seq2)
1001 {
1002         return (int32_t)(seq1 - seq2) >= 0;
1003 }
1004
1005 uint32_t
1006 i915_get_gem_seqno(struct drm_device *dev)
1007 {
1008         drm_i915_private_t *dev_priv = dev->dev_private;
1009
1010         return READ_HWSP(dev_priv, I915_GEM_HWS_INDEX);
1011 }
1012
1013 /**
1014  * This function clears the request list as sequence numbers are passed.
1015  */
1016 void
1017 i915_gem_retire_requests(struct drm_device *dev)
1018 {
1019         drm_i915_private_t *dev_priv = dev->dev_private;
1020         uint32_t seqno;
1021
1022         seqno = i915_get_gem_seqno(dev);
1023
1024         while (!list_empty(&dev_priv->mm.request_list)) {
1025                 struct drm_i915_gem_request *request;
1026                 uint32_t retiring_seqno;
1027
1028                 request = list_first_entry(&dev_priv->mm.request_list,
1029                                            struct drm_i915_gem_request,
1030                                            list);
1031                 retiring_seqno = request->seqno;
1032
1033                 if (i915_seqno_passed(seqno, retiring_seqno) ||
1034                     dev_priv->mm.wedged) {
1035                         i915_gem_retire_request(dev, request);
1036
1037                         list_del(&request->list);
1038                         drm_free(request, sizeof(*request), DRM_MEM_DRIVER);
1039                 } else
1040                         break;
1041         }
1042 }
1043
1044 void
1045 i915_gem_retire_work_handler(struct work_struct *work)
1046 {
1047         drm_i915_private_t *dev_priv;
1048         struct drm_device *dev;
1049
1050         dev_priv = container_of(work, drm_i915_private_t,
1051                                 mm.retire_work.work);
1052         dev = dev_priv->dev;
1053
1054         mutex_lock(&dev->struct_mutex);
1055         i915_gem_retire_requests(dev);
1056         if (!dev_priv->mm.suspended &&
1057             !list_empty(&dev_priv->mm.request_list))
1058                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
1059         mutex_unlock(&dev->struct_mutex);
1060 }
1061
1062 /**
1063  * Waits for a sequence number to be signaled, and cleans up the
1064  * request and object lists appropriately for that event.
1065  */
1066 static int
1067 i915_wait_request(struct drm_device *dev, uint32_t seqno)
1068 {
1069         drm_i915_private_t *dev_priv = dev->dev_private;
1070         int ret = 0;
1071
1072         BUG_ON(seqno == 0);
1073
1074         if (!i915_seqno_passed(i915_get_gem_seqno(dev), seqno)) {
1075                 dev_priv->mm.waiting_gem_seqno = seqno;
1076                 i915_user_irq_get(dev);
1077                 ret = wait_event_interruptible(dev_priv->irq_queue,
1078                                                i915_seqno_passed(i915_get_gem_seqno(dev),
1079                                                                  seqno) ||
1080                                                dev_priv->mm.wedged);
1081                 i915_user_irq_put(dev);
1082                 dev_priv->mm.waiting_gem_seqno = 0;
1083         }
1084         if (dev_priv->mm.wedged)
1085                 ret = -EIO;
1086
1087         if (ret && ret != -ERESTARTSYS)
1088                 DRM_ERROR("%s returns %d (awaiting %d at %d)\n",
1089                           __func__, ret, seqno, i915_get_gem_seqno(dev));
1090
1091         /* Directly dispatch request retiring.  While we have the work queue
1092          * to handle this, the waiter on a request often wants an associated
1093          * buffer to have made it to the inactive list, and we would need
1094          * a separate wait queue to handle that.
1095          */
1096         if (ret == 0)
1097                 i915_gem_retire_requests(dev);
1098
1099         return ret;
1100 }
1101
1102 static void
1103 i915_gem_flush(struct drm_device *dev,
1104                uint32_t invalidate_domains,
1105                uint32_t flush_domains)
1106 {
1107         drm_i915_private_t *dev_priv = dev->dev_private;
1108         uint32_t cmd;
1109         RING_LOCALS;
1110
1111 #if WATCH_EXEC
1112         DRM_INFO("%s: invalidate %08x flush %08x\n", __func__,
1113                   invalidate_domains, flush_domains);
1114 #endif
1115
1116         if (flush_domains & I915_GEM_DOMAIN_CPU)
1117                 drm_agp_chipset_flush(dev);
1118
1119         if ((invalidate_domains | flush_domains) & ~(I915_GEM_DOMAIN_CPU |
1120                                                      I915_GEM_DOMAIN_GTT)) {
1121                 /*
1122                  * read/write caches:
1123                  *
1124                  * I915_GEM_DOMAIN_RENDER is always invalidated, but is
1125                  * only flushed if MI_NO_WRITE_FLUSH is unset.  On 965, it is
1126                  * also flushed at 2d versus 3d pipeline switches.
1127                  *
1128                  * read-only caches:
1129                  *
1130                  * I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
1131                  * MI_READ_FLUSH is set, and is always flushed on 965.
1132                  *
1133                  * I915_GEM_DOMAIN_COMMAND may not exist?
1134                  *
1135                  * I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
1136                  * invalidated when MI_EXE_FLUSH is set.
1137                  *
1138                  * I915_GEM_DOMAIN_VERTEX, which exists on 965, is
1139                  * invalidated with every MI_FLUSH.
1140                  *
1141                  * TLBs:
1142                  *
1143                  * On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
1144                  * and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
1145                  * I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
1146                  * are flushed at any MI_FLUSH.
1147                  */
1148
1149                 cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
1150                 if ((invalidate_domains|flush_domains) &
1151                     I915_GEM_DOMAIN_RENDER)
1152                         cmd &= ~MI_NO_WRITE_FLUSH;
1153                 if (!IS_I965G(dev)) {
1154                         /*
1155                          * On the 965, the sampler cache always gets flushed
1156                          * and this bit is reserved.
1157                          */
1158                         if (invalidate_domains & I915_GEM_DOMAIN_SAMPLER)
1159                                 cmd |= MI_READ_FLUSH;
1160                 }
1161                 if (invalidate_domains & I915_GEM_DOMAIN_INSTRUCTION)
1162                         cmd |= MI_EXE_FLUSH;
1163
1164 #if WATCH_EXEC
1165                 DRM_INFO("%s: queue flush %08x to ring\n", __func__, cmd);
1166 #endif
1167                 BEGIN_LP_RING(2);
1168                 OUT_RING(cmd);
1169                 OUT_RING(0); /* noop */
1170                 ADVANCE_LP_RING();
1171         }
1172 }
1173
1174 /**
1175  * Ensures that all rendering to the object has completed and the object is
1176  * safe to unbind from the GTT or access from the CPU.
1177  */
1178 static int
1179 i915_gem_object_wait_rendering(struct drm_gem_object *obj)
1180 {
1181         struct drm_device *dev = obj->dev;
1182         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1183         int ret;
1184
1185         /* This function only exists to support waiting for existing rendering,
1186          * not for emitting required flushes.
1187          */
1188         BUG_ON((obj->write_domain & I915_GEM_GPU_DOMAINS) != 0);
1189
1190         /* If there is rendering queued on the buffer being evicted, wait for
1191          * it.
1192          */
1193         if (obj_priv->active) {
1194 #if WATCH_BUF
1195                 DRM_INFO("%s: object %p wait for seqno %08x\n",
1196                           __func__, obj, obj_priv->last_rendering_seqno);
1197 #endif
1198                 ret = i915_wait_request(dev, obj_priv->last_rendering_seqno);
1199                 if (ret != 0)
1200                         return ret;
1201         }
1202
1203         return 0;
1204 }
1205
1206 /**
1207  * Unbinds an object from the GTT aperture.
1208  */
1209 static int
1210 i915_gem_object_unbind(struct drm_gem_object *obj)
1211 {
1212         struct drm_device *dev = obj->dev;
1213         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1214         loff_t offset;
1215         int ret = 0;
1216
1217 #if WATCH_BUF
1218         DRM_INFO("%s:%d %p\n", __func__, __LINE__, obj);
1219         DRM_INFO("gtt_space %p\n", obj_priv->gtt_space);
1220 #endif
1221         if (obj_priv->gtt_space == NULL)
1222                 return 0;
1223
1224         if (obj_priv->pin_count != 0) {
1225                 DRM_ERROR("Attempting to unbind pinned buffer\n");
1226                 return -EINVAL;
1227         }
1228
1229         /* Move the object to the CPU domain to ensure that
1230          * any possible CPU writes while it's not in the GTT
1231          * are flushed when we go to remap it. This will
1232          * also ensure that all pending GPU writes are finished
1233          * before we unbind.
1234          */
1235         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
1236         if (ret) {
1237                 if (ret != -ERESTARTSYS)
1238                         DRM_ERROR("set_domain failed: %d\n", ret);
1239                 return ret;
1240         }
1241
1242         if (obj_priv->agp_mem != NULL) {
1243                 drm_unbind_agp(obj_priv->agp_mem);
1244                 drm_free_agp(obj_priv->agp_mem, obj->size / PAGE_SIZE);
1245                 obj_priv->agp_mem = NULL;
1246         }
1247
1248         BUG_ON(obj_priv->active);
1249
1250         /* blow away mappings if mapped through GTT */
1251         offset = ((loff_t) obj->map_list.hash.key) << PAGE_SHIFT;
1252         if (dev->dev_mapping)
1253                 unmap_mapping_range(dev->dev_mapping, offset, obj->size, 1);
1254
1255         if (obj_priv->fence_reg != I915_FENCE_REG_NONE)
1256                 i915_gem_clear_fence_reg(obj);
1257
1258         i915_gem_object_free_page_list(obj);
1259
1260         if (obj_priv->gtt_space) {
1261                 atomic_dec(&dev->gtt_count);
1262                 atomic_sub(obj->size, &dev->gtt_memory);
1263
1264                 drm_mm_put_block(obj_priv->gtt_space);
1265                 obj_priv->gtt_space = NULL;
1266         }
1267
1268         /* Remove ourselves from the LRU list if present. */
1269         if (!list_empty(&obj_priv->list))
1270                 list_del_init(&obj_priv->list);
1271
1272         return 0;
1273 }
1274
1275 static int
1276 i915_gem_evict_something(struct drm_device *dev)
1277 {
1278         drm_i915_private_t *dev_priv = dev->dev_private;
1279         struct drm_gem_object *obj;
1280         struct drm_i915_gem_object *obj_priv;
1281         int ret = 0;
1282
1283         for (;;) {
1284                 /* If there's an inactive buffer available now, grab it
1285                  * and be done.
1286                  */
1287                 if (!list_empty(&dev_priv->mm.inactive_list)) {
1288                         obj_priv = list_first_entry(&dev_priv->mm.inactive_list,
1289                                                     struct drm_i915_gem_object,
1290                                                     list);
1291                         obj = obj_priv->obj;
1292                         BUG_ON(obj_priv->pin_count != 0);
1293 #if WATCH_LRU
1294                         DRM_INFO("%s: evicting %p\n", __func__, obj);
1295 #endif
1296                         BUG_ON(obj_priv->active);
1297
1298                         /* Wait on the rendering and unbind the buffer. */
1299                         ret = i915_gem_object_unbind(obj);
1300                         break;
1301                 }
1302
1303                 /* If we didn't get anything, but the ring is still processing
1304                  * things, wait for one of those things to finish and hopefully
1305                  * leave us a buffer to evict.
1306                  */
1307                 if (!list_empty(&dev_priv->mm.request_list)) {
1308                         struct drm_i915_gem_request *request;
1309
1310                         request = list_first_entry(&dev_priv->mm.request_list,
1311                                                    struct drm_i915_gem_request,
1312                                                    list);
1313
1314                         ret = i915_wait_request(dev, request->seqno);
1315                         if (ret)
1316                                 break;
1317
1318                         /* if waiting caused an object to become inactive,
1319                          * then loop around and wait for it. Otherwise, we
1320                          * assume that waiting freed and unbound something,
1321                          * so there should now be some space in the GTT
1322                          */
1323                         if (!list_empty(&dev_priv->mm.inactive_list))
1324                                 continue;
1325                         break;
1326                 }
1327
1328                 /* If we didn't have anything on the request list but there
1329                  * are buffers awaiting a flush, emit one and try again.
1330                  * When we wait on it, those buffers waiting for that flush
1331                  * will get moved to inactive.
1332                  */
1333                 if (!list_empty(&dev_priv->mm.flushing_list)) {
1334                         obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
1335                                                     struct drm_i915_gem_object,
1336                                                     list);
1337                         obj = obj_priv->obj;
1338
1339                         i915_gem_flush(dev,
1340                                        obj->write_domain,
1341                                        obj->write_domain);
1342                         i915_add_request(dev, obj->write_domain);
1343
1344                         obj = NULL;
1345                         continue;
1346                 }
1347
1348                 DRM_ERROR("inactive empty %d request empty %d "
1349                           "flushing empty %d\n",
1350                           list_empty(&dev_priv->mm.inactive_list),
1351                           list_empty(&dev_priv->mm.request_list),
1352                           list_empty(&dev_priv->mm.flushing_list));
1353                 /* If we didn't do any of the above, there's nothing to be done
1354                  * and we just can't fit it in.
1355                  */
1356                 return -ENOMEM;
1357         }
1358         return ret;
1359 }
1360
1361 static int
1362 i915_gem_evict_everything(struct drm_device *dev)
1363 {
1364         int ret;
1365
1366         for (;;) {
1367                 ret = i915_gem_evict_something(dev);
1368                 if (ret != 0)
1369                         break;
1370         }
1371         if (ret == -ENOMEM)
1372                 return 0;
1373         return ret;
1374 }
1375
1376 static int
1377 i915_gem_object_get_page_list(struct drm_gem_object *obj)
1378 {
1379         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1380         int page_count, i;
1381         struct address_space *mapping;
1382         struct inode *inode;
1383         struct page *page;
1384         int ret;
1385
1386         if (obj_priv->page_list)
1387                 return 0;
1388
1389         /* Get the list of pages out of our struct file.  They'll be pinned
1390          * at this point until we release them.
1391          */
1392         page_count = obj->size / PAGE_SIZE;
1393         BUG_ON(obj_priv->page_list != NULL);
1394         obj_priv->page_list = drm_calloc(page_count, sizeof(struct page *),
1395                                          DRM_MEM_DRIVER);
1396         if (obj_priv->page_list == NULL) {
1397                 DRM_ERROR("Faled to allocate page list\n");
1398                 return -ENOMEM;
1399         }
1400
1401         inode = obj->filp->f_path.dentry->d_inode;
1402         mapping = inode->i_mapping;
1403         for (i = 0; i < page_count; i++) {
1404                 page = read_mapping_page(mapping, i, NULL);
1405                 if (IS_ERR(page)) {
1406                         ret = PTR_ERR(page);
1407                         DRM_ERROR("read_mapping_page failed: %d\n", ret);
1408                         i915_gem_object_free_page_list(obj);
1409                         return ret;
1410                 }
1411                 obj_priv->page_list[i] = page;
1412         }
1413         return 0;
1414 }
1415
1416 static void i965_write_fence_reg(struct drm_i915_fence_reg *reg)
1417 {
1418         struct drm_gem_object *obj = reg->obj;
1419         struct drm_device *dev = obj->dev;
1420         drm_i915_private_t *dev_priv = dev->dev_private;
1421         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1422         int regnum = obj_priv->fence_reg;
1423         uint64_t val;
1424
1425         val = (uint64_t)((obj_priv->gtt_offset + obj->size - 4096) &
1426                     0xfffff000) << 32;
1427         val |= obj_priv->gtt_offset & 0xfffff000;
1428         val |= ((obj_priv->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
1429         if (obj_priv->tiling_mode == I915_TILING_Y)
1430                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
1431         val |= I965_FENCE_REG_VALID;
1432
1433         I915_WRITE64(FENCE_REG_965_0 + (regnum * 8), val);
1434 }
1435
1436 static void i915_write_fence_reg(struct drm_i915_fence_reg *reg)
1437 {
1438         struct drm_gem_object *obj = reg->obj;
1439         struct drm_device *dev = obj->dev;
1440         drm_i915_private_t *dev_priv = dev->dev_private;
1441         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1442         int regnum = obj_priv->fence_reg;
1443         uint32_t val;
1444         uint32_t pitch_val;
1445
1446         if ((obj_priv->gtt_offset & ~I915_FENCE_START_MASK) ||
1447             (obj_priv->gtt_offset & (obj->size - 1))) {
1448                 WARN(1, "%s: object not 1M or size aligned\n", __FUNCTION__);
1449                 return;
1450         }
1451
1452         if (obj_priv->tiling_mode == I915_TILING_Y && (IS_I945G(dev) ||
1453                                                        IS_I945GM(dev) ||
1454                                                        IS_G33(dev)))
1455                 pitch_val = (obj_priv->stride / 128) - 1;
1456         else
1457                 pitch_val = (obj_priv->stride / 512) - 1;
1458
1459         val = obj_priv->gtt_offset;
1460         if (obj_priv->tiling_mode == I915_TILING_Y)
1461                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
1462         val |= I915_FENCE_SIZE_BITS(obj->size);
1463         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
1464         val |= I830_FENCE_REG_VALID;
1465
1466         I915_WRITE(FENCE_REG_830_0 + (regnum * 4), val);
1467 }
1468
1469 static void i830_write_fence_reg(struct drm_i915_fence_reg *reg)
1470 {
1471         struct drm_gem_object *obj = reg->obj;
1472         struct drm_device *dev = obj->dev;
1473         drm_i915_private_t *dev_priv = dev->dev_private;
1474         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1475         int regnum = obj_priv->fence_reg;
1476         uint32_t val;
1477         uint32_t pitch_val;
1478
1479         if ((obj_priv->gtt_offset & ~I915_FENCE_START_MASK) ||
1480             (obj_priv->gtt_offset & (obj->size - 1))) {
1481                 WARN(1, "%s: object not 1M or size aligned\n", __FUNCTION__);
1482                 return;
1483         }
1484
1485         pitch_val = (obj_priv->stride / 128) - 1;
1486
1487         val = obj_priv->gtt_offset;
1488         if (obj_priv->tiling_mode == I915_TILING_Y)
1489                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
1490         val |= I830_FENCE_SIZE_BITS(obj->size);
1491         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
1492         val |= I830_FENCE_REG_VALID;
1493
1494         I915_WRITE(FENCE_REG_830_0 + (regnum * 4), val);
1495
1496 }
1497
1498 /**
1499  * i915_gem_object_get_fence_reg - set up a fence reg for an object
1500  * @obj: object to map through a fence reg
1501  *
1502  * When mapping objects through the GTT, userspace wants to be able to write
1503  * to them without having to worry about swizzling if the object is tiled.
1504  *
1505  * This function walks the fence regs looking for a free one for @obj,
1506  * stealing one if it can't find any.
1507  *
1508  * It then sets up the reg based on the object's properties: address, pitch
1509  * and tiling format.
1510  */
1511 static void
1512 i915_gem_object_get_fence_reg(struct drm_gem_object *obj)
1513 {
1514         struct drm_device *dev = obj->dev;
1515         struct drm_i915_private *dev_priv = dev->dev_private;
1516         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1517         struct drm_i915_fence_reg *reg = NULL;
1518         int i, ret;
1519
1520         switch (obj_priv->tiling_mode) {
1521         case I915_TILING_NONE:
1522                 WARN(1, "allocating a fence for non-tiled object?\n");
1523                 break;
1524         case I915_TILING_X:
1525                 WARN(obj_priv->stride & (512 - 1),
1526                      "object is X tiled but has non-512B pitch\n");
1527                 break;
1528         case I915_TILING_Y:
1529                 WARN(obj_priv->stride & (128 - 1),
1530                      "object is Y tiled but has non-128B pitch\n");
1531                 break;
1532         }
1533
1534         /* First try to find a free reg */
1535         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
1536                 reg = &dev_priv->fence_regs[i];
1537                 if (!reg->obj)
1538                         break;
1539         }
1540
1541         /* None available, try to steal one or wait for a user to finish */
1542         if (i == dev_priv->num_fence_regs) {
1543                 struct drm_i915_gem_object *old_obj_priv = NULL;
1544                 loff_t offset;
1545
1546 try_again:
1547                 /* Could try to use LRU here instead... */
1548                 for (i = dev_priv->fence_reg_start;
1549                      i < dev_priv->num_fence_regs; i++) {
1550                         reg = &dev_priv->fence_regs[i];
1551                         old_obj_priv = reg->obj->driver_private;
1552                         if (!old_obj_priv->pin_count)
1553                                 break;
1554                 }
1555
1556                 /*
1557                  * Now things get ugly... we have to wait for one of the
1558                  * objects to finish before trying again.
1559                  */
1560                 if (i == dev_priv->num_fence_regs) {
1561                         ret = i915_gem_object_wait_rendering(reg->obj);
1562                         if (ret) {
1563                                 WARN(ret, "wait_rendering failed: %d\n", ret);
1564                                 return;
1565                         }
1566                         goto try_again;
1567                 }
1568
1569                 /*
1570                  * Zap this virtual mapping so we can set up a fence again
1571                  * for this object next time we need it.
1572                  */
1573                 offset = ((loff_t) reg->obj->map_list.hash.key) << PAGE_SHIFT;
1574                 if (dev->dev_mapping)
1575                         unmap_mapping_range(dev->dev_mapping, offset,
1576                                             reg->obj->size, 1);
1577                 old_obj_priv->fence_reg = I915_FENCE_REG_NONE;
1578         }
1579
1580         obj_priv->fence_reg = i;
1581         reg->obj = obj;
1582
1583         if (IS_I965G(dev))
1584                 i965_write_fence_reg(reg);
1585         else if (IS_I9XX(dev))
1586                 i915_write_fence_reg(reg);
1587         else
1588                 i830_write_fence_reg(reg);
1589 }
1590
1591 /**
1592  * i915_gem_clear_fence_reg - clear out fence register info
1593  * @obj: object to clear
1594  *
1595  * Zeroes out the fence register itself and clears out the associated
1596  * data structures in dev_priv and obj_priv.
1597  */
1598 static void
1599 i915_gem_clear_fence_reg(struct drm_gem_object *obj)
1600 {
1601         struct drm_device *dev = obj->dev;
1602         drm_i915_private_t *dev_priv = dev->dev_private;
1603         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1604
1605         if (IS_I965G(dev))
1606                 I915_WRITE64(FENCE_REG_965_0 + (obj_priv->fence_reg * 8), 0);
1607         else
1608                 I915_WRITE(FENCE_REG_830_0 + (obj_priv->fence_reg * 4), 0);
1609
1610         dev_priv->fence_regs[obj_priv->fence_reg].obj = NULL;
1611         obj_priv->fence_reg = I915_FENCE_REG_NONE;
1612 }
1613
1614 /**
1615  * Finds free space in the GTT aperture and binds the object there.
1616  */
1617 static int
1618 i915_gem_object_bind_to_gtt(struct drm_gem_object *obj, unsigned alignment)
1619 {
1620         struct drm_device *dev = obj->dev;
1621         drm_i915_private_t *dev_priv = dev->dev_private;
1622         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1623         struct drm_mm_node *free_space;
1624         int page_count, ret;
1625
1626         if (alignment == 0)
1627                 alignment = PAGE_SIZE;
1628         if (alignment & (PAGE_SIZE - 1)) {
1629                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
1630                 return -EINVAL;
1631         }
1632
1633  search_free:
1634         free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
1635                                         obj->size, alignment, 0);
1636         if (free_space != NULL) {
1637                 obj_priv->gtt_space = drm_mm_get_block(free_space, obj->size,
1638                                                        alignment);
1639                 if (obj_priv->gtt_space != NULL) {
1640                         obj_priv->gtt_space->private = obj;
1641                         obj_priv->gtt_offset = obj_priv->gtt_space->start;
1642                 }
1643         }
1644         if (obj_priv->gtt_space == NULL) {
1645                 /* If the gtt is empty and we're still having trouble
1646                  * fitting our object in, we're out of memory.
1647                  */
1648 #if WATCH_LRU
1649                 DRM_INFO("%s: GTT full, evicting something\n", __func__);
1650 #endif
1651                 if (list_empty(&dev_priv->mm.inactive_list) &&
1652                     list_empty(&dev_priv->mm.flushing_list) &&
1653                     list_empty(&dev_priv->mm.active_list)) {
1654                         DRM_ERROR("GTT full, but LRU list empty\n");
1655                         return -ENOMEM;
1656                 }
1657
1658                 ret = i915_gem_evict_something(dev);
1659                 if (ret != 0) {
1660                         if (ret != -ERESTARTSYS)
1661                                 DRM_ERROR("Failed to evict a buffer %d\n", ret);
1662                         return ret;
1663                 }
1664                 goto search_free;
1665         }
1666
1667 #if WATCH_BUF
1668         DRM_INFO("Binding object of size %d at 0x%08x\n",
1669                  obj->size, obj_priv->gtt_offset);
1670 #endif
1671         ret = i915_gem_object_get_page_list(obj);
1672         if (ret) {
1673                 drm_mm_put_block(obj_priv->gtt_space);
1674                 obj_priv->gtt_space = NULL;
1675                 return ret;
1676         }
1677
1678         page_count = obj->size / PAGE_SIZE;
1679         /* Create an AGP memory structure pointing at our pages, and bind it
1680          * into the GTT.
1681          */
1682         obj_priv->agp_mem = drm_agp_bind_pages(dev,
1683                                                obj_priv->page_list,
1684                                                page_count,
1685                                                obj_priv->gtt_offset,
1686                                                obj_priv->agp_type);
1687         if (obj_priv->agp_mem == NULL) {
1688                 i915_gem_object_free_page_list(obj);
1689                 drm_mm_put_block(obj_priv->gtt_space);
1690                 obj_priv->gtt_space = NULL;
1691                 return -ENOMEM;
1692         }
1693         atomic_inc(&dev->gtt_count);
1694         atomic_add(obj->size, &dev->gtt_memory);
1695
1696         /* Assert that the object is not currently in any GPU domain. As it
1697          * wasn't in the GTT, there shouldn't be any way it could have been in
1698          * a GPU cache
1699          */
1700         BUG_ON(obj->read_domains & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
1701         BUG_ON(obj->write_domain & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
1702
1703         return 0;
1704 }
1705
1706 void
1707 i915_gem_clflush_object(struct drm_gem_object *obj)
1708 {
1709         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
1710
1711         /* If we don't have a page list set up, then we're not pinned
1712          * to GPU, and we can ignore the cache flush because it'll happen
1713          * again at bind time.
1714          */
1715         if (obj_priv->page_list == NULL)
1716                 return;
1717
1718         drm_clflush_pages(obj_priv->page_list, obj->size / PAGE_SIZE);
1719 }
1720
1721 /** Flushes any GPU write domain for the object if it's dirty. */
1722 static void
1723 i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj)
1724 {
1725         struct drm_device *dev = obj->dev;
1726         uint32_t seqno;
1727
1728         if ((obj->write_domain & I915_GEM_GPU_DOMAINS) == 0)
1729                 return;
1730
1731         /* Queue the GPU write cache flushing we need. */
1732         i915_gem_flush(dev, 0, obj->write_domain);
1733         seqno = i915_add_request(dev, obj->write_domain);
1734         obj->write_domain = 0;
1735         i915_gem_object_move_to_active(obj, seqno);
1736 }
1737
1738 /** Flushes the GTT write domain for the object if it's dirty. */
1739 static void
1740 i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj)
1741 {
1742         if (obj->write_domain != I915_GEM_DOMAIN_GTT)
1743                 return;
1744
1745         /* No actual flushing is required for the GTT write domain.   Writes
1746          * to it immediately go to main memory as far as we know, so there's
1747          * no chipset flush.  It also doesn't land in render cache.
1748          */
1749         obj->write_domain = 0;
1750 }
1751
1752 /** Flushes the CPU write domain for the object if it's dirty. */
1753 static void
1754 i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj)
1755 {
1756         struct drm_device *dev = obj->dev;
1757
1758         if (obj->write_domain != I915_GEM_DOMAIN_CPU)
1759                 return;
1760
1761         i915_gem_clflush_object(obj);
1762         drm_agp_chipset_flush(dev);
1763         obj->write_domain = 0;
1764 }
1765
1766 /**
1767  * Moves a single object to the GTT read, and possibly write domain.
1768  *
1769  * This function returns when the move is complete, including waiting on
1770  * flushes to occur.
1771  */
1772 int
1773 i915_gem_object_set_to_gtt_domain(struct drm_gem_object *obj, int write)
1774 {
1775         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1776         int ret;
1777
1778         /* Not valid to be called on unbound objects. */
1779         if (obj_priv->gtt_space == NULL)
1780                 return -EINVAL;
1781
1782         i915_gem_object_flush_gpu_write_domain(obj);
1783         /* Wait on any GPU rendering and flushing to occur. */
1784         ret = i915_gem_object_wait_rendering(obj);
1785         if (ret != 0)
1786                 return ret;
1787
1788         /* If we're writing through the GTT domain, then CPU and GPU caches
1789          * will need to be invalidated at next use.
1790          */
1791         if (write)
1792                 obj->read_domains &= I915_GEM_DOMAIN_GTT;
1793
1794         i915_gem_object_flush_cpu_write_domain(obj);
1795
1796         /* It should now be out of any other write domains, and we can update
1797          * the domain values for our changes.
1798          */
1799         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
1800         obj->read_domains |= I915_GEM_DOMAIN_GTT;
1801         if (write) {
1802                 obj->write_domain = I915_GEM_DOMAIN_GTT;
1803                 obj_priv->dirty = 1;
1804         }
1805
1806         return 0;
1807 }
1808
1809 /**
1810  * Moves a single object to the CPU read, and possibly write domain.
1811  *
1812  * This function returns when the move is complete, including waiting on
1813  * flushes to occur.
1814  */
1815 static int
1816 i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj, int write)
1817 {
1818         struct drm_device *dev = obj->dev;
1819         int ret;
1820
1821         i915_gem_object_flush_gpu_write_domain(obj);
1822         /* Wait on any GPU rendering and flushing to occur. */
1823         ret = i915_gem_object_wait_rendering(obj);
1824         if (ret != 0)
1825                 return ret;
1826
1827         i915_gem_object_flush_gtt_write_domain(obj);
1828
1829         /* If we have a partially-valid cache of the object in the CPU,
1830          * finish invalidating it and free the per-page flags.
1831          */
1832         i915_gem_object_set_to_full_cpu_read_domain(obj);
1833
1834         /* Flush the CPU cache if it's still invalid. */
1835         if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
1836                 i915_gem_clflush_object(obj);
1837                 drm_agp_chipset_flush(dev);
1838
1839                 obj->read_domains |= I915_GEM_DOMAIN_CPU;
1840         }
1841
1842         /* It should now be out of any other write domains, and we can update
1843          * the domain values for our changes.
1844          */
1845         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
1846
1847         /* If we're writing through the CPU, then the GPU read domains will
1848          * need to be invalidated at next use.
1849          */
1850         if (write) {
1851                 obj->read_domains &= I915_GEM_DOMAIN_CPU;
1852                 obj->write_domain = I915_GEM_DOMAIN_CPU;
1853         }
1854
1855         return 0;
1856 }
1857
1858 /*
1859  * Set the next domain for the specified object. This
1860  * may not actually perform the necessary flushing/invaliding though,
1861  * as that may want to be batched with other set_domain operations
1862  *
1863  * This is (we hope) the only really tricky part of gem. The goal
1864  * is fairly simple -- track which caches hold bits of the object
1865  * and make sure they remain coherent. A few concrete examples may
1866  * help to explain how it works. For shorthand, we use the notation
1867  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
1868  * a pair of read and write domain masks.
1869  *
1870  * Case 1: the batch buffer
1871  *
1872  *      1. Allocated
1873  *      2. Written by CPU
1874  *      3. Mapped to GTT
1875  *      4. Read by GPU
1876  *      5. Unmapped from GTT
1877  *      6. Freed
1878  *
1879  *      Let's take these a step at a time
1880  *
1881  *      1. Allocated
1882  *              Pages allocated from the kernel may still have
1883  *              cache contents, so we set them to (CPU, CPU) always.
1884  *      2. Written by CPU (using pwrite)
1885  *              The pwrite function calls set_domain (CPU, CPU) and
1886  *              this function does nothing (as nothing changes)
1887  *      3. Mapped by GTT
1888  *              This function asserts that the object is not
1889  *              currently in any GPU-based read or write domains
1890  *      4. Read by GPU
1891  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
1892  *              As write_domain is zero, this function adds in the
1893  *              current read domains (CPU+COMMAND, 0).
1894  *              flush_domains is set to CPU.
1895  *              invalidate_domains is set to COMMAND
1896  *              clflush is run to get data out of the CPU caches
1897  *              then i915_dev_set_domain calls i915_gem_flush to
1898  *              emit an MI_FLUSH and drm_agp_chipset_flush
1899  *      5. Unmapped from GTT
1900  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
1901  *              flush_domains and invalidate_domains end up both zero
1902  *              so no flushing/invalidating happens
1903  *      6. Freed
1904  *              yay, done
1905  *
1906  * Case 2: The shared render buffer
1907  *
1908  *      1. Allocated
1909  *      2. Mapped to GTT
1910  *      3. Read/written by GPU
1911  *      4. set_domain to (CPU,CPU)
1912  *      5. Read/written by CPU
1913  *      6. Read/written by GPU
1914  *
1915  *      1. Allocated
1916  *              Same as last example, (CPU, CPU)
1917  *      2. Mapped to GTT
1918  *              Nothing changes (assertions find that it is not in the GPU)
1919  *      3. Read/written by GPU
1920  *              execbuffer calls set_domain (RENDER, RENDER)
1921  *              flush_domains gets CPU
1922  *              invalidate_domains gets GPU
1923  *              clflush (obj)
1924  *              MI_FLUSH and drm_agp_chipset_flush
1925  *      4. set_domain (CPU, CPU)
1926  *              flush_domains gets GPU
1927  *              invalidate_domains gets CPU
1928  *              wait_rendering (obj) to make sure all drawing is complete.
1929  *              This will include an MI_FLUSH to get the data from GPU
1930  *              to memory
1931  *              clflush (obj) to invalidate the CPU cache
1932  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
1933  *      5. Read/written by CPU
1934  *              cache lines are loaded and dirtied
1935  *      6. Read written by GPU
1936  *              Same as last GPU access
1937  *
1938  * Case 3: The constant buffer
1939  *
1940  *      1. Allocated
1941  *      2. Written by CPU
1942  *      3. Read by GPU
1943  *      4. Updated (written) by CPU again
1944  *      5. Read by GPU
1945  *
1946  *      1. Allocated
1947  *              (CPU, CPU)
1948  *      2. Written by CPU
1949  *              (CPU, CPU)
1950  *      3. Read by GPU
1951  *              (CPU+RENDER, 0)
1952  *              flush_domains = CPU
1953  *              invalidate_domains = RENDER
1954  *              clflush (obj)
1955  *              MI_FLUSH
1956  *              drm_agp_chipset_flush
1957  *      4. Updated (written) by CPU again
1958  *              (CPU, CPU)
1959  *              flush_domains = 0 (no previous write domain)
1960  *              invalidate_domains = 0 (no new read domains)
1961  *      5. Read by GPU
1962  *              (CPU+RENDER, 0)
1963  *              flush_domains = CPU
1964  *              invalidate_domains = RENDER
1965  *              clflush (obj)
1966  *              MI_FLUSH
1967  *              drm_agp_chipset_flush
1968  */
1969 static void
1970 i915_gem_object_set_to_gpu_domain(struct drm_gem_object *obj,
1971                                   uint32_t read_domains,
1972                                   uint32_t write_domain)
1973 {
1974         struct drm_device               *dev = obj->dev;
1975         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
1976         uint32_t                        invalidate_domains = 0;
1977         uint32_t                        flush_domains = 0;
1978
1979         BUG_ON(read_domains & I915_GEM_DOMAIN_CPU);
1980         BUG_ON(write_domain == I915_GEM_DOMAIN_CPU);
1981
1982 #if WATCH_BUF
1983         DRM_INFO("%s: object %p read %08x -> %08x write %08x -> %08x\n",
1984                  __func__, obj,
1985                  obj->read_domains, read_domains,
1986                  obj->write_domain, write_domain);
1987 #endif
1988         /*
1989          * If the object isn't moving to a new write domain,
1990          * let the object stay in multiple read domains
1991          */
1992         if (write_domain == 0)
1993                 read_domains |= obj->read_domains;
1994         else
1995                 obj_priv->dirty = 1;
1996
1997         /*
1998          * Flush the current write domain if
1999          * the new read domains don't match. Invalidate
2000          * any read domains which differ from the old
2001          * write domain
2002          */
2003         if (obj->write_domain && obj->write_domain != read_domains) {
2004                 flush_domains |= obj->write_domain;
2005                 invalidate_domains |= read_domains & ~obj->write_domain;
2006         }
2007         /*
2008          * Invalidate any read caches which may have
2009          * stale data. That is, any new read domains.
2010          */
2011         invalidate_domains |= read_domains & ~obj->read_domains;
2012         if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU) {
2013 #if WATCH_BUF
2014                 DRM_INFO("%s: CPU domain flush %08x invalidate %08x\n",
2015                          __func__, flush_domains, invalidate_domains);
2016 #endif
2017                 i915_gem_clflush_object(obj);
2018         }
2019
2020         if ((write_domain | flush_domains) != 0)
2021                 obj->write_domain = write_domain;
2022         obj->read_domains = read_domains;
2023
2024         dev->invalidate_domains |= invalidate_domains;
2025         dev->flush_domains |= flush_domains;
2026 #if WATCH_BUF
2027         DRM_INFO("%s: read %08x write %08x invalidate %08x flush %08x\n",
2028                  __func__,
2029                  obj->read_domains, obj->write_domain,
2030                  dev->invalidate_domains, dev->flush_domains);
2031 #endif
2032 }
2033
2034 /**
2035  * Moves the object from a partially CPU read to a full one.
2036  *
2037  * Note that this only resolves i915_gem_object_set_cpu_read_domain_range(),
2038  * and doesn't handle transitioning from !(read_domains & I915_GEM_DOMAIN_CPU).
2039  */
2040 static void
2041 i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj)
2042 {
2043         struct drm_device *dev = obj->dev;
2044         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2045
2046         if (!obj_priv->page_cpu_valid)
2047                 return;
2048
2049         /* If we're partially in the CPU read domain, finish moving it in.
2050          */
2051         if (obj->read_domains & I915_GEM_DOMAIN_CPU) {
2052                 int i;
2053
2054                 for (i = 0; i <= (obj->size - 1) / PAGE_SIZE; i++) {
2055                         if (obj_priv->page_cpu_valid[i])
2056                                 continue;
2057                         drm_clflush_pages(obj_priv->page_list + i, 1);
2058                 }
2059                 drm_agp_chipset_flush(dev);
2060         }
2061
2062         /* Free the page_cpu_valid mappings which are now stale, whether
2063          * or not we've got I915_GEM_DOMAIN_CPU.
2064          */
2065         drm_free(obj_priv->page_cpu_valid, obj->size / PAGE_SIZE,
2066                  DRM_MEM_DRIVER);
2067         obj_priv->page_cpu_valid = NULL;
2068 }
2069
2070 /**
2071  * Set the CPU read domain on a range of the object.
2072  *
2073  * The object ends up with I915_GEM_DOMAIN_CPU in its read flags although it's
2074  * not entirely valid.  The page_cpu_valid member of the object flags which
2075  * pages have been flushed, and will be respected by
2076  * i915_gem_object_set_to_cpu_domain() if it's called on to get a valid mapping
2077  * of the whole object.
2078  *
2079  * This function returns when the move is complete, including waiting on
2080  * flushes to occur.
2081  */
2082 static int
2083 i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
2084                                           uint64_t offset, uint64_t size)
2085 {
2086         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2087         int i, ret;
2088
2089         if (offset == 0 && size == obj->size)
2090                 return i915_gem_object_set_to_cpu_domain(obj, 0);
2091
2092         i915_gem_object_flush_gpu_write_domain(obj);
2093         /* Wait on any GPU rendering and flushing to occur. */
2094         ret = i915_gem_object_wait_rendering(obj);
2095         if (ret != 0)
2096                 return ret;
2097         i915_gem_object_flush_gtt_write_domain(obj);
2098
2099         /* If we're already fully in the CPU read domain, we're done. */
2100         if (obj_priv->page_cpu_valid == NULL &&
2101             (obj->read_domains & I915_GEM_DOMAIN_CPU) != 0)
2102                 return 0;
2103
2104         /* Otherwise, create/clear the per-page CPU read domain flag if we're
2105          * newly adding I915_GEM_DOMAIN_CPU
2106          */
2107         if (obj_priv->page_cpu_valid == NULL) {
2108                 obj_priv->page_cpu_valid = drm_calloc(1, obj->size / PAGE_SIZE,
2109                                                       DRM_MEM_DRIVER);
2110                 if (obj_priv->page_cpu_valid == NULL)
2111                         return -ENOMEM;
2112         } else if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0)
2113                 memset(obj_priv->page_cpu_valid, 0, obj->size / PAGE_SIZE);
2114
2115         /* Flush the cache on any pages that are still invalid from the CPU's
2116          * perspective.
2117          */
2118         for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
2119              i++) {
2120                 if (obj_priv->page_cpu_valid[i])
2121                         continue;
2122
2123                 drm_clflush_pages(obj_priv->page_list + i, 1);
2124
2125                 obj_priv->page_cpu_valid[i] = 1;
2126         }
2127
2128         /* It should now be out of any other write domains, and we can update
2129          * the domain values for our changes.
2130          */
2131         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
2132
2133         obj->read_domains |= I915_GEM_DOMAIN_CPU;
2134
2135         return 0;
2136 }
2137
2138 /**
2139  * Pin an object to the GTT and evaluate the relocations landing in it.
2140  */
2141 static int
2142 i915_gem_object_pin_and_relocate(struct drm_gem_object *obj,
2143                                  struct drm_file *file_priv,
2144                                  struct drm_i915_gem_exec_object *entry)
2145 {
2146         struct drm_device *dev = obj->dev;
2147         drm_i915_private_t *dev_priv = dev->dev_private;
2148         struct drm_i915_gem_relocation_entry reloc;
2149         struct drm_i915_gem_relocation_entry __user *relocs;
2150         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2151         int i, ret;
2152         void __iomem *reloc_page;
2153
2154         /* Choose the GTT offset for our buffer and put it there. */
2155         ret = i915_gem_object_pin(obj, (uint32_t) entry->alignment);
2156         if (ret)
2157                 return ret;
2158
2159         entry->offset = obj_priv->gtt_offset;
2160
2161         relocs = (struct drm_i915_gem_relocation_entry __user *)
2162                  (uintptr_t) entry->relocs_ptr;
2163         /* Apply the relocations, using the GTT aperture to avoid cache
2164          * flushing requirements.
2165          */
2166         for (i = 0; i < entry->relocation_count; i++) {
2167                 struct drm_gem_object *target_obj;
2168                 struct drm_i915_gem_object *target_obj_priv;
2169                 uint32_t reloc_val, reloc_offset;
2170                 uint32_t __iomem *reloc_entry;
2171
2172                 ret = copy_from_user(&reloc, relocs + i, sizeof(reloc));
2173                 if (ret != 0) {
2174                         i915_gem_object_unpin(obj);
2175                         return ret;
2176                 }
2177
2178                 target_obj = drm_gem_object_lookup(obj->dev, file_priv,
2179                                                    reloc.target_handle);
2180                 if (target_obj == NULL) {
2181                         i915_gem_object_unpin(obj);
2182                         return -EBADF;
2183                 }
2184                 target_obj_priv = target_obj->driver_private;
2185
2186                 /* The target buffer should have appeared before us in the
2187                  * exec_object list, so it should have a GTT space bound by now.
2188                  */
2189                 if (target_obj_priv->gtt_space == NULL) {
2190                         DRM_ERROR("No GTT space found for object %d\n",
2191                                   reloc.target_handle);
2192                         drm_gem_object_unreference(target_obj);
2193                         i915_gem_object_unpin(obj);
2194                         return -EINVAL;
2195                 }
2196
2197                 if (reloc.offset > obj->size - 4) {
2198                         DRM_ERROR("Relocation beyond object bounds: "
2199                                   "obj %p target %d offset %d size %d.\n",
2200                                   obj, reloc.target_handle,
2201                                   (int) reloc.offset, (int) obj->size);
2202                         drm_gem_object_unreference(target_obj);
2203                         i915_gem_object_unpin(obj);
2204                         return -EINVAL;
2205                 }
2206                 if (reloc.offset & 3) {
2207                         DRM_ERROR("Relocation not 4-byte aligned: "
2208                                   "obj %p target %d offset %d.\n",
2209                                   obj, reloc.target_handle,
2210                                   (int) reloc.offset);
2211                         drm_gem_object_unreference(target_obj);
2212                         i915_gem_object_unpin(obj);
2213                         return -EINVAL;
2214                 }
2215
2216                 if (reloc.write_domain & I915_GEM_DOMAIN_CPU ||
2217                     reloc.read_domains & I915_GEM_DOMAIN_CPU) {
2218                         DRM_ERROR("reloc with read/write CPU domains: "
2219                                   "obj %p target %d offset %d "
2220                                   "read %08x write %08x",
2221                                   obj, reloc.target_handle,
2222                                   (int) reloc.offset,
2223                                   reloc.read_domains,
2224                                   reloc.write_domain);
2225                         return -EINVAL;
2226                 }
2227
2228                 if (reloc.write_domain && target_obj->pending_write_domain &&
2229                     reloc.write_domain != target_obj->pending_write_domain) {
2230                         DRM_ERROR("Write domain conflict: "
2231                                   "obj %p target %d offset %d "
2232                                   "new %08x old %08x\n",
2233                                   obj, reloc.target_handle,
2234                                   (int) reloc.offset,
2235                                   reloc.write_domain,
2236                                   target_obj->pending_write_domain);
2237                         drm_gem_object_unreference(target_obj);
2238                         i915_gem_object_unpin(obj);
2239                         return -EINVAL;
2240                 }
2241
2242 #if WATCH_RELOC
2243                 DRM_INFO("%s: obj %p offset %08x target %d "
2244                          "read %08x write %08x gtt %08x "
2245                          "presumed %08x delta %08x\n",
2246                          __func__,
2247                          obj,
2248                          (int) reloc.offset,
2249                          (int) reloc.target_handle,
2250                          (int) reloc.read_domains,
2251                          (int) reloc.write_domain,
2252                          (int) target_obj_priv->gtt_offset,
2253                          (int) reloc.presumed_offset,
2254                          reloc.delta);
2255 #endif
2256
2257                 target_obj->pending_read_domains |= reloc.read_domains;
2258                 target_obj->pending_write_domain |= reloc.write_domain;
2259
2260                 /* If the relocation already has the right value in it, no
2261                  * more work needs to be done.
2262                  */
2263                 if (target_obj_priv->gtt_offset == reloc.presumed_offset) {
2264                         drm_gem_object_unreference(target_obj);
2265                         continue;
2266                 }
2267
2268                 ret = i915_gem_object_set_to_gtt_domain(obj, 1);
2269                 if (ret != 0) {
2270                         drm_gem_object_unreference(target_obj);
2271                         i915_gem_object_unpin(obj);
2272                         return -EINVAL;
2273                 }
2274
2275                 /* Map the page containing the relocation we're going to
2276                  * perform.
2277                  */
2278                 reloc_offset = obj_priv->gtt_offset + reloc.offset;
2279                 reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
2280                                                       (reloc_offset &
2281                                                        ~(PAGE_SIZE - 1)));
2282                 reloc_entry = (uint32_t __iomem *)(reloc_page +
2283                                                    (reloc_offset & (PAGE_SIZE - 1)));
2284                 reloc_val = target_obj_priv->gtt_offset + reloc.delta;
2285
2286 #if WATCH_BUF
2287                 DRM_INFO("Applied relocation: %p@0x%08x %08x -> %08x\n",
2288                           obj, (unsigned int) reloc.offset,
2289                           readl(reloc_entry), reloc_val);
2290 #endif
2291                 writel(reloc_val, reloc_entry);
2292                 io_mapping_unmap_atomic(reloc_page);
2293
2294                 /* Write the updated presumed offset for this entry back out
2295                  * to the user.
2296                  */
2297                 reloc.presumed_offset = target_obj_priv->gtt_offset;
2298                 ret = copy_to_user(relocs + i, &reloc, sizeof(reloc));
2299                 if (ret != 0) {
2300                         drm_gem_object_unreference(target_obj);
2301                         i915_gem_object_unpin(obj);
2302                         return ret;
2303                 }
2304
2305                 drm_gem_object_unreference(target_obj);
2306         }
2307
2308 #if WATCH_BUF
2309         if (0)
2310                 i915_gem_dump_object(obj, 128, __func__, ~0);
2311 #endif
2312         return 0;
2313 }
2314
2315 /** Dispatch a batchbuffer to the ring
2316  */
2317 static int
2318 i915_dispatch_gem_execbuffer(struct drm_device *dev,
2319                               struct drm_i915_gem_execbuffer *exec,
2320                               uint64_t exec_offset)
2321 {
2322         drm_i915_private_t *dev_priv = dev->dev_private;
2323         struct drm_clip_rect __user *boxes = (struct drm_clip_rect __user *)
2324                                              (uintptr_t) exec->cliprects_ptr;
2325         int nbox = exec->num_cliprects;
2326         int i = 0, count;
2327         uint32_t        exec_start, exec_len;
2328         RING_LOCALS;
2329
2330         exec_start = (uint32_t) exec_offset + exec->batch_start_offset;
2331         exec_len = (uint32_t) exec->batch_len;
2332
2333         if ((exec_start | exec_len) & 0x7) {
2334                 DRM_ERROR("alignment\n");
2335                 return -EINVAL;
2336         }
2337
2338         if (!exec_start)
2339                 return -EINVAL;
2340
2341         count = nbox ? nbox : 1;
2342
2343         for (i = 0; i < count; i++) {
2344                 if (i < nbox) {
2345                         int ret = i915_emit_box(dev, boxes, i,
2346                                                 exec->DR1, exec->DR4);
2347                         if (ret)
2348                                 return ret;
2349                 }
2350
2351                 if (IS_I830(dev) || IS_845G(dev)) {
2352                         BEGIN_LP_RING(4);
2353                         OUT_RING(MI_BATCH_BUFFER);
2354                         OUT_RING(exec_start | MI_BATCH_NON_SECURE);
2355                         OUT_RING(exec_start + exec_len - 4);
2356                         OUT_RING(0);
2357                         ADVANCE_LP_RING();
2358                 } else {
2359                         BEGIN_LP_RING(2);
2360                         if (IS_I965G(dev)) {
2361                                 OUT_RING(MI_BATCH_BUFFER_START |
2362                                          (2 << 6) |
2363                                          MI_BATCH_NON_SECURE_I965);
2364                                 OUT_RING(exec_start);
2365                         } else {
2366                                 OUT_RING(MI_BATCH_BUFFER_START |
2367                                          (2 << 6));
2368                                 OUT_RING(exec_start | MI_BATCH_NON_SECURE);
2369                         }
2370                         ADVANCE_LP_RING();
2371                 }
2372         }
2373
2374         /* XXX breadcrumb */
2375         return 0;
2376 }
2377
2378 /* Throttle our rendering by waiting until the ring has completed our requests
2379  * emitted over 20 msec ago.
2380  *
2381  * This should get us reasonable parallelism between CPU and GPU but also
2382  * relatively low latency when blocking on a particular request to finish.
2383  */
2384 static int
2385 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file_priv)
2386 {
2387         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
2388         int ret = 0;
2389         uint32_t seqno;
2390
2391         mutex_lock(&dev->struct_mutex);
2392         seqno = i915_file_priv->mm.last_gem_throttle_seqno;
2393         i915_file_priv->mm.last_gem_throttle_seqno =
2394                 i915_file_priv->mm.last_gem_seqno;
2395         if (seqno)
2396                 ret = i915_wait_request(dev, seqno);
2397         mutex_unlock(&dev->struct_mutex);
2398         return ret;
2399 }
2400
2401 int
2402 i915_gem_execbuffer(struct drm_device *dev, void *data,
2403                     struct drm_file *file_priv)
2404 {
2405         drm_i915_private_t *dev_priv = dev->dev_private;
2406         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
2407         struct drm_i915_gem_execbuffer *args = data;
2408         struct drm_i915_gem_exec_object *exec_list = NULL;
2409         struct drm_gem_object **object_list = NULL;
2410         struct drm_gem_object *batch_obj;
2411         int ret, i, pinned = 0;
2412         uint64_t exec_offset;
2413         uint32_t seqno, flush_domains;
2414         int pin_tries;
2415
2416 #if WATCH_EXEC
2417         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
2418                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
2419 #endif
2420
2421         if (args->buffer_count < 1) {
2422                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
2423                 return -EINVAL;
2424         }
2425         /* Copy in the exec list from userland */
2426         exec_list = drm_calloc(sizeof(*exec_list), args->buffer_count,
2427                                DRM_MEM_DRIVER);
2428         object_list = drm_calloc(sizeof(*object_list), args->buffer_count,
2429                                  DRM_MEM_DRIVER);
2430         if (exec_list == NULL || object_list == NULL) {
2431                 DRM_ERROR("Failed to allocate exec or object list "
2432                           "for %d buffers\n",
2433                           args->buffer_count);
2434                 ret = -ENOMEM;
2435                 goto pre_mutex_err;
2436         }
2437         ret = copy_from_user(exec_list,
2438                              (struct drm_i915_relocation_entry __user *)
2439                              (uintptr_t) args->buffers_ptr,
2440                              sizeof(*exec_list) * args->buffer_count);
2441         if (ret != 0) {
2442                 DRM_ERROR("copy %d exec entries failed %d\n",
2443                           args->buffer_count, ret);
2444                 goto pre_mutex_err;
2445         }
2446
2447         mutex_lock(&dev->struct_mutex);
2448
2449         i915_verify_inactive(dev, __FILE__, __LINE__);
2450
2451         if (dev_priv->mm.wedged) {
2452                 DRM_ERROR("Execbuf while wedged\n");
2453                 mutex_unlock(&dev->struct_mutex);
2454                 return -EIO;
2455         }
2456
2457         if (dev_priv->mm.suspended) {
2458                 DRM_ERROR("Execbuf while VT-switched.\n");
2459                 mutex_unlock(&dev->struct_mutex);
2460                 return -EBUSY;
2461         }
2462
2463         /* Look up object handles */
2464         for (i = 0; i < args->buffer_count; i++) {
2465                 object_list[i] = drm_gem_object_lookup(dev, file_priv,
2466                                                        exec_list[i].handle);
2467                 if (object_list[i] == NULL) {
2468                         DRM_ERROR("Invalid object handle %d at index %d\n",
2469                                    exec_list[i].handle, i);
2470                         ret = -EBADF;
2471                         goto err;
2472                 }
2473         }
2474
2475         /* Pin and relocate */
2476         for (pin_tries = 0; ; pin_tries++) {
2477                 ret = 0;
2478                 for (i = 0; i < args->buffer_count; i++) {
2479                         object_list[i]->pending_read_domains = 0;
2480                         object_list[i]->pending_write_domain = 0;
2481                         ret = i915_gem_object_pin_and_relocate(object_list[i],
2482                                                                file_priv,
2483                                                                &exec_list[i]);
2484                         if (ret)
2485                                 break;
2486                         pinned = i + 1;
2487                 }
2488                 /* success */
2489                 if (ret == 0)
2490                         break;
2491
2492                 /* error other than GTT full, or we've already tried again */
2493                 if (ret != -ENOMEM || pin_tries >= 1) {
2494                         if (ret != -ERESTARTSYS)
2495                                 DRM_ERROR("Failed to pin buffers %d\n", ret);
2496                         goto err;
2497                 }
2498
2499                 /* unpin all of our buffers */
2500                 for (i = 0; i < pinned; i++)
2501                         i915_gem_object_unpin(object_list[i]);
2502                 pinned = 0;
2503
2504                 /* evict everyone we can from the aperture */
2505                 ret = i915_gem_evict_everything(dev);
2506                 if (ret)
2507                         goto err;
2508         }
2509
2510         /* Set the pending read domains for the batch buffer to COMMAND */
2511         batch_obj = object_list[args->buffer_count-1];
2512         batch_obj->pending_read_domains = I915_GEM_DOMAIN_COMMAND;
2513         batch_obj->pending_write_domain = 0;
2514
2515         i915_verify_inactive(dev, __FILE__, __LINE__);
2516
2517         /* Zero the global flush/invalidate flags. These
2518          * will be modified as new domains are computed
2519          * for each object
2520          */
2521         dev->invalidate_domains = 0;
2522         dev->flush_domains = 0;
2523
2524         for (i = 0; i < args->buffer_count; i++) {
2525                 struct drm_gem_object *obj = object_list[i];
2526
2527                 /* Compute new gpu domains and update invalidate/flush */
2528                 i915_gem_object_set_to_gpu_domain(obj,
2529                                                   obj->pending_read_domains,
2530                                                   obj->pending_write_domain);
2531         }
2532
2533         i915_verify_inactive(dev, __FILE__, __LINE__);
2534
2535         if (dev->invalidate_domains | dev->flush_domains) {
2536 #if WATCH_EXEC
2537                 DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
2538                           __func__,
2539                          dev->invalidate_domains,
2540                          dev->flush_domains);
2541 #endif
2542                 i915_gem_flush(dev,
2543                                dev->invalidate_domains,
2544                                dev->flush_domains);
2545                 if (dev->flush_domains)
2546                         (void)i915_add_request(dev, dev->flush_domains);
2547         }
2548
2549         i915_verify_inactive(dev, __FILE__, __LINE__);
2550
2551 #if WATCH_COHERENCY
2552         for (i = 0; i < args->buffer_count; i++) {
2553                 i915_gem_object_check_coherency(object_list[i],
2554                                                 exec_list[i].handle);
2555         }
2556 #endif
2557
2558         exec_offset = exec_list[args->buffer_count - 1].offset;
2559
2560 #if WATCH_EXEC
2561         i915_gem_dump_object(object_list[args->buffer_count - 1],
2562                               args->batch_len,
2563                               __func__,
2564                               ~0);
2565 #endif
2566
2567         /* Exec the batchbuffer */
2568         ret = i915_dispatch_gem_execbuffer(dev, args, exec_offset);
2569         if (ret) {
2570                 DRM_ERROR("dispatch failed %d\n", ret);
2571                 goto err;
2572         }
2573
2574         /*
2575          * Ensure that the commands in the batch buffer are
2576          * finished before the interrupt fires
2577          */
2578         flush_domains = i915_retire_commands(dev);
2579
2580         i915_verify_inactive(dev, __FILE__, __LINE__);
2581
2582         /*
2583          * Get a seqno representing the execution of the current buffer,
2584          * which we can wait on.  We would like to mitigate these interrupts,
2585          * likely by only creating seqnos occasionally (so that we have
2586          * *some* interrupts representing completion of buffers that we can
2587          * wait on when trying to clear up gtt space).
2588          */
2589         seqno = i915_add_request(dev, flush_domains);
2590         BUG_ON(seqno == 0);
2591         i915_file_priv->mm.last_gem_seqno = seqno;
2592         for (i = 0; i < args->buffer_count; i++) {
2593                 struct drm_gem_object *obj = object_list[i];
2594
2595                 i915_gem_object_move_to_active(obj, seqno);
2596 #if WATCH_LRU
2597                 DRM_INFO("%s: move to exec list %p\n", __func__, obj);
2598 #endif
2599         }
2600 #if WATCH_LRU
2601         i915_dump_lru(dev, __func__);
2602 #endif
2603
2604         i915_verify_inactive(dev, __FILE__, __LINE__);
2605
2606         /* Copy the new buffer offsets back to the user's exec list. */
2607         ret = copy_to_user((struct drm_i915_relocation_entry __user *)
2608                            (uintptr_t) args->buffers_ptr,
2609                            exec_list,
2610                            sizeof(*exec_list) * args->buffer_count);
2611         if (ret)
2612                 DRM_ERROR("failed to copy %d exec entries "
2613                           "back to user (%d)\n",
2614                            args->buffer_count, ret);
2615 err:
2616         for (i = 0; i < pinned; i++)
2617                 i915_gem_object_unpin(object_list[i]);
2618
2619         for (i = 0; i < args->buffer_count; i++)
2620                 drm_gem_object_unreference(object_list[i]);
2621
2622         mutex_unlock(&dev->struct_mutex);
2623
2624 pre_mutex_err:
2625         drm_free(object_list, sizeof(*object_list) * args->buffer_count,
2626                  DRM_MEM_DRIVER);
2627         drm_free(exec_list, sizeof(*exec_list) * args->buffer_count,
2628                  DRM_MEM_DRIVER);
2629
2630         return ret;
2631 }
2632
2633 int
2634 i915_gem_object_pin(struct drm_gem_object *obj, uint32_t alignment)
2635 {
2636         struct drm_device *dev = obj->dev;
2637         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2638         int ret;
2639
2640         i915_verify_inactive(dev, __FILE__, __LINE__);
2641         if (obj_priv->gtt_space == NULL) {
2642                 ret = i915_gem_object_bind_to_gtt(obj, alignment);
2643                 if (ret != 0) {
2644                         if (ret != -ERESTARTSYS)
2645                                 DRM_ERROR("Failure to bind: %d", ret);
2646                         return ret;
2647                 }
2648         }
2649         obj_priv->pin_count++;
2650
2651         /* If the object is not active and not pending a flush,
2652          * remove it from the inactive list
2653          */
2654         if (obj_priv->pin_count == 1) {
2655                 atomic_inc(&dev->pin_count);
2656                 atomic_add(obj->size, &dev->pin_memory);
2657                 if (!obj_priv->active &&
2658                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
2659                                            I915_GEM_DOMAIN_GTT)) == 0 &&
2660                     !list_empty(&obj_priv->list))
2661                         list_del_init(&obj_priv->list);
2662         }
2663         i915_verify_inactive(dev, __FILE__, __LINE__);
2664
2665         return 0;
2666 }
2667
2668 void
2669 i915_gem_object_unpin(struct drm_gem_object *obj)
2670 {
2671         struct drm_device *dev = obj->dev;
2672         drm_i915_private_t *dev_priv = dev->dev_private;
2673         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2674
2675         i915_verify_inactive(dev, __FILE__, __LINE__);
2676         obj_priv->pin_count--;
2677         BUG_ON(obj_priv->pin_count < 0);
2678         BUG_ON(obj_priv->gtt_space == NULL);
2679
2680         /* If the object is no longer pinned, and is
2681          * neither active nor being flushed, then stick it on
2682          * the inactive list
2683          */
2684         if (obj_priv->pin_count == 0) {
2685                 if (!obj_priv->active &&
2686                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
2687                                            I915_GEM_DOMAIN_GTT)) == 0)
2688                         list_move_tail(&obj_priv->list,
2689                                        &dev_priv->mm.inactive_list);
2690                 atomic_dec(&dev->pin_count);
2691                 atomic_sub(obj->size, &dev->pin_memory);
2692         }
2693         i915_verify_inactive(dev, __FILE__, __LINE__);
2694 }
2695
2696 int
2697 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
2698                    struct drm_file *file_priv)
2699 {
2700         struct drm_i915_gem_pin *args = data;
2701         struct drm_gem_object *obj;
2702         struct drm_i915_gem_object *obj_priv;
2703         int ret;
2704
2705         mutex_lock(&dev->struct_mutex);
2706
2707         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
2708         if (obj == NULL) {
2709                 DRM_ERROR("Bad handle in i915_gem_pin_ioctl(): %d\n",
2710                           args->handle);
2711                 mutex_unlock(&dev->struct_mutex);
2712                 return -EBADF;
2713         }
2714         obj_priv = obj->driver_private;
2715
2716         if (obj_priv->pin_filp != NULL && obj_priv->pin_filp != file_priv) {
2717                 DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
2718                           args->handle);
2719                 mutex_unlock(&dev->struct_mutex);
2720                 return -EINVAL;
2721         }
2722
2723         obj_priv->user_pin_count++;
2724         obj_priv->pin_filp = file_priv;
2725         if (obj_priv->user_pin_count == 1) {
2726                 ret = i915_gem_object_pin(obj, args->alignment);
2727                 if (ret != 0) {
2728                         drm_gem_object_unreference(obj);
2729                         mutex_unlock(&dev->struct_mutex);
2730                         return ret;
2731                 }
2732         }
2733
2734         /* XXX - flush the CPU caches for pinned objects
2735          * as the X server doesn't manage domains yet
2736          */
2737         i915_gem_object_flush_cpu_write_domain(obj);
2738         args->offset = obj_priv->gtt_offset;
2739         drm_gem_object_unreference(obj);
2740         mutex_unlock(&dev->struct_mutex);
2741
2742         return 0;
2743 }
2744
2745 int
2746 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
2747                      struct drm_file *file_priv)
2748 {
2749         struct drm_i915_gem_pin *args = data;
2750         struct drm_gem_object *obj;
2751         struct drm_i915_gem_object *obj_priv;
2752
2753         mutex_lock(&dev->struct_mutex);
2754
2755         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
2756         if (obj == NULL) {
2757                 DRM_ERROR("Bad handle in i915_gem_unpin_ioctl(): %d\n",
2758                           args->handle);
2759                 mutex_unlock(&dev->struct_mutex);
2760                 return -EBADF;
2761         }
2762
2763         obj_priv = obj->driver_private;
2764         if (obj_priv->pin_filp != file_priv) {
2765                 DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
2766                           args->handle);
2767                 drm_gem_object_unreference(obj);
2768                 mutex_unlock(&dev->struct_mutex);
2769                 return -EINVAL;
2770         }
2771         obj_priv->user_pin_count--;
2772         if (obj_priv->user_pin_count == 0) {
2773                 obj_priv->pin_filp = NULL;
2774                 i915_gem_object_unpin(obj);
2775         }
2776
2777         drm_gem_object_unreference(obj);
2778         mutex_unlock(&dev->struct_mutex);
2779         return 0;
2780 }
2781
2782 int
2783 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
2784                     struct drm_file *file_priv)
2785 {
2786         struct drm_i915_gem_busy *args = data;
2787         struct drm_gem_object *obj;
2788         struct drm_i915_gem_object *obj_priv;
2789
2790         mutex_lock(&dev->struct_mutex);
2791         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
2792         if (obj == NULL) {
2793                 DRM_ERROR("Bad handle in i915_gem_busy_ioctl(): %d\n",
2794                           args->handle);
2795                 mutex_unlock(&dev->struct_mutex);
2796                 return -EBADF;
2797         }
2798
2799         obj_priv = obj->driver_private;
2800         /* Don't count being on the flushing list against the object being
2801          * done.  Otherwise, a buffer left on the flushing list but not getting
2802          * flushed (because nobody's flushing that domain) won't ever return
2803          * unbusy and get reused by libdrm's bo cache.  The other expected
2804          * consumer of this interface, OpenGL's occlusion queries, also specs
2805          * that the objects get unbusy "eventually" without any interference.
2806          */
2807         args->busy = obj_priv->active && obj_priv->last_rendering_seqno != 0;
2808
2809         drm_gem_object_unreference(obj);
2810         mutex_unlock(&dev->struct_mutex);
2811         return 0;
2812 }
2813
2814 int
2815 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
2816                         struct drm_file *file_priv)
2817 {
2818     return i915_gem_ring_throttle(dev, file_priv);
2819 }
2820
2821 int i915_gem_init_object(struct drm_gem_object *obj)
2822 {
2823         struct drm_i915_gem_object *obj_priv;
2824
2825         obj_priv = drm_calloc(1, sizeof(*obj_priv), DRM_MEM_DRIVER);
2826         if (obj_priv == NULL)
2827                 return -ENOMEM;
2828
2829         /*
2830          * We've just allocated pages from the kernel,
2831          * so they've just been written by the CPU with
2832          * zeros. They'll need to be clflushed before we
2833          * use them with the GPU.
2834          */
2835         obj->write_domain = I915_GEM_DOMAIN_CPU;
2836         obj->read_domains = I915_GEM_DOMAIN_CPU;
2837
2838         obj_priv->agp_type = AGP_USER_MEMORY;
2839
2840         obj->driver_private = obj_priv;
2841         obj_priv->obj = obj;
2842         obj_priv->fence_reg = I915_FENCE_REG_NONE;
2843         INIT_LIST_HEAD(&obj_priv->list);
2844
2845         return 0;
2846 }
2847
2848 void i915_gem_free_object(struct drm_gem_object *obj)
2849 {
2850         struct drm_device *dev = obj->dev;
2851         struct drm_gem_mm *mm = dev->mm_private;
2852         struct drm_map_list *list;
2853         struct drm_map *map;
2854         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2855
2856         while (obj_priv->pin_count > 0)
2857                 i915_gem_object_unpin(obj);
2858
2859         i915_gem_object_unbind(obj);
2860
2861         list = &obj->map_list;
2862         drm_ht_remove_item(&mm->offset_hash, &list->hash);
2863
2864         if (list->file_offset_node) {
2865                 drm_mm_put_block(list->file_offset_node);
2866                 list->file_offset_node = NULL;
2867         }
2868
2869         map = list->map;
2870         if (map) {
2871                 drm_free(map, sizeof(*map), DRM_MEM_DRIVER);
2872                 list->map = NULL;
2873         }
2874
2875         drm_free(obj_priv->page_cpu_valid, 1, DRM_MEM_DRIVER);
2876         drm_free(obj->driver_private, 1, DRM_MEM_DRIVER);
2877 }
2878
2879 /** Unbinds all objects that are on the given buffer list. */
2880 static int
2881 i915_gem_evict_from_list(struct drm_device *dev, struct list_head *head)
2882 {
2883         struct drm_gem_object *obj;
2884         struct drm_i915_gem_object *obj_priv;
2885         int ret;
2886
2887         while (!list_empty(head)) {
2888                 obj_priv = list_first_entry(head,
2889                                             struct drm_i915_gem_object,
2890                                             list);
2891                 obj = obj_priv->obj;
2892
2893                 if (obj_priv->pin_count != 0) {
2894                         DRM_ERROR("Pinned object in unbind list\n");
2895                         mutex_unlock(&dev->struct_mutex);
2896                         return -EINVAL;
2897                 }
2898
2899                 ret = i915_gem_object_unbind(obj);
2900                 if (ret != 0) {
2901                         DRM_ERROR("Error unbinding object in LeaveVT: %d\n",
2902                                   ret);
2903                         mutex_unlock(&dev->struct_mutex);
2904                         return ret;
2905                 }
2906         }
2907
2908
2909         return 0;
2910 }
2911
2912 static int
2913 i915_gem_idle(struct drm_device *dev)
2914 {
2915         drm_i915_private_t *dev_priv = dev->dev_private;
2916         uint32_t seqno, cur_seqno, last_seqno;
2917         int stuck, ret;
2918
2919         mutex_lock(&dev->struct_mutex);
2920
2921         if (dev_priv->mm.suspended || dev_priv->ring.ring_obj == NULL) {
2922                 mutex_unlock(&dev->struct_mutex);
2923                 return 0;
2924         }
2925
2926         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
2927          * We need to replace this with a semaphore, or something.
2928          */
2929         dev_priv->mm.suspended = 1;
2930
2931         /* Cancel the retire work handler, wait for it to finish if running
2932          */
2933         mutex_unlock(&dev->struct_mutex);
2934         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
2935         mutex_lock(&dev->struct_mutex);
2936
2937         i915_kernel_lost_context(dev);
2938
2939         /* Flush the GPU along with all non-CPU write domains
2940          */
2941         i915_gem_flush(dev, ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT),
2942                        ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
2943         seqno = i915_add_request(dev, ~I915_GEM_DOMAIN_CPU);
2944
2945         if (seqno == 0) {
2946                 mutex_unlock(&dev->struct_mutex);
2947                 return -ENOMEM;
2948         }
2949
2950         dev_priv->mm.waiting_gem_seqno = seqno;
2951         last_seqno = 0;
2952         stuck = 0;
2953         for (;;) {
2954                 cur_seqno = i915_get_gem_seqno(dev);
2955                 if (i915_seqno_passed(cur_seqno, seqno))
2956                         break;
2957                 if (last_seqno == cur_seqno) {
2958                         if (stuck++ > 100) {
2959                                 DRM_ERROR("hardware wedged\n");
2960                                 dev_priv->mm.wedged = 1;
2961                                 DRM_WAKEUP(&dev_priv->irq_queue);
2962                                 break;
2963                         }
2964                 }
2965                 msleep(10);
2966                 last_seqno = cur_seqno;
2967         }
2968         dev_priv->mm.waiting_gem_seqno = 0;
2969
2970         i915_gem_retire_requests(dev);
2971
2972         if (!dev_priv->mm.wedged) {
2973                 /* Active and flushing should now be empty as we've
2974                  * waited for a sequence higher than any pending execbuffer
2975                  */
2976                 WARN_ON(!list_empty(&dev_priv->mm.active_list));
2977                 WARN_ON(!list_empty(&dev_priv->mm.flushing_list));
2978                 /* Request should now be empty as we've also waited
2979                  * for the last request in the list
2980                  */
2981                 WARN_ON(!list_empty(&dev_priv->mm.request_list));
2982         }
2983
2984         /* Empty the active and flushing lists to inactive.  If there's
2985          * anything left at this point, it means that we're wedged and
2986          * nothing good's going to happen by leaving them there.  So strip
2987          * the GPU domains and just stuff them onto inactive.
2988          */
2989         while (!list_empty(&dev_priv->mm.active_list)) {
2990                 struct drm_i915_gem_object *obj_priv;
2991
2992                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
2993                                             struct drm_i915_gem_object,
2994                                             list);
2995                 obj_priv->obj->write_domain &= ~I915_GEM_GPU_DOMAINS;
2996                 i915_gem_object_move_to_inactive(obj_priv->obj);
2997         }
2998
2999         while (!list_empty(&dev_priv->mm.flushing_list)) {
3000                 struct drm_i915_gem_object *obj_priv;
3001
3002                 obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
3003                                             struct drm_i915_gem_object,
3004                                             list);
3005                 obj_priv->obj->write_domain &= ~I915_GEM_GPU_DOMAINS;
3006                 i915_gem_object_move_to_inactive(obj_priv->obj);
3007         }
3008
3009
3010         /* Move all inactive buffers out of the GTT. */
3011         ret = i915_gem_evict_from_list(dev, &dev_priv->mm.inactive_list);
3012         WARN_ON(!list_empty(&dev_priv->mm.inactive_list));
3013         if (ret) {
3014                 mutex_unlock(&dev->struct_mutex);
3015                 return ret;
3016         }
3017
3018         i915_gem_cleanup_ringbuffer(dev);
3019         mutex_unlock(&dev->struct_mutex);
3020
3021         return 0;
3022 }
3023
3024 static int
3025 i915_gem_init_hws(struct drm_device *dev)
3026 {
3027         drm_i915_private_t *dev_priv = dev->dev_private;
3028         struct drm_gem_object *obj;
3029         struct drm_i915_gem_object *obj_priv;
3030         int ret;
3031
3032         /* If we need a physical address for the status page, it's already
3033          * initialized at driver load time.
3034          */
3035         if (!I915_NEED_GFX_HWS(dev))
3036                 return 0;
3037
3038         obj = drm_gem_object_alloc(dev, 4096);
3039         if (obj == NULL) {
3040                 DRM_ERROR("Failed to allocate status page\n");
3041                 return -ENOMEM;
3042         }
3043         obj_priv = obj->driver_private;
3044         obj_priv->agp_type = AGP_USER_CACHED_MEMORY;
3045
3046         ret = i915_gem_object_pin(obj, 4096);
3047         if (ret != 0) {
3048                 drm_gem_object_unreference(obj);
3049                 return ret;
3050         }
3051
3052         dev_priv->status_gfx_addr = obj_priv->gtt_offset;
3053
3054         dev_priv->hw_status_page = kmap(obj_priv->page_list[0]);
3055         if (dev_priv->hw_status_page == NULL) {
3056                 DRM_ERROR("Failed to map status page.\n");
3057                 memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
3058                 drm_gem_object_unreference(obj);
3059                 return -EINVAL;
3060         }
3061         dev_priv->hws_obj = obj;
3062         memset(dev_priv->hw_status_page, 0, PAGE_SIZE);
3063         I915_WRITE(HWS_PGA, dev_priv->status_gfx_addr);
3064         I915_READ(HWS_PGA); /* posting read */
3065         DRM_DEBUG("hws offset: 0x%08x\n", dev_priv->status_gfx_addr);
3066
3067         return 0;
3068 }
3069
3070 int
3071 i915_gem_init_ringbuffer(struct drm_device *dev)
3072 {
3073         drm_i915_private_t *dev_priv = dev->dev_private;
3074         struct drm_gem_object *obj;
3075         struct drm_i915_gem_object *obj_priv;
3076         drm_i915_ring_buffer_t *ring = &dev_priv->ring;
3077         int ret;
3078         u32 head;
3079
3080         ret = i915_gem_init_hws(dev);
3081         if (ret != 0)
3082                 return ret;
3083
3084         obj = drm_gem_object_alloc(dev, 128 * 1024);
3085         if (obj == NULL) {
3086                 DRM_ERROR("Failed to allocate ringbuffer\n");
3087                 return -ENOMEM;
3088         }
3089         obj_priv = obj->driver_private;
3090
3091         ret = i915_gem_object_pin(obj, 4096);
3092         if (ret != 0) {
3093                 drm_gem_object_unreference(obj);
3094                 return ret;
3095         }
3096
3097         /* Set up the kernel mapping for the ring. */
3098         ring->Size = obj->size;
3099         ring->tail_mask = obj->size - 1;
3100
3101         ring->map.offset = dev->agp->base + obj_priv->gtt_offset;
3102         ring->map.size = obj->size;
3103         ring->map.type = 0;
3104         ring->map.flags = 0;
3105         ring->map.mtrr = 0;
3106
3107         drm_core_ioremap_wc(&ring->map, dev);
3108         if (ring->map.handle == NULL) {
3109                 DRM_ERROR("Failed to map ringbuffer.\n");
3110                 memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
3111                 drm_gem_object_unreference(obj);
3112                 return -EINVAL;
3113         }
3114         ring->ring_obj = obj;
3115         ring->virtual_start = ring->map.handle;
3116
3117         /* Stop the ring if it's running. */
3118         I915_WRITE(PRB0_CTL, 0);
3119         I915_WRITE(PRB0_TAIL, 0);
3120         I915_WRITE(PRB0_HEAD, 0);
3121
3122         /* Initialize the ring. */
3123         I915_WRITE(PRB0_START, obj_priv->gtt_offset);
3124         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
3125
3126         /* G45 ring initialization fails to reset head to zero */
3127         if (head != 0) {
3128                 DRM_ERROR("Ring head not reset to zero "
3129                           "ctl %08x head %08x tail %08x start %08x\n",
3130                           I915_READ(PRB0_CTL),
3131                           I915_READ(PRB0_HEAD),
3132                           I915_READ(PRB0_TAIL),
3133                           I915_READ(PRB0_START));
3134                 I915_WRITE(PRB0_HEAD, 0);
3135
3136                 DRM_ERROR("Ring head forced to zero "
3137                           "ctl %08x head %08x tail %08x start %08x\n",
3138                           I915_READ(PRB0_CTL),
3139                           I915_READ(PRB0_HEAD),
3140                           I915_READ(PRB0_TAIL),
3141                           I915_READ(PRB0_START));
3142         }
3143
3144         I915_WRITE(PRB0_CTL,
3145                    ((obj->size - 4096) & RING_NR_PAGES) |
3146                    RING_NO_REPORT |
3147                    RING_VALID);
3148
3149         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
3150
3151         /* If the head is still not zero, the ring is dead */
3152         if (head != 0) {
3153                 DRM_ERROR("Ring initialization failed "
3154                           "ctl %08x head %08x tail %08x start %08x\n",
3155                           I915_READ(PRB0_CTL),
3156                           I915_READ(PRB0_HEAD),
3157                           I915_READ(PRB0_TAIL),
3158                           I915_READ(PRB0_START));
3159                 return -EIO;
3160         }
3161
3162         /* Update our cache of the ring state */
3163         if (!drm_core_check_feature(dev, DRIVER_MODESET))
3164                 i915_kernel_lost_context(dev);
3165         else {
3166                 ring->head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
3167                 ring->tail = I915_READ(PRB0_TAIL) & TAIL_ADDR;
3168                 ring->space = ring->head - (ring->tail + 8);
3169                 if (ring->space < 0)
3170                         ring->space += ring->Size;
3171         }
3172
3173         return 0;
3174 }
3175
3176 void
3177 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
3178 {
3179         drm_i915_private_t *dev_priv = dev->dev_private;
3180
3181         if (dev_priv->ring.ring_obj == NULL)
3182                 return;
3183
3184         drm_core_ioremapfree(&dev_priv->ring.map, dev);
3185
3186         i915_gem_object_unpin(dev_priv->ring.ring_obj);
3187         drm_gem_object_unreference(dev_priv->ring.ring_obj);
3188         dev_priv->ring.ring_obj = NULL;
3189         memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
3190
3191         if (dev_priv->hws_obj != NULL) {
3192                 struct drm_gem_object *obj = dev_priv->hws_obj;
3193                 struct drm_i915_gem_object *obj_priv = obj->driver_private;
3194
3195                 kunmap(obj_priv->page_list[0]);
3196                 i915_gem_object_unpin(obj);
3197                 drm_gem_object_unreference(obj);
3198                 dev_priv->hws_obj = NULL;
3199                 memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
3200                 dev_priv->hw_status_page = NULL;
3201
3202                 /* Write high address into HWS_PGA when disabling. */
3203                 I915_WRITE(HWS_PGA, 0x1ffff000);
3204         }
3205 }
3206
3207 int
3208 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
3209                        struct drm_file *file_priv)
3210 {
3211         drm_i915_private_t *dev_priv = dev->dev_private;
3212         int ret;
3213
3214         if (drm_core_check_feature(dev, DRIVER_MODESET))
3215                 return 0;
3216
3217         if (dev_priv->mm.wedged) {
3218                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
3219                 dev_priv->mm.wedged = 0;
3220         }
3221
3222         ret = i915_gem_init_ringbuffer(dev);
3223         if (ret != 0)
3224                 return ret;
3225
3226         dev_priv->mm.gtt_mapping = io_mapping_create_wc(dev->agp->base,
3227                                                         dev->agp->agp_info.aper_size
3228                                                         * 1024 * 1024);
3229
3230         mutex_lock(&dev->struct_mutex);
3231         BUG_ON(!list_empty(&dev_priv->mm.active_list));
3232         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
3233         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
3234         BUG_ON(!list_empty(&dev_priv->mm.request_list));
3235         dev_priv->mm.suspended = 0;
3236         mutex_unlock(&dev->struct_mutex);
3237
3238         drm_irq_install(dev);
3239
3240         return 0;
3241 }
3242
3243 int
3244 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
3245                        struct drm_file *file_priv)
3246 {
3247         drm_i915_private_t *dev_priv = dev->dev_private;
3248         int ret;
3249
3250         if (drm_core_check_feature(dev, DRIVER_MODESET))
3251                 return 0;
3252
3253         ret = i915_gem_idle(dev);
3254         drm_irq_uninstall(dev);
3255
3256         io_mapping_free(dev_priv->mm.gtt_mapping);
3257         return ret;
3258 }
3259
3260 void
3261 i915_gem_lastclose(struct drm_device *dev)
3262 {
3263         int ret;
3264
3265         ret = i915_gem_idle(dev);
3266         if (ret)
3267                 DRM_ERROR("failed to idle hardware: %d\n", ret);
3268 }
3269
3270 void
3271 i915_gem_load(struct drm_device *dev)
3272 {
3273         drm_i915_private_t *dev_priv = dev->dev_private;
3274
3275         INIT_LIST_HEAD(&dev_priv->mm.active_list);
3276         INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
3277         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
3278         INIT_LIST_HEAD(&dev_priv->mm.request_list);
3279         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
3280                           i915_gem_retire_work_handler);
3281         dev_priv->mm.next_gem_seqno = 1;
3282
3283         /* Old X drivers will take 0-2 for front, back, depth buffers */
3284         dev_priv->fence_reg_start = 3;
3285
3286         if (IS_I965G(dev))
3287                 dev_priv->num_fence_regs = 16;
3288         else
3289                 dev_priv->num_fence_regs = 8;
3290
3291         i915_gem_detect_bit_6_swizzle(dev);
3292 }