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