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