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