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