a5ca9599b232f86ec4b96b48889e52ca594dcad7
[safe/jmp/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 "i915_trace.h"
33 #include "intel_drv.h"
34 #include <linux/slab.h>
35 #include <linux/swap.h>
36 #include <linux/pci.h>
37
38 static void i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj);
39 static void i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj);
40 static void i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj);
41 static int i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj,
42                                              int write);
43 static int i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
44                                                      uint64_t offset,
45                                                      uint64_t size);
46 static void i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj);
47 static int i915_gem_object_wait_rendering(struct drm_gem_object *obj);
48 static int i915_gem_object_bind_to_gtt(struct drm_gem_object *obj,
49                                            unsigned alignment);
50 static void i915_gem_clear_fence_reg(struct drm_gem_object *obj);
51 static int i915_gem_evict_something(struct drm_device *dev, int min_size);
52 static int i915_gem_evict_from_inactive_list(struct drm_device *dev);
53 static int i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
54                                 struct drm_i915_gem_pwrite *args,
55                                 struct drm_file *file_priv);
56
57 static LIST_HEAD(shrink_list);
58 static DEFINE_SPINLOCK(shrink_list_lock);
59
60 int i915_gem_do_init(struct drm_device *dev, unsigned long start,
61                      unsigned long end)
62 {
63         drm_i915_private_t *dev_priv = dev->dev_private;
64
65         if (start >= end ||
66             (start & (PAGE_SIZE - 1)) != 0 ||
67             (end & (PAGE_SIZE - 1)) != 0) {
68                 return -EINVAL;
69         }
70
71         drm_mm_init(&dev_priv->mm.gtt_space, start,
72                     end - start);
73
74         dev->gtt_total = (uint32_t) (end - start);
75
76         return 0;
77 }
78
79 int
80 i915_gem_init_ioctl(struct drm_device *dev, void *data,
81                     struct drm_file *file_priv)
82 {
83         struct drm_i915_gem_init *args = data;
84         int ret;
85
86         mutex_lock(&dev->struct_mutex);
87         ret = i915_gem_do_init(dev, args->gtt_start, args->gtt_end);
88         mutex_unlock(&dev->struct_mutex);
89
90         return ret;
91 }
92
93 int
94 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
95                             struct drm_file *file_priv)
96 {
97         struct drm_i915_gem_get_aperture *args = data;
98
99         if (!(dev->driver->driver_features & DRIVER_GEM))
100                 return -ENODEV;
101
102         args->aper_size = dev->gtt_total;
103         args->aper_available_size = (args->aper_size -
104                                      atomic_read(&dev->pin_memory));
105
106         return 0;
107 }
108
109
110 /**
111  * Creates a new mm object and returns a handle to it.
112  */
113 int
114 i915_gem_create_ioctl(struct drm_device *dev, void *data,
115                       struct drm_file *file_priv)
116 {
117         struct drm_i915_gem_create *args = data;
118         struct drm_gem_object *obj;
119         int ret;
120         u32 handle;
121
122         args->size = roundup(args->size, PAGE_SIZE);
123
124         /* Allocate the new object */
125         obj = i915_gem_alloc_object(dev, args->size);
126         if (obj == NULL)
127                 return -ENOMEM;
128
129         ret = drm_gem_handle_create(file_priv, obj, &handle);
130         drm_gem_object_handle_unreference_unlocked(obj);
131
132         if (ret)
133                 return ret;
134
135         args->handle = handle;
136
137         return 0;
138 }
139
140 static inline int
141 fast_shmem_read(struct page **pages,
142                 loff_t page_base, int page_offset,
143                 char __user *data,
144                 int length)
145 {
146         char __iomem *vaddr;
147         int unwritten;
148
149         vaddr = kmap_atomic(pages[page_base >> PAGE_SHIFT], KM_USER0);
150         if (vaddr == NULL)
151                 return -ENOMEM;
152         unwritten = __copy_to_user_inatomic(data, vaddr + page_offset, length);
153         kunmap_atomic(vaddr, KM_USER0);
154
155         if (unwritten)
156                 return -EFAULT;
157
158         return 0;
159 }
160
161 static int i915_gem_object_needs_bit17_swizzle(struct drm_gem_object *obj)
162 {
163         drm_i915_private_t *dev_priv = obj->dev->dev_private;
164         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
165
166         return dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_9_10_17 &&
167                 obj_priv->tiling_mode != I915_TILING_NONE;
168 }
169
170 static inline int
171 slow_shmem_copy(struct page *dst_page,
172                 int dst_offset,
173                 struct page *src_page,
174                 int src_offset,
175                 int length)
176 {
177         char *dst_vaddr, *src_vaddr;
178
179         dst_vaddr = kmap_atomic(dst_page, KM_USER0);
180         if (dst_vaddr == NULL)
181                 return -ENOMEM;
182
183         src_vaddr = kmap_atomic(src_page, KM_USER1);
184         if (src_vaddr == NULL) {
185                 kunmap_atomic(dst_vaddr, KM_USER0);
186                 return -ENOMEM;
187         }
188
189         memcpy(dst_vaddr + dst_offset, src_vaddr + src_offset, length);
190
191         kunmap_atomic(src_vaddr, KM_USER1);
192         kunmap_atomic(dst_vaddr, KM_USER0);
193
194         return 0;
195 }
196
197 static inline int
198 slow_shmem_bit17_copy(struct page *gpu_page,
199                       int gpu_offset,
200                       struct page *cpu_page,
201                       int cpu_offset,
202                       int length,
203                       int is_read)
204 {
205         char *gpu_vaddr, *cpu_vaddr;
206
207         /* Use the unswizzled path if this page isn't affected. */
208         if ((page_to_phys(gpu_page) & (1 << 17)) == 0) {
209                 if (is_read)
210                         return slow_shmem_copy(cpu_page, cpu_offset,
211                                                gpu_page, gpu_offset, length);
212                 else
213                         return slow_shmem_copy(gpu_page, gpu_offset,
214                                                cpu_page, cpu_offset, length);
215         }
216
217         gpu_vaddr = kmap_atomic(gpu_page, KM_USER0);
218         if (gpu_vaddr == NULL)
219                 return -ENOMEM;
220
221         cpu_vaddr = kmap_atomic(cpu_page, KM_USER1);
222         if (cpu_vaddr == NULL) {
223                 kunmap_atomic(gpu_vaddr, KM_USER0);
224                 return -ENOMEM;
225         }
226
227         /* Copy the data, XORing A6 with A17 (1). The user already knows he's
228          * XORing with the other bits (A9 for Y, A9 and A10 for X)
229          */
230         while (length > 0) {
231                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
232                 int this_length = min(cacheline_end - gpu_offset, length);
233                 int swizzled_gpu_offset = gpu_offset ^ 64;
234
235                 if (is_read) {
236                         memcpy(cpu_vaddr + cpu_offset,
237                                gpu_vaddr + swizzled_gpu_offset,
238                                this_length);
239                 } else {
240                         memcpy(gpu_vaddr + swizzled_gpu_offset,
241                                cpu_vaddr + cpu_offset,
242                                this_length);
243                 }
244                 cpu_offset += this_length;
245                 gpu_offset += this_length;
246                 length -= this_length;
247         }
248
249         kunmap_atomic(cpu_vaddr, KM_USER1);
250         kunmap_atomic(gpu_vaddr, KM_USER0);
251
252         return 0;
253 }
254
255 /**
256  * This is the fast shmem pread path, which attempts to copy_from_user directly
257  * from the backing pages of the object to the user's address space.  On a
258  * fault, it fails so we can fall back to i915_gem_shmem_pwrite_slow().
259  */
260 static int
261 i915_gem_shmem_pread_fast(struct drm_device *dev, struct drm_gem_object *obj,
262                           struct drm_i915_gem_pread *args,
263                           struct drm_file *file_priv)
264 {
265         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
266         ssize_t remain;
267         loff_t offset, page_base;
268         char __user *user_data;
269         int page_offset, page_length;
270         int ret;
271
272         user_data = (char __user *) (uintptr_t) args->data_ptr;
273         remain = args->size;
274
275         mutex_lock(&dev->struct_mutex);
276
277         ret = i915_gem_object_get_pages(obj, 0);
278         if (ret != 0)
279                 goto fail_unlock;
280
281         ret = i915_gem_object_set_cpu_read_domain_range(obj, args->offset,
282                                                         args->size);
283         if (ret != 0)
284                 goto fail_put_pages;
285
286         obj_priv = to_intel_bo(obj);
287         offset = args->offset;
288
289         while (remain > 0) {
290                 /* Operation in this page
291                  *
292                  * page_base = page offset within aperture
293                  * page_offset = offset within page
294                  * page_length = bytes to copy for this page
295                  */
296                 page_base = (offset & ~(PAGE_SIZE-1));
297                 page_offset = offset & (PAGE_SIZE-1);
298                 page_length = remain;
299                 if ((page_offset + remain) > PAGE_SIZE)
300                         page_length = PAGE_SIZE - page_offset;
301
302                 ret = fast_shmem_read(obj_priv->pages,
303                                       page_base, page_offset,
304                                       user_data, page_length);
305                 if (ret)
306                         goto fail_put_pages;
307
308                 remain -= page_length;
309                 user_data += page_length;
310                 offset += page_length;
311         }
312
313 fail_put_pages:
314         i915_gem_object_put_pages(obj);
315 fail_unlock:
316         mutex_unlock(&dev->struct_mutex);
317
318         return ret;
319 }
320
321 static int
322 i915_gem_object_get_pages_or_evict(struct drm_gem_object *obj)
323 {
324         int ret;
325
326         ret = i915_gem_object_get_pages(obj, __GFP_NORETRY | __GFP_NOWARN);
327
328         /* If we've insufficient memory to map in the pages, attempt
329          * to make some space by throwing out some old buffers.
330          */
331         if (ret == -ENOMEM) {
332                 struct drm_device *dev = obj->dev;
333
334                 ret = i915_gem_evict_something(dev, obj->size);
335                 if (ret)
336                         return ret;
337
338                 ret = i915_gem_object_get_pages(obj, 0);
339         }
340
341         return ret;
342 }
343
344 /**
345  * This is the fallback shmem pread path, which allocates temporary storage
346  * in kernel space to copy_to_user into outside of the struct_mutex, so we
347  * can copy out of the object's backing pages while holding the struct mutex
348  * and not take page faults.
349  */
350 static int
351 i915_gem_shmem_pread_slow(struct drm_device *dev, struct drm_gem_object *obj,
352                           struct drm_i915_gem_pread *args,
353                           struct drm_file *file_priv)
354 {
355         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
356         struct mm_struct *mm = current->mm;
357         struct page **user_pages;
358         ssize_t remain;
359         loff_t offset, pinned_pages, i;
360         loff_t first_data_page, last_data_page, num_pages;
361         int shmem_page_index, shmem_page_offset;
362         int data_page_index,  data_page_offset;
363         int page_length;
364         int ret;
365         uint64_t data_ptr = args->data_ptr;
366         int do_bit17_swizzling;
367
368         remain = args->size;
369
370         /* Pin the user pages containing the data.  We can't fault while
371          * holding the struct mutex, yet we want to hold it while
372          * dereferencing the user data.
373          */
374         first_data_page = data_ptr / PAGE_SIZE;
375         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
376         num_pages = last_data_page - first_data_page + 1;
377
378         user_pages = drm_calloc_large(num_pages, sizeof(struct page *));
379         if (user_pages == NULL)
380                 return -ENOMEM;
381
382         down_read(&mm->mmap_sem);
383         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
384                                       num_pages, 1, 0, user_pages, NULL);
385         up_read(&mm->mmap_sem);
386         if (pinned_pages < num_pages) {
387                 ret = -EFAULT;
388                 goto fail_put_user_pages;
389         }
390
391         do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
392
393         mutex_lock(&dev->struct_mutex);
394
395         ret = i915_gem_object_get_pages_or_evict(obj);
396         if (ret)
397                 goto fail_unlock;
398
399         ret = i915_gem_object_set_cpu_read_domain_range(obj, args->offset,
400                                                         args->size);
401         if (ret != 0)
402                 goto fail_put_pages;
403
404         obj_priv = to_intel_bo(obj);
405         offset = args->offset;
406
407         while (remain > 0) {
408                 /* Operation in this page
409                  *
410                  * shmem_page_index = page number within shmem file
411                  * shmem_page_offset = offset within page in shmem file
412                  * data_page_index = page number in get_user_pages return
413                  * data_page_offset = offset with data_page_index page.
414                  * page_length = bytes to copy for this page
415                  */
416                 shmem_page_index = offset / PAGE_SIZE;
417                 shmem_page_offset = offset & ~PAGE_MASK;
418                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
419                 data_page_offset = data_ptr & ~PAGE_MASK;
420
421                 page_length = remain;
422                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
423                         page_length = PAGE_SIZE - shmem_page_offset;
424                 if ((data_page_offset + page_length) > PAGE_SIZE)
425                         page_length = PAGE_SIZE - data_page_offset;
426
427                 if (do_bit17_swizzling) {
428                         ret = slow_shmem_bit17_copy(obj_priv->pages[shmem_page_index],
429                                                     shmem_page_offset,
430                                                     user_pages[data_page_index],
431                                                     data_page_offset,
432                                                     page_length,
433                                                     1);
434                 } else {
435                         ret = slow_shmem_copy(user_pages[data_page_index],
436                                               data_page_offset,
437                                               obj_priv->pages[shmem_page_index],
438                                               shmem_page_offset,
439                                               page_length);
440                 }
441                 if (ret)
442                         goto fail_put_pages;
443
444                 remain -= page_length;
445                 data_ptr += page_length;
446                 offset += page_length;
447         }
448
449 fail_put_pages:
450         i915_gem_object_put_pages(obj);
451 fail_unlock:
452         mutex_unlock(&dev->struct_mutex);
453 fail_put_user_pages:
454         for (i = 0; i < pinned_pages; i++) {
455                 SetPageDirty(user_pages[i]);
456                 page_cache_release(user_pages[i]);
457         }
458         drm_free_large(user_pages);
459
460         return ret;
461 }
462
463 /**
464  * Reads data from the object referenced by handle.
465  *
466  * On error, the contents of *data are undefined.
467  */
468 int
469 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
470                      struct drm_file *file_priv)
471 {
472         struct drm_i915_gem_pread *args = data;
473         struct drm_gem_object *obj;
474         struct drm_i915_gem_object *obj_priv;
475         int ret;
476
477         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
478         if (obj == NULL)
479                 return -EBADF;
480         obj_priv = to_intel_bo(obj);
481
482         /* Bounds check source.
483          *
484          * XXX: This could use review for overflow issues...
485          */
486         if (args->offset > obj->size || args->size > obj->size ||
487             args->offset + args->size > obj->size) {
488                 drm_gem_object_unreference_unlocked(obj);
489                 return -EINVAL;
490         }
491
492         if (i915_gem_object_needs_bit17_swizzle(obj)) {
493                 ret = i915_gem_shmem_pread_slow(dev, obj, args, file_priv);
494         } else {
495                 ret = i915_gem_shmem_pread_fast(dev, obj, args, file_priv);
496                 if (ret != 0)
497                         ret = i915_gem_shmem_pread_slow(dev, obj, args,
498                                                         file_priv);
499         }
500
501         drm_gem_object_unreference_unlocked(obj);
502
503         return ret;
504 }
505
506 /* This is the fast write path which cannot handle
507  * page faults in the source data
508  */
509
510 static inline int
511 fast_user_write(struct io_mapping *mapping,
512                 loff_t page_base, int page_offset,
513                 char __user *user_data,
514                 int length)
515 {
516         char *vaddr_atomic;
517         unsigned long unwritten;
518
519         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
520         unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
521                                                       user_data, length);
522         io_mapping_unmap_atomic(vaddr_atomic);
523         if (unwritten)
524                 return -EFAULT;
525         return 0;
526 }
527
528 /* Here's the write path which can sleep for
529  * page faults
530  */
531
532 static inline int
533 slow_kernel_write(struct io_mapping *mapping,
534                   loff_t gtt_base, int gtt_offset,
535                   struct page *user_page, int user_offset,
536                   int length)
537 {
538         char *src_vaddr, *dst_vaddr;
539         unsigned long unwritten;
540
541         dst_vaddr = io_mapping_map_atomic_wc(mapping, gtt_base);
542         src_vaddr = kmap_atomic(user_page, KM_USER1);
543         unwritten = __copy_from_user_inatomic_nocache(dst_vaddr + gtt_offset,
544                                                       src_vaddr + user_offset,
545                                                       length);
546         kunmap_atomic(src_vaddr, KM_USER1);
547         io_mapping_unmap_atomic(dst_vaddr);
548         if (unwritten)
549                 return -EFAULT;
550         return 0;
551 }
552
553 static inline int
554 fast_shmem_write(struct page **pages,
555                  loff_t page_base, int page_offset,
556                  char __user *data,
557                  int length)
558 {
559         char __iomem *vaddr;
560         unsigned long unwritten;
561
562         vaddr = kmap_atomic(pages[page_base >> PAGE_SHIFT], KM_USER0);
563         if (vaddr == NULL)
564                 return -ENOMEM;
565         unwritten = __copy_from_user_inatomic(vaddr + page_offset, data, length);
566         kunmap_atomic(vaddr, KM_USER0);
567
568         if (unwritten)
569                 return -EFAULT;
570         return 0;
571 }
572
573 /**
574  * This is the fast pwrite path, where we copy the data directly from the
575  * user into the GTT, uncached.
576  */
577 static int
578 i915_gem_gtt_pwrite_fast(struct drm_device *dev, struct drm_gem_object *obj,
579                          struct drm_i915_gem_pwrite *args,
580                          struct drm_file *file_priv)
581 {
582         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
583         drm_i915_private_t *dev_priv = dev->dev_private;
584         ssize_t remain;
585         loff_t offset, page_base;
586         char __user *user_data;
587         int page_offset, page_length;
588         int ret;
589
590         user_data = (char __user *) (uintptr_t) args->data_ptr;
591         remain = args->size;
592         if (!access_ok(VERIFY_READ, user_data, remain))
593                 return -EFAULT;
594
595
596         mutex_lock(&dev->struct_mutex);
597         ret = i915_gem_object_pin(obj, 0);
598         if (ret) {
599                 mutex_unlock(&dev->struct_mutex);
600                 return ret;
601         }
602         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
603         if (ret)
604                 goto fail;
605
606         obj_priv = to_intel_bo(obj);
607         offset = obj_priv->gtt_offset + args->offset;
608
609         while (remain > 0) {
610                 /* Operation in this page
611                  *
612                  * page_base = page offset within aperture
613                  * page_offset = offset within page
614                  * page_length = bytes to copy for this page
615                  */
616                 page_base = (offset & ~(PAGE_SIZE-1));
617                 page_offset = offset & (PAGE_SIZE-1);
618                 page_length = remain;
619                 if ((page_offset + remain) > PAGE_SIZE)
620                         page_length = PAGE_SIZE - page_offset;
621
622                 ret = fast_user_write (dev_priv->mm.gtt_mapping, page_base,
623                                        page_offset, user_data, page_length);
624
625                 /* If we get a fault while copying data, then (presumably) our
626                  * source page isn't available.  Return the error and we'll
627                  * retry in the slow path.
628                  */
629                 if (ret)
630                         goto fail;
631
632                 remain -= page_length;
633                 user_data += page_length;
634                 offset += page_length;
635         }
636
637 fail:
638         i915_gem_object_unpin(obj);
639         mutex_unlock(&dev->struct_mutex);
640
641         return ret;
642 }
643
644 /**
645  * This is the fallback GTT pwrite path, which uses get_user_pages to pin
646  * the memory and maps it using kmap_atomic for copying.
647  *
648  * This code resulted in x11perf -rgb10text consuming about 10% more CPU
649  * than using i915_gem_gtt_pwrite_fast on a G45 (32-bit).
650  */
651 static int
652 i915_gem_gtt_pwrite_slow(struct drm_device *dev, struct drm_gem_object *obj,
653                          struct drm_i915_gem_pwrite *args,
654                          struct drm_file *file_priv)
655 {
656         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
657         drm_i915_private_t *dev_priv = dev->dev_private;
658         ssize_t remain;
659         loff_t gtt_page_base, offset;
660         loff_t first_data_page, last_data_page, num_pages;
661         loff_t pinned_pages, i;
662         struct page **user_pages;
663         struct mm_struct *mm = current->mm;
664         int gtt_page_offset, data_page_offset, data_page_index, page_length;
665         int ret;
666         uint64_t data_ptr = args->data_ptr;
667
668         remain = args->size;
669
670         /* Pin the user pages containing the data.  We can't fault while
671          * holding the struct mutex, and all of the pwrite implementations
672          * want to hold it while dereferencing the user data.
673          */
674         first_data_page = data_ptr / PAGE_SIZE;
675         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
676         num_pages = last_data_page - first_data_page + 1;
677
678         user_pages = drm_calloc_large(num_pages, sizeof(struct page *));
679         if (user_pages == NULL)
680                 return -ENOMEM;
681
682         down_read(&mm->mmap_sem);
683         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
684                                       num_pages, 0, 0, user_pages, NULL);
685         up_read(&mm->mmap_sem);
686         if (pinned_pages < num_pages) {
687                 ret = -EFAULT;
688                 goto out_unpin_pages;
689         }
690
691         mutex_lock(&dev->struct_mutex);
692         ret = i915_gem_object_pin(obj, 0);
693         if (ret)
694                 goto out_unlock;
695
696         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
697         if (ret)
698                 goto out_unpin_object;
699
700         obj_priv = to_intel_bo(obj);
701         offset = obj_priv->gtt_offset + args->offset;
702
703         while (remain > 0) {
704                 /* Operation in this page
705                  *
706                  * gtt_page_base = page offset within aperture
707                  * gtt_page_offset = offset within page in aperture
708                  * data_page_index = page number in get_user_pages return
709                  * data_page_offset = offset with data_page_index page.
710                  * page_length = bytes to copy for this page
711                  */
712                 gtt_page_base = offset & PAGE_MASK;
713                 gtt_page_offset = offset & ~PAGE_MASK;
714                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
715                 data_page_offset = data_ptr & ~PAGE_MASK;
716
717                 page_length = remain;
718                 if ((gtt_page_offset + page_length) > PAGE_SIZE)
719                         page_length = PAGE_SIZE - gtt_page_offset;
720                 if ((data_page_offset + page_length) > PAGE_SIZE)
721                         page_length = PAGE_SIZE - data_page_offset;
722
723                 ret = slow_kernel_write(dev_priv->mm.gtt_mapping,
724                                         gtt_page_base, gtt_page_offset,
725                                         user_pages[data_page_index],
726                                         data_page_offset,
727                                         page_length);
728
729                 /* If we get a fault while copying data, then (presumably) our
730                  * source page isn't available.  Return the error and we'll
731                  * retry in the slow path.
732                  */
733                 if (ret)
734                         goto out_unpin_object;
735
736                 remain -= page_length;
737                 offset += page_length;
738                 data_ptr += page_length;
739         }
740
741 out_unpin_object:
742         i915_gem_object_unpin(obj);
743 out_unlock:
744         mutex_unlock(&dev->struct_mutex);
745 out_unpin_pages:
746         for (i = 0; i < pinned_pages; i++)
747                 page_cache_release(user_pages[i]);
748         drm_free_large(user_pages);
749
750         return ret;
751 }
752
753 /**
754  * This is the fast shmem pwrite path, which attempts to directly
755  * copy_from_user into the kmapped pages backing the object.
756  */
757 static int
758 i915_gem_shmem_pwrite_fast(struct drm_device *dev, struct drm_gem_object *obj,
759                            struct drm_i915_gem_pwrite *args,
760                            struct drm_file *file_priv)
761 {
762         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
763         ssize_t remain;
764         loff_t offset, page_base;
765         char __user *user_data;
766         int page_offset, page_length;
767         int ret;
768
769         user_data = (char __user *) (uintptr_t) args->data_ptr;
770         remain = args->size;
771
772         mutex_lock(&dev->struct_mutex);
773
774         ret = i915_gem_object_get_pages(obj, 0);
775         if (ret != 0)
776                 goto fail_unlock;
777
778         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
779         if (ret != 0)
780                 goto fail_put_pages;
781
782         obj_priv = to_intel_bo(obj);
783         offset = args->offset;
784         obj_priv->dirty = 1;
785
786         while (remain > 0) {
787                 /* Operation in this page
788                  *
789                  * page_base = page offset within aperture
790                  * page_offset = offset within page
791                  * page_length = bytes to copy for this page
792                  */
793                 page_base = (offset & ~(PAGE_SIZE-1));
794                 page_offset = offset & (PAGE_SIZE-1);
795                 page_length = remain;
796                 if ((page_offset + remain) > PAGE_SIZE)
797                         page_length = PAGE_SIZE - page_offset;
798
799                 ret = fast_shmem_write(obj_priv->pages,
800                                        page_base, page_offset,
801                                        user_data, page_length);
802                 if (ret)
803                         goto fail_put_pages;
804
805                 remain -= page_length;
806                 user_data += page_length;
807                 offset += page_length;
808         }
809
810 fail_put_pages:
811         i915_gem_object_put_pages(obj);
812 fail_unlock:
813         mutex_unlock(&dev->struct_mutex);
814
815         return ret;
816 }
817
818 /**
819  * This is the fallback shmem pwrite path, which uses get_user_pages to pin
820  * the memory and maps it using kmap_atomic for copying.
821  *
822  * This avoids taking mmap_sem for faulting on the user's address while the
823  * struct_mutex is held.
824  */
825 static int
826 i915_gem_shmem_pwrite_slow(struct drm_device *dev, struct drm_gem_object *obj,
827                            struct drm_i915_gem_pwrite *args,
828                            struct drm_file *file_priv)
829 {
830         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
831         struct mm_struct *mm = current->mm;
832         struct page **user_pages;
833         ssize_t remain;
834         loff_t offset, pinned_pages, i;
835         loff_t first_data_page, last_data_page, num_pages;
836         int shmem_page_index, shmem_page_offset;
837         int data_page_index,  data_page_offset;
838         int page_length;
839         int ret;
840         uint64_t data_ptr = args->data_ptr;
841         int do_bit17_swizzling;
842
843         remain = args->size;
844
845         /* Pin the user pages containing the data.  We can't fault while
846          * holding the struct mutex, and all of the pwrite implementations
847          * want to hold it while dereferencing the user data.
848          */
849         first_data_page = data_ptr / PAGE_SIZE;
850         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
851         num_pages = last_data_page - first_data_page + 1;
852
853         user_pages = drm_calloc_large(num_pages, sizeof(struct page *));
854         if (user_pages == NULL)
855                 return -ENOMEM;
856
857         down_read(&mm->mmap_sem);
858         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
859                                       num_pages, 0, 0, user_pages, NULL);
860         up_read(&mm->mmap_sem);
861         if (pinned_pages < num_pages) {
862                 ret = -EFAULT;
863                 goto fail_put_user_pages;
864         }
865
866         do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
867
868         mutex_lock(&dev->struct_mutex);
869
870         ret = i915_gem_object_get_pages_or_evict(obj);
871         if (ret)
872                 goto fail_unlock;
873
874         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
875         if (ret != 0)
876                 goto fail_put_pages;
877
878         obj_priv = to_intel_bo(obj);
879         offset = args->offset;
880         obj_priv->dirty = 1;
881
882         while (remain > 0) {
883                 /* Operation in this page
884                  *
885                  * shmem_page_index = page number within shmem file
886                  * shmem_page_offset = offset within page in shmem file
887                  * data_page_index = page number in get_user_pages return
888                  * data_page_offset = offset with data_page_index page.
889                  * page_length = bytes to copy for this page
890                  */
891                 shmem_page_index = offset / PAGE_SIZE;
892                 shmem_page_offset = offset & ~PAGE_MASK;
893                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
894                 data_page_offset = data_ptr & ~PAGE_MASK;
895
896                 page_length = remain;
897                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
898                         page_length = PAGE_SIZE - shmem_page_offset;
899                 if ((data_page_offset + page_length) > PAGE_SIZE)
900                         page_length = PAGE_SIZE - data_page_offset;
901
902                 if (do_bit17_swizzling) {
903                         ret = slow_shmem_bit17_copy(obj_priv->pages[shmem_page_index],
904                                                     shmem_page_offset,
905                                                     user_pages[data_page_index],
906                                                     data_page_offset,
907                                                     page_length,
908                                                     0);
909                 } else {
910                         ret = slow_shmem_copy(obj_priv->pages[shmem_page_index],
911                                               shmem_page_offset,
912                                               user_pages[data_page_index],
913                                               data_page_offset,
914                                               page_length);
915                 }
916                 if (ret)
917                         goto fail_put_pages;
918
919                 remain -= page_length;
920                 data_ptr += page_length;
921                 offset += page_length;
922         }
923
924 fail_put_pages:
925         i915_gem_object_put_pages(obj);
926 fail_unlock:
927         mutex_unlock(&dev->struct_mutex);
928 fail_put_user_pages:
929         for (i = 0; i < pinned_pages; i++)
930                 page_cache_release(user_pages[i]);
931         drm_free_large(user_pages);
932
933         return ret;
934 }
935
936 /**
937  * Writes data to the object referenced by handle.
938  *
939  * On error, the contents of the buffer that were to be modified are undefined.
940  */
941 int
942 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
943                       struct drm_file *file_priv)
944 {
945         struct drm_i915_gem_pwrite *args = data;
946         struct drm_gem_object *obj;
947         struct drm_i915_gem_object *obj_priv;
948         int ret = 0;
949
950         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
951         if (obj == NULL)
952                 return -EBADF;
953         obj_priv = to_intel_bo(obj);
954
955         /* Bounds check destination.
956          *
957          * XXX: This could use review for overflow issues...
958          */
959         if (args->offset > obj->size || args->size > obj->size ||
960             args->offset + args->size > obj->size) {
961                 drm_gem_object_unreference_unlocked(obj);
962                 return -EINVAL;
963         }
964
965         /* We can only do the GTT pwrite on untiled buffers, as otherwise
966          * it would end up going through the fenced access, and we'll get
967          * different detiling behavior between reading and writing.
968          * pread/pwrite currently are reading and writing from the CPU
969          * perspective, requiring manual detiling by the client.
970          */
971         if (obj_priv->phys_obj)
972                 ret = i915_gem_phys_pwrite(dev, obj, args, file_priv);
973         else if (obj_priv->tiling_mode == I915_TILING_NONE &&
974                  dev->gtt_total != 0) {
975                 ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file_priv);
976                 if (ret == -EFAULT) {
977                         ret = i915_gem_gtt_pwrite_slow(dev, obj, args,
978                                                        file_priv);
979                 }
980         } else if (i915_gem_object_needs_bit17_swizzle(obj)) {
981                 ret = i915_gem_shmem_pwrite_slow(dev, obj, args, file_priv);
982         } else {
983                 ret = i915_gem_shmem_pwrite_fast(dev, obj, args, file_priv);
984                 if (ret == -EFAULT) {
985                         ret = i915_gem_shmem_pwrite_slow(dev, obj, args,
986                                                          file_priv);
987                 }
988         }
989
990 #if WATCH_PWRITE
991         if (ret)
992                 DRM_INFO("pwrite failed %d\n", ret);
993 #endif
994
995         drm_gem_object_unreference_unlocked(obj);
996
997         return ret;
998 }
999
1000 /**
1001  * Called when user space prepares to use an object with the CPU, either
1002  * through the mmap ioctl's mapping or a GTT mapping.
1003  */
1004 int
1005 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1006                           struct drm_file *file_priv)
1007 {
1008         struct drm_i915_private *dev_priv = dev->dev_private;
1009         struct drm_i915_gem_set_domain *args = data;
1010         struct drm_gem_object *obj;
1011         struct drm_i915_gem_object *obj_priv;
1012         uint32_t read_domains = args->read_domains;
1013         uint32_t write_domain = args->write_domain;
1014         int ret;
1015
1016         if (!(dev->driver->driver_features & DRIVER_GEM))
1017                 return -ENODEV;
1018
1019         /* Only handle setting domains to types used by the CPU. */
1020         if (write_domain & I915_GEM_GPU_DOMAINS)
1021                 return -EINVAL;
1022
1023         if (read_domains & I915_GEM_GPU_DOMAINS)
1024                 return -EINVAL;
1025
1026         /* Having something in the write domain implies it's in the read
1027          * domain, and only that read domain.  Enforce that in the request.
1028          */
1029         if (write_domain != 0 && read_domains != write_domain)
1030                 return -EINVAL;
1031
1032         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1033         if (obj == NULL)
1034                 return -EBADF;
1035         obj_priv = to_intel_bo(obj);
1036
1037         mutex_lock(&dev->struct_mutex);
1038
1039         intel_mark_busy(dev, obj);
1040
1041 #if WATCH_BUF
1042         DRM_INFO("set_domain_ioctl %p(%zd), %08x %08x\n",
1043                  obj, obj->size, read_domains, write_domain);
1044 #endif
1045         if (read_domains & I915_GEM_DOMAIN_GTT) {
1046                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
1047
1048                 /* Update the LRU on the fence for the CPU access that's
1049                  * about to occur.
1050                  */
1051                 if (obj_priv->fence_reg != I915_FENCE_REG_NONE) {
1052                         struct drm_i915_fence_reg *reg =
1053                                 &dev_priv->fence_regs[obj_priv->fence_reg];
1054                         list_move_tail(&reg->lru_list,
1055                                        &dev_priv->mm.fence_list);
1056                 }
1057
1058                 /* Silently promote "you're not bound, there was nothing to do"
1059                  * to success, since the client was just asking us to
1060                  * make sure everything was done.
1061                  */
1062                 if (ret == -EINVAL)
1063                         ret = 0;
1064         } else {
1065                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
1066         }
1067
1068         drm_gem_object_unreference(obj);
1069         mutex_unlock(&dev->struct_mutex);
1070         return ret;
1071 }
1072
1073 /**
1074  * Called when user space has done writes to this buffer
1075  */
1076 int
1077 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1078                       struct drm_file *file_priv)
1079 {
1080         struct drm_i915_gem_sw_finish *args = data;
1081         struct drm_gem_object *obj;
1082         struct drm_i915_gem_object *obj_priv;
1083         int ret = 0;
1084
1085         if (!(dev->driver->driver_features & DRIVER_GEM))
1086                 return -ENODEV;
1087
1088         mutex_lock(&dev->struct_mutex);
1089         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1090         if (obj == NULL) {
1091                 mutex_unlock(&dev->struct_mutex);
1092                 return -EBADF;
1093         }
1094
1095 #if WATCH_BUF
1096         DRM_INFO("%s: sw_finish %d (%p %zd)\n",
1097                  __func__, args->handle, obj, obj->size);
1098 #endif
1099         obj_priv = to_intel_bo(obj);
1100
1101         /* Pinned buffers may be scanout, so flush the cache */
1102         if (obj_priv->pin_count)
1103                 i915_gem_object_flush_cpu_write_domain(obj);
1104
1105         drm_gem_object_unreference(obj);
1106         mutex_unlock(&dev->struct_mutex);
1107         return ret;
1108 }
1109
1110 /**
1111  * Maps the contents of an object, returning the address it is mapped
1112  * into.
1113  *
1114  * While the mapping holds a reference on the contents of the object, it doesn't
1115  * imply a ref on the object itself.
1116  */
1117 int
1118 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1119                    struct drm_file *file_priv)
1120 {
1121         struct drm_i915_gem_mmap *args = data;
1122         struct drm_gem_object *obj;
1123         loff_t offset;
1124         unsigned long addr;
1125
1126         if (!(dev->driver->driver_features & DRIVER_GEM))
1127                 return -ENODEV;
1128
1129         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1130         if (obj == NULL)
1131                 return -EBADF;
1132
1133         offset = args->offset;
1134
1135         down_write(&current->mm->mmap_sem);
1136         addr = do_mmap(obj->filp, 0, args->size,
1137                        PROT_READ | PROT_WRITE, MAP_SHARED,
1138                        args->offset);
1139         up_write(&current->mm->mmap_sem);
1140         drm_gem_object_unreference_unlocked(obj);
1141         if (IS_ERR((void *)addr))
1142                 return addr;
1143
1144         args->addr_ptr = (uint64_t) addr;
1145
1146         return 0;
1147 }
1148
1149 /**
1150  * i915_gem_fault - fault a page into the GTT
1151  * vma: VMA in question
1152  * vmf: fault info
1153  *
1154  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1155  * from userspace.  The fault handler takes care of binding the object to
1156  * the GTT (if needed), allocating and programming a fence register (again,
1157  * only if needed based on whether the old reg is still valid or the object
1158  * is tiled) and inserting a new PTE into the faulting process.
1159  *
1160  * Note that the faulting process may involve evicting existing objects
1161  * from the GTT and/or fence registers to make room.  So performance may
1162  * suffer if the GTT working set is large or there are few fence registers
1163  * left.
1164  */
1165 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1166 {
1167         struct drm_gem_object *obj = vma->vm_private_data;
1168         struct drm_device *dev = obj->dev;
1169         struct drm_i915_private *dev_priv = dev->dev_private;
1170         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1171         pgoff_t page_offset;
1172         unsigned long pfn;
1173         int ret = 0;
1174         bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1175
1176         /* We don't use vmf->pgoff since that has the fake offset */
1177         page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
1178                 PAGE_SHIFT;
1179
1180         /* Now bind it into the GTT if needed */
1181         mutex_lock(&dev->struct_mutex);
1182         if (!obj_priv->gtt_space) {
1183                 ret = i915_gem_object_bind_to_gtt(obj, 0);
1184                 if (ret)
1185                         goto unlock;
1186
1187                 list_add_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
1188
1189                 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1190                 if (ret)
1191                         goto unlock;
1192         }
1193
1194         /* Need a new fence register? */
1195         if (obj_priv->tiling_mode != I915_TILING_NONE) {
1196                 ret = i915_gem_object_get_fence_reg(obj);
1197                 if (ret)
1198                         goto unlock;
1199         }
1200
1201         pfn = ((dev->agp->base + obj_priv->gtt_offset) >> PAGE_SHIFT) +
1202                 page_offset;
1203
1204         /* Finally, remap it using the new GTT offset */
1205         ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
1206 unlock:
1207         mutex_unlock(&dev->struct_mutex);
1208
1209         switch (ret) {
1210         case 0:
1211         case -ERESTARTSYS:
1212                 return VM_FAULT_NOPAGE;
1213         case -ENOMEM:
1214         case -EAGAIN:
1215                 return VM_FAULT_OOM;
1216         default:
1217                 return VM_FAULT_SIGBUS;
1218         }
1219 }
1220
1221 /**
1222  * i915_gem_create_mmap_offset - create a fake mmap offset for an object
1223  * @obj: obj in question
1224  *
1225  * GEM memory mapping works by handing back to userspace a fake mmap offset
1226  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
1227  * up the object based on the offset and sets up the various memory mapping
1228  * structures.
1229  *
1230  * This routine allocates and attaches a fake offset for @obj.
1231  */
1232 static int
1233 i915_gem_create_mmap_offset(struct drm_gem_object *obj)
1234 {
1235         struct drm_device *dev = obj->dev;
1236         struct drm_gem_mm *mm = dev->mm_private;
1237         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1238         struct drm_map_list *list;
1239         struct drm_local_map *map;
1240         int ret = 0;
1241
1242         /* Set the object up for mmap'ing */
1243         list = &obj->map_list;
1244         list->map = kzalloc(sizeof(struct drm_map_list), GFP_KERNEL);
1245         if (!list->map)
1246                 return -ENOMEM;
1247
1248         map = list->map;
1249         map->type = _DRM_GEM;
1250         map->size = obj->size;
1251         map->handle = obj;
1252
1253         /* Get a DRM GEM mmap offset allocated... */
1254         list->file_offset_node = drm_mm_search_free(&mm->offset_manager,
1255                                                     obj->size / PAGE_SIZE, 0, 0);
1256         if (!list->file_offset_node) {
1257                 DRM_ERROR("failed to allocate offset for bo %d\n", obj->name);
1258                 ret = -ENOMEM;
1259                 goto out_free_list;
1260         }
1261
1262         list->file_offset_node = drm_mm_get_block(list->file_offset_node,
1263                                                   obj->size / PAGE_SIZE, 0);
1264         if (!list->file_offset_node) {
1265                 ret = -ENOMEM;
1266                 goto out_free_list;
1267         }
1268
1269         list->hash.key = list->file_offset_node->start;
1270         if (drm_ht_insert_item(&mm->offset_hash, &list->hash)) {
1271                 DRM_ERROR("failed to add to map hash\n");
1272                 ret = -ENOMEM;
1273                 goto out_free_mm;
1274         }
1275
1276         /* By now we should be all set, any drm_mmap request on the offset
1277          * below will get to our mmap & fault handler */
1278         obj_priv->mmap_offset = ((uint64_t) list->hash.key) << PAGE_SHIFT;
1279
1280         return 0;
1281
1282 out_free_mm:
1283         drm_mm_put_block(list->file_offset_node);
1284 out_free_list:
1285         kfree(list->map);
1286
1287         return ret;
1288 }
1289
1290 /**
1291  * i915_gem_release_mmap - remove physical page mappings
1292  * @obj: obj in question
1293  *
1294  * Preserve the reservation of the mmapping with the DRM core code, but
1295  * relinquish ownership of the pages back to the system.
1296  *
1297  * It is vital that we remove the page mapping if we have mapped a tiled
1298  * object through the GTT and then lose the fence register due to
1299  * resource pressure. Similarly if the object has been moved out of the
1300  * aperture, than pages mapped into userspace must be revoked. Removing the
1301  * mapping will then trigger a page fault on the next user access, allowing
1302  * fixup by i915_gem_fault().
1303  */
1304 void
1305 i915_gem_release_mmap(struct drm_gem_object *obj)
1306 {
1307         struct drm_device *dev = obj->dev;
1308         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1309
1310         if (dev->dev_mapping)
1311                 unmap_mapping_range(dev->dev_mapping,
1312                                     obj_priv->mmap_offset, obj->size, 1);
1313 }
1314
1315 static void
1316 i915_gem_free_mmap_offset(struct drm_gem_object *obj)
1317 {
1318         struct drm_device *dev = obj->dev;
1319         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1320         struct drm_gem_mm *mm = dev->mm_private;
1321         struct drm_map_list *list;
1322
1323         list = &obj->map_list;
1324         drm_ht_remove_item(&mm->offset_hash, &list->hash);
1325
1326         if (list->file_offset_node) {
1327                 drm_mm_put_block(list->file_offset_node);
1328                 list->file_offset_node = NULL;
1329         }
1330
1331         if (list->map) {
1332                 kfree(list->map);
1333                 list->map = NULL;
1334         }
1335
1336         obj_priv->mmap_offset = 0;
1337 }
1338
1339 /**
1340  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
1341  * @obj: object to check
1342  *
1343  * Return the required GTT alignment for an object, taking into account
1344  * potential fence register mapping if needed.
1345  */
1346 static uint32_t
1347 i915_gem_get_gtt_alignment(struct drm_gem_object *obj)
1348 {
1349         struct drm_device *dev = obj->dev;
1350         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1351         int start, i;
1352
1353         /*
1354          * Minimum alignment is 4k (GTT page size), but might be greater
1355          * if a fence register is needed for the object.
1356          */
1357         if (IS_I965G(dev) || obj_priv->tiling_mode == I915_TILING_NONE)
1358                 return 4096;
1359
1360         /*
1361          * Previous chips need to be aligned to the size of the smallest
1362          * fence register that can contain the object.
1363          */
1364         if (IS_I9XX(dev))
1365                 start = 1024*1024;
1366         else
1367                 start = 512*1024;
1368
1369         for (i = start; i < obj->size; i <<= 1)
1370                 ;
1371
1372         return i;
1373 }
1374
1375 /**
1376  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
1377  * @dev: DRM device
1378  * @data: GTT mapping ioctl data
1379  * @file_priv: GEM object info
1380  *
1381  * Simply returns the fake offset to userspace so it can mmap it.
1382  * The mmap call will end up in drm_gem_mmap(), which will set things
1383  * up so we can get faults in the handler above.
1384  *
1385  * The fault handler will take care of binding the object into the GTT
1386  * (since it may have been evicted to make room for something), allocating
1387  * a fence register, and mapping the appropriate aperture address into
1388  * userspace.
1389  */
1390 int
1391 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
1392                         struct drm_file *file_priv)
1393 {
1394         struct drm_i915_gem_mmap_gtt *args = data;
1395         struct drm_i915_private *dev_priv = dev->dev_private;
1396         struct drm_gem_object *obj;
1397         struct drm_i915_gem_object *obj_priv;
1398         int ret;
1399
1400         if (!(dev->driver->driver_features & DRIVER_GEM))
1401                 return -ENODEV;
1402
1403         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
1404         if (obj == NULL)
1405                 return -EBADF;
1406
1407         mutex_lock(&dev->struct_mutex);
1408
1409         obj_priv = to_intel_bo(obj);
1410
1411         if (obj_priv->madv != I915_MADV_WILLNEED) {
1412                 DRM_ERROR("Attempting to mmap a purgeable buffer\n");
1413                 drm_gem_object_unreference(obj);
1414                 mutex_unlock(&dev->struct_mutex);
1415                 return -EINVAL;
1416         }
1417
1418
1419         if (!obj_priv->mmap_offset) {
1420                 ret = i915_gem_create_mmap_offset(obj);
1421                 if (ret) {
1422                         drm_gem_object_unreference(obj);
1423                         mutex_unlock(&dev->struct_mutex);
1424                         return ret;
1425                 }
1426         }
1427
1428         args->offset = obj_priv->mmap_offset;
1429
1430         /*
1431          * Pull it into the GTT so that we have a page list (makes the
1432          * initial fault faster and any subsequent flushing possible).
1433          */
1434         if (!obj_priv->agp_mem) {
1435                 ret = i915_gem_object_bind_to_gtt(obj, 0);
1436                 if (ret) {
1437                         drm_gem_object_unreference(obj);
1438                         mutex_unlock(&dev->struct_mutex);
1439                         return ret;
1440                 }
1441                 list_add_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
1442         }
1443
1444         drm_gem_object_unreference(obj);
1445         mutex_unlock(&dev->struct_mutex);
1446
1447         return 0;
1448 }
1449
1450 void
1451 i915_gem_object_put_pages(struct drm_gem_object *obj)
1452 {
1453         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1454         int page_count = obj->size / PAGE_SIZE;
1455         int i;
1456
1457         BUG_ON(obj_priv->pages_refcount == 0);
1458         BUG_ON(obj_priv->madv == __I915_MADV_PURGED);
1459
1460         if (--obj_priv->pages_refcount != 0)
1461                 return;
1462
1463         if (obj_priv->tiling_mode != I915_TILING_NONE)
1464                 i915_gem_object_save_bit_17_swizzle(obj);
1465
1466         if (obj_priv->madv == I915_MADV_DONTNEED)
1467                 obj_priv->dirty = 0;
1468
1469         for (i = 0; i < page_count; i++) {
1470                 if (obj_priv->dirty)
1471                         set_page_dirty(obj_priv->pages[i]);
1472
1473                 if (obj_priv->madv == I915_MADV_WILLNEED)
1474                         mark_page_accessed(obj_priv->pages[i]);
1475
1476                 page_cache_release(obj_priv->pages[i]);
1477         }
1478         obj_priv->dirty = 0;
1479
1480         drm_free_large(obj_priv->pages);
1481         obj_priv->pages = NULL;
1482 }
1483
1484 static void
1485 i915_gem_object_move_to_active(struct drm_gem_object *obj, uint32_t seqno,
1486                                struct intel_ring_buffer *ring)
1487 {
1488         struct drm_device *dev = obj->dev;
1489         drm_i915_private_t *dev_priv = dev->dev_private;
1490         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1491         BUG_ON(ring == NULL);
1492         obj_priv->ring = ring;
1493
1494         /* Add a reference if we're newly entering the active list. */
1495         if (!obj_priv->active) {
1496                 drm_gem_object_reference(obj);
1497                 obj_priv->active = 1;
1498         }
1499         /* Move from whatever list we were on to the tail of execution. */
1500         spin_lock(&dev_priv->mm.active_list_lock);
1501         list_move_tail(&obj_priv->list, &ring->active_list);
1502         spin_unlock(&dev_priv->mm.active_list_lock);
1503         obj_priv->last_rendering_seqno = seqno;
1504 }
1505
1506 static void
1507 i915_gem_object_move_to_flushing(struct drm_gem_object *obj)
1508 {
1509         struct drm_device *dev = obj->dev;
1510         drm_i915_private_t *dev_priv = dev->dev_private;
1511         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1512
1513         BUG_ON(!obj_priv->active);
1514         list_move_tail(&obj_priv->list, &dev_priv->mm.flushing_list);
1515         obj_priv->last_rendering_seqno = 0;
1516 }
1517
1518 /* Immediately discard the backing storage */
1519 static void
1520 i915_gem_object_truncate(struct drm_gem_object *obj)
1521 {
1522         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1523         struct inode *inode;
1524
1525         inode = obj->filp->f_path.dentry->d_inode;
1526         if (inode->i_op->truncate)
1527                 inode->i_op->truncate (inode);
1528
1529         obj_priv->madv = __I915_MADV_PURGED;
1530 }
1531
1532 static inline int
1533 i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj_priv)
1534 {
1535         return obj_priv->madv == I915_MADV_DONTNEED;
1536 }
1537
1538 static void
1539 i915_gem_object_move_to_inactive(struct drm_gem_object *obj)
1540 {
1541         struct drm_device *dev = obj->dev;
1542         drm_i915_private_t *dev_priv = dev->dev_private;
1543         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1544
1545         i915_verify_inactive(dev, __FILE__, __LINE__);
1546         if (obj_priv->pin_count != 0)
1547                 list_del_init(&obj_priv->list);
1548         else
1549                 list_move_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
1550
1551         BUG_ON(!list_empty(&obj_priv->gpu_write_list));
1552
1553         obj_priv->last_rendering_seqno = 0;
1554         obj_priv->ring = NULL;
1555         if (obj_priv->active) {
1556                 obj_priv->active = 0;
1557                 drm_gem_object_unreference(obj);
1558         }
1559         i915_verify_inactive(dev, __FILE__, __LINE__);
1560 }
1561
1562 static void
1563 i915_gem_process_flushing_list(struct drm_device *dev,
1564                                uint32_t flush_domains, uint32_t seqno,
1565                                struct intel_ring_buffer *ring)
1566 {
1567         drm_i915_private_t *dev_priv = dev->dev_private;
1568         struct drm_i915_gem_object *obj_priv, *next;
1569
1570         list_for_each_entry_safe(obj_priv, next,
1571                                  &dev_priv->mm.gpu_write_list,
1572                                  gpu_write_list) {
1573                 struct drm_gem_object *obj = &obj_priv->base;
1574
1575                 if ((obj->write_domain & flush_domains) ==
1576                     obj->write_domain &&
1577                     obj_priv->ring->ring_flag == ring->ring_flag) {
1578                         uint32_t old_write_domain = obj->write_domain;
1579
1580                         obj->write_domain = 0;
1581                         list_del_init(&obj_priv->gpu_write_list);
1582                         i915_gem_object_move_to_active(obj, seqno, ring);
1583
1584                         /* update the fence lru list */
1585                         if (obj_priv->fence_reg != I915_FENCE_REG_NONE) {
1586                                 struct drm_i915_fence_reg *reg =
1587                                         &dev_priv->fence_regs[obj_priv->fence_reg];
1588                                 list_move_tail(&reg->lru_list,
1589                                                 &dev_priv->mm.fence_list);
1590                         }
1591
1592                         trace_i915_gem_object_change_domain(obj,
1593                                                             obj->read_domains,
1594                                                             old_write_domain);
1595                 }
1596         }
1597 }
1598
1599 uint32_t
1600 i915_add_request(struct drm_device *dev, struct drm_file *file_priv,
1601                  uint32_t flush_domains, struct intel_ring_buffer *ring)
1602 {
1603         drm_i915_private_t *dev_priv = dev->dev_private;
1604         struct drm_i915_file_private *i915_file_priv = NULL;
1605         struct drm_i915_gem_request *request;
1606         uint32_t seqno;
1607         int was_empty;
1608
1609         if (file_priv != NULL)
1610                 i915_file_priv = file_priv->driver_priv;
1611
1612         request = kzalloc(sizeof(*request), GFP_KERNEL);
1613         if (request == NULL)
1614                 return 0;
1615
1616         seqno = ring->add_request(dev, ring, file_priv, flush_domains);
1617
1618         request->seqno = seqno;
1619         request->ring = ring;
1620         request->emitted_jiffies = jiffies;
1621         was_empty = list_empty(&ring->request_list);
1622         list_add_tail(&request->list, &ring->request_list);
1623
1624         if (i915_file_priv) {
1625                 list_add_tail(&request->client_list,
1626                               &i915_file_priv->mm.request_list);
1627         } else {
1628                 INIT_LIST_HEAD(&request->client_list);
1629         }
1630
1631         /* Associate any objects on the flushing list matching the write
1632          * domain we're flushing with our flush.
1633          */
1634         if (flush_domains != 0) 
1635                 i915_gem_process_flushing_list(dev, flush_domains, seqno, ring);
1636
1637         if (!dev_priv->mm.suspended) {
1638                 mod_timer(&dev_priv->hangcheck_timer, jiffies + DRM_I915_HANGCHECK_PERIOD);
1639                 if (was_empty)
1640                         queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
1641         }
1642         return seqno;
1643 }
1644
1645 /**
1646  * Command execution barrier
1647  *
1648  * Ensures that all commands in the ring are finished
1649  * before signalling the CPU
1650  */
1651 static uint32_t
1652 i915_retire_commands(struct drm_device *dev, struct intel_ring_buffer *ring)
1653 {
1654         uint32_t flush_domains = 0;
1655
1656         /* The sampler always gets flushed on i965 (sigh) */
1657         if (IS_I965G(dev))
1658                 flush_domains |= I915_GEM_DOMAIN_SAMPLER;
1659
1660         ring->flush(dev, ring,
1661                         I915_GEM_DOMAIN_COMMAND, flush_domains);
1662         return flush_domains;
1663 }
1664
1665 /**
1666  * Moves buffers associated only with the given active seqno from the active
1667  * to inactive list, potentially freeing them.
1668  */
1669 static void
1670 i915_gem_retire_request(struct drm_device *dev,
1671                         struct drm_i915_gem_request *request)
1672 {
1673         drm_i915_private_t *dev_priv = dev->dev_private;
1674
1675         trace_i915_gem_request_retire(dev, request->seqno);
1676
1677         /* Move any buffers on the active list that are no longer referenced
1678          * by the ringbuffer to the flushing/inactive lists as appropriate.
1679          */
1680         spin_lock(&dev_priv->mm.active_list_lock);
1681         while (!list_empty(&request->ring->active_list)) {
1682                 struct drm_gem_object *obj;
1683                 struct drm_i915_gem_object *obj_priv;
1684
1685                 obj_priv = list_first_entry(&request->ring->active_list,
1686                                             struct drm_i915_gem_object,
1687                                             list);
1688                 obj = &obj_priv->base;
1689
1690                 /* If the seqno being retired doesn't match the oldest in the
1691                  * list, then the oldest in the list must still be newer than
1692                  * this seqno.
1693                  */
1694                 if (obj_priv->last_rendering_seqno != request->seqno)
1695                         goto out;
1696
1697 #if WATCH_LRU
1698                 DRM_INFO("%s: retire %d moves to inactive list %p\n",
1699                          __func__, request->seqno, obj);
1700 #endif
1701
1702                 if (obj->write_domain != 0)
1703                         i915_gem_object_move_to_flushing(obj);
1704                 else {
1705                         /* Take a reference on the object so it won't be
1706                          * freed while the spinlock is held.  The list
1707                          * protection for this spinlock is safe when breaking
1708                          * the lock like this since the next thing we do
1709                          * is just get the head of the list again.
1710                          */
1711                         drm_gem_object_reference(obj);
1712                         i915_gem_object_move_to_inactive(obj);
1713                         spin_unlock(&dev_priv->mm.active_list_lock);
1714                         drm_gem_object_unreference(obj);
1715                         spin_lock(&dev_priv->mm.active_list_lock);
1716                 }
1717         }
1718 out:
1719         spin_unlock(&dev_priv->mm.active_list_lock);
1720 }
1721
1722 /**
1723  * Returns true if seq1 is later than seq2.
1724  */
1725 bool
1726 i915_seqno_passed(uint32_t seq1, uint32_t seq2)
1727 {
1728         return (int32_t)(seq1 - seq2) >= 0;
1729 }
1730
1731 uint32_t
1732 i915_get_gem_seqno(struct drm_device *dev,
1733                    struct intel_ring_buffer *ring)
1734 {
1735         return ring->get_gem_seqno(dev, ring);
1736 }
1737
1738 /**
1739  * This function clears the request list as sequence numbers are passed.
1740  */
1741 void
1742 i915_gem_retire_requests(struct drm_device *dev,
1743                 struct intel_ring_buffer *ring)
1744 {
1745         drm_i915_private_t *dev_priv = dev->dev_private;
1746         uint32_t seqno;
1747
1748         if (!ring->status_page.page_addr
1749                         || list_empty(&ring->request_list))
1750                 return;
1751
1752         seqno = i915_get_gem_seqno(dev, ring);
1753
1754         while (!list_empty(&ring->request_list)) {
1755                 struct drm_i915_gem_request *request;
1756                 uint32_t retiring_seqno;
1757
1758                 request = list_first_entry(&ring->request_list,
1759                                            struct drm_i915_gem_request,
1760                                            list);
1761                 retiring_seqno = request->seqno;
1762
1763                 if (i915_seqno_passed(seqno, retiring_seqno) ||
1764                     atomic_read(&dev_priv->mm.wedged)) {
1765                         i915_gem_retire_request(dev, request);
1766
1767                         list_del(&request->list);
1768                         list_del(&request->client_list);
1769                         kfree(request);
1770                 } else
1771                         break;
1772         }
1773
1774         if (unlikely (dev_priv->trace_irq_seqno &&
1775                       i915_seqno_passed(dev_priv->trace_irq_seqno, seqno))) {
1776
1777                 ring->user_irq_put(dev, ring);
1778                 dev_priv->trace_irq_seqno = 0;
1779         }
1780 }
1781
1782 void
1783 i915_gem_retire_work_handler(struct work_struct *work)
1784 {
1785         drm_i915_private_t *dev_priv;
1786         struct drm_device *dev;
1787
1788         dev_priv = container_of(work, drm_i915_private_t,
1789                                 mm.retire_work.work);
1790         dev = dev_priv->dev;
1791
1792         mutex_lock(&dev->struct_mutex);
1793         i915_gem_retire_requests(dev, &dev_priv->render_ring);
1794
1795         if (HAS_BSD(dev))
1796                 i915_gem_retire_requests(dev, &dev_priv->bsd_ring);
1797
1798         if (!dev_priv->mm.suspended &&
1799                 (!list_empty(&dev_priv->render_ring.request_list) ||
1800                         (HAS_BSD(dev) &&
1801                          !list_empty(&dev_priv->bsd_ring.request_list))))
1802                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
1803         mutex_unlock(&dev->struct_mutex);
1804 }
1805
1806 int
1807 i915_do_wait_request(struct drm_device *dev, uint32_t seqno,
1808                 int interruptible, struct intel_ring_buffer *ring)
1809 {
1810         drm_i915_private_t *dev_priv = dev->dev_private;
1811         u32 ier;
1812         int ret = 0;
1813
1814         BUG_ON(seqno == 0);
1815
1816         if (atomic_read(&dev_priv->mm.wedged))
1817                 return -EIO;
1818
1819         if (!i915_seqno_passed(ring->get_gem_seqno(dev, ring), seqno)) {
1820                 if (HAS_PCH_SPLIT(dev))
1821                         ier = I915_READ(DEIER) | I915_READ(GTIER);
1822                 else
1823                         ier = I915_READ(IER);
1824                 if (!ier) {
1825                         DRM_ERROR("something (likely vbetool) disabled "
1826                                   "interrupts, re-enabling\n");
1827                         i915_driver_irq_preinstall(dev);
1828                         i915_driver_irq_postinstall(dev);
1829                 }
1830
1831                 trace_i915_gem_request_wait_begin(dev, seqno);
1832
1833                 ring->waiting_gem_seqno = seqno;
1834                 ring->user_irq_get(dev, ring);
1835                 if (interruptible)
1836                         ret = wait_event_interruptible(ring->irq_queue,
1837                                 i915_seqno_passed(
1838                                         ring->get_gem_seqno(dev, ring), seqno)
1839                                 || atomic_read(&dev_priv->mm.wedged));
1840                 else
1841                         wait_event(ring->irq_queue,
1842                                 i915_seqno_passed(
1843                                         ring->get_gem_seqno(dev, ring), seqno)
1844                                 || atomic_read(&dev_priv->mm.wedged));
1845
1846                 ring->user_irq_put(dev, ring);
1847                 ring->waiting_gem_seqno = 0;
1848
1849                 trace_i915_gem_request_wait_end(dev, seqno);
1850         }
1851         if (atomic_read(&dev_priv->mm.wedged))
1852                 ret = -EIO;
1853
1854         if (ret && ret != -ERESTARTSYS)
1855                 DRM_ERROR("%s returns %d (awaiting %d at %d)\n",
1856                           __func__, ret, seqno, ring->get_gem_seqno(dev, ring));
1857
1858         /* Directly dispatch request retiring.  While we have the work queue
1859          * to handle this, the waiter on a request often wants an associated
1860          * buffer to have made it to the inactive list, and we would need
1861          * a separate wait queue to handle that.
1862          */
1863         if (ret == 0)
1864                 i915_gem_retire_requests(dev, ring);
1865
1866         return ret;
1867 }
1868
1869 /**
1870  * Waits for a sequence number to be signaled, and cleans up the
1871  * request and object lists appropriately for that event.
1872  */
1873 static int
1874 i915_wait_request(struct drm_device *dev, uint32_t seqno,
1875                 struct intel_ring_buffer *ring)
1876 {
1877         return i915_do_wait_request(dev, seqno, 1, ring);
1878 }
1879
1880 static void
1881 i915_gem_flush(struct drm_device *dev,
1882                uint32_t invalidate_domains,
1883                uint32_t flush_domains)
1884 {
1885         drm_i915_private_t *dev_priv = dev->dev_private;
1886         if (flush_domains & I915_GEM_DOMAIN_CPU)
1887                 drm_agp_chipset_flush(dev);
1888         dev_priv->render_ring.flush(dev, &dev_priv->render_ring,
1889                         invalidate_domains,
1890                         flush_domains);
1891
1892         if (HAS_BSD(dev))
1893                 dev_priv->bsd_ring.flush(dev, &dev_priv->bsd_ring,
1894                                 invalidate_domains,
1895                                 flush_domains);
1896 }
1897
1898 static void
1899 i915_gem_flush_ring(struct drm_device *dev,
1900                uint32_t invalidate_domains,
1901                uint32_t flush_domains,
1902                struct intel_ring_buffer *ring)
1903 {
1904         if (flush_domains & I915_GEM_DOMAIN_CPU)
1905                 drm_agp_chipset_flush(dev);
1906         ring->flush(dev, ring,
1907                         invalidate_domains,
1908                         flush_domains);
1909 }
1910
1911 /**
1912  * Ensures that all rendering to the object has completed and the object is
1913  * safe to unbind from the GTT or access from the CPU.
1914  */
1915 static int
1916 i915_gem_object_wait_rendering(struct drm_gem_object *obj)
1917 {
1918         struct drm_device *dev = obj->dev;
1919         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1920         int ret;
1921
1922         /* This function only exists to support waiting for existing rendering,
1923          * not for emitting required flushes.
1924          */
1925         BUG_ON((obj->write_domain & I915_GEM_GPU_DOMAINS) != 0);
1926
1927         /* If there is rendering queued on the buffer being evicted, wait for
1928          * it.
1929          */
1930         if (obj_priv->active) {
1931 #if WATCH_BUF
1932                 DRM_INFO("%s: object %p wait for seqno %08x\n",
1933                           __func__, obj, obj_priv->last_rendering_seqno);
1934 #endif
1935                 ret = i915_wait_request(dev,
1936                                 obj_priv->last_rendering_seqno, obj_priv->ring);
1937                 if (ret != 0)
1938                         return ret;
1939         }
1940
1941         return 0;
1942 }
1943
1944 /**
1945  * Unbinds an object from the GTT aperture.
1946  */
1947 int
1948 i915_gem_object_unbind(struct drm_gem_object *obj)
1949 {
1950         struct drm_device *dev = obj->dev;
1951         drm_i915_private_t *dev_priv = dev->dev_private;
1952         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
1953         int ret = 0;
1954
1955 #if WATCH_BUF
1956         DRM_INFO("%s:%d %p\n", __func__, __LINE__, obj);
1957         DRM_INFO("gtt_space %p\n", obj_priv->gtt_space);
1958 #endif
1959         if (obj_priv->gtt_space == NULL)
1960                 return 0;
1961
1962         if (obj_priv->pin_count != 0) {
1963                 DRM_ERROR("Attempting to unbind pinned buffer\n");
1964                 return -EINVAL;
1965         }
1966
1967         /* blow away mappings if mapped through GTT */
1968         i915_gem_release_mmap(obj);
1969
1970         /* Move the object to the CPU domain to ensure that
1971          * any possible CPU writes while it's not in the GTT
1972          * are flushed when we go to remap it. This will
1973          * also ensure that all pending GPU writes are finished
1974          * before we unbind.
1975          */
1976         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
1977         if (ret) {
1978                 if (ret != -ERESTARTSYS)
1979                         DRM_ERROR("set_domain failed: %d\n", ret);
1980                 return ret;
1981         }
1982
1983         BUG_ON(obj_priv->active);
1984
1985         /* release the fence reg _after_ flushing */
1986         if (obj_priv->fence_reg != I915_FENCE_REG_NONE)
1987                 i915_gem_clear_fence_reg(obj);
1988
1989         if (obj_priv->agp_mem != NULL) {
1990                 drm_unbind_agp(obj_priv->agp_mem);
1991                 drm_free_agp(obj_priv->agp_mem, obj->size / PAGE_SIZE);
1992                 obj_priv->agp_mem = NULL;
1993         }
1994
1995         i915_gem_object_put_pages(obj);
1996         BUG_ON(obj_priv->pages_refcount);
1997
1998         if (obj_priv->gtt_space) {
1999                 atomic_dec(&dev->gtt_count);
2000                 atomic_sub(obj->size, &dev->gtt_memory);
2001
2002                 drm_mm_put_block(obj_priv->gtt_space);
2003                 obj_priv->gtt_space = NULL;
2004         }
2005
2006         /* Remove ourselves from the LRU list if present. */
2007         spin_lock(&dev_priv->mm.active_list_lock);
2008         if (!list_empty(&obj_priv->list))
2009                 list_del_init(&obj_priv->list);
2010         spin_unlock(&dev_priv->mm.active_list_lock);
2011
2012         if (i915_gem_object_is_purgeable(obj_priv))
2013                 i915_gem_object_truncate(obj);
2014
2015         trace_i915_gem_object_unbind(obj);
2016
2017         return 0;
2018 }
2019
2020 static struct drm_gem_object *
2021 i915_gem_find_inactive_object(struct drm_device *dev, int min_size)
2022 {
2023         drm_i915_private_t *dev_priv = dev->dev_private;
2024         struct drm_i915_gem_object *obj_priv;
2025         struct drm_gem_object *best = NULL;
2026         struct drm_gem_object *first = NULL;
2027
2028         /* Try to find the smallest clean object */
2029         list_for_each_entry(obj_priv, &dev_priv->mm.inactive_list, list) {
2030                 struct drm_gem_object *obj = &obj_priv->base;
2031                 if (obj->size >= min_size) {
2032                         if ((!obj_priv->dirty ||
2033                              i915_gem_object_is_purgeable(obj_priv)) &&
2034                             (!best || obj->size < best->size)) {
2035                                 best = obj;
2036                                 if (best->size == min_size)
2037                                         return best;
2038                         }
2039                         if (!first)
2040                             first = obj;
2041                 }
2042         }
2043
2044         return best ? best : first;
2045 }
2046
2047 static int
2048 i915_gpu_idle(struct drm_device *dev)
2049 {
2050         drm_i915_private_t *dev_priv = dev->dev_private;
2051         bool lists_empty;
2052         uint32_t seqno1, seqno2;
2053         int ret;
2054
2055         spin_lock(&dev_priv->mm.active_list_lock);
2056         lists_empty = (list_empty(&dev_priv->mm.flushing_list) &&
2057                        list_empty(&dev_priv->render_ring.active_list) &&
2058                        (!HAS_BSD(dev) ||
2059                         list_empty(&dev_priv->bsd_ring.active_list)));
2060         spin_unlock(&dev_priv->mm.active_list_lock);
2061
2062         if (lists_empty)
2063                 return 0;
2064
2065         /* Flush everything onto the inactive list. */
2066         i915_gem_flush(dev, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
2067         seqno1 = i915_add_request(dev, NULL, I915_GEM_GPU_DOMAINS,
2068                         &dev_priv->render_ring);
2069         if (seqno1 == 0)
2070                 return -ENOMEM;
2071         ret = i915_wait_request(dev, seqno1, &dev_priv->render_ring);
2072
2073         if (HAS_BSD(dev)) {
2074                 seqno2 = i915_add_request(dev, NULL, I915_GEM_GPU_DOMAINS,
2075                                 &dev_priv->bsd_ring);
2076                 if (seqno2 == 0)
2077                         return -ENOMEM;
2078
2079                 ret = i915_wait_request(dev, seqno2, &dev_priv->bsd_ring);
2080                 if (ret)
2081                         return ret;
2082         }
2083
2084
2085         return ret;
2086 }
2087
2088 static int
2089 i915_gem_evict_everything(struct drm_device *dev)
2090 {
2091         drm_i915_private_t *dev_priv = dev->dev_private;
2092         int ret;
2093         bool lists_empty;
2094
2095         spin_lock(&dev_priv->mm.active_list_lock);
2096         lists_empty = (list_empty(&dev_priv->mm.inactive_list) &&
2097                        list_empty(&dev_priv->mm.flushing_list) &&
2098                        list_empty(&dev_priv->render_ring.active_list) &&
2099                        (!HAS_BSD(dev)
2100                         || list_empty(&dev_priv->bsd_ring.active_list)));
2101         spin_unlock(&dev_priv->mm.active_list_lock);
2102
2103         if (lists_empty)
2104                 return -ENOSPC;
2105
2106         /* Flush everything (on to the inactive lists) and evict */
2107         ret = i915_gpu_idle(dev);
2108         if (ret)
2109                 return ret;
2110
2111         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
2112
2113         ret = i915_gem_evict_from_inactive_list(dev);
2114         if (ret)
2115                 return ret;
2116
2117         spin_lock(&dev_priv->mm.active_list_lock);
2118         lists_empty = (list_empty(&dev_priv->mm.inactive_list) &&
2119                        list_empty(&dev_priv->mm.flushing_list) &&
2120                        list_empty(&dev_priv->render_ring.active_list) &&
2121                        (!HAS_BSD(dev)
2122                         || list_empty(&dev_priv->bsd_ring.active_list)));
2123         spin_unlock(&dev_priv->mm.active_list_lock);
2124         BUG_ON(!lists_empty);
2125
2126         return 0;
2127 }
2128
2129 static int
2130 i915_gem_evict_something(struct drm_device *dev, int min_size)
2131 {
2132         drm_i915_private_t *dev_priv = dev->dev_private;
2133         struct drm_gem_object *obj;
2134         int ret;
2135
2136         struct intel_ring_buffer *render_ring = &dev_priv->render_ring;
2137         struct intel_ring_buffer *bsd_ring = &dev_priv->bsd_ring;
2138         for (;;) {
2139                 i915_gem_retire_requests(dev, render_ring);
2140
2141                 if (HAS_BSD(dev))
2142                         i915_gem_retire_requests(dev, bsd_ring);
2143
2144                 /* If there's an inactive buffer available now, grab it
2145                  * and be done.
2146                  */
2147                 obj = i915_gem_find_inactive_object(dev, min_size);
2148                 if (obj) {
2149                         struct drm_i915_gem_object *obj_priv;
2150
2151 #if WATCH_LRU
2152                         DRM_INFO("%s: evicting %p\n", __func__, obj);
2153 #endif
2154                         obj_priv = to_intel_bo(obj);
2155                         BUG_ON(obj_priv->pin_count != 0);
2156                         BUG_ON(obj_priv->active);
2157
2158                         /* Wait on the rendering and unbind the buffer. */
2159                         return i915_gem_object_unbind(obj);
2160                 }
2161
2162                 /* If we didn't get anything, but the ring is still processing
2163                  * things, wait for the next to finish and hopefully leave us
2164                  * a buffer to evict.
2165                  */
2166                 if (!list_empty(&render_ring->request_list)) {
2167                         struct drm_i915_gem_request *request;
2168
2169                         request = list_first_entry(&render_ring->request_list,
2170                                                    struct drm_i915_gem_request,
2171                                                    list);
2172
2173                         ret = i915_wait_request(dev,
2174                                         request->seqno, request->ring);
2175                         if (ret)
2176                                 return ret;
2177
2178                         continue;
2179                 }
2180
2181                 if (HAS_BSD(dev) && !list_empty(&bsd_ring->request_list)) {
2182                         struct drm_i915_gem_request *request;
2183
2184                         request = list_first_entry(&bsd_ring->request_list,
2185                                                    struct drm_i915_gem_request,
2186                                                    list);
2187
2188                         ret = i915_wait_request(dev,
2189                                         request->seqno, request->ring);
2190                         if (ret)
2191                                 return ret;
2192
2193                         continue;
2194                 }
2195
2196                 /* If we didn't have anything on the request list but there
2197                  * are buffers awaiting a flush, emit one and try again.
2198                  * When we wait on it, those buffers waiting for that flush
2199                  * will get moved to inactive.
2200                  */
2201                 if (!list_empty(&dev_priv->mm.flushing_list)) {
2202                         struct drm_i915_gem_object *obj_priv;
2203
2204                         /* Find an object that we can immediately reuse */
2205                         list_for_each_entry(obj_priv, &dev_priv->mm.flushing_list, list) {
2206                                 obj = &obj_priv->base;
2207                                 if (obj->size >= min_size)
2208                                         break;
2209
2210                                 obj = NULL;
2211                         }
2212
2213                         if (obj != NULL) {
2214                                 uint32_t seqno;
2215
2216                                 i915_gem_flush_ring(dev,
2217                                                obj->write_domain,
2218                                                obj->write_domain,
2219                                                obj_priv->ring);
2220                                 seqno = i915_add_request(dev, NULL,
2221                                                 obj->write_domain,
2222                                                 obj_priv->ring);
2223                                 if (seqno == 0)
2224                                         return -ENOMEM;
2225                                 continue;
2226                         }
2227                 }
2228
2229                 /* If we didn't do any of the above, there's no single buffer
2230                  * large enough to swap out for the new one, so just evict
2231                  * everything and start again. (This should be rare.)
2232                  */
2233                 if (!list_empty (&dev_priv->mm.inactive_list))
2234                         return i915_gem_evict_from_inactive_list(dev);
2235                 else
2236                         return i915_gem_evict_everything(dev);
2237         }
2238 }
2239
2240 int
2241 i915_gem_object_get_pages(struct drm_gem_object *obj,
2242                           gfp_t gfpmask)
2243 {
2244         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2245         int page_count, i;
2246         struct address_space *mapping;
2247         struct inode *inode;
2248         struct page *page;
2249
2250         BUG_ON(obj_priv->pages_refcount
2251                         == DRM_I915_GEM_OBJECT_MAX_PAGES_REFCOUNT);
2252
2253         if (obj_priv->pages_refcount++ != 0)
2254                 return 0;
2255
2256         /* Get the list of pages out of our struct file.  They'll be pinned
2257          * at this point until we release them.
2258          */
2259         page_count = obj->size / PAGE_SIZE;
2260         BUG_ON(obj_priv->pages != NULL);
2261         obj_priv->pages = drm_calloc_large(page_count, sizeof(struct page *));
2262         if (obj_priv->pages == NULL) {
2263                 obj_priv->pages_refcount--;
2264                 return -ENOMEM;
2265         }
2266
2267         inode = obj->filp->f_path.dentry->d_inode;
2268         mapping = inode->i_mapping;
2269         for (i = 0; i < page_count; i++) {
2270                 page = read_cache_page_gfp(mapping, i,
2271                                            mapping_gfp_mask (mapping) |
2272                                            __GFP_COLD |
2273                                            gfpmask);
2274                 if (IS_ERR(page))
2275                         goto err_pages;
2276
2277                 obj_priv->pages[i] = page;
2278         }
2279
2280         if (obj_priv->tiling_mode != I915_TILING_NONE)
2281                 i915_gem_object_do_bit_17_swizzle(obj);
2282
2283         return 0;
2284
2285 err_pages:
2286         while (i--)
2287                 page_cache_release(obj_priv->pages[i]);
2288
2289         drm_free_large(obj_priv->pages);
2290         obj_priv->pages = NULL;
2291         obj_priv->pages_refcount--;
2292         return PTR_ERR(page);
2293 }
2294
2295 static void sandybridge_write_fence_reg(struct drm_i915_fence_reg *reg)
2296 {
2297         struct drm_gem_object *obj = reg->obj;
2298         struct drm_device *dev = obj->dev;
2299         drm_i915_private_t *dev_priv = dev->dev_private;
2300         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2301         int regnum = obj_priv->fence_reg;
2302         uint64_t val;
2303
2304         val = (uint64_t)((obj_priv->gtt_offset + obj->size - 4096) &
2305                     0xfffff000) << 32;
2306         val |= obj_priv->gtt_offset & 0xfffff000;
2307         val |= (uint64_t)((obj_priv->stride / 128) - 1) <<
2308                 SANDYBRIDGE_FENCE_PITCH_SHIFT;
2309
2310         if (obj_priv->tiling_mode == I915_TILING_Y)
2311                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2312         val |= I965_FENCE_REG_VALID;
2313
2314         I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + (regnum * 8), val);
2315 }
2316
2317 static void i965_write_fence_reg(struct drm_i915_fence_reg *reg)
2318 {
2319         struct drm_gem_object *obj = reg->obj;
2320         struct drm_device *dev = obj->dev;
2321         drm_i915_private_t *dev_priv = dev->dev_private;
2322         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2323         int regnum = obj_priv->fence_reg;
2324         uint64_t val;
2325
2326         val = (uint64_t)((obj_priv->gtt_offset + obj->size - 4096) &
2327                     0xfffff000) << 32;
2328         val |= obj_priv->gtt_offset & 0xfffff000;
2329         val |= ((obj_priv->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
2330         if (obj_priv->tiling_mode == I915_TILING_Y)
2331                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2332         val |= I965_FENCE_REG_VALID;
2333
2334         I915_WRITE64(FENCE_REG_965_0 + (regnum * 8), val);
2335 }
2336
2337 static void i915_write_fence_reg(struct drm_i915_fence_reg *reg)
2338 {
2339         struct drm_gem_object *obj = reg->obj;
2340         struct drm_device *dev = obj->dev;
2341         drm_i915_private_t *dev_priv = dev->dev_private;
2342         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2343         int regnum = obj_priv->fence_reg;
2344         int tile_width;
2345         uint32_t fence_reg, val;
2346         uint32_t pitch_val;
2347
2348         if ((obj_priv->gtt_offset & ~I915_FENCE_START_MASK) ||
2349             (obj_priv->gtt_offset & (obj->size - 1))) {
2350                 WARN(1, "%s: object 0x%08x not 1M or size (0x%zx) aligned\n",
2351                      __func__, obj_priv->gtt_offset, obj->size);
2352                 return;
2353         }
2354
2355         if (obj_priv->tiling_mode == I915_TILING_Y &&
2356             HAS_128_BYTE_Y_TILING(dev))
2357                 tile_width = 128;
2358         else
2359                 tile_width = 512;
2360
2361         /* Note: pitch better be a power of two tile widths */
2362         pitch_val = obj_priv->stride / tile_width;
2363         pitch_val = ffs(pitch_val) - 1;
2364
2365         if (obj_priv->tiling_mode == I915_TILING_Y &&
2366             HAS_128_BYTE_Y_TILING(dev))
2367                 WARN_ON(pitch_val > I830_FENCE_MAX_PITCH_VAL);
2368         else
2369                 WARN_ON(pitch_val > I915_FENCE_MAX_PITCH_VAL);
2370
2371         val = obj_priv->gtt_offset;
2372         if (obj_priv->tiling_mode == I915_TILING_Y)
2373                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2374         val |= I915_FENCE_SIZE_BITS(obj->size);
2375         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2376         val |= I830_FENCE_REG_VALID;
2377
2378         if (regnum < 8)
2379                 fence_reg = FENCE_REG_830_0 + (regnum * 4);
2380         else
2381                 fence_reg = FENCE_REG_945_8 + ((regnum - 8) * 4);
2382         I915_WRITE(fence_reg, val);
2383 }
2384
2385 static void i830_write_fence_reg(struct drm_i915_fence_reg *reg)
2386 {
2387         struct drm_gem_object *obj = reg->obj;
2388         struct drm_device *dev = obj->dev;
2389         drm_i915_private_t *dev_priv = dev->dev_private;
2390         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2391         int regnum = obj_priv->fence_reg;
2392         uint32_t val;
2393         uint32_t pitch_val;
2394         uint32_t fence_size_bits;
2395
2396         if ((obj_priv->gtt_offset & ~I830_FENCE_START_MASK) ||
2397             (obj_priv->gtt_offset & (obj->size - 1))) {
2398                 WARN(1, "%s: object 0x%08x not 512K or size aligned\n",
2399                      __func__, obj_priv->gtt_offset);
2400                 return;
2401         }
2402
2403         pitch_val = obj_priv->stride / 128;
2404         pitch_val = ffs(pitch_val) - 1;
2405         WARN_ON(pitch_val > I830_FENCE_MAX_PITCH_VAL);
2406
2407         val = obj_priv->gtt_offset;
2408         if (obj_priv->tiling_mode == I915_TILING_Y)
2409                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2410         fence_size_bits = I830_FENCE_SIZE_BITS(obj->size);
2411         WARN_ON(fence_size_bits & ~0x00000f00);
2412         val |= fence_size_bits;
2413         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2414         val |= I830_FENCE_REG_VALID;
2415
2416         I915_WRITE(FENCE_REG_830_0 + (regnum * 4), val);
2417 }
2418
2419 static int i915_find_fence_reg(struct drm_device *dev)
2420 {
2421         struct drm_i915_fence_reg *reg = NULL;
2422         struct drm_i915_gem_object *obj_priv = NULL;
2423         struct drm_i915_private *dev_priv = dev->dev_private;
2424         struct drm_gem_object *obj = NULL;
2425         int i, avail, ret;
2426
2427         /* First try to find a free reg */
2428         avail = 0;
2429         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
2430                 reg = &dev_priv->fence_regs[i];
2431                 if (!reg->obj)
2432                         return i;
2433
2434                 obj_priv = to_intel_bo(reg->obj);
2435                 if (!obj_priv->pin_count)
2436                     avail++;
2437         }
2438
2439         if (avail == 0)
2440                 return -ENOSPC;
2441
2442         /* None available, try to steal one or wait for a user to finish */
2443         i = I915_FENCE_REG_NONE;
2444         list_for_each_entry(reg, &dev_priv->mm.fence_list,
2445                             lru_list) {
2446                 obj = reg->obj;
2447                 obj_priv = to_intel_bo(obj);
2448
2449                 if (obj_priv->pin_count)
2450                         continue;
2451
2452                 /* found one! */
2453                 i = obj_priv->fence_reg;
2454                 break;
2455         }
2456
2457         BUG_ON(i == I915_FENCE_REG_NONE);
2458
2459         /* We only have a reference on obj from the active list. put_fence_reg
2460          * might drop that one, causing a use-after-free in it. So hold a
2461          * private reference to obj like the other callers of put_fence_reg
2462          * (set_tiling ioctl) do. */
2463         drm_gem_object_reference(obj);
2464         ret = i915_gem_object_put_fence_reg(obj);
2465         drm_gem_object_unreference(obj);
2466         if (ret != 0)
2467                 return ret;
2468
2469         return i;
2470 }
2471
2472 /**
2473  * i915_gem_object_get_fence_reg - set up a fence reg for an object
2474  * @obj: object to map through a fence reg
2475  *
2476  * When mapping objects through the GTT, userspace wants to be able to write
2477  * to them without having to worry about swizzling if the object is tiled.
2478  *
2479  * This function walks the fence regs looking for a free one for @obj,
2480  * stealing one if it can't find any.
2481  *
2482  * It then sets up the reg based on the object's properties: address, pitch
2483  * and tiling format.
2484  */
2485 int
2486 i915_gem_object_get_fence_reg(struct drm_gem_object *obj)
2487 {
2488         struct drm_device *dev = obj->dev;
2489         struct drm_i915_private *dev_priv = dev->dev_private;
2490         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2491         struct drm_i915_fence_reg *reg = NULL;
2492         int ret;
2493
2494         /* Just update our place in the LRU if our fence is getting used. */
2495         if (obj_priv->fence_reg != I915_FENCE_REG_NONE) {
2496                 reg = &dev_priv->fence_regs[obj_priv->fence_reg];
2497                 list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2498                 return 0;
2499         }
2500
2501         switch (obj_priv->tiling_mode) {
2502         case I915_TILING_NONE:
2503                 WARN(1, "allocating a fence for non-tiled object?\n");
2504                 break;
2505         case I915_TILING_X:
2506                 if (!obj_priv->stride)
2507                         return -EINVAL;
2508                 WARN((obj_priv->stride & (512 - 1)),
2509                      "object 0x%08x is X tiled but has non-512B pitch\n",
2510                      obj_priv->gtt_offset);
2511                 break;
2512         case I915_TILING_Y:
2513                 if (!obj_priv->stride)
2514                         return -EINVAL;
2515                 WARN((obj_priv->stride & (128 - 1)),
2516                      "object 0x%08x is Y tiled but has non-128B pitch\n",
2517                      obj_priv->gtt_offset);
2518                 break;
2519         }
2520
2521         ret = i915_find_fence_reg(dev);
2522         if (ret < 0)
2523                 return ret;
2524
2525         obj_priv->fence_reg = ret;
2526         reg = &dev_priv->fence_regs[obj_priv->fence_reg];
2527         list_add_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2528
2529         reg->obj = obj;
2530
2531         if (IS_GEN6(dev))
2532                 sandybridge_write_fence_reg(reg);
2533         else if (IS_I965G(dev))
2534                 i965_write_fence_reg(reg);
2535         else if (IS_I9XX(dev))
2536                 i915_write_fence_reg(reg);
2537         else
2538                 i830_write_fence_reg(reg);
2539
2540         trace_i915_gem_object_get_fence(obj, obj_priv->fence_reg,
2541                         obj_priv->tiling_mode);
2542
2543         return 0;
2544 }
2545
2546 /**
2547  * i915_gem_clear_fence_reg - clear out fence register info
2548  * @obj: object to clear
2549  *
2550  * Zeroes out the fence register itself and clears out the associated
2551  * data structures in dev_priv and obj_priv.
2552  */
2553 static void
2554 i915_gem_clear_fence_reg(struct drm_gem_object *obj)
2555 {
2556         struct drm_device *dev = obj->dev;
2557         drm_i915_private_t *dev_priv = dev->dev_private;
2558         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2559         struct drm_i915_fence_reg *reg =
2560                 &dev_priv->fence_regs[obj_priv->fence_reg];
2561
2562         if (IS_GEN6(dev)) {
2563                 I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 +
2564                              (obj_priv->fence_reg * 8), 0);
2565         } else if (IS_I965G(dev)) {
2566                 I915_WRITE64(FENCE_REG_965_0 + (obj_priv->fence_reg * 8), 0);
2567         } else {
2568                 uint32_t fence_reg;
2569
2570                 if (obj_priv->fence_reg < 8)
2571                         fence_reg = FENCE_REG_830_0 + obj_priv->fence_reg * 4;
2572                 else
2573                         fence_reg = FENCE_REG_945_8 + (obj_priv->fence_reg -
2574                                                        8) * 4;
2575
2576                 I915_WRITE(fence_reg, 0);
2577         }
2578
2579         reg->obj = NULL;
2580         obj_priv->fence_reg = I915_FENCE_REG_NONE;
2581         list_del_init(&reg->lru_list);
2582 }
2583
2584 /**
2585  * i915_gem_object_put_fence_reg - waits on outstanding fenced access
2586  * to the buffer to finish, and then resets the fence register.
2587  * @obj: tiled object holding a fence register.
2588  *
2589  * Zeroes out the fence register itself and clears out the associated
2590  * data structures in dev_priv and obj_priv.
2591  */
2592 int
2593 i915_gem_object_put_fence_reg(struct drm_gem_object *obj)
2594 {
2595         struct drm_device *dev = obj->dev;
2596         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2597
2598         if (obj_priv->fence_reg == I915_FENCE_REG_NONE)
2599                 return 0;
2600
2601         /* If we've changed tiling, GTT-mappings of the object
2602          * need to re-fault to ensure that the correct fence register
2603          * setup is in place.
2604          */
2605         i915_gem_release_mmap(obj);
2606
2607         /* On the i915, GPU access to tiled buffers is via a fence,
2608          * therefore we must wait for any outstanding access to complete
2609          * before clearing the fence.
2610          */
2611         if (!IS_I965G(dev)) {
2612                 int ret;
2613
2614                 i915_gem_object_flush_gpu_write_domain(obj);
2615                 ret = i915_gem_object_wait_rendering(obj);
2616                 if (ret != 0)
2617                         return ret;
2618         }
2619
2620         i915_gem_object_flush_gtt_write_domain(obj);
2621         i915_gem_clear_fence_reg (obj);
2622
2623         return 0;
2624 }
2625
2626 /**
2627  * Finds free space in the GTT aperture and binds the object there.
2628  */
2629 static int
2630 i915_gem_object_bind_to_gtt(struct drm_gem_object *obj, unsigned alignment)
2631 {
2632         struct drm_device *dev = obj->dev;
2633         drm_i915_private_t *dev_priv = dev->dev_private;
2634         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2635         struct drm_mm_node *free_space;
2636         gfp_t gfpmask =  __GFP_NORETRY | __GFP_NOWARN;
2637         int ret;
2638
2639         if (obj_priv->madv != I915_MADV_WILLNEED) {
2640                 DRM_ERROR("Attempting to bind a purgeable object\n");
2641                 return -EINVAL;
2642         }
2643
2644         if (alignment == 0)
2645                 alignment = i915_gem_get_gtt_alignment(obj);
2646         if (alignment & (i915_gem_get_gtt_alignment(obj) - 1)) {
2647                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
2648                 return -EINVAL;
2649         }
2650
2651  search_free:
2652         free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
2653                                         obj->size, alignment, 0);
2654         if (free_space != NULL) {
2655                 obj_priv->gtt_space = drm_mm_get_block(free_space, obj->size,
2656                                                        alignment);
2657                 if (obj_priv->gtt_space != NULL) {
2658                         obj_priv->gtt_space->private = obj;
2659                         obj_priv->gtt_offset = obj_priv->gtt_space->start;
2660                 }
2661         }
2662         if (obj_priv->gtt_space == NULL) {
2663                 /* If the gtt is empty and we're still having trouble
2664                  * fitting our object in, we're out of memory.
2665                  */
2666 #if WATCH_LRU
2667                 DRM_INFO("%s: GTT full, evicting something\n", __func__);
2668 #endif
2669                 ret = i915_gem_evict_something(dev, obj->size);
2670                 if (ret)
2671                         return ret;
2672
2673                 goto search_free;
2674         }
2675
2676 #if WATCH_BUF
2677         DRM_INFO("Binding object of size %zd at 0x%08x\n",
2678                  obj->size, obj_priv->gtt_offset);
2679 #endif
2680         ret = i915_gem_object_get_pages(obj, gfpmask);
2681         if (ret) {
2682                 drm_mm_put_block(obj_priv->gtt_space);
2683                 obj_priv->gtt_space = NULL;
2684
2685                 if (ret == -ENOMEM) {
2686                         /* first try to clear up some space from the GTT */
2687                         ret = i915_gem_evict_something(dev, obj->size);
2688                         if (ret) {
2689                                 /* now try to shrink everyone else */
2690                                 if (gfpmask) {
2691                                         gfpmask = 0;
2692                                         goto search_free;
2693                                 }
2694
2695                                 return ret;
2696                         }
2697
2698                         goto search_free;
2699                 }
2700
2701                 return ret;
2702         }
2703
2704         /* Create an AGP memory structure pointing at our pages, and bind it
2705          * into the GTT.
2706          */
2707         obj_priv->agp_mem = drm_agp_bind_pages(dev,
2708                                                obj_priv->pages,
2709                                                obj->size >> PAGE_SHIFT,
2710                                                obj_priv->gtt_offset,
2711                                                obj_priv->agp_type);
2712         if (obj_priv->agp_mem == NULL) {
2713                 i915_gem_object_put_pages(obj);
2714                 drm_mm_put_block(obj_priv->gtt_space);
2715                 obj_priv->gtt_space = NULL;
2716
2717                 ret = i915_gem_evict_something(dev, obj->size);
2718                 if (ret)
2719                         return ret;
2720
2721                 goto search_free;
2722         }
2723         atomic_inc(&dev->gtt_count);
2724         atomic_add(obj->size, &dev->gtt_memory);
2725
2726         /* Assert that the object is not currently in any GPU domain. As it
2727          * wasn't in the GTT, there shouldn't be any way it could have been in
2728          * a GPU cache
2729          */
2730         BUG_ON(obj->read_domains & I915_GEM_GPU_DOMAINS);
2731         BUG_ON(obj->write_domain & I915_GEM_GPU_DOMAINS);
2732
2733         trace_i915_gem_object_bind(obj, obj_priv->gtt_offset);
2734
2735         return 0;
2736 }
2737
2738 void
2739 i915_gem_clflush_object(struct drm_gem_object *obj)
2740 {
2741         struct drm_i915_gem_object      *obj_priv = to_intel_bo(obj);
2742
2743         /* If we don't have a page list set up, then we're not pinned
2744          * to GPU, and we can ignore the cache flush because it'll happen
2745          * again at bind time.
2746          */
2747         if (obj_priv->pages == NULL)
2748                 return;
2749
2750         trace_i915_gem_object_clflush(obj);
2751
2752         drm_clflush_pages(obj_priv->pages, obj->size / PAGE_SIZE);
2753 }
2754
2755 /** Flushes any GPU write domain for the object if it's dirty. */
2756 static void
2757 i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj)
2758 {
2759         struct drm_device *dev = obj->dev;
2760         uint32_t old_write_domain;
2761         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2762
2763         if ((obj->write_domain & I915_GEM_GPU_DOMAINS) == 0)
2764                 return;
2765
2766         /* Queue the GPU write cache flushing we need. */
2767         old_write_domain = obj->write_domain;
2768         i915_gem_flush(dev, 0, obj->write_domain);
2769         (void) i915_add_request(dev, NULL, obj->write_domain, obj_priv->ring);
2770         BUG_ON(obj->write_domain);
2771
2772         trace_i915_gem_object_change_domain(obj,
2773                                             obj->read_domains,
2774                                             old_write_domain);
2775 }
2776
2777 /** Flushes the GTT write domain for the object if it's dirty. */
2778 static void
2779 i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj)
2780 {
2781         uint32_t old_write_domain;
2782
2783         if (obj->write_domain != I915_GEM_DOMAIN_GTT)
2784                 return;
2785
2786         /* No actual flushing is required for the GTT write domain.   Writes
2787          * to it immediately go to main memory as far as we know, so there's
2788          * no chipset flush.  It also doesn't land in render cache.
2789          */
2790         old_write_domain = obj->write_domain;
2791         obj->write_domain = 0;
2792
2793         trace_i915_gem_object_change_domain(obj,
2794                                             obj->read_domains,
2795                                             old_write_domain);
2796 }
2797
2798 /** Flushes the CPU write domain for the object if it's dirty. */
2799 static void
2800 i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj)
2801 {
2802         struct drm_device *dev = obj->dev;
2803         uint32_t old_write_domain;
2804
2805         if (obj->write_domain != I915_GEM_DOMAIN_CPU)
2806                 return;
2807
2808         i915_gem_clflush_object(obj);
2809         drm_agp_chipset_flush(dev);
2810         old_write_domain = obj->write_domain;
2811         obj->write_domain = 0;
2812
2813         trace_i915_gem_object_change_domain(obj,
2814                                             obj->read_domains,
2815                                             old_write_domain);
2816 }
2817
2818 void
2819 i915_gem_object_flush_write_domain(struct drm_gem_object *obj)
2820 {
2821         switch (obj->write_domain) {
2822         case I915_GEM_DOMAIN_GTT:
2823                 i915_gem_object_flush_gtt_write_domain(obj);
2824                 break;
2825         case I915_GEM_DOMAIN_CPU:
2826                 i915_gem_object_flush_cpu_write_domain(obj);
2827                 break;
2828         default:
2829                 i915_gem_object_flush_gpu_write_domain(obj);
2830                 break;
2831         }
2832 }
2833
2834 /**
2835  * Moves a single object to the GTT read, and possibly write domain.
2836  *
2837  * This function returns when the move is complete, including waiting on
2838  * flushes to occur.
2839  */
2840 int
2841 i915_gem_object_set_to_gtt_domain(struct drm_gem_object *obj, int write)
2842 {
2843         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2844         uint32_t old_write_domain, old_read_domains;
2845         int ret;
2846
2847         /* Not valid to be called on unbound objects. */
2848         if (obj_priv->gtt_space == NULL)
2849                 return -EINVAL;
2850
2851         i915_gem_object_flush_gpu_write_domain(obj);
2852         /* Wait on any GPU rendering and flushing to occur. */
2853         ret = i915_gem_object_wait_rendering(obj);
2854         if (ret != 0)
2855                 return ret;
2856
2857         old_write_domain = obj->write_domain;
2858         old_read_domains = obj->read_domains;
2859
2860         /* If we're writing through the GTT domain, then CPU and GPU caches
2861          * will need to be invalidated at next use.
2862          */
2863         if (write)
2864                 obj->read_domains &= I915_GEM_DOMAIN_GTT;
2865
2866         i915_gem_object_flush_cpu_write_domain(obj);
2867
2868         /* It should now be out of any other write domains, and we can update
2869          * the domain values for our changes.
2870          */
2871         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
2872         obj->read_domains |= I915_GEM_DOMAIN_GTT;
2873         if (write) {
2874                 obj->write_domain = I915_GEM_DOMAIN_GTT;
2875                 obj_priv->dirty = 1;
2876         }
2877
2878         trace_i915_gem_object_change_domain(obj,
2879                                             old_read_domains,
2880                                             old_write_domain);
2881
2882         return 0;
2883 }
2884
2885 /*
2886  * Prepare buffer for display plane. Use uninterruptible for possible flush
2887  * wait, as in modesetting process we're not supposed to be interrupted.
2888  */
2889 int
2890 i915_gem_object_set_to_display_plane(struct drm_gem_object *obj)
2891 {
2892         struct drm_device *dev = obj->dev;
2893         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
2894         uint32_t old_write_domain, old_read_domains;
2895         int ret;
2896
2897         /* Not valid to be called on unbound objects. */
2898         if (obj_priv->gtt_space == NULL)
2899                 return -EINVAL;
2900
2901         i915_gem_object_flush_gpu_write_domain(obj);
2902
2903         /* Wait on any GPU rendering and flushing to occur. */
2904         if (obj_priv->active) {
2905 #if WATCH_BUF
2906                 DRM_INFO("%s: object %p wait for seqno %08x\n",
2907                           __func__, obj, obj_priv->last_rendering_seqno);
2908 #endif
2909                 ret = i915_do_wait_request(dev,
2910                                 obj_priv->last_rendering_seqno,
2911                                 0,
2912                                 obj_priv->ring);
2913                 if (ret != 0)
2914                         return ret;
2915         }
2916
2917         i915_gem_object_flush_cpu_write_domain(obj);
2918
2919         old_write_domain = obj->write_domain;
2920         old_read_domains = obj->read_domains;
2921
2922         /* It should now be out of any other write domains, and we can update
2923          * the domain values for our changes.
2924          */
2925         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
2926         obj->read_domains = I915_GEM_DOMAIN_GTT;
2927         obj->write_domain = I915_GEM_DOMAIN_GTT;
2928         obj_priv->dirty = 1;
2929
2930         trace_i915_gem_object_change_domain(obj,
2931                                             old_read_domains,
2932                                             old_write_domain);
2933
2934         return 0;
2935 }
2936
2937 /**
2938  * Moves a single object to the CPU read, and possibly write domain.
2939  *
2940  * This function returns when the move is complete, including waiting on
2941  * flushes to occur.
2942  */
2943 static int
2944 i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj, int write)
2945 {
2946         uint32_t old_write_domain, old_read_domains;
2947         int ret;
2948
2949         i915_gem_object_flush_gpu_write_domain(obj);
2950         /* Wait on any GPU rendering and flushing to occur. */
2951         ret = i915_gem_object_wait_rendering(obj);
2952         if (ret != 0)
2953                 return ret;
2954
2955         i915_gem_object_flush_gtt_write_domain(obj);
2956
2957         /* If we have a partially-valid cache of the object in the CPU,
2958          * finish invalidating it and free the per-page flags.
2959          */
2960         i915_gem_object_set_to_full_cpu_read_domain(obj);
2961
2962         old_write_domain = obj->write_domain;
2963         old_read_domains = obj->read_domains;
2964
2965         /* Flush the CPU cache if it's still invalid. */
2966         if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
2967                 i915_gem_clflush_object(obj);
2968
2969                 obj->read_domains |= I915_GEM_DOMAIN_CPU;
2970         }
2971
2972         /* It should now be out of any other write domains, and we can update
2973          * the domain values for our changes.
2974          */
2975         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
2976
2977         /* If we're writing through the CPU, then the GPU read domains will
2978          * need to be invalidated at next use.
2979          */
2980         if (write) {
2981                 obj->read_domains &= I915_GEM_DOMAIN_CPU;
2982                 obj->write_domain = I915_GEM_DOMAIN_CPU;
2983         }
2984
2985         trace_i915_gem_object_change_domain(obj,
2986                                             old_read_domains,
2987                                             old_write_domain);
2988
2989         return 0;
2990 }
2991
2992 /*
2993  * Set the next domain for the specified object. This
2994  * may not actually perform the necessary flushing/invaliding though,
2995  * as that may want to be batched with other set_domain operations
2996  *
2997  * This is (we hope) the only really tricky part of gem. The goal
2998  * is fairly simple -- track which caches hold bits of the object
2999  * and make sure they remain coherent. A few concrete examples may
3000  * help to explain how it works. For shorthand, we use the notation
3001  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
3002  * a pair of read and write domain masks.
3003  *
3004  * Case 1: the batch buffer
3005  *
3006  *      1. Allocated
3007  *      2. Written by CPU
3008  *      3. Mapped to GTT
3009  *      4. Read by GPU
3010  *      5. Unmapped from GTT
3011  *      6. Freed
3012  *
3013  *      Let's take these a step at a time
3014  *
3015  *      1. Allocated
3016  *              Pages allocated from the kernel may still have
3017  *              cache contents, so we set them to (CPU, CPU) always.
3018  *      2. Written by CPU (using pwrite)
3019  *              The pwrite function calls set_domain (CPU, CPU) and
3020  *              this function does nothing (as nothing changes)
3021  *      3. Mapped by GTT
3022  *              This function asserts that the object is not
3023  *              currently in any GPU-based read or write domains
3024  *      4. Read by GPU
3025  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
3026  *              As write_domain is zero, this function adds in the
3027  *              current read domains (CPU+COMMAND, 0).
3028  *              flush_domains is set to CPU.
3029  *              invalidate_domains is set to COMMAND
3030  *              clflush is run to get data out of the CPU caches
3031  *              then i915_dev_set_domain calls i915_gem_flush to
3032  *              emit an MI_FLUSH and drm_agp_chipset_flush
3033  *      5. Unmapped from GTT
3034  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
3035  *              flush_domains and invalidate_domains end up both zero
3036  *              so no flushing/invalidating happens
3037  *      6. Freed
3038  *              yay, done
3039  *
3040  * Case 2: The shared render buffer
3041  *
3042  *      1. Allocated
3043  *      2. Mapped to GTT
3044  *      3. Read/written by GPU
3045  *      4. set_domain to (CPU,CPU)
3046  *      5. Read/written by CPU
3047  *      6. Read/written by GPU
3048  *
3049  *      1. Allocated
3050  *              Same as last example, (CPU, CPU)
3051  *      2. Mapped to GTT
3052  *              Nothing changes (assertions find that it is not in the GPU)
3053  *      3. Read/written by GPU
3054  *              execbuffer calls set_domain (RENDER, RENDER)
3055  *              flush_domains gets CPU
3056  *              invalidate_domains gets GPU
3057  *              clflush (obj)
3058  *              MI_FLUSH and drm_agp_chipset_flush
3059  *      4. set_domain (CPU, CPU)
3060  *              flush_domains gets GPU
3061  *              invalidate_domains gets CPU
3062  *              wait_rendering (obj) to make sure all drawing is complete.
3063  *              This will include an MI_FLUSH to get the data from GPU
3064  *              to memory
3065  *              clflush (obj) to invalidate the CPU cache
3066  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
3067  *      5. Read/written by CPU
3068  *              cache lines are loaded and dirtied
3069  *      6. Read written by GPU
3070  *              Same as last GPU access
3071  *
3072  * Case 3: The constant buffer
3073  *
3074  *      1. Allocated
3075  *      2. Written by CPU
3076  *      3. Read by GPU
3077  *      4. Updated (written) by CPU again
3078  *      5. Read by GPU
3079  *
3080  *      1. Allocated
3081  *              (CPU, CPU)
3082  *      2. Written by CPU
3083  *              (CPU, CPU)
3084  *      3. Read by GPU
3085  *              (CPU+RENDER, 0)
3086  *              flush_domains = CPU
3087  *              invalidate_domains = RENDER
3088  *              clflush (obj)
3089  *              MI_FLUSH
3090  *              drm_agp_chipset_flush
3091  *      4. Updated (written) by CPU again
3092  *              (CPU, CPU)
3093  *              flush_domains = 0 (no previous write domain)
3094  *              invalidate_domains = 0 (no new read domains)
3095  *      5. Read by GPU
3096  *              (CPU+RENDER, 0)
3097  *              flush_domains = CPU
3098  *              invalidate_domains = RENDER
3099  *              clflush (obj)
3100  *              MI_FLUSH
3101  *              drm_agp_chipset_flush
3102  */
3103 static void
3104 i915_gem_object_set_to_gpu_domain(struct drm_gem_object *obj)
3105 {
3106         struct drm_device               *dev = obj->dev;
3107         struct drm_i915_gem_object      *obj_priv = to_intel_bo(obj);
3108         uint32_t                        invalidate_domains = 0;
3109         uint32_t                        flush_domains = 0;
3110         uint32_t                        old_read_domains;
3111
3112         BUG_ON(obj->pending_read_domains & I915_GEM_DOMAIN_CPU);
3113         BUG_ON(obj->pending_write_domain == I915_GEM_DOMAIN_CPU);
3114
3115         intel_mark_busy(dev, obj);
3116
3117 #if WATCH_BUF
3118         DRM_INFO("%s: object %p read %08x -> %08x write %08x -> %08x\n",
3119                  __func__, obj,
3120                  obj->read_domains, obj->pending_read_domains,
3121                  obj->write_domain, obj->pending_write_domain);
3122 #endif
3123         /*
3124          * If the object isn't moving to a new write domain,
3125          * let the object stay in multiple read domains
3126          */
3127         if (obj->pending_write_domain == 0)
3128                 obj->pending_read_domains |= obj->read_domains;
3129         else
3130                 obj_priv->dirty = 1;
3131
3132         /*
3133          * Flush the current write domain if
3134          * the new read domains don't match. Invalidate
3135          * any read domains which differ from the old
3136          * write domain
3137          */
3138         if (obj->write_domain &&
3139             obj->write_domain != obj->pending_read_domains) {
3140                 flush_domains |= obj->write_domain;
3141                 invalidate_domains |=
3142                         obj->pending_read_domains & ~obj->write_domain;
3143         }
3144         /*
3145          * Invalidate any read caches which may have
3146          * stale data. That is, any new read domains.
3147          */
3148         invalidate_domains |= obj->pending_read_domains & ~obj->read_domains;
3149         if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU) {
3150 #if WATCH_BUF
3151                 DRM_INFO("%s: CPU domain flush %08x invalidate %08x\n",
3152                          __func__, flush_domains, invalidate_domains);
3153 #endif
3154                 i915_gem_clflush_object(obj);
3155         }
3156
3157         old_read_domains = obj->read_domains;
3158
3159         /* The actual obj->write_domain will be updated with
3160          * pending_write_domain after we emit the accumulated flush for all
3161          * of our domain changes in execbuffers (which clears objects'
3162          * write_domains).  So if we have a current write domain that we
3163          * aren't changing, set pending_write_domain to that.
3164          */
3165         if (flush_domains == 0 && obj->pending_write_domain == 0)
3166                 obj->pending_write_domain = obj->write_domain;
3167         obj->read_domains = obj->pending_read_domains;
3168
3169         dev->invalidate_domains |= invalidate_domains;
3170         dev->flush_domains |= flush_domains;
3171 #if WATCH_BUF
3172         DRM_INFO("%s: read %08x write %08x invalidate %08x flush %08x\n",
3173                  __func__,
3174                  obj->read_domains, obj->write_domain,
3175                  dev->invalidate_domains, dev->flush_domains);
3176 #endif
3177
3178         trace_i915_gem_object_change_domain(obj,
3179                                             old_read_domains,
3180                                             obj->write_domain);
3181 }
3182
3183 /**
3184  * Moves the object from a partially CPU read to a full one.
3185  *
3186  * Note that this only resolves i915_gem_object_set_cpu_read_domain_range(),
3187  * and doesn't handle transitioning from !(read_domains & I915_GEM_DOMAIN_CPU).
3188  */
3189 static void
3190 i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj)
3191 {
3192         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
3193
3194         if (!obj_priv->page_cpu_valid)
3195                 return;
3196
3197         /* If we're partially in the CPU read domain, finish moving it in.
3198          */
3199         if (obj->read_domains & I915_GEM_DOMAIN_CPU) {
3200                 int i;
3201
3202                 for (i = 0; i <= (obj->size - 1) / PAGE_SIZE; i++) {
3203                         if (obj_priv->page_cpu_valid[i])
3204                                 continue;
3205                         drm_clflush_pages(obj_priv->pages + i, 1);
3206                 }
3207         }
3208
3209         /* Free the page_cpu_valid mappings which are now stale, whether
3210          * or not we've got I915_GEM_DOMAIN_CPU.
3211          */
3212         kfree(obj_priv->page_cpu_valid);
3213         obj_priv->page_cpu_valid = NULL;
3214 }
3215
3216 /**
3217  * Set the CPU read domain on a range of the object.
3218  *
3219  * The object ends up with I915_GEM_DOMAIN_CPU in its read flags although it's
3220  * not entirely valid.  The page_cpu_valid member of the object flags which
3221  * pages have been flushed, and will be respected by
3222  * i915_gem_object_set_to_cpu_domain() if it's called on to get a valid mapping
3223  * of the whole object.
3224  *
3225  * This function returns when the move is complete, including waiting on
3226  * flushes to occur.
3227  */
3228 static int
3229 i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
3230                                           uint64_t offset, uint64_t size)
3231 {
3232         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
3233         uint32_t old_read_domains;
3234         int i, ret;
3235
3236         if (offset == 0 && size == obj->size)
3237                 return i915_gem_object_set_to_cpu_domain(obj, 0);
3238
3239         i915_gem_object_flush_gpu_write_domain(obj);
3240         /* Wait on any GPU rendering and flushing to occur. */
3241         ret = i915_gem_object_wait_rendering(obj);
3242         if (ret != 0)
3243                 return ret;
3244         i915_gem_object_flush_gtt_write_domain(obj);
3245
3246         /* If we're already fully in the CPU read domain, we're done. */
3247         if (obj_priv->page_cpu_valid == NULL &&
3248             (obj->read_domains & I915_GEM_DOMAIN_CPU) != 0)
3249                 return 0;
3250
3251         /* Otherwise, create/clear the per-page CPU read domain flag if we're
3252          * newly adding I915_GEM_DOMAIN_CPU
3253          */
3254         if (obj_priv->page_cpu_valid == NULL) {
3255                 obj_priv->page_cpu_valid = kzalloc(obj->size / PAGE_SIZE,
3256                                                    GFP_KERNEL);
3257                 if (obj_priv->page_cpu_valid == NULL)
3258                         return -ENOMEM;
3259         } else if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0)
3260                 memset(obj_priv->page_cpu_valid, 0, obj->size / PAGE_SIZE);
3261
3262         /* Flush the cache on any pages that are still invalid from the CPU's
3263          * perspective.
3264          */
3265         for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
3266              i++) {
3267                 if (obj_priv->page_cpu_valid[i])
3268                         continue;
3269
3270                 drm_clflush_pages(obj_priv->pages + i, 1);
3271
3272                 obj_priv->page_cpu_valid[i] = 1;
3273         }
3274
3275         /* It should now be out of any other write domains, and we can update
3276          * the domain values for our changes.
3277          */
3278         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3279
3280         old_read_domains = obj->read_domains;
3281         obj->read_domains |= I915_GEM_DOMAIN_CPU;
3282
3283         trace_i915_gem_object_change_domain(obj,
3284                                             old_read_domains,
3285                                             obj->write_domain);
3286
3287         return 0;
3288 }
3289
3290 /**
3291  * Pin an object to the GTT and evaluate the relocations landing in it.
3292  */
3293 static int
3294 i915_gem_object_pin_and_relocate(struct drm_gem_object *obj,
3295                                  struct drm_file *file_priv,
3296                                  struct drm_i915_gem_exec_object2 *entry,
3297                                  struct drm_i915_gem_relocation_entry *relocs)
3298 {
3299         struct drm_device *dev = obj->dev;
3300         drm_i915_private_t *dev_priv = dev->dev_private;
3301         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
3302         int i, ret;
3303         void __iomem *reloc_page;
3304         bool need_fence;
3305
3306         need_fence = entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
3307                      obj_priv->tiling_mode != I915_TILING_NONE;
3308
3309         /* Check fence reg constraints and rebind if necessary */
3310         if (need_fence &&
3311             !i915_gem_object_fence_offset_ok(obj,
3312                                              obj_priv->tiling_mode)) {
3313                 ret = i915_gem_object_unbind(obj);
3314                 if (ret)
3315                         return ret;
3316         }
3317
3318         /* Choose the GTT offset for our buffer and put it there. */
3319         ret = i915_gem_object_pin(obj, (uint32_t) entry->alignment);
3320         if (ret)
3321                 return ret;
3322
3323         /*
3324          * Pre-965 chips need a fence register set up in order to
3325          * properly handle blits to/from tiled surfaces.
3326          */
3327         if (need_fence) {
3328                 ret = i915_gem_object_get_fence_reg(obj);
3329                 if (ret != 0) {
3330                         if (ret != -EBUSY && ret != -ERESTARTSYS)
3331                                 DRM_ERROR("Failure to install fence: %d\n",
3332                                           ret);
3333                         i915_gem_object_unpin(obj);
3334                         return ret;
3335                 }
3336         }
3337
3338         entry->offset = obj_priv->gtt_offset;
3339
3340         /* Apply the relocations, using the GTT aperture to avoid cache
3341          * flushing requirements.
3342          */
3343         for (i = 0; i < entry->relocation_count; i++) {
3344                 struct drm_i915_gem_relocation_entry *reloc= &relocs[i];
3345                 struct drm_gem_object *target_obj;
3346                 struct drm_i915_gem_object *target_obj_priv;
3347                 uint32_t reloc_val, reloc_offset;
3348                 uint32_t __iomem *reloc_entry;
3349
3350                 target_obj = drm_gem_object_lookup(obj->dev, file_priv,
3351                                                    reloc->target_handle);
3352                 if (target_obj == NULL) {
3353                         i915_gem_object_unpin(obj);
3354                         return -EBADF;
3355                 }
3356                 target_obj_priv = to_intel_bo(target_obj);
3357
3358 #if WATCH_RELOC
3359                 DRM_INFO("%s: obj %p offset %08x target %d "
3360                          "read %08x write %08x gtt %08x "
3361                          "presumed %08x delta %08x\n",
3362                          __func__,
3363                          obj,
3364                          (int) reloc->offset,
3365                          (int) reloc->target_handle,
3366                          (int) reloc->read_domains,
3367                          (int) reloc->write_domain,
3368                          (int) target_obj_priv->gtt_offset,
3369                          (int) reloc->presumed_offset,
3370                          reloc->delta);
3371 #endif
3372
3373                 /* The target buffer should have appeared before us in the
3374                  * exec_object list, so it should have a GTT space bound by now.
3375                  */
3376                 if (target_obj_priv->gtt_space == NULL) {
3377                         DRM_ERROR("No GTT space found for object %d\n",
3378                                   reloc->target_handle);
3379                         drm_gem_object_unreference(target_obj);
3380                         i915_gem_object_unpin(obj);
3381                         return -EINVAL;
3382                 }
3383
3384                 /* Validate that the target is in a valid r/w GPU domain */
3385                 if (reloc->write_domain & (reloc->write_domain - 1)) {
3386                         DRM_ERROR("reloc with multiple write domains: "
3387                                   "obj %p target %d offset %d "
3388                                   "read %08x write %08x",
3389                                   obj, reloc->target_handle,
3390                                   (int) reloc->offset,
3391                                   reloc->read_domains,
3392                                   reloc->write_domain);
3393                         return -EINVAL;
3394                 }
3395                 if (reloc->write_domain & I915_GEM_DOMAIN_CPU ||
3396                     reloc->read_domains & I915_GEM_DOMAIN_CPU) {
3397                         DRM_ERROR("reloc with read/write CPU domains: "
3398                                   "obj %p target %d offset %d "
3399                                   "read %08x write %08x",
3400                                   obj, reloc->target_handle,
3401                                   (int) reloc->offset,
3402                                   reloc->read_domains,
3403                                   reloc->write_domain);
3404                         drm_gem_object_unreference(target_obj);
3405                         i915_gem_object_unpin(obj);
3406                         return -EINVAL;
3407                 }
3408                 if (reloc->write_domain && target_obj->pending_write_domain &&
3409                     reloc->write_domain != target_obj->pending_write_domain) {
3410                         DRM_ERROR("Write domain conflict: "
3411                                   "obj %p target %d offset %d "
3412                                   "new %08x old %08x\n",
3413                                   obj, reloc->target_handle,
3414                                   (int) reloc->offset,
3415                                   reloc->write_domain,
3416                                   target_obj->pending_write_domain);
3417                         drm_gem_object_unreference(target_obj);
3418                         i915_gem_object_unpin(obj);
3419                         return -EINVAL;
3420                 }
3421
3422                 target_obj->pending_read_domains |= reloc->read_domains;
3423                 target_obj->pending_write_domain |= reloc->write_domain;
3424
3425                 /* If the relocation already has the right value in it, no
3426                  * more work needs to be done.
3427                  */
3428                 if (target_obj_priv->gtt_offset == reloc->presumed_offset) {
3429                         drm_gem_object_unreference(target_obj);
3430                         continue;
3431                 }
3432
3433                 /* Check that the relocation address is valid... */
3434                 if (reloc->offset > obj->size - 4) {
3435                         DRM_ERROR("Relocation beyond object bounds: "
3436                                   "obj %p target %d offset %d size %d.\n",
3437                                   obj, reloc->target_handle,
3438                                   (int) reloc->offset, (int) obj->size);
3439                         drm_gem_object_unreference(target_obj);
3440                         i915_gem_object_unpin(obj);
3441                         return -EINVAL;
3442                 }
3443                 if (reloc->offset & 3) {
3444                         DRM_ERROR("Relocation not 4-byte aligned: "
3445                                   "obj %p target %d offset %d.\n",
3446                                   obj, reloc->target_handle,
3447                                   (int) reloc->offset);
3448                         drm_gem_object_unreference(target_obj);
3449                         i915_gem_object_unpin(obj);
3450                         return -EINVAL;
3451                 }
3452
3453                 /* and points to somewhere within the target object. */
3454                 if (reloc->delta >= target_obj->size) {
3455                         DRM_ERROR("Relocation beyond target object bounds: "
3456                                   "obj %p target %d delta %d size %d.\n",
3457                                   obj, reloc->target_handle,
3458                                   (int) reloc->delta, (int) target_obj->size);
3459                         drm_gem_object_unreference(target_obj);
3460                         i915_gem_object_unpin(obj);
3461                         return -EINVAL;
3462                 }
3463
3464                 ret = i915_gem_object_set_to_gtt_domain(obj, 1);
3465                 if (ret != 0) {
3466                         drm_gem_object_unreference(target_obj);
3467                         i915_gem_object_unpin(obj);
3468                         return -EINVAL;
3469                 }
3470
3471                 /* Map the page containing the relocation we're going to
3472                  * perform.
3473                  */
3474                 reloc_offset = obj_priv->gtt_offset + reloc->offset;
3475                 reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
3476                                                       (reloc_offset &
3477                                                        ~(PAGE_SIZE - 1)));
3478                 reloc_entry = (uint32_t __iomem *)(reloc_page +
3479                                                    (reloc_offset & (PAGE_SIZE - 1)));
3480                 reloc_val = target_obj_priv->gtt_offset + reloc->delta;
3481
3482 #if WATCH_BUF
3483                 DRM_INFO("Applied relocation: %p@0x%08x %08x -> %08x\n",
3484                           obj, (unsigned int) reloc->offset,
3485                           readl(reloc_entry), reloc_val);
3486 #endif
3487                 writel(reloc_val, reloc_entry);
3488                 io_mapping_unmap_atomic(reloc_page);
3489
3490                 /* The updated presumed offset for this entry will be
3491                  * copied back out to the user.
3492                  */
3493                 reloc->presumed_offset = target_obj_priv->gtt_offset;
3494
3495                 drm_gem_object_unreference(target_obj);
3496         }
3497
3498 #if WATCH_BUF
3499         if (0)
3500                 i915_gem_dump_object(obj, 128, __func__, ~0);
3501 #endif
3502         return 0;
3503 }
3504
3505 /* Throttle our rendering by waiting until the ring has completed our requests
3506  * emitted over 20 msec ago.
3507  *
3508  * Note that if we were to use the current jiffies each time around the loop,
3509  * we wouldn't escape the function with any frames outstanding if the time to
3510  * render a frame was over 20ms.
3511  *
3512  * This should get us reasonable parallelism between CPU and GPU but also
3513  * relatively low latency when blocking on a particular request to finish.
3514  */
3515 static int
3516 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file_priv)
3517 {
3518         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
3519         int ret = 0;
3520         unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
3521
3522         mutex_lock(&dev->struct_mutex);
3523         while (!list_empty(&i915_file_priv->mm.request_list)) {
3524                 struct drm_i915_gem_request *request;
3525
3526                 request = list_first_entry(&i915_file_priv->mm.request_list,
3527                                            struct drm_i915_gem_request,
3528                                            client_list);
3529
3530                 if (time_after_eq(request->emitted_jiffies, recent_enough))
3531                         break;
3532
3533                 ret = i915_wait_request(dev, request->seqno, request->ring);
3534                 if (ret != 0)
3535                         break;
3536         }
3537         mutex_unlock(&dev->struct_mutex);
3538
3539         return ret;
3540 }
3541
3542 static int
3543 i915_gem_get_relocs_from_user(struct drm_i915_gem_exec_object2 *exec_list,
3544                               uint32_t buffer_count,
3545                               struct drm_i915_gem_relocation_entry **relocs)
3546 {
3547         uint32_t reloc_count = 0, reloc_index = 0, i;
3548         int ret;
3549
3550         *relocs = NULL;
3551         for (i = 0; i < buffer_count; i++) {
3552                 if (reloc_count + exec_list[i].relocation_count < reloc_count)
3553                         return -EINVAL;
3554                 reloc_count += exec_list[i].relocation_count;
3555         }
3556
3557         *relocs = drm_calloc_large(reloc_count, sizeof(**relocs));
3558         if (*relocs == NULL) {
3559                 DRM_ERROR("failed to alloc relocs, count %d\n", reloc_count);
3560                 return -ENOMEM;
3561         }
3562
3563         for (i = 0; i < buffer_count; i++) {
3564                 struct drm_i915_gem_relocation_entry __user *user_relocs;
3565
3566                 user_relocs = (void __user *)(uintptr_t)exec_list[i].relocs_ptr;
3567
3568                 ret = copy_from_user(&(*relocs)[reloc_index],
3569                                      user_relocs,
3570                                      exec_list[i].relocation_count *
3571                                      sizeof(**relocs));
3572                 if (ret != 0) {
3573                         drm_free_large(*relocs);
3574                         *relocs = NULL;
3575                         return -EFAULT;
3576                 }
3577
3578                 reloc_index += exec_list[i].relocation_count;
3579         }
3580
3581         return 0;
3582 }
3583
3584 static int
3585 i915_gem_put_relocs_to_user(struct drm_i915_gem_exec_object2 *exec_list,
3586                             uint32_t buffer_count,
3587                             struct drm_i915_gem_relocation_entry *relocs)
3588 {
3589         uint32_t reloc_count = 0, i;
3590         int ret = 0;
3591
3592         if (relocs == NULL)
3593             return 0;
3594
3595         for (i = 0; i < buffer_count; i++) {
3596                 struct drm_i915_gem_relocation_entry __user *user_relocs;
3597                 int unwritten;
3598
3599                 user_relocs = (void __user *)(uintptr_t)exec_list[i].relocs_ptr;
3600
3601                 unwritten = copy_to_user(user_relocs,
3602                                          &relocs[reloc_count],
3603                                          exec_list[i].relocation_count *
3604                                          sizeof(*relocs));
3605
3606                 if (unwritten) {
3607                         ret = -EFAULT;
3608                         goto err;
3609                 }
3610
3611                 reloc_count += exec_list[i].relocation_count;
3612         }
3613
3614 err:
3615         drm_free_large(relocs);
3616
3617         return ret;
3618 }
3619
3620 static int
3621 i915_gem_check_execbuffer (struct drm_i915_gem_execbuffer2 *exec,
3622                            uint64_t exec_offset)
3623 {
3624         uint32_t exec_start, exec_len;
3625
3626         exec_start = (uint32_t) exec_offset + exec->batch_start_offset;
3627         exec_len = (uint32_t) exec->batch_len;
3628
3629         if ((exec_start | exec_len) & 0x7)
3630                 return -EINVAL;
3631
3632         if (!exec_start)
3633                 return -EINVAL;
3634
3635         return 0;
3636 }
3637
3638 static int
3639 i915_gem_wait_for_pending_flip(struct drm_device *dev,
3640                                struct drm_gem_object **object_list,
3641                                int count)
3642 {
3643         drm_i915_private_t *dev_priv = dev->dev_private;
3644         struct drm_i915_gem_object *obj_priv;
3645         DEFINE_WAIT(wait);
3646         int i, ret = 0;
3647
3648         for (;;) {
3649                 prepare_to_wait(&dev_priv->pending_flip_queue,
3650                                 &wait, TASK_INTERRUPTIBLE);
3651                 for (i = 0; i < count; i++) {
3652                         obj_priv = to_intel_bo(object_list[i]);
3653                         if (atomic_read(&obj_priv->pending_flip) > 0)
3654                                 break;
3655                 }
3656                 if (i == count)
3657                         break;
3658
3659                 if (!signal_pending(current)) {
3660                         mutex_unlock(&dev->struct_mutex);
3661                         schedule();
3662                         mutex_lock(&dev->struct_mutex);
3663                         continue;
3664                 }
3665                 ret = -ERESTARTSYS;
3666                 break;
3667         }
3668         finish_wait(&dev_priv->pending_flip_queue, &wait);
3669
3670         return ret;
3671 }
3672
3673 int
3674 i915_gem_do_execbuffer(struct drm_device *dev, void *data,
3675                        struct drm_file *file_priv,
3676                        struct drm_i915_gem_execbuffer2 *args,
3677                        struct drm_i915_gem_exec_object2 *exec_list)
3678 {
3679         drm_i915_private_t *dev_priv = dev->dev_private;
3680         struct drm_gem_object **object_list = NULL;
3681         struct drm_gem_object *batch_obj;
3682         struct drm_i915_gem_object *obj_priv;
3683         struct drm_clip_rect *cliprects = NULL;
3684         struct drm_i915_gem_relocation_entry *relocs = NULL;
3685         int ret = 0, ret2, i, pinned = 0;
3686         uint64_t exec_offset;
3687         uint32_t seqno, flush_domains, reloc_index;
3688         int pin_tries, flips;
3689
3690         struct intel_ring_buffer *ring = NULL;
3691
3692 #if WATCH_EXEC
3693         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
3694                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
3695 #endif
3696         if (args->flags & I915_EXEC_BSD) {
3697                 if (!HAS_BSD(dev)) {
3698                         DRM_ERROR("execbuf with wrong flag\n");
3699                         return -EINVAL;
3700                 }
3701                 ring = &dev_priv->bsd_ring;
3702         } else {
3703                 ring = &dev_priv->render_ring;
3704         }
3705
3706
3707         if (args->buffer_count < 1) {
3708                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
3709                 return -EINVAL;
3710         }
3711         object_list = drm_malloc_ab(sizeof(*object_list), args->buffer_count);
3712         if (object_list == NULL) {
3713                 DRM_ERROR("Failed to allocate object list for %d buffers\n",
3714                           args->buffer_count);
3715                 ret = -ENOMEM;
3716                 goto pre_mutex_err;
3717         }
3718
3719         if (args->num_cliprects != 0) {
3720                 cliprects = kcalloc(args->num_cliprects, sizeof(*cliprects),
3721                                     GFP_KERNEL);
3722                 if (cliprects == NULL) {
3723                         ret = -ENOMEM;
3724                         goto pre_mutex_err;
3725                 }
3726
3727                 ret = copy_from_user(cliprects,
3728                                      (struct drm_clip_rect __user *)
3729                                      (uintptr_t) args->cliprects_ptr,
3730                                      sizeof(*cliprects) * args->num_cliprects);
3731                 if (ret != 0) {
3732                         DRM_ERROR("copy %d cliprects failed: %d\n",
3733                                   args->num_cliprects, ret);
3734                         goto pre_mutex_err;
3735                 }
3736         }
3737
3738         ret = i915_gem_get_relocs_from_user(exec_list, args->buffer_count,
3739                                             &relocs);
3740         if (ret != 0)
3741                 goto pre_mutex_err;
3742
3743         mutex_lock(&dev->struct_mutex);
3744
3745         i915_verify_inactive(dev, __FILE__, __LINE__);
3746
3747         if (atomic_read(&dev_priv->mm.wedged)) {
3748                 mutex_unlock(&dev->struct_mutex);
3749                 ret = -EIO;
3750                 goto pre_mutex_err;
3751         }
3752
3753         if (dev_priv->mm.suspended) {
3754                 mutex_unlock(&dev->struct_mutex);
3755                 ret = -EBUSY;
3756                 goto pre_mutex_err;
3757         }
3758
3759         /* Look up object handles */
3760         flips = 0;
3761         for (i = 0; i < args->buffer_count; i++) {
3762                 object_list[i] = drm_gem_object_lookup(dev, file_priv,
3763                                                        exec_list[i].handle);
3764                 if (object_list[i] == NULL) {
3765                         DRM_ERROR("Invalid object handle %d at index %d\n",
3766                                    exec_list[i].handle, i);
3767                         /* prevent error path from reading uninitialized data */
3768                         args->buffer_count = i + 1;
3769                         ret = -EBADF;
3770                         goto err;
3771                 }
3772
3773                 obj_priv = to_intel_bo(object_list[i]);
3774                 if (obj_priv->in_execbuffer) {
3775                         DRM_ERROR("Object %p appears more than once in object list\n",
3776                                    object_list[i]);
3777                         /* prevent error path from reading uninitialized data */
3778                         args->buffer_count = i + 1;
3779                         ret = -EBADF;
3780                         goto err;
3781                 }
3782                 obj_priv->in_execbuffer = true;
3783                 flips += atomic_read(&obj_priv->pending_flip);
3784         }
3785
3786         if (flips > 0) {
3787                 ret = i915_gem_wait_for_pending_flip(dev, object_list,
3788                                                      args->buffer_count);
3789                 if (ret)
3790                         goto err;
3791         }
3792
3793         /* Pin and relocate */
3794         for (pin_tries = 0; ; pin_tries++) {
3795                 ret = 0;
3796                 reloc_index = 0;
3797
3798                 for (i = 0; i < args->buffer_count; i++) {
3799                         object_list[i]->pending_read_domains = 0;
3800                         object_list[i]->pending_write_domain = 0;
3801                         ret = i915_gem_object_pin_and_relocate(object_list[i],
3802                                                                file_priv,
3803                                                                &exec_list[i],
3804                                                                &relocs[reloc_index]);
3805                         if (ret)
3806                                 break;
3807                         pinned = i + 1;
3808                         reloc_index += exec_list[i].relocation_count;
3809                 }
3810                 /* success */
3811                 if (ret == 0)
3812                         break;
3813
3814                 /* error other than GTT full, or we've already tried again */
3815                 if (ret != -ENOSPC || pin_tries >= 1) {
3816                         if (ret != -ERESTARTSYS) {
3817                                 unsigned long long total_size = 0;
3818                                 for (i = 0; i < args->buffer_count; i++)
3819                                         total_size += object_list[i]->size;
3820                                 DRM_ERROR("Failed to pin buffer %d of %d, total %llu bytes: %d\n",
3821                                           pinned+1, args->buffer_count,
3822                                           total_size, ret);
3823                                 DRM_ERROR("%d objects [%d pinned], "
3824                                           "%d object bytes [%d pinned], "
3825                                           "%d/%d gtt bytes\n",
3826                                           atomic_read(&dev->object_count),
3827                                           atomic_read(&dev->pin_count),
3828                                           atomic_read(&dev->object_memory),
3829                                           atomic_read(&dev->pin_memory),
3830                                           atomic_read(&dev->gtt_memory),
3831                                           dev->gtt_total);
3832                         }
3833                         goto err;
3834                 }
3835
3836                 /* unpin all of our buffers */
3837                 for (i = 0; i < pinned; i++)
3838                         i915_gem_object_unpin(object_list[i]);
3839                 pinned = 0;
3840
3841                 /* evict everyone we can from the aperture */
3842                 ret = i915_gem_evict_everything(dev);
3843                 if (ret && ret != -ENOSPC)
3844                         goto err;
3845         }
3846
3847         /* Set the pending read domains for the batch buffer to COMMAND */
3848         batch_obj = object_list[args->buffer_count-1];
3849         if (batch_obj->pending_write_domain) {
3850                 DRM_ERROR("Attempting to use self-modifying batch buffer\n");
3851                 ret = -EINVAL;
3852                 goto err;
3853         }
3854         batch_obj->pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
3855
3856         /* Sanity check the batch buffer, prior to moving objects */
3857         exec_offset = exec_list[args->buffer_count - 1].offset;
3858         ret = i915_gem_check_execbuffer (args, exec_offset);
3859         if (ret != 0) {
3860                 DRM_ERROR("execbuf with invalid offset/length\n");
3861                 goto err;
3862         }
3863
3864         i915_verify_inactive(dev, __FILE__, __LINE__);
3865
3866         /* Zero the global flush/invalidate flags. These
3867          * will be modified as new domains are computed
3868          * for each object
3869          */
3870         dev->invalidate_domains = 0;
3871         dev->flush_domains = 0;
3872
3873         for (i = 0; i < args->buffer_count; i++) {
3874                 struct drm_gem_object *obj = object_list[i];
3875
3876                 /* Compute new gpu domains and update invalidate/flush */
3877                 i915_gem_object_set_to_gpu_domain(obj);
3878         }
3879
3880         i915_verify_inactive(dev, __FILE__, __LINE__);
3881
3882         if (dev->invalidate_domains | dev->flush_domains) {
3883 #if WATCH_EXEC
3884                 DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
3885                           __func__,
3886                          dev->invalidate_domains,
3887                          dev->flush_domains);
3888 #endif
3889                 i915_gem_flush(dev,
3890                                dev->invalidate_domains,
3891                                dev->flush_domains);
3892                 if (dev->flush_domains & I915_GEM_GPU_DOMAINS) {
3893                         (void)i915_add_request(dev, file_priv,
3894                                         dev->flush_domains,
3895                                         &dev_priv->render_ring);
3896
3897                         if (HAS_BSD(dev))
3898                                 (void)i915_add_request(dev, file_priv,
3899                                                 dev->flush_domains,
3900                                                 &dev_priv->bsd_ring);
3901                 }
3902         }
3903
3904         for (i = 0; i < args->buffer_count; i++) {
3905                 struct drm_gem_object *obj = object_list[i];
3906                 struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
3907                 uint32_t old_write_domain = obj->write_domain;
3908
3909                 obj->write_domain = obj->pending_write_domain;
3910                 if (obj->write_domain)
3911                         list_move_tail(&obj_priv->gpu_write_list,
3912                                        &dev_priv->mm.gpu_write_list);
3913                 else
3914                         list_del_init(&obj_priv->gpu_write_list);
3915
3916                 trace_i915_gem_object_change_domain(obj,
3917                                                     obj->read_domains,
3918                                                     old_write_domain);
3919         }
3920
3921         i915_verify_inactive(dev, __FILE__, __LINE__);
3922
3923 #if WATCH_COHERENCY
3924         for (i = 0; i < args->buffer_count; i++) {
3925                 i915_gem_object_check_coherency(object_list[i],
3926                                                 exec_list[i].handle);
3927         }
3928 #endif
3929
3930 #if WATCH_EXEC
3931         i915_gem_dump_object(batch_obj,
3932                               args->batch_len,
3933                               __func__,
3934                               ~0);
3935 #endif
3936
3937         /* Exec the batchbuffer */
3938         ret = ring->dispatch_gem_execbuffer(dev, ring, args,
3939                         cliprects, exec_offset);
3940         if (ret) {
3941                 DRM_ERROR("dispatch failed %d\n", ret);
3942                 goto err;
3943         }
3944
3945         /*
3946          * Ensure that the commands in the batch buffer are
3947          * finished before the interrupt fires
3948          */
3949         flush_domains = i915_retire_commands(dev, ring);
3950
3951         i915_verify_inactive(dev, __FILE__, __LINE__);
3952
3953         /*
3954          * Get a seqno representing the execution of the current buffer,
3955          * which we can wait on.  We would like to mitigate these interrupts,
3956          * likely by only creating seqnos occasionally (so that we have
3957          * *some* interrupts representing completion of buffers that we can
3958          * wait on when trying to clear up gtt space).
3959          */
3960         seqno = i915_add_request(dev, file_priv, flush_domains, ring);
3961         BUG_ON(seqno == 0);
3962         for (i = 0; i < args->buffer_count; i++) {
3963                 struct drm_gem_object *obj = object_list[i];
3964                 obj_priv = to_intel_bo(obj);
3965
3966                 i915_gem_object_move_to_active(obj, seqno, ring);
3967 #if WATCH_LRU
3968                 DRM_INFO("%s: move to exec list %p\n", __func__, obj);
3969 #endif
3970         }
3971 #if WATCH_LRU
3972         i915_dump_lru(dev, __func__);
3973 #endif
3974
3975         i915_verify_inactive(dev, __FILE__, __LINE__);
3976
3977 err:
3978         for (i = 0; i < pinned; i++)
3979                 i915_gem_object_unpin(object_list[i]);
3980
3981         for (i = 0; i < args->buffer_count; i++) {
3982                 if (object_list[i]) {
3983                         obj_priv = to_intel_bo(object_list[i]);
3984                         obj_priv->in_execbuffer = false;
3985                 }
3986                 drm_gem_object_unreference(object_list[i]);
3987         }
3988
3989         mutex_unlock(&dev->struct_mutex);
3990
3991 pre_mutex_err:
3992         /* Copy the updated relocations out regardless of current error
3993          * state.  Failure to update the relocs would mean that the next
3994          * time userland calls execbuf, it would do so with presumed offset
3995          * state that didn't match the actual object state.
3996          */
3997         ret2 = i915_gem_put_relocs_to_user(exec_list, args->buffer_count,
3998                                            relocs);
3999         if (ret2 != 0) {
4000                 DRM_ERROR("Failed to copy relocations back out: %d\n", ret2);
4001
4002                 if (ret == 0)
4003                         ret = ret2;
4004         }
4005
4006         drm_free_large(object_list);
4007         kfree(cliprects);
4008
4009         return ret;
4010 }
4011
4012 /*
4013  * Legacy execbuffer just creates an exec2 list from the original exec object
4014  * list array and passes it to the real function.
4015  */
4016 int
4017 i915_gem_execbuffer(struct drm_device *dev, void *data,
4018                     struct drm_file *file_priv)
4019 {
4020         struct drm_i915_gem_execbuffer *args = data;
4021         struct drm_i915_gem_execbuffer2 exec2;
4022         struct drm_i915_gem_exec_object *exec_list = NULL;
4023         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
4024         int ret, i;
4025
4026 #if WATCH_EXEC
4027         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
4028                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
4029 #endif
4030
4031         if (args->buffer_count < 1) {
4032                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
4033                 return -EINVAL;
4034         }
4035
4036         /* Copy in the exec list from userland */
4037         exec_list = drm_malloc_ab(sizeof(*exec_list), args->buffer_count);
4038         exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
4039         if (exec_list == NULL || exec2_list == NULL) {
4040                 DRM_ERROR("Failed to allocate exec list for %d buffers\n",
4041                           args->buffer_count);
4042                 drm_free_large(exec_list);
4043                 drm_free_large(exec2_list);
4044                 return -ENOMEM;
4045         }
4046         ret = copy_from_user(exec_list,
4047                              (struct drm_i915_relocation_entry __user *)
4048                              (uintptr_t) args->buffers_ptr,
4049                              sizeof(*exec_list) * args->buffer_count);
4050         if (ret != 0) {
4051                 DRM_ERROR("copy %d exec entries failed %d\n",
4052                           args->buffer_count, ret);
4053                 drm_free_large(exec_list);
4054                 drm_free_large(exec2_list);
4055                 return -EFAULT;
4056         }
4057
4058         for (i = 0; i < args->buffer_count; i++) {
4059                 exec2_list[i].handle = exec_list[i].handle;
4060                 exec2_list[i].relocation_count = exec_list[i].relocation_count;
4061                 exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
4062                 exec2_list[i].alignment = exec_list[i].alignment;
4063                 exec2_list[i].offset = exec_list[i].offset;
4064                 if (!IS_I965G(dev))
4065                         exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
4066                 else
4067                         exec2_list[i].flags = 0;
4068         }
4069
4070         exec2.buffers_ptr = args->buffers_ptr;
4071         exec2.buffer_count = args->buffer_count;
4072         exec2.batch_start_offset = args->batch_start_offset;
4073         exec2.batch_len = args->batch_len;
4074         exec2.DR1 = args->DR1;
4075         exec2.DR4 = args->DR4;
4076         exec2.num_cliprects = args->num_cliprects;
4077         exec2.cliprects_ptr = args->cliprects_ptr;
4078         exec2.flags = I915_EXEC_RENDER;
4079
4080         ret = i915_gem_do_execbuffer(dev, data, file_priv, &exec2, exec2_list);
4081         if (!ret) {
4082                 /* Copy the new buffer offsets back to the user's exec list. */
4083                 for (i = 0; i < args->buffer_count; i++)
4084                         exec_list[i].offset = exec2_list[i].offset;
4085                 /* ... and back out to userspace */
4086                 ret = copy_to_user((struct drm_i915_relocation_entry __user *)
4087                                    (uintptr_t) args->buffers_ptr,
4088                                    exec_list,
4089                                    sizeof(*exec_list) * args->buffer_count);
4090                 if (ret) {
4091                         ret = -EFAULT;
4092                         DRM_ERROR("failed to copy %d exec entries "
4093                                   "back to user (%d)\n",
4094                                   args->buffer_count, ret);
4095                 }
4096         }
4097
4098         drm_free_large(exec_list);
4099         drm_free_large(exec2_list);
4100         return ret;
4101 }
4102
4103 int
4104 i915_gem_execbuffer2(struct drm_device *dev, void *data,
4105                      struct drm_file *file_priv)
4106 {
4107         struct drm_i915_gem_execbuffer2 *args = data;
4108         struct drm_i915_gem_exec_object2 *exec2_list = NULL;
4109         int ret;
4110
4111 #if WATCH_EXEC
4112         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
4113                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
4114 #endif
4115
4116         if (args->buffer_count < 1) {
4117                 DRM_ERROR("execbuf2 with %d buffers\n", args->buffer_count);
4118                 return -EINVAL;
4119         }
4120
4121         exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
4122         if (exec2_list == NULL) {
4123                 DRM_ERROR("Failed to allocate exec list for %d buffers\n",
4124                           args->buffer_count);
4125                 return -ENOMEM;
4126         }
4127         ret = copy_from_user(exec2_list,
4128                              (struct drm_i915_relocation_entry __user *)
4129                              (uintptr_t) args->buffers_ptr,
4130                              sizeof(*exec2_list) * args->buffer_count);
4131         if (ret != 0) {
4132                 DRM_ERROR("copy %d exec entries failed %d\n",
4133                           args->buffer_count, ret);
4134                 drm_free_large(exec2_list);
4135                 return -EFAULT;
4136         }
4137
4138         ret = i915_gem_do_execbuffer(dev, data, file_priv, args, exec2_list);
4139         if (!ret) {
4140                 /* Copy the new buffer offsets back to the user's exec list. */
4141                 ret = copy_to_user((struct drm_i915_relocation_entry __user *)
4142                                    (uintptr_t) args->buffers_ptr,
4143                                    exec2_list,
4144                                    sizeof(*exec2_list) * args->buffer_count);
4145                 if (ret) {
4146                         ret = -EFAULT;
4147                         DRM_ERROR("failed to copy %d exec entries "
4148                                   "back to user (%d)\n",
4149                                   args->buffer_count, ret);
4150                 }
4151         }
4152
4153         drm_free_large(exec2_list);
4154         return ret;
4155 }
4156
4157 int
4158 i915_gem_object_pin(struct drm_gem_object *obj, uint32_t alignment)
4159 {
4160         struct drm_device *dev = obj->dev;
4161         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
4162         int ret;
4163
4164         BUG_ON(obj_priv->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT);
4165
4166         i915_verify_inactive(dev, __FILE__, __LINE__);
4167
4168         if (obj_priv->gtt_space != NULL) {
4169                 if (alignment == 0)
4170                         alignment = i915_gem_get_gtt_alignment(obj);
4171                 if (obj_priv->gtt_offset & (alignment - 1)) {
4172                         ret = i915_gem_object_unbind(obj);
4173                         if (ret)
4174                                 return ret;
4175                 }
4176         }
4177
4178         if (obj_priv->gtt_space == NULL) {
4179                 ret = i915_gem_object_bind_to_gtt(obj, alignment);
4180                 if (ret)
4181                         return ret;
4182         }
4183
4184         obj_priv->pin_count++;
4185
4186         /* If the object is not active and not pending a flush,
4187          * remove it from the inactive list
4188          */
4189         if (obj_priv->pin_count == 1) {
4190                 atomic_inc(&dev->pin_count);
4191                 atomic_add(obj->size, &dev->pin_memory);
4192                 if (!obj_priv->active &&
4193                     (obj->write_domain & I915_GEM_GPU_DOMAINS) == 0 &&
4194                     !list_empty(&obj_priv->list))
4195                         list_del_init(&obj_priv->list);
4196         }
4197         i915_verify_inactive(dev, __FILE__, __LINE__);
4198
4199         return 0;
4200 }
4201
4202 void
4203 i915_gem_object_unpin(struct drm_gem_object *obj)
4204 {
4205         struct drm_device *dev = obj->dev;
4206         drm_i915_private_t *dev_priv = dev->dev_private;
4207         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
4208
4209         i915_verify_inactive(dev, __FILE__, __LINE__);
4210         obj_priv->pin_count--;
4211         BUG_ON(obj_priv->pin_count < 0);
4212         BUG_ON(obj_priv->gtt_space == NULL);
4213
4214         /* If the object is no longer pinned, and is
4215          * neither active nor being flushed, then stick it on
4216          * the inactive list
4217          */
4218         if (obj_priv->pin_count == 0) {
4219                 if (!obj_priv->active &&
4220                     (obj->write_domain & I915_GEM_GPU_DOMAINS) == 0)
4221                         list_move_tail(&obj_priv->list,
4222                                        &dev_priv->mm.inactive_list);
4223                 atomic_dec(&dev->pin_count);
4224                 atomic_sub(obj->size, &dev->pin_memory);
4225         }
4226         i915_verify_inactive(dev, __FILE__, __LINE__);
4227 }
4228
4229 int
4230 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
4231                    struct drm_file *file_priv)
4232 {
4233         struct drm_i915_gem_pin *args = data;
4234         struct drm_gem_object *obj;
4235         struct drm_i915_gem_object *obj_priv;
4236         int ret;
4237
4238         mutex_lock(&dev->struct_mutex);
4239
4240         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
4241         if (obj == NULL) {
4242                 DRM_ERROR("Bad handle in i915_gem_pin_ioctl(): %d\n",
4243                           args->handle);
4244                 mutex_unlock(&dev->struct_mutex);
4245                 return -EBADF;
4246         }
4247         obj_priv = to_intel_bo(obj);
4248
4249         if (obj_priv->madv != I915_MADV_WILLNEED) {
4250                 DRM_ERROR("Attempting to pin a purgeable buffer\n");
4251                 drm_gem_object_unreference(obj);
4252                 mutex_unlock(&dev->struct_mutex);
4253                 return -EINVAL;
4254         }
4255
4256         if (obj_priv->pin_filp != NULL && obj_priv->pin_filp != file_priv) {
4257                 DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
4258                           args->handle);
4259                 drm_gem_object_unreference(obj);
4260                 mutex_unlock(&dev->struct_mutex);
4261                 return -EINVAL;
4262         }
4263
4264         obj_priv->user_pin_count++;
4265         obj_priv->pin_filp = file_priv;
4266         if (obj_priv->user_pin_count == 1) {
4267                 ret = i915_gem_object_pin(obj, args->alignment);
4268                 if (ret != 0) {
4269                         drm_gem_object_unreference(obj);
4270                         mutex_unlock(&dev->struct_mutex);
4271                         return ret;
4272                 }
4273         }
4274
4275         /* XXX - flush the CPU caches for pinned objects
4276          * as the X server doesn't manage domains yet
4277          */
4278         i915_gem_object_flush_cpu_write_domain(obj);
4279         args->offset = obj_priv->gtt_offset;
4280         drm_gem_object_unreference(obj);
4281         mutex_unlock(&dev->struct_mutex);
4282
4283         return 0;
4284 }
4285
4286 int
4287 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
4288                      struct drm_file *file_priv)
4289 {
4290         struct drm_i915_gem_pin *args = data;
4291         struct drm_gem_object *obj;
4292         struct drm_i915_gem_object *obj_priv;
4293
4294         mutex_lock(&dev->struct_mutex);
4295
4296         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
4297         if (obj == NULL) {
4298                 DRM_ERROR("Bad handle in i915_gem_unpin_ioctl(): %d\n",
4299                           args->handle);
4300                 mutex_unlock(&dev->struct_mutex);
4301                 return -EBADF;
4302         }
4303
4304         obj_priv = to_intel_bo(obj);
4305         if (obj_priv->pin_filp != file_priv) {
4306                 DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
4307                           args->handle);
4308                 drm_gem_object_unreference(obj);
4309                 mutex_unlock(&dev->struct_mutex);
4310                 return -EINVAL;
4311         }
4312         obj_priv->user_pin_count--;
4313         if (obj_priv->user_pin_count == 0) {
4314                 obj_priv->pin_filp = NULL;
4315                 i915_gem_object_unpin(obj);
4316         }
4317
4318         drm_gem_object_unreference(obj);
4319         mutex_unlock(&dev->struct_mutex);
4320         return 0;
4321 }
4322
4323 int
4324 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4325                     struct drm_file *file_priv)
4326 {
4327         struct drm_i915_gem_busy *args = data;
4328         struct drm_gem_object *obj;
4329         struct drm_i915_gem_object *obj_priv;
4330         drm_i915_private_t *dev_priv = dev->dev_private;
4331
4332         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
4333         if (obj == NULL) {
4334                 DRM_ERROR("Bad handle in i915_gem_busy_ioctl(): %d\n",
4335                           args->handle);
4336                 return -EBADF;
4337         }
4338
4339         mutex_lock(&dev->struct_mutex);
4340         /* Update the active list for the hardware's current position.
4341          * Otherwise this only updates on a delayed timer or when irqs are
4342          * actually unmasked, and our working set ends up being larger than
4343          * required.
4344          */
4345         i915_gem_retire_requests(dev, &dev_priv->render_ring);
4346
4347         if (HAS_BSD(dev))
4348                 i915_gem_retire_requests(dev, &dev_priv->bsd_ring);
4349
4350         obj_priv = to_intel_bo(obj);
4351         /* Don't count being on the flushing list against the object being
4352          * done.  Otherwise, a buffer left on the flushing list but not getting
4353          * flushed (because nobody's flushing that domain) won't ever return
4354          * unbusy and get reused by libdrm's bo cache.  The other expected
4355          * consumer of this interface, OpenGL's occlusion queries, also specs
4356          * that the objects get unbusy "eventually" without any interference.
4357          */
4358         args->busy = obj_priv->active && obj_priv->last_rendering_seqno != 0;
4359
4360         drm_gem_object_unreference(obj);
4361         mutex_unlock(&dev->struct_mutex);
4362         return 0;
4363 }
4364
4365 int
4366 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
4367                         struct drm_file *file_priv)
4368 {
4369     return i915_gem_ring_throttle(dev, file_priv);
4370 }
4371
4372 int
4373 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
4374                        struct drm_file *file_priv)
4375 {
4376         struct drm_i915_gem_madvise *args = data;
4377         struct drm_gem_object *obj;
4378         struct drm_i915_gem_object *obj_priv;
4379
4380         switch (args->madv) {
4381         case I915_MADV_DONTNEED:
4382         case I915_MADV_WILLNEED:
4383             break;
4384         default:
4385             return -EINVAL;
4386         }
4387
4388         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
4389         if (obj == NULL) {
4390                 DRM_ERROR("Bad handle in i915_gem_madvise_ioctl(): %d\n",
4391                           args->handle);
4392                 return -EBADF;
4393         }
4394
4395         mutex_lock(&dev->struct_mutex);
4396         obj_priv = to_intel_bo(obj);
4397
4398         if (obj_priv->pin_count) {
4399                 drm_gem_object_unreference(obj);
4400                 mutex_unlock(&dev->struct_mutex);
4401
4402                 DRM_ERROR("Attempted i915_gem_madvise_ioctl() on a pinned object\n");
4403                 return -EINVAL;
4404         }
4405
4406         if (obj_priv->madv != __I915_MADV_PURGED)
4407                 obj_priv->madv = args->madv;
4408
4409         /* if the object is no longer bound, discard its backing storage */
4410         if (i915_gem_object_is_purgeable(obj_priv) &&
4411             obj_priv->gtt_space == NULL)
4412                 i915_gem_object_truncate(obj);
4413
4414         args->retained = obj_priv->madv != __I915_MADV_PURGED;
4415
4416         drm_gem_object_unreference(obj);
4417         mutex_unlock(&dev->struct_mutex);
4418
4419         return 0;
4420 }
4421
4422 struct drm_gem_object * i915_gem_alloc_object(struct drm_device *dev,
4423                                               size_t size)
4424 {
4425         struct drm_i915_gem_object *obj;
4426
4427         obj = kzalloc(sizeof(*obj), GFP_KERNEL);
4428         if (obj == NULL)
4429                 return NULL;
4430
4431         if (drm_gem_object_init(dev, &obj->base, size) != 0) {
4432                 kfree(obj);
4433                 return NULL;
4434         }
4435
4436         obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4437         obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4438
4439         obj->agp_type = AGP_USER_MEMORY;
4440         obj->base.driver_private = NULL;
4441         obj->fence_reg = I915_FENCE_REG_NONE;
4442         INIT_LIST_HEAD(&obj->list);
4443         INIT_LIST_HEAD(&obj->gpu_write_list);
4444         obj->madv = I915_MADV_WILLNEED;
4445
4446         trace_i915_gem_object_create(&obj->base);
4447
4448         return &obj->base;
4449 }
4450
4451 int i915_gem_init_object(struct drm_gem_object *obj)
4452 {
4453         BUG();
4454
4455         return 0;
4456 }
4457
4458 void i915_gem_free_object(struct drm_gem_object *obj)
4459 {
4460         struct drm_device *dev = obj->dev;
4461         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
4462
4463         trace_i915_gem_object_destroy(obj);
4464
4465         while (obj_priv->pin_count > 0)
4466                 i915_gem_object_unpin(obj);
4467
4468         if (obj_priv->phys_obj)
4469                 i915_gem_detach_phys_object(dev, obj);
4470
4471         i915_gem_object_unbind(obj);
4472
4473         if (obj_priv->mmap_offset)
4474                 i915_gem_free_mmap_offset(obj);
4475
4476         drm_gem_object_release(obj);
4477
4478         kfree(obj_priv->page_cpu_valid);
4479         kfree(obj_priv->bit_17);
4480         kfree(obj_priv);
4481 }
4482
4483 /** Unbinds all inactive objects. */
4484 static int
4485 i915_gem_evict_from_inactive_list(struct drm_device *dev)
4486 {
4487         drm_i915_private_t *dev_priv = dev->dev_private;
4488
4489         while (!list_empty(&dev_priv->mm.inactive_list)) {
4490                 struct drm_gem_object *obj;
4491                 int ret;
4492
4493                 obj = &list_first_entry(&dev_priv->mm.inactive_list,
4494                                         struct drm_i915_gem_object,
4495                                         list)->base;
4496
4497                 ret = i915_gem_object_unbind(obj);
4498                 if (ret != 0) {
4499                         DRM_ERROR("Error unbinding object: %d\n", ret);
4500                         return ret;
4501                 }
4502         }
4503
4504         return 0;
4505 }
4506
4507 int
4508 i915_gem_idle(struct drm_device *dev)
4509 {
4510         drm_i915_private_t *dev_priv = dev->dev_private;
4511         int ret;
4512
4513         mutex_lock(&dev->struct_mutex);
4514
4515         if (dev_priv->mm.suspended ||
4516                         (dev_priv->render_ring.gem_object == NULL) ||
4517                         (HAS_BSD(dev) &&
4518                          dev_priv->bsd_ring.gem_object == NULL)) {
4519                 mutex_unlock(&dev->struct_mutex);
4520                 return 0;
4521         }
4522
4523         ret = i915_gpu_idle(dev);
4524         if (ret) {
4525                 mutex_unlock(&dev->struct_mutex);
4526                 return ret;
4527         }
4528
4529         /* Under UMS, be paranoid and evict. */
4530         if (!drm_core_check_feature(dev, DRIVER_MODESET)) {
4531                 ret = i915_gem_evict_from_inactive_list(dev);
4532                 if (ret) {
4533                         mutex_unlock(&dev->struct_mutex);
4534                         return ret;
4535                 }
4536         }
4537
4538         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
4539          * We need to replace this with a semaphore, or something.
4540          * And not confound mm.suspended!
4541          */
4542         dev_priv->mm.suspended = 1;
4543         del_timer(&dev_priv->hangcheck_timer);
4544
4545         i915_kernel_lost_context(dev);
4546         i915_gem_cleanup_ringbuffer(dev);
4547
4548         mutex_unlock(&dev->struct_mutex);
4549
4550         /* Cancel the retire work handler, which should be idle now. */
4551         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
4552
4553         return 0;
4554 }
4555
4556 /*
4557  * 965+ support PIPE_CONTROL commands, which provide finer grained control
4558  * over cache flushing.
4559  */
4560 static int
4561 i915_gem_init_pipe_control(struct drm_device *dev)
4562 {
4563         drm_i915_private_t *dev_priv = dev->dev_private;
4564         struct drm_gem_object *obj;
4565         struct drm_i915_gem_object *obj_priv;
4566         int ret;
4567
4568         obj = i915_gem_alloc_object(dev, 4096);
4569         if (obj == NULL) {
4570                 DRM_ERROR("Failed to allocate seqno page\n");
4571                 ret = -ENOMEM;
4572                 goto err;
4573         }
4574         obj_priv = to_intel_bo(obj);
4575         obj_priv->agp_type = AGP_USER_CACHED_MEMORY;
4576
4577         ret = i915_gem_object_pin(obj, 4096);
4578         if (ret)
4579                 goto err_unref;
4580
4581         dev_priv->seqno_gfx_addr = obj_priv->gtt_offset;
4582         dev_priv->seqno_page =  kmap(obj_priv->pages[0]);
4583         if (dev_priv->seqno_page == NULL)
4584                 goto err_unpin;
4585
4586         dev_priv->seqno_obj = obj;
4587         memset(dev_priv->seqno_page, 0, PAGE_SIZE);
4588
4589         return 0;
4590
4591 err_unpin:
4592         i915_gem_object_unpin(obj);
4593 err_unref:
4594         drm_gem_object_unreference(obj);
4595 err:
4596         return ret;
4597 }
4598
4599
4600 static void
4601 i915_gem_cleanup_pipe_control(struct drm_device *dev)
4602 {
4603         drm_i915_private_t *dev_priv = dev->dev_private;
4604         struct drm_gem_object *obj;
4605         struct drm_i915_gem_object *obj_priv;
4606
4607         obj = dev_priv->seqno_obj;
4608         obj_priv = to_intel_bo(obj);
4609         kunmap(obj_priv->pages[0]);
4610         i915_gem_object_unpin(obj);
4611         drm_gem_object_unreference(obj);
4612         dev_priv->seqno_obj = NULL;
4613
4614         dev_priv->seqno_page = NULL;
4615 }
4616
4617 int
4618 i915_gem_init_ringbuffer(struct drm_device *dev)
4619 {
4620         drm_i915_private_t *dev_priv = dev->dev_private;
4621         int ret;
4622         dev_priv->render_ring = render_ring;
4623         if (!I915_NEED_GFX_HWS(dev)) {
4624                 dev_priv->render_ring.status_page.page_addr
4625                         = dev_priv->status_page_dmah->vaddr;
4626                 memset(dev_priv->render_ring.status_page.page_addr,
4627                                 0, PAGE_SIZE);
4628         }
4629         if (HAS_PIPE_CONTROL(dev)) {
4630                 ret = i915_gem_init_pipe_control(dev);
4631                 if (ret)
4632                         return ret;
4633         }
4634         ret = intel_init_ring_buffer(dev, &dev_priv->render_ring);
4635         if (!ret && HAS_BSD(dev)) {
4636                 dev_priv->bsd_ring = bsd_ring;
4637                 ret = intel_init_ring_buffer(dev, &dev_priv->bsd_ring);
4638         }
4639         return ret;
4640 }
4641
4642 void
4643 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
4644 {
4645         drm_i915_private_t *dev_priv = dev->dev_private;
4646
4647         intel_cleanup_ring_buffer(dev, &dev_priv->render_ring);
4648         if (HAS_BSD(dev))
4649                 intel_cleanup_ring_buffer(dev, &dev_priv->bsd_ring);
4650         if (HAS_PIPE_CONTROL(dev))
4651                 i915_gem_cleanup_pipe_control(dev);
4652 }
4653
4654 int
4655 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
4656                        struct drm_file *file_priv)
4657 {
4658         drm_i915_private_t *dev_priv = dev->dev_private;
4659         int ret;
4660
4661         if (drm_core_check_feature(dev, DRIVER_MODESET))
4662                 return 0;
4663
4664         if (atomic_read(&dev_priv->mm.wedged)) {
4665                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
4666                 atomic_set(&dev_priv->mm.wedged, 0);
4667         }
4668
4669         mutex_lock(&dev->struct_mutex);
4670         dev_priv->mm.suspended = 0;
4671
4672         ret = i915_gem_init_ringbuffer(dev);
4673         if (ret != 0) {
4674                 mutex_unlock(&dev->struct_mutex);
4675                 return ret;
4676         }
4677
4678         spin_lock(&dev_priv->mm.active_list_lock);
4679         BUG_ON(!list_empty(&dev_priv->render_ring.active_list));
4680         BUG_ON(HAS_BSD(dev) && !list_empty(&dev_priv->bsd_ring.active_list));
4681         spin_unlock(&dev_priv->mm.active_list_lock);
4682
4683         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
4684         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
4685         BUG_ON(!list_empty(&dev_priv->render_ring.request_list));
4686         BUG_ON(HAS_BSD(dev) && !list_empty(&dev_priv->bsd_ring.request_list));
4687         mutex_unlock(&dev->struct_mutex);
4688
4689         drm_irq_install(dev);
4690
4691         return 0;
4692 }
4693
4694 int
4695 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
4696                        struct drm_file *file_priv)
4697 {
4698         if (drm_core_check_feature(dev, DRIVER_MODESET))
4699                 return 0;
4700
4701         drm_irq_uninstall(dev);
4702         return i915_gem_idle(dev);
4703 }
4704
4705 void
4706 i915_gem_lastclose(struct drm_device *dev)
4707 {
4708         int ret;
4709
4710         if (drm_core_check_feature(dev, DRIVER_MODESET))
4711                 return;
4712
4713         ret = i915_gem_idle(dev);
4714         if (ret)
4715                 DRM_ERROR("failed to idle hardware: %d\n", ret);
4716 }
4717
4718 void
4719 i915_gem_load(struct drm_device *dev)
4720 {
4721         int i;
4722         drm_i915_private_t *dev_priv = dev->dev_private;
4723
4724         spin_lock_init(&dev_priv->mm.active_list_lock);
4725         INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
4726         INIT_LIST_HEAD(&dev_priv->mm.gpu_write_list);
4727         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
4728         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
4729         INIT_LIST_HEAD(&dev_priv->render_ring.active_list);
4730         INIT_LIST_HEAD(&dev_priv->render_ring.request_list);
4731         if (HAS_BSD(dev)) {
4732                 INIT_LIST_HEAD(&dev_priv->bsd_ring.active_list);
4733                 INIT_LIST_HEAD(&dev_priv->bsd_ring.request_list);
4734         }
4735         for (i = 0; i < 16; i++)
4736                 INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
4737         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
4738                           i915_gem_retire_work_handler);
4739         spin_lock(&shrink_list_lock);
4740         list_add(&dev_priv->mm.shrink_list, &shrink_list);
4741         spin_unlock(&shrink_list_lock);
4742
4743         /* Old X drivers will take 0-2 for front, back, depth buffers */
4744         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4745                 dev_priv->fence_reg_start = 3;
4746
4747         if (IS_I965G(dev) || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4748                 dev_priv->num_fence_regs = 16;
4749         else
4750                 dev_priv->num_fence_regs = 8;
4751
4752         /* Initialize fence registers to zero */
4753         if (IS_I965G(dev)) {
4754                 for (i = 0; i < 16; i++)
4755                         I915_WRITE64(FENCE_REG_965_0 + (i * 8), 0);
4756         } else {
4757                 for (i = 0; i < 8; i++)
4758                         I915_WRITE(FENCE_REG_830_0 + (i * 4), 0);
4759                 if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4760                         for (i = 0; i < 8; i++)
4761                                 I915_WRITE(FENCE_REG_945_8 + (i * 4), 0);
4762         }
4763         i915_gem_detect_bit_6_swizzle(dev);
4764         init_waitqueue_head(&dev_priv->pending_flip_queue);
4765 }
4766
4767 /*
4768  * Create a physically contiguous memory object for this object
4769  * e.g. for cursor + overlay regs
4770  */
4771 int i915_gem_init_phys_object(struct drm_device *dev,
4772                               int id, int size)
4773 {
4774         drm_i915_private_t *dev_priv = dev->dev_private;
4775         struct drm_i915_gem_phys_object *phys_obj;
4776         int ret;
4777
4778         if (dev_priv->mm.phys_objs[id - 1] || !size)
4779                 return 0;
4780
4781         phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
4782         if (!phys_obj)
4783                 return -ENOMEM;
4784
4785         phys_obj->id = id;
4786
4787         phys_obj->handle = drm_pci_alloc(dev, size, 0);
4788         if (!phys_obj->handle) {
4789                 ret = -ENOMEM;
4790                 goto kfree_obj;
4791         }
4792 #ifdef CONFIG_X86
4793         set_memory_wc((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
4794 #endif
4795
4796         dev_priv->mm.phys_objs[id - 1] = phys_obj;
4797
4798         return 0;
4799 kfree_obj:
4800         kfree(phys_obj);
4801         return ret;
4802 }
4803
4804 void i915_gem_free_phys_object(struct drm_device *dev, int id)
4805 {
4806         drm_i915_private_t *dev_priv = dev->dev_private;
4807         struct drm_i915_gem_phys_object *phys_obj;
4808
4809         if (!dev_priv->mm.phys_objs[id - 1])
4810                 return;
4811
4812         phys_obj = dev_priv->mm.phys_objs[id - 1];
4813         if (phys_obj->cur_obj) {
4814                 i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
4815         }
4816
4817 #ifdef CONFIG_X86
4818         set_memory_wb((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
4819 #endif
4820         drm_pci_free(dev, phys_obj->handle);
4821         kfree(phys_obj);
4822         dev_priv->mm.phys_objs[id - 1] = NULL;
4823 }
4824
4825 void i915_gem_free_all_phys_object(struct drm_device *dev)
4826 {
4827         int i;
4828
4829         for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
4830                 i915_gem_free_phys_object(dev, i);
4831 }
4832
4833 void i915_gem_detach_phys_object(struct drm_device *dev,
4834                                  struct drm_gem_object *obj)
4835 {
4836         struct drm_i915_gem_object *obj_priv;
4837         int i;
4838         int ret;
4839         int page_count;
4840
4841         obj_priv = to_intel_bo(obj);
4842         if (!obj_priv->phys_obj)
4843                 return;
4844
4845         ret = i915_gem_object_get_pages(obj, 0);
4846         if (ret)
4847                 goto out;
4848
4849         page_count = obj->size / PAGE_SIZE;
4850
4851         for (i = 0; i < page_count; i++) {
4852                 char *dst = kmap_atomic(obj_priv->pages[i], KM_USER0);
4853                 char *src = obj_priv->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4854
4855                 memcpy(dst, src, PAGE_SIZE);
4856                 kunmap_atomic(dst, KM_USER0);
4857         }
4858         drm_clflush_pages(obj_priv->pages, page_count);
4859         drm_agp_chipset_flush(dev);
4860
4861         i915_gem_object_put_pages(obj);
4862 out:
4863         obj_priv->phys_obj->cur_obj = NULL;
4864         obj_priv->phys_obj = NULL;
4865 }
4866
4867 int
4868 i915_gem_attach_phys_object(struct drm_device *dev,
4869                             struct drm_gem_object *obj, int id)
4870 {
4871         drm_i915_private_t *dev_priv = dev->dev_private;
4872         struct drm_i915_gem_object *obj_priv;
4873         int ret = 0;
4874         int page_count;
4875         int i;
4876
4877         if (id > I915_MAX_PHYS_OBJECT)
4878                 return -EINVAL;
4879
4880         obj_priv = to_intel_bo(obj);
4881
4882         if (obj_priv->phys_obj) {
4883                 if (obj_priv->phys_obj->id == id)
4884                         return 0;
4885                 i915_gem_detach_phys_object(dev, obj);
4886         }
4887
4888
4889         /* create a new object */
4890         if (!dev_priv->mm.phys_objs[id - 1]) {
4891                 ret = i915_gem_init_phys_object(dev, id,
4892                                                 obj->size);
4893                 if (ret) {
4894                         DRM_ERROR("failed to init phys object %d size: %zu\n", id, obj->size);
4895                         goto out;
4896                 }
4897         }
4898
4899         /* bind to the object */
4900         obj_priv->phys_obj = dev_priv->mm.phys_objs[id - 1];
4901         obj_priv->phys_obj->cur_obj = obj;
4902
4903         ret = i915_gem_object_get_pages(obj, 0);
4904         if (ret) {
4905                 DRM_ERROR("failed to get page list\n");
4906                 goto out;
4907         }
4908
4909         page_count = obj->size / PAGE_SIZE;
4910
4911         for (i = 0; i < page_count; i++) {
4912                 char *src = kmap_atomic(obj_priv->pages[i], KM_USER0);
4913                 char *dst = obj_priv->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4914
4915                 memcpy(dst, src, PAGE_SIZE);
4916                 kunmap_atomic(src, KM_USER0);
4917         }
4918
4919         i915_gem_object_put_pages(obj);
4920
4921         return 0;
4922 out:
4923         return ret;
4924 }
4925
4926 static int
4927 i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
4928                      struct drm_i915_gem_pwrite *args,
4929                      struct drm_file *file_priv)
4930 {
4931         struct drm_i915_gem_object *obj_priv = to_intel_bo(obj);
4932         void *obj_addr;
4933         int ret;
4934         char __user *user_data;
4935
4936         user_data = (char __user *) (uintptr_t) args->data_ptr;
4937         obj_addr = obj_priv->phys_obj->handle->vaddr + args->offset;
4938
4939         DRM_DEBUG_DRIVER("obj_addr %p, %lld\n", obj_addr, args->size);
4940         ret = copy_from_user(obj_addr, user_data, args->size);
4941         if (ret)
4942                 return -EFAULT;
4943
4944         drm_agp_chipset_flush(dev);
4945         return 0;
4946 }
4947
4948 void i915_gem_release(struct drm_device * dev, struct drm_file *file_priv)
4949 {
4950         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
4951
4952         /* Clean up our request list when the client is going away, so that
4953          * later retire_requests won't dereference our soon-to-be-gone
4954          * file_priv.
4955          */
4956         mutex_lock(&dev->struct_mutex);
4957         while (!list_empty(&i915_file_priv->mm.request_list))
4958                 list_del_init(i915_file_priv->mm.request_list.next);
4959         mutex_unlock(&dev->struct_mutex);
4960 }
4961
4962 static int
4963 i915_gpu_is_active(struct drm_device *dev)
4964 {
4965         drm_i915_private_t *dev_priv = dev->dev_private;
4966         int lists_empty;
4967
4968         spin_lock(&dev_priv->mm.active_list_lock);
4969         lists_empty = list_empty(&dev_priv->mm.flushing_list) &&
4970                       list_empty(&dev_priv->render_ring.active_list);
4971         if (HAS_BSD(dev))
4972                 lists_empty &= list_empty(&dev_priv->bsd_ring.active_list);
4973         spin_unlock(&dev_priv->mm.active_list_lock);
4974
4975         return !lists_empty;
4976 }
4977
4978 static int
4979 i915_gem_shrink(int nr_to_scan, gfp_t gfp_mask)
4980 {
4981         drm_i915_private_t *dev_priv, *next_dev;
4982         struct drm_i915_gem_object *obj_priv, *next_obj;
4983         int cnt = 0;
4984         int would_deadlock = 1;
4985
4986         /* "fast-path" to count number of available objects */
4987         if (nr_to_scan == 0) {
4988                 spin_lock(&shrink_list_lock);
4989                 list_for_each_entry(dev_priv, &shrink_list, mm.shrink_list) {
4990                         struct drm_device *dev = dev_priv->dev;
4991
4992                         if (mutex_trylock(&dev->struct_mutex)) {
4993                                 list_for_each_entry(obj_priv,
4994                                                     &dev_priv->mm.inactive_list,
4995                                                     list)
4996                                         cnt++;
4997                                 mutex_unlock(&dev->struct_mutex);
4998                         }
4999                 }
5000                 spin_unlock(&shrink_list_lock);
5001
5002                 return (cnt / 100) * sysctl_vfs_cache_pressure;
5003         }
5004
5005         spin_lock(&shrink_list_lock);
5006
5007 rescan:
5008         /* first scan for clean buffers */
5009         list_for_each_entry_safe(dev_priv, next_dev,
5010                                  &shrink_list, mm.shrink_list) {
5011                 struct drm_device *dev = dev_priv->dev;
5012
5013                 if (! mutex_trylock(&dev->struct_mutex))
5014                         continue;
5015
5016                 spin_unlock(&shrink_list_lock);
5017                 i915_gem_retire_requests(dev, &dev_priv->render_ring);
5018
5019                 if (HAS_BSD(dev))
5020                         i915_gem_retire_requests(dev, &dev_priv->bsd_ring);
5021
5022                 list_for_each_entry_safe(obj_priv, next_obj,
5023                                          &dev_priv->mm.inactive_list,
5024                                          list) {
5025                         if (i915_gem_object_is_purgeable(obj_priv)) {
5026                                 i915_gem_object_unbind(&obj_priv->base);
5027                                 if (--nr_to_scan <= 0)
5028                                         break;
5029                         }
5030                 }
5031
5032                 spin_lock(&shrink_list_lock);
5033                 mutex_unlock(&dev->struct_mutex);
5034
5035                 would_deadlock = 0;
5036
5037                 if (nr_to_scan <= 0)
5038                         break;
5039         }
5040
5041         /* second pass, evict/count anything still on the inactive list */
5042         list_for_each_entry_safe(dev_priv, next_dev,
5043                                  &shrink_list, mm.shrink_list) {
5044                 struct drm_device *dev = dev_priv->dev;
5045
5046                 if (! mutex_trylock(&dev->struct_mutex))
5047                         continue;
5048
5049                 spin_unlock(&shrink_list_lock);
5050
5051                 list_for_each_entry_safe(obj_priv, next_obj,
5052                                          &dev_priv->mm.inactive_list,
5053                                          list) {
5054                         if (nr_to_scan > 0) {
5055                                 i915_gem_object_unbind(&obj_priv->base);
5056                                 nr_to_scan--;
5057                         } else
5058                                 cnt++;
5059                 }
5060
5061                 spin_lock(&shrink_list_lock);
5062                 mutex_unlock(&dev->struct_mutex);
5063
5064                 would_deadlock = 0;
5065         }
5066
5067         if (nr_to_scan) {
5068                 int active = 0;
5069
5070                 /*
5071                  * We are desperate for pages, so as a last resort, wait
5072                  * for the GPU to finish and discard whatever we can.
5073                  * This has a dramatic impact to reduce the number of
5074                  * OOM-killer events whilst running the GPU aggressively.
5075                  */
5076                 list_for_each_entry(dev_priv, &shrink_list, mm.shrink_list) {
5077                         struct drm_device *dev = dev_priv->dev;
5078
5079                         if (!mutex_trylock(&dev->struct_mutex))
5080                                 continue;
5081
5082                         spin_unlock(&shrink_list_lock);
5083
5084                         if (i915_gpu_is_active(dev)) {
5085                                 i915_gpu_idle(dev);
5086                                 active++;
5087                         }
5088
5089                         spin_lock(&shrink_list_lock);
5090                         mutex_unlock(&dev->struct_mutex);
5091                 }
5092
5093                 if (active)
5094                         goto rescan;
5095         }
5096
5097         spin_unlock(&shrink_list_lock);
5098
5099         if (would_deadlock)
5100                 return -1;
5101         else if (cnt > 0)
5102                 return (cnt / 100) * sysctl_vfs_cache_pressure;
5103         else
5104                 return 0;
5105 }
5106
5107 static struct shrinker shrinker = {
5108         .shrink = i915_gem_shrink,
5109         .seeks = DEFAULT_SEEKS,
5110 };
5111
5112 __init void
5113 i915_gem_shrinker_init(void)
5114 {
5115     register_shrinker(&shrinker);
5116 }
5117
5118 __exit void
5119 i915_gem_shrinker_exit(void)
5120 {
5121     unregister_shrinker(&shrinker);
5122 }