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