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