Update to 3.4-rc4.
[linux-flexiantxendom0-3.2.10.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/shmem_fs.h>
35 #include <linux/slab.h>
36 #include <linux/swap.h>
37 #include <linux/pci.h>
38
39 static __must_check int i915_gem_object_flush_gpu_write_domain(struct drm_i915_gem_object *obj);
40 static void i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj);
41 static void i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj);
42 static __must_check int i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj,
43                                                           bool write);
44 static __must_check int i915_gem_object_set_cpu_read_domain_range(struct drm_i915_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_i915_gem_object *obj);
48 static __must_check int i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
49                                                     unsigned alignment,
50                                                     bool map_and_fenceable);
51 static void i915_gem_clear_fence_reg(struct drm_device *dev,
52                                      struct drm_i915_fence_reg *reg);
53 static int i915_gem_phys_pwrite(struct drm_device *dev,
54                                 struct drm_i915_gem_object *obj,
55                                 struct drm_i915_gem_pwrite *args,
56                                 struct drm_file *file);
57 static void i915_gem_free_object_tail(struct drm_i915_gem_object *obj);
58
59 static int i915_gem_inactive_shrink(struct shrinker *shrinker,
60                                     struct shrink_control *sc);
61 static void i915_gem_object_truncate(struct drm_i915_gem_object *obj);
62
63 /* some bookkeeping */
64 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
65                                   size_t size)
66 {
67         dev_priv->mm.object_count++;
68         dev_priv->mm.object_memory += size;
69 }
70
71 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
72                                      size_t size)
73 {
74         dev_priv->mm.object_count--;
75         dev_priv->mm.object_memory -= size;
76 }
77
78 static int
79 i915_gem_wait_for_error(struct drm_device *dev)
80 {
81         struct drm_i915_private *dev_priv = dev->dev_private;
82         struct completion *x = &dev_priv->error_completion;
83         unsigned long flags;
84         int ret;
85
86         if (!atomic_read(&dev_priv->mm.wedged))
87                 return 0;
88
89         ret = wait_for_completion_interruptible(x);
90         if (ret)
91                 return ret;
92
93         if (atomic_read(&dev_priv->mm.wedged)) {
94                 /* GPU is hung, bump the completion count to account for
95                  * the token we just consumed so that we never hit zero and
96                  * end up waiting upon a subsequent completion event that
97                  * will never happen.
98                  */
99                 spin_lock_irqsave(&x->wait.lock, flags);
100                 x->done++;
101                 spin_unlock_irqrestore(&x->wait.lock, flags);
102         }
103         return 0;
104 }
105
106 int i915_mutex_lock_interruptible(struct drm_device *dev)
107 {
108         int ret;
109
110         ret = i915_gem_wait_for_error(dev);
111         if (ret)
112                 return ret;
113
114         ret = mutex_lock_interruptible(&dev->struct_mutex);
115         if (ret)
116                 return ret;
117
118         WARN_ON(i915_verify_lists(dev));
119         return 0;
120 }
121
122 static inline bool
123 i915_gem_object_is_inactive(struct drm_i915_gem_object *obj)
124 {
125         return obj->gtt_space && !obj->active && obj->pin_count == 0;
126 }
127
128 void i915_gem_do_init(struct drm_device *dev,
129                       unsigned long start,
130                       unsigned long mappable_end,
131                       unsigned long end)
132 {
133         drm_i915_private_t *dev_priv = dev->dev_private;
134
135         drm_mm_init(&dev_priv->mm.gtt_space, start, end - start);
136
137         dev_priv->mm.gtt_start = start;
138         dev_priv->mm.gtt_mappable_end = mappable_end;
139         dev_priv->mm.gtt_end = end;
140         dev_priv->mm.gtt_total = end - start;
141         dev_priv->mm.mappable_gtt_total = min(end, mappable_end) - start;
142
143         /* Take over this portion of the GTT */
144         intel_gtt_clear_range(start / PAGE_SIZE, (end-start) / PAGE_SIZE);
145 }
146
147 int
148 i915_gem_init_ioctl(struct drm_device *dev, void *data,
149                     struct drm_file *file)
150 {
151         struct drm_i915_gem_init *args = data;
152
153         if (args->gtt_start >= args->gtt_end ||
154             (args->gtt_end | args->gtt_start) & (PAGE_SIZE - 1))
155                 return -EINVAL;
156
157         mutex_lock(&dev->struct_mutex);
158         i915_gem_do_init(dev, args->gtt_start, args->gtt_end, args->gtt_end);
159         mutex_unlock(&dev->struct_mutex);
160
161         return 0;
162 }
163
164 int
165 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
166                             struct drm_file *file)
167 {
168         struct drm_i915_private *dev_priv = dev->dev_private;
169         struct drm_i915_gem_get_aperture *args = data;
170         struct drm_i915_gem_object *obj;
171         size_t pinned;
172
173         if (!(dev->driver->driver_features & DRIVER_GEM))
174                 return -ENODEV;
175
176         pinned = 0;
177         mutex_lock(&dev->struct_mutex);
178         list_for_each_entry(obj, &dev_priv->mm.pinned_list, mm_list)
179                 pinned += obj->gtt_space->size;
180         mutex_unlock(&dev->struct_mutex);
181
182         args->aper_size = dev_priv->mm.gtt_total;
183         args->aper_available_size = args->aper_size - pinned;
184
185         return 0;
186 }
187
188 static int
189 i915_gem_create(struct drm_file *file,
190                 struct drm_device *dev,
191                 uint64_t size,
192                 uint32_t *handle_p)
193 {
194         struct drm_i915_gem_object *obj;
195         int ret;
196         u32 handle;
197
198         size = roundup(size, PAGE_SIZE);
199         if (size == 0)
200                 return -EINVAL;
201
202         /* Allocate the new object */
203         obj = i915_gem_alloc_object(dev, size);
204         if (obj == NULL)
205                 return -ENOMEM;
206
207         ret = drm_gem_handle_create(file, &obj->base, &handle);
208         if (ret) {
209                 drm_gem_object_release(&obj->base);
210                 i915_gem_info_remove_obj(dev->dev_private, obj->base.size);
211                 kfree(obj);
212                 return ret;
213         }
214
215         /* drop reference from allocate - handle holds it now */
216         drm_gem_object_unreference(&obj->base);
217         trace_i915_gem_object_create(obj);
218
219         *handle_p = handle;
220         return 0;
221 }
222
223 int
224 i915_gem_dumb_create(struct drm_file *file,
225                      struct drm_device *dev,
226                      struct drm_mode_create_dumb *args)
227 {
228         /* have to work out size/pitch and return them */
229         args->pitch = ALIGN(args->width * ((args->bpp + 7) / 8), 64);
230         args->size = args->pitch * args->height;
231         return i915_gem_create(file, dev,
232                                args->size, &args->handle);
233 }
234
235 int i915_gem_dumb_destroy(struct drm_file *file,
236                           struct drm_device *dev,
237                           uint32_t handle)
238 {
239         return drm_gem_handle_delete(file, handle);
240 }
241
242 /**
243  * Creates a new mm object and returns a handle to it.
244  */
245 int
246 i915_gem_create_ioctl(struct drm_device *dev, void *data,
247                       struct drm_file *file)
248 {
249         struct drm_i915_gem_create *args = data;
250         return i915_gem_create(file, dev,
251                                args->size, &args->handle);
252 }
253
254 static int i915_gem_object_needs_bit17_swizzle(struct drm_i915_gem_object *obj)
255 {
256         drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
257
258         return dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_9_10_17 &&
259                 obj->tiling_mode != I915_TILING_NONE;
260 }
261
262 /**
263  * This is the fast shmem pread path, which attempts to copy_from_user directly
264  * from the backing pages of the object to the user's address space.  On a
265  * fault, it fails so we can fall back to i915_gem_shmem_pwrite_slow().
266  */
267 static int
268 i915_gem_shmem_pread_fast(struct drm_device *dev,
269                           struct drm_i915_gem_object *obj,
270                           struct drm_i915_gem_pread *args,
271                           struct drm_file *file)
272 {
273         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
274         ssize_t remain;
275         loff_t offset;
276         char __user *user_data;
277         int page_offset, page_length;
278
279         user_data = (char __user *) (uintptr_t) args->data_ptr;
280         remain = args->size;
281
282         offset = args->offset;
283
284         while (remain > 0) {
285                 struct page *page;
286                 char *vaddr;
287                 int ret;
288
289                 /* Operation in this page
290                  *
291                  * page_offset = offset within page
292                  * page_length = bytes to copy for this page
293                  */
294                 page_offset = offset_in_page(offset);
295                 page_length = remain;
296                 if ((page_offset + remain) > PAGE_SIZE)
297                         page_length = PAGE_SIZE - page_offset;
298
299                 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
300                 if (IS_ERR(page))
301                         return PTR_ERR(page);
302
303                 vaddr = kmap_atomic(page);
304                 ret = __copy_to_user_inatomic(user_data,
305                                               vaddr + page_offset,
306                                               page_length);
307                 kunmap_atomic(vaddr);
308
309                 mark_page_accessed(page);
310                 page_cache_release(page);
311                 if (ret)
312                         return -EFAULT;
313
314                 remain -= page_length;
315                 user_data += page_length;
316                 offset += page_length;
317         }
318
319         return 0;
320 }
321
322 static inline int
323 __copy_to_user_swizzled(char __user *cpu_vaddr,
324                         const char *gpu_vaddr, int gpu_offset,
325                         int length)
326 {
327         int ret, cpu_offset = 0;
328
329         while (length > 0) {
330                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
331                 int this_length = min(cacheline_end - gpu_offset, length);
332                 int swizzled_gpu_offset = gpu_offset ^ 64;
333
334                 ret = __copy_to_user(cpu_vaddr + cpu_offset,
335                                      gpu_vaddr + swizzled_gpu_offset,
336                                      this_length);
337                 if (ret)
338                         return ret + length;
339
340                 cpu_offset += this_length;
341                 gpu_offset += this_length;
342                 length -= this_length;
343         }
344
345         return 0;
346 }
347
348 static inline int
349 __copy_from_user_swizzled(char __user *gpu_vaddr, int gpu_offset,
350                           const char *cpu_vaddr,
351                           int length)
352 {
353         int ret, cpu_offset = 0;
354
355         while (length > 0) {
356                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
357                 int this_length = min(cacheline_end - gpu_offset, length);
358                 int swizzled_gpu_offset = gpu_offset ^ 64;
359
360                 ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
361                                        cpu_vaddr + cpu_offset,
362                                        this_length);
363                 if (ret)
364                         return ret + length;
365
366                 cpu_offset += this_length;
367                 gpu_offset += this_length;
368                 length -= this_length;
369         }
370
371         return 0;
372 }
373
374 /**
375  * This is the fallback shmem pread path, which allocates temporary storage
376  * in kernel space to copy_to_user into outside of the struct_mutex, so we
377  * can copy out of the object's backing pages while holding the struct mutex
378  * and not take page faults.
379  */
380 static int
381 i915_gem_shmem_pread_slow(struct drm_device *dev,
382                           struct drm_i915_gem_object *obj,
383                           struct drm_i915_gem_pread *args,
384                           struct drm_file *file)
385 {
386         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
387         char __user *user_data;
388         ssize_t remain;
389         loff_t offset;
390         int shmem_page_offset, page_length, ret;
391         int obj_do_bit17_swizzling, page_do_bit17_swizzling;
392
393         user_data = (char __user *) (uintptr_t) args->data_ptr;
394         remain = args->size;
395
396         obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
397
398         offset = args->offset;
399
400         mutex_unlock(&dev->struct_mutex);
401
402         while (remain > 0) {
403                 struct page *page;
404                 char *vaddr;
405
406                 /* Operation in this page
407                  *
408                  * shmem_page_offset = offset within page in shmem file
409                  * page_length = bytes to copy for this page
410                  */
411                 shmem_page_offset = offset_in_page(offset);
412                 page_length = remain;
413                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
414                         page_length = PAGE_SIZE - shmem_page_offset;
415
416                 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
417                 if (IS_ERR(page)) {
418                         ret = PTR_ERR(page);
419                         goto out;
420                 }
421
422                 page_do_bit17_swizzling = obj_do_bit17_swizzling &&
423                         (page_to_phys(page) & (1 << 17)) != 0;
424
425                 vaddr = kmap(page);
426                 if (page_do_bit17_swizzling)
427                         ret = __copy_to_user_swizzled(user_data,
428                                                       vaddr, shmem_page_offset,
429                                                       page_length);
430                 else
431                         ret = __copy_to_user(user_data,
432                                              vaddr + shmem_page_offset,
433                                              page_length);
434                 kunmap(page);
435
436                 mark_page_accessed(page);
437                 page_cache_release(page);
438
439                 if (ret) {
440                         ret = -EFAULT;
441                         goto out;
442                 }
443
444                 remain -= page_length;
445                 user_data += page_length;
446                 offset += page_length;
447         }
448
449 out:
450         mutex_lock(&dev->struct_mutex);
451         /* Fixup: Kill any reinstated backing storage pages */
452         if (obj->madv == __I915_MADV_PURGED)
453                 i915_gem_object_truncate(obj);
454
455         return ret;
456 }
457
458 /**
459  * Reads data from the object referenced by handle.
460  *
461  * On error, the contents of *data are undefined.
462  */
463 int
464 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
465                      struct drm_file *file)
466 {
467         struct drm_i915_gem_pread *args = data;
468         struct drm_i915_gem_object *obj;
469         int ret = 0;
470
471         if (args->size == 0)
472                 return 0;
473
474         if (!access_ok(VERIFY_WRITE,
475                        (char __user *)(uintptr_t)args->data_ptr,
476                        args->size))
477                 return -EFAULT;
478
479         ret = fault_in_pages_writeable((char __user *)(uintptr_t)args->data_ptr,
480                                        args->size);
481         if (ret)
482                 return -EFAULT;
483
484         ret = i915_mutex_lock_interruptible(dev);
485         if (ret)
486                 return ret;
487
488         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
489         if (&obj->base == NULL) {
490                 ret = -ENOENT;
491                 goto unlock;
492         }
493
494         /* Bounds check source.  */
495         if (args->offset > obj->base.size ||
496             args->size > obj->base.size - args->offset) {
497                 ret = -EINVAL;
498                 goto out;
499         }
500
501         trace_i915_gem_object_pread(obj, args->offset, args->size);
502
503         ret = i915_gem_object_set_cpu_read_domain_range(obj,
504                                                         args->offset,
505                                                         args->size);
506         if (ret)
507                 goto out;
508
509         ret = -EFAULT;
510         if (!i915_gem_object_needs_bit17_swizzle(obj))
511                 ret = i915_gem_shmem_pread_fast(dev, obj, args, file);
512         if (ret == -EFAULT)
513                 ret = i915_gem_shmem_pread_slow(dev, obj, args, file);
514
515 out:
516         drm_gem_object_unreference(&obj->base);
517 unlock:
518         mutex_unlock(&dev->struct_mutex);
519         return ret;
520 }
521
522 /* This is the fast write path which cannot handle
523  * page faults in the source data
524  */
525
526 static inline int
527 fast_user_write(struct io_mapping *mapping,
528                 loff_t page_base, int page_offset,
529                 char __user *user_data,
530                 int length)
531 {
532         char *vaddr_atomic;
533         unsigned long unwritten;
534
535         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
536         unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
537                                                       user_data, length);
538         io_mapping_unmap_atomic(vaddr_atomic);
539         return unwritten;
540 }
541
542 /* Here's the write path which can sleep for
543  * page faults
544  */
545
546 static inline void
547 slow_kernel_write(struct io_mapping *mapping,
548                   loff_t gtt_base, int gtt_offset,
549                   struct page *user_page, int user_offset,
550                   int length)
551 {
552         char __iomem *dst_vaddr;
553         char *src_vaddr;
554
555         dst_vaddr = io_mapping_map_wc(mapping, gtt_base);
556         src_vaddr = kmap(user_page);
557
558         memcpy_toio(dst_vaddr + gtt_offset,
559                     src_vaddr + user_offset,
560                     length);
561
562         kunmap(user_page);
563         io_mapping_unmap(dst_vaddr);
564 }
565
566 /**
567  * This is the fast pwrite path, where we copy the data directly from the
568  * user into the GTT, uncached.
569  */
570 static int
571 i915_gem_gtt_pwrite_fast(struct drm_device *dev,
572                          struct drm_i915_gem_object *obj,
573                          struct drm_i915_gem_pwrite *args,
574                          struct drm_file *file)
575 {
576         drm_i915_private_t *dev_priv = dev->dev_private;
577         ssize_t remain;
578         loff_t offset, page_base;
579         char __user *user_data;
580         int page_offset, page_length;
581
582         user_data = (char __user *) (uintptr_t) args->data_ptr;
583         remain = args->size;
584
585         offset = obj->gtt_offset + args->offset;
586
587         while (remain > 0) {
588                 /* Operation in this page
589                  *
590                  * page_base = page offset within aperture
591                  * page_offset = offset within page
592                  * page_length = bytes to copy for this page
593                  */
594                 page_base = offset & PAGE_MASK;
595                 page_offset = offset_in_page(offset);
596                 page_length = remain;
597                 if ((page_offset + remain) > PAGE_SIZE)
598                         page_length = PAGE_SIZE - page_offset;
599
600                 /* If we get a fault while copying data, then (presumably) our
601                  * source page isn't available.  Return the error and we'll
602                  * retry in the slow path.
603                  */
604                 if (fast_user_write(dev_priv->mm.gtt_mapping, page_base,
605                                     page_offset, user_data, page_length))
606                         return -EFAULT;
607
608                 remain -= page_length;
609                 user_data += page_length;
610                 offset += page_length;
611         }
612
613         return 0;
614 }
615
616 /**
617  * This is the fallback GTT pwrite path, which uses get_user_pages to pin
618  * the memory and maps it using kmap_atomic for copying.
619  *
620  * This code resulted in x11perf -rgb10text consuming about 10% more CPU
621  * than using i915_gem_gtt_pwrite_fast on a G45 (32-bit).
622  */
623 static int
624 i915_gem_gtt_pwrite_slow(struct drm_device *dev,
625                          struct drm_i915_gem_object *obj,
626                          struct drm_i915_gem_pwrite *args,
627                          struct drm_file *file)
628 {
629         drm_i915_private_t *dev_priv = dev->dev_private;
630         ssize_t remain;
631         loff_t gtt_page_base, offset;
632         loff_t first_data_page, last_data_page, num_pages;
633         loff_t pinned_pages, i;
634         struct page **user_pages;
635         struct mm_struct *mm = current->mm;
636         int gtt_page_offset, data_page_offset, data_page_index, page_length;
637         int ret;
638         uint64_t data_ptr = args->data_ptr;
639
640         remain = args->size;
641
642         /* Pin the user pages containing the data.  We can't fault while
643          * holding the struct mutex, and all of the pwrite implementations
644          * want to hold it while dereferencing the user data.
645          */
646         first_data_page = data_ptr / PAGE_SIZE;
647         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
648         num_pages = last_data_page - first_data_page + 1;
649
650         user_pages = drm_malloc_ab(num_pages, sizeof(struct page *));
651         if (user_pages == NULL)
652                 return -ENOMEM;
653
654         mutex_unlock(&dev->struct_mutex);
655         down_read(&mm->mmap_sem);
656         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
657                                       num_pages, 0, 0, user_pages, NULL);
658         up_read(&mm->mmap_sem);
659         mutex_lock(&dev->struct_mutex);
660         if (pinned_pages < num_pages) {
661                 ret = -EFAULT;
662                 goto out_unpin_pages;
663         }
664
665         ret = i915_gem_object_set_to_gtt_domain(obj, true);
666         if (ret)
667                 goto out_unpin_pages;
668
669         ret = i915_gem_object_put_fence(obj);
670         if (ret)
671                 goto out_unpin_pages;
672
673         offset = obj->gtt_offset + args->offset;
674
675         while (remain > 0) {
676                 /* Operation in this page
677                  *
678                  * gtt_page_base = page offset within aperture
679                  * gtt_page_offset = offset within page in aperture
680                  * data_page_index = page number in get_user_pages return
681                  * data_page_offset = offset with data_page_index page.
682                  * page_length = bytes to copy for this page
683                  */
684                 gtt_page_base = offset & PAGE_MASK;
685                 gtt_page_offset = offset_in_page(offset);
686                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
687                 data_page_offset = offset_in_page(data_ptr);
688
689                 page_length = remain;
690                 if ((gtt_page_offset + page_length) > PAGE_SIZE)
691                         page_length = PAGE_SIZE - gtt_page_offset;
692                 if ((data_page_offset + page_length) > PAGE_SIZE)
693                         page_length = PAGE_SIZE - data_page_offset;
694
695                 slow_kernel_write(dev_priv->mm.gtt_mapping,
696                                   gtt_page_base, gtt_page_offset,
697                                   user_pages[data_page_index],
698                                   data_page_offset,
699                                   page_length);
700
701                 remain -= page_length;
702                 offset += page_length;
703                 data_ptr += page_length;
704         }
705
706 out_unpin_pages:
707         for (i = 0; i < pinned_pages; i++)
708                 page_cache_release(user_pages[i]);
709         drm_free_large(user_pages);
710
711         return ret;
712 }
713
714 /**
715  * This is the fast shmem pwrite path, which attempts to directly
716  * copy_from_user into the kmapped pages backing the object.
717  */
718 static int
719 i915_gem_shmem_pwrite_fast(struct drm_device *dev,
720                            struct drm_i915_gem_object *obj,
721                            struct drm_i915_gem_pwrite *args,
722                            struct drm_file *file)
723 {
724         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
725         ssize_t remain;
726         loff_t offset;
727         char __user *user_data;
728         int page_offset, page_length;
729
730         user_data = (char __user *) (uintptr_t) args->data_ptr;
731         remain = args->size;
732
733         offset = args->offset;
734         obj->dirty = 1;
735
736         while (remain > 0) {
737                 struct page *page;
738                 char *vaddr;
739                 int ret;
740
741                 /* Operation in this page
742                  *
743                  * page_offset = offset within page
744                  * page_length = bytes to copy for this page
745                  */
746                 page_offset = offset_in_page(offset);
747                 page_length = remain;
748                 if ((page_offset + remain) > PAGE_SIZE)
749                         page_length = PAGE_SIZE - page_offset;
750
751                 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
752                 if (IS_ERR(page))
753                         return PTR_ERR(page);
754
755                 vaddr = kmap_atomic(page);
756                 ret = __copy_from_user_inatomic(vaddr + page_offset,
757                                                 user_data,
758                                                 page_length);
759                 kunmap_atomic(vaddr);
760
761                 set_page_dirty(page);
762                 mark_page_accessed(page);
763                 page_cache_release(page);
764
765                 /* If we get a fault while copying data, then (presumably) our
766                  * source page isn't available.  Return the error and we'll
767                  * retry in the slow path.
768                  */
769                 if (ret)
770                         return -EFAULT;
771
772                 remain -= page_length;
773                 user_data += page_length;
774                 offset += page_length;
775         }
776
777         return 0;
778 }
779
780 /**
781  * This is the fallback shmem pwrite path, which uses get_user_pages to pin
782  * the memory and maps it using kmap_atomic for copying.
783  *
784  * This avoids taking mmap_sem for faulting on the user's address while the
785  * struct_mutex is held.
786  */
787 static int
788 i915_gem_shmem_pwrite_slow(struct drm_device *dev,
789                            struct drm_i915_gem_object *obj,
790                            struct drm_i915_gem_pwrite *args,
791                            struct drm_file *file)
792 {
793         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
794         ssize_t remain;
795         loff_t offset;
796         char __user *user_data;
797         int shmem_page_offset, page_length, ret;
798         int obj_do_bit17_swizzling, page_do_bit17_swizzling;
799
800         user_data = (char __user *) (uintptr_t) args->data_ptr;
801         remain = args->size;
802
803         obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
804
805         offset = args->offset;
806         obj->dirty = 1;
807
808         mutex_unlock(&dev->struct_mutex);
809
810         while (remain > 0) {
811                 struct page *page;
812                 char *vaddr;
813
814                 /* Operation in this page
815                  *
816                  * shmem_page_offset = offset within page in shmem file
817                  * page_length = bytes to copy for this page
818                  */
819                 shmem_page_offset = offset_in_page(offset);
820
821                 page_length = remain;
822                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
823                         page_length = PAGE_SIZE - shmem_page_offset;
824
825                 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
826                 if (IS_ERR(page)) {
827                         ret = PTR_ERR(page);
828                         goto out;
829                 }
830
831                 page_do_bit17_swizzling = obj_do_bit17_swizzling &&
832                         (page_to_phys(page) & (1 << 17)) != 0;
833
834                 vaddr = kmap(page);
835                 if (page_do_bit17_swizzling)
836                         ret = __copy_from_user_swizzled(vaddr, shmem_page_offset,
837                                                         user_data,
838                                                         page_length);
839                 else
840                         ret = __copy_from_user(vaddr + shmem_page_offset,
841                                                user_data,
842                                                page_length);
843                 kunmap(page);
844
845                 set_page_dirty(page);
846                 mark_page_accessed(page);
847                 page_cache_release(page);
848
849                 if (ret) {
850                         ret = -EFAULT;
851                         goto out;
852                 }
853
854                 remain -= page_length;
855                 user_data += page_length;
856                 offset += page_length;
857         }
858
859 out:
860         mutex_lock(&dev->struct_mutex);
861         /* Fixup: Kill any reinstated backing storage pages */
862         if (obj->madv == __I915_MADV_PURGED)
863                 i915_gem_object_truncate(obj);
864         /* and flush dirty cachelines in case the object isn't in the cpu write
865          * domain anymore. */
866         if (obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
867                 i915_gem_clflush_object(obj);
868                 intel_gtt_chipset_flush();
869         }
870
871         return ret;
872 }
873
874 /**
875  * Writes data to the object referenced by handle.
876  *
877  * On error, the contents of the buffer that were to be modified are undefined.
878  */
879 int
880 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
881                       struct drm_file *file)
882 {
883         struct drm_i915_gem_pwrite *args = data;
884         struct drm_i915_gem_object *obj;
885         int ret;
886
887         if (args->size == 0)
888                 return 0;
889
890         if (!access_ok(VERIFY_READ,
891                        (char __user *)(uintptr_t)args->data_ptr,
892                        args->size))
893                 return -EFAULT;
894
895         ret = fault_in_pages_readable((char __user *)(uintptr_t)args->data_ptr,
896                                       args->size);
897         if (ret)
898                 return -EFAULT;
899
900         ret = i915_mutex_lock_interruptible(dev);
901         if (ret)
902                 return ret;
903
904         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
905         if (&obj->base == NULL) {
906                 ret = -ENOENT;
907                 goto unlock;
908         }
909
910         /* Bounds check destination. */
911         if (args->offset > obj->base.size ||
912             args->size > obj->base.size - args->offset) {
913                 ret = -EINVAL;
914                 goto out;
915         }
916
917         trace_i915_gem_object_pwrite(obj, args->offset, args->size);
918
919         /* We can only do the GTT pwrite on untiled buffers, as otherwise
920          * it would end up going through the fenced access, and we'll get
921          * different detiling behavior between reading and writing.
922          * pread/pwrite currently are reading and writing from the CPU
923          * perspective, requiring manual detiling by the client.
924          */
925         if (obj->phys_obj) {
926                 ret = i915_gem_phys_pwrite(dev, obj, args, file);
927                 goto out;
928         }
929
930         if (obj->gtt_space &&
931             obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
932                 ret = i915_gem_object_pin(obj, 0, true);
933                 if (ret)
934                         goto out;
935
936                 ret = i915_gem_object_set_to_gtt_domain(obj, true);
937                 if (ret)
938                         goto out_unpin;
939
940                 ret = i915_gem_object_put_fence(obj);
941                 if (ret)
942                         goto out_unpin;
943
944                 ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file);
945                 if (ret == -EFAULT)
946                         ret = i915_gem_gtt_pwrite_slow(dev, obj, args, file);
947
948 out_unpin:
949                 i915_gem_object_unpin(obj);
950
951                 if (ret != -EFAULT)
952                         goto out;
953                 /* Fall through to the shmfs paths because the gtt paths might
954                  * fail with non-page-backed user pointers (e.g. gtt mappings
955                  * when moving data between textures). */
956         }
957
958         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
959         if (ret)
960                 goto out;
961
962         ret = -EFAULT;
963         if (!i915_gem_object_needs_bit17_swizzle(obj))
964                 ret = i915_gem_shmem_pwrite_fast(dev, obj, args, file);
965         if (ret == -EFAULT)
966                 ret = i915_gem_shmem_pwrite_slow(dev, obj, args, file);
967
968 out:
969         drm_gem_object_unreference(&obj->base);
970 unlock:
971         mutex_unlock(&dev->struct_mutex);
972         return ret;
973 }
974
975 /**
976  * Called when user space prepares to use an object with the CPU, either
977  * through the mmap ioctl's mapping or a GTT mapping.
978  */
979 int
980 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
981                           struct drm_file *file)
982 {
983         struct drm_i915_gem_set_domain *args = data;
984         struct drm_i915_gem_object *obj;
985         uint32_t read_domains = args->read_domains;
986         uint32_t write_domain = args->write_domain;
987         int ret;
988
989         if (!(dev->driver->driver_features & DRIVER_GEM))
990                 return -ENODEV;
991
992         /* Only handle setting domains to types used by the CPU. */
993         if (write_domain & I915_GEM_GPU_DOMAINS)
994                 return -EINVAL;
995
996         if (read_domains & I915_GEM_GPU_DOMAINS)
997                 return -EINVAL;
998
999         /* Having something in the write domain implies it's in the read
1000          * domain, and only that read domain.  Enforce that in the request.
1001          */
1002         if (write_domain != 0 && read_domains != write_domain)
1003                 return -EINVAL;
1004
1005         ret = i915_mutex_lock_interruptible(dev);
1006         if (ret)
1007                 return ret;
1008
1009         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1010         if (&obj->base == NULL) {
1011                 ret = -ENOENT;
1012                 goto unlock;
1013         }
1014
1015         if (read_domains & I915_GEM_DOMAIN_GTT) {
1016                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
1017
1018                 /* Silently promote "you're not bound, there was nothing to do"
1019                  * to success, since the client was just asking us to
1020                  * make sure everything was done.
1021                  */
1022                 if (ret == -EINVAL)
1023                         ret = 0;
1024         } else {
1025                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
1026         }
1027
1028         drm_gem_object_unreference(&obj->base);
1029 unlock:
1030         mutex_unlock(&dev->struct_mutex);
1031         return ret;
1032 }
1033
1034 /**
1035  * Called when user space has done writes to this buffer
1036  */
1037 int
1038 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1039                          struct drm_file *file)
1040 {
1041         struct drm_i915_gem_sw_finish *args = data;
1042         struct drm_i915_gem_object *obj;
1043         int ret = 0;
1044
1045         if (!(dev->driver->driver_features & DRIVER_GEM))
1046                 return -ENODEV;
1047
1048         ret = i915_mutex_lock_interruptible(dev);
1049         if (ret)
1050                 return ret;
1051
1052         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1053         if (&obj->base == NULL) {
1054                 ret = -ENOENT;
1055                 goto unlock;
1056         }
1057
1058         /* Pinned buffers may be scanout, so flush the cache */
1059         if (obj->pin_count)
1060                 i915_gem_object_flush_cpu_write_domain(obj);
1061
1062         drm_gem_object_unreference(&obj->base);
1063 unlock:
1064         mutex_unlock(&dev->struct_mutex);
1065         return ret;
1066 }
1067
1068 /**
1069  * Maps the contents of an object, returning the address it is mapped
1070  * into.
1071  *
1072  * While the mapping holds a reference on the contents of the object, it doesn't
1073  * imply a ref on the object itself.
1074  */
1075 int
1076 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1077                     struct drm_file *file)
1078 {
1079         struct drm_i915_gem_mmap *args = data;
1080         struct drm_gem_object *obj;
1081         unsigned long addr;
1082
1083         if (!(dev->driver->driver_features & DRIVER_GEM))
1084                 return -ENODEV;
1085
1086         obj = drm_gem_object_lookup(dev, file, args->handle);
1087         if (obj == NULL)
1088                 return -ENOENT;
1089
1090         addr = vm_mmap(obj->filp, 0, args->size,
1091                        PROT_READ | PROT_WRITE, MAP_SHARED,
1092                        args->offset);
1093         drm_gem_object_unreference_unlocked(obj);
1094         if (IS_ERR((void *)addr))
1095                 return addr;
1096
1097         args->addr_ptr = (uint64_t) addr;
1098
1099         return 0;
1100 }
1101
1102 #ifdef CONFIG_XEN
1103 int i915_gem_mmap(struct file *filp, struct vm_area_struct *vma)
1104 {
1105         int ret = drm_gem_mmap(filp, vma);
1106
1107         pgprot_val(vma->vm_page_prot) |= _PAGE_IOMAP;
1108
1109         return ret;
1110 }
1111 #endif
1112
1113 /**
1114  * i915_gem_fault - fault a page into the GTT
1115  * vma: VMA in question
1116  * vmf: fault info
1117  *
1118  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1119  * from userspace.  The fault handler takes care of binding the object to
1120  * the GTT (if needed), allocating and programming a fence register (again,
1121  * only if needed based on whether the old reg is still valid or the object
1122  * is tiled) and inserting a new PTE into the faulting process.
1123  *
1124  * Note that the faulting process may involve evicting existing objects
1125  * from the GTT and/or fence registers to make room.  So performance may
1126  * suffer if the GTT working set is large or there are few fence registers
1127  * left.
1128  */
1129 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1130 {
1131         struct drm_i915_gem_object *obj = to_intel_bo(vma->vm_private_data);
1132         struct drm_device *dev = obj->base.dev;
1133         drm_i915_private_t *dev_priv = dev->dev_private;
1134         pgoff_t page_offset;
1135         unsigned long pfn;
1136         int ret = 0;
1137         bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1138
1139         /* We don't use vmf->pgoff since that has the fake offset */
1140         page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
1141                 PAGE_SHIFT;
1142
1143         ret = i915_mutex_lock_interruptible(dev);
1144         if (ret)
1145                 goto out;
1146
1147         trace_i915_gem_object_fault(obj, page_offset, true, write);
1148
1149         /* Now bind it into the GTT if needed */
1150         if (!obj->map_and_fenceable) {
1151                 ret = i915_gem_object_unbind(obj);
1152                 if (ret)
1153                         goto unlock;
1154         }
1155         if (!obj->gtt_space) {
1156                 ret = i915_gem_object_bind_to_gtt(obj, 0, true);
1157                 if (ret)
1158                         goto unlock;
1159
1160                 ret = i915_gem_object_set_to_gtt_domain(obj, write);
1161                 if (ret)
1162                         goto unlock;
1163         }
1164
1165         if (obj->tiling_mode == I915_TILING_NONE)
1166                 ret = i915_gem_object_put_fence(obj);
1167         else
1168                 ret = i915_gem_object_get_fence(obj, NULL);
1169         if (ret)
1170                 goto unlock;
1171
1172         if (i915_gem_object_is_inactive(obj))
1173                 list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1174
1175         obj->fault_mappable = true;
1176
1177         pfn = ((dev->agp->base + obj->gtt_offset) >> PAGE_SHIFT) +
1178                 page_offset;
1179
1180         /* Finally, remap it using the new GTT offset */
1181         ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
1182 unlock:
1183         mutex_unlock(&dev->struct_mutex);
1184 out:
1185         switch (ret) {
1186         case -EIO:
1187         case -EAGAIN:
1188                 /* Give the error handler a chance to run and move the
1189                  * objects off the GPU active list. Next time we service the
1190                  * fault, we should be able to transition the page into the
1191                  * GTT without touching the GPU (and so avoid further
1192                  * EIO/EGAIN). If the GPU is wedged, then there is no issue
1193                  * with coherency, just lost writes.
1194                  */
1195                 set_need_resched();
1196         case 0:
1197         case -ERESTARTSYS:
1198         case -EINTR:
1199                 return VM_FAULT_NOPAGE;
1200         case -ENOMEM:
1201                 return VM_FAULT_OOM;
1202         default:
1203                 return VM_FAULT_SIGBUS;
1204         }
1205 }
1206
1207 /**
1208  * i915_gem_release_mmap - remove physical page mappings
1209  * @obj: obj in question
1210  *
1211  * Preserve the reservation of the mmapping with the DRM core code, but
1212  * relinquish ownership of the pages back to the system.
1213  *
1214  * It is vital that we remove the page mapping if we have mapped a tiled
1215  * object through the GTT and then lose the fence register due to
1216  * resource pressure. Similarly if the object has been moved out of the
1217  * aperture, than pages mapped into userspace must be revoked. Removing the
1218  * mapping will then trigger a page fault on the next user access, allowing
1219  * fixup by i915_gem_fault().
1220  */
1221 void
1222 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
1223 {
1224         if (!obj->fault_mappable)
1225                 return;
1226
1227         if (obj->base.dev->dev_mapping)
1228                 unmap_mapping_range(obj->base.dev->dev_mapping,
1229                                     (loff_t)obj->base.map_list.hash.key<<PAGE_SHIFT,
1230                                     obj->base.size, 1);
1231
1232         obj->fault_mappable = false;
1233 }
1234
1235 static uint32_t
1236 i915_gem_get_gtt_size(struct drm_device *dev, uint32_t size, int tiling_mode)
1237 {
1238         uint32_t gtt_size;
1239
1240         if (INTEL_INFO(dev)->gen >= 4 ||
1241             tiling_mode == I915_TILING_NONE)
1242                 return size;
1243
1244         /* Previous chips need a power-of-two fence region when tiling */
1245         if (INTEL_INFO(dev)->gen == 3)
1246                 gtt_size = 1024*1024;
1247         else
1248                 gtt_size = 512*1024;
1249
1250         while (gtt_size < size)
1251                 gtt_size <<= 1;
1252
1253         return gtt_size;
1254 }
1255
1256 /**
1257  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
1258  * @obj: object to check
1259  *
1260  * Return the required GTT alignment for an object, taking into account
1261  * potential fence register mapping.
1262  */
1263 static uint32_t
1264 i915_gem_get_gtt_alignment(struct drm_device *dev,
1265                            uint32_t size,
1266                            int tiling_mode)
1267 {
1268         /*
1269          * Minimum alignment is 4k (GTT page size), but might be greater
1270          * if a fence register is needed for the object.
1271          */
1272         if (INTEL_INFO(dev)->gen >= 4 ||
1273             tiling_mode == I915_TILING_NONE)
1274                 return 4096;
1275
1276         /*
1277          * Previous chips need to be aligned to the size of the smallest
1278          * fence register that can contain the object.
1279          */
1280         return i915_gem_get_gtt_size(dev, size, tiling_mode);
1281 }
1282
1283 /**
1284  * i915_gem_get_unfenced_gtt_alignment - return required GTT alignment for an
1285  *                                       unfenced object
1286  * @dev: the device
1287  * @size: size of the object
1288  * @tiling_mode: tiling mode of the object
1289  *
1290  * Return the required GTT alignment for an object, only taking into account
1291  * unfenced tiled surface requirements.
1292  */
1293 uint32_t
1294 i915_gem_get_unfenced_gtt_alignment(struct drm_device *dev,
1295                                     uint32_t size,
1296                                     int tiling_mode)
1297 {
1298         /*
1299          * Minimum alignment is 4k (GTT page size) for sane hw.
1300          */
1301         if (INTEL_INFO(dev)->gen >= 4 || IS_G33(dev) ||
1302             tiling_mode == I915_TILING_NONE)
1303                 return 4096;
1304
1305         /* Previous hardware however needs to be aligned to a power-of-two
1306          * tile height. The simplest method for determining this is to reuse
1307          * the power-of-tile object size.
1308          */
1309         return i915_gem_get_gtt_size(dev, size, tiling_mode);
1310 }
1311
1312 int
1313 i915_gem_mmap_gtt(struct drm_file *file,
1314                   struct drm_device *dev,
1315                   uint32_t handle,
1316                   uint64_t *offset)
1317 {
1318         struct drm_i915_private *dev_priv = dev->dev_private;
1319         struct drm_i915_gem_object *obj;
1320         int ret;
1321
1322         if (!(dev->driver->driver_features & DRIVER_GEM))
1323                 return -ENODEV;
1324
1325         ret = i915_mutex_lock_interruptible(dev);
1326         if (ret)
1327                 return ret;
1328
1329         obj = to_intel_bo(drm_gem_object_lookup(dev, file, handle));
1330         if (&obj->base == NULL) {
1331                 ret = -ENOENT;
1332                 goto unlock;
1333         }
1334
1335         if (obj->base.size > dev_priv->mm.gtt_mappable_end) {
1336                 ret = -E2BIG;
1337                 goto out;
1338         }
1339
1340         if (obj->madv != I915_MADV_WILLNEED) {
1341                 DRM_ERROR("Attempting to mmap a purgeable buffer\n");
1342                 ret = -EINVAL;
1343                 goto out;
1344         }
1345
1346         if (!obj->base.map_list.map) {
1347                 ret = drm_gem_create_mmap_offset(&obj->base);
1348                 if (ret)
1349                         goto out;
1350         }
1351
1352         *offset = (u64)obj->base.map_list.hash.key << PAGE_SHIFT;
1353
1354 out:
1355         drm_gem_object_unreference(&obj->base);
1356 unlock:
1357         mutex_unlock(&dev->struct_mutex);
1358         return ret;
1359 }
1360
1361 /**
1362  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
1363  * @dev: DRM device
1364  * @data: GTT mapping ioctl data
1365  * @file: GEM object info
1366  *
1367  * Simply returns the fake offset to userspace so it can mmap it.
1368  * The mmap call will end up in drm_gem_mmap(), which will set things
1369  * up so we can get faults in the handler above.
1370  *
1371  * The fault handler will take care of binding the object into the GTT
1372  * (since it may have been evicted to make room for something), allocating
1373  * a fence register, and mapping the appropriate aperture address into
1374  * userspace.
1375  */
1376 int
1377 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
1378                         struct drm_file *file)
1379 {
1380         struct drm_i915_gem_mmap_gtt *args = data;
1381
1382         if (!(dev->driver->driver_features & DRIVER_GEM))
1383                 return -ENODEV;
1384
1385         return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
1386 }
1387
1388
1389 static int
1390 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj,
1391                               gfp_t gfpmask)
1392 {
1393         int page_count, i;
1394         struct address_space *mapping;
1395         struct inode *inode;
1396         struct page *page;
1397
1398         /* Get the list of pages out of our struct file.  They'll be pinned
1399          * at this point until we release them.
1400          */
1401         page_count = obj->base.size / PAGE_SIZE;
1402         BUG_ON(obj->pages != NULL);
1403         obj->pages = drm_malloc_ab(page_count, sizeof(struct page *));
1404         if (obj->pages == NULL)
1405                 return -ENOMEM;
1406
1407         inode = obj->base.filp->f_path.dentry->d_inode;
1408         mapping = inode->i_mapping;
1409         gfpmask |= mapping_gfp_mask(mapping);
1410
1411         for (i = 0; i < page_count; i++) {
1412                 page = shmem_read_mapping_page_gfp(mapping, i, gfpmask);
1413                 if (IS_ERR(page))
1414                         goto err_pages;
1415
1416                 obj->pages[i] = page;
1417         }
1418
1419         if (i915_gem_object_needs_bit17_swizzle(obj))
1420                 i915_gem_object_do_bit_17_swizzle(obj);
1421
1422         return 0;
1423
1424 err_pages:
1425         while (i--)
1426                 page_cache_release(obj->pages[i]);
1427
1428         drm_free_large(obj->pages);
1429         obj->pages = NULL;
1430         return PTR_ERR(page);
1431 }
1432
1433 static void
1434 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
1435 {
1436         int page_count = obj->base.size / PAGE_SIZE;
1437         int i;
1438
1439         BUG_ON(obj->madv == __I915_MADV_PURGED);
1440
1441         if (i915_gem_object_needs_bit17_swizzle(obj))
1442                 i915_gem_object_save_bit_17_swizzle(obj);
1443
1444         if (obj->madv == I915_MADV_DONTNEED)
1445                 obj->dirty = 0;
1446
1447         for (i = 0; i < page_count; i++) {
1448                 if (obj->dirty)
1449                         set_page_dirty(obj->pages[i]);
1450
1451                 if (obj->madv == I915_MADV_WILLNEED)
1452                         mark_page_accessed(obj->pages[i]);
1453
1454                 page_cache_release(obj->pages[i]);
1455         }
1456         obj->dirty = 0;
1457
1458         drm_free_large(obj->pages);
1459         obj->pages = NULL;
1460 }
1461
1462 void
1463 i915_gem_object_move_to_active(struct drm_i915_gem_object *obj,
1464                                struct intel_ring_buffer *ring,
1465                                u32 seqno)
1466 {
1467         struct drm_device *dev = obj->base.dev;
1468         struct drm_i915_private *dev_priv = dev->dev_private;
1469
1470         BUG_ON(ring == NULL);
1471         obj->ring = ring;
1472
1473         /* Add a reference if we're newly entering the active list. */
1474         if (!obj->active) {
1475                 drm_gem_object_reference(&obj->base);
1476                 obj->active = 1;
1477         }
1478
1479         /* Move from whatever list we were on to the tail of execution. */
1480         list_move_tail(&obj->mm_list, &dev_priv->mm.active_list);
1481         list_move_tail(&obj->ring_list, &ring->active_list);
1482
1483         obj->last_rendering_seqno = seqno;
1484
1485         if (obj->fenced_gpu_access) {
1486                 obj->last_fenced_seqno = seqno;
1487                 obj->last_fenced_ring = ring;
1488
1489                 /* Bump MRU to take account of the delayed flush */
1490                 if (obj->fence_reg != I915_FENCE_REG_NONE) {
1491                         struct drm_i915_fence_reg *reg;
1492
1493                         reg = &dev_priv->fence_regs[obj->fence_reg];
1494                         list_move_tail(&reg->lru_list,
1495                                        &dev_priv->mm.fence_list);
1496                 }
1497         }
1498 }
1499
1500 static void
1501 i915_gem_object_move_off_active(struct drm_i915_gem_object *obj)
1502 {
1503         list_del_init(&obj->ring_list);
1504         obj->last_rendering_seqno = 0;
1505         obj->last_fenced_seqno = 0;
1506 }
1507
1508 static void
1509 i915_gem_object_move_to_flushing(struct drm_i915_gem_object *obj)
1510 {
1511         struct drm_device *dev = obj->base.dev;
1512         drm_i915_private_t *dev_priv = dev->dev_private;
1513
1514         BUG_ON(!obj->active);
1515         list_move_tail(&obj->mm_list, &dev_priv->mm.flushing_list);
1516
1517         i915_gem_object_move_off_active(obj);
1518 }
1519
1520 static void
1521 i915_gem_object_move_to_inactive(struct drm_i915_gem_object *obj)
1522 {
1523         struct drm_device *dev = obj->base.dev;
1524         struct drm_i915_private *dev_priv = dev->dev_private;
1525
1526         if (obj->pin_count != 0)
1527                 list_move_tail(&obj->mm_list, &dev_priv->mm.pinned_list);
1528         else
1529                 list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
1530
1531         BUG_ON(!list_empty(&obj->gpu_write_list));
1532         BUG_ON(!obj->active);
1533         obj->ring = NULL;
1534         obj->last_fenced_ring = NULL;
1535
1536         i915_gem_object_move_off_active(obj);
1537         obj->fenced_gpu_access = false;
1538
1539         obj->active = 0;
1540         obj->pending_gpu_write = false;
1541         drm_gem_object_unreference(&obj->base);
1542
1543         WARN_ON(i915_verify_lists(dev));
1544 }
1545
1546 /* Immediately discard the backing storage */
1547 static void
1548 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
1549 {
1550         struct inode *inode;
1551
1552         /* Our goal here is to return as much of the memory as
1553          * is possible back to the system as we are called from OOM.
1554          * To do this we must instruct the shmfs to drop all of its
1555          * backing pages, *now*.
1556          */
1557         inode = obj->base.filp->f_path.dentry->d_inode;
1558         shmem_truncate_range(inode, 0, (loff_t)-1);
1559
1560         obj->madv = __I915_MADV_PURGED;
1561 }
1562
1563 static inline int
1564 i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj)
1565 {
1566         return obj->madv == I915_MADV_DONTNEED;
1567 }
1568
1569 static void
1570 i915_gem_process_flushing_list(struct intel_ring_buffer *ring,
1571                                uint32_t flush_domains)
1572 {
1573         struct drm_i915_gem_object *obj, *next;
1574
1575         list_for_each_entry_safe(obj, next,
1576                                  &ring->gpu_write_list,
1577                                  gpu_write_list) {
1578                 if (obj->base.write_domain & flush_domains) {
1579                         uint32_t old_write_domain = obj->base.write_domain;
1580
1581                         obj->base.write_domain = 0;
1582                         list_del_init(&obj->gpu_write_list);
1583                         i915_gem_object_move_to_active(obj, ring,
1584                                                        i915_gem_next_request_seqno(ring));
1585
1586                         trace_i915_gem_object_change_domain(obj,
1587                                                             obj->base.read_domains,
1588                                                             old_write_domain);
1589                 }
1590         }
1591 }
1592
1593 static u32
1594 i915_gem_get_seqno(struct drm_device *dev)
1595 {
1596         drm_i915_private_t *dev_priv = dev->dev_private;
1597         u32 seqno = dev_priv->next_seqno;
1598
1599         /* reserve 0 for non-seqno */
1600         if (++dev_priv->next_seqno == 0)
1601                 dev_priv->next_seqno = 1;
1602
1603         return seqno;
1604 }
1605
1606 u32
1607 i915_gem_next_request_seqno(struct intel_ring_buffer *ring)
1608 {
1609         if (ring->outstanding_lazy_request == 0)
1610                 ring->outstanding_lazy_request = i915_gem_get_seqno(ring->dev);
1611
1612         return ring->outstanding_lazy_request;
1613 }
1614
1615 int
1616 i915_add_request(struct intel_ring_buffer *ring,
1617                  struct drm_file *file,
1618                  struct drm_i915_gem_request *request)
1619 {
1620         drm_i915_private_t *dev_priv = ring->dev->dev_private;
1621         uint32_t seqno;
1622         u32 request_ring_position;
1623         int was_empty;
1624         int ret;
1625
1626         BUG_ON(request == NULL);
1627         seqno = i915_gem_next_request_seqno(ring);
1628
1629         /* Record the position of the start of the request so that
1630          * should we detect the updated seqno part-way through the
1631          * GPU processing the request, we never over-estimate the
1632          * position of the head.
1633          */
1634         request_ring_position = intel_ring_get_tail(ring);
1635
1636         ret = ring->add_request(ring, &seqno);
1637         if (ret)
1638             return ret;
1639
1640         trace_i915_gem_request_add(ring, seqno);
1641
1642         request->seqno = seqno;
1643         request->ring = ring;
1644         request->tail = request_ring_position;
1645         request->emitted_jiffies = jiffies;
1646         was_empty = list_empty(&ring->request_list);
1647         list_add_tail(&request->list, &ring->request_list);
1648
1649         if (file) {
1650                 struct drm_i915_file_private *file_priv = file->driver_priv;
1651
1652                 spin_lock(&file_priv->mm.lock);
1653                 request->file_priv = file_priv;
1654                 list_add_tail(&request->client_list,
1655                               &file_priv->mm.request_list);
1656                 spin_unlock(&file_priv->mm.lock);
1657         }
1658
1659         ring->outstanding_lazy_request = 0;
1660
1661         if (!dev_priv->mm.suspended) {
1662                 if (i915_enable_hangcheck) {
1663                         mod_timer(&dev_priv->hangcheck_timer,
1664                                   jiffies +
1665                                   msecs_to_jiffies(DRM_I915_HANGCHECK_PERIOD));
1666                 }
1667                 if (was_empty)
1668                         queue_delayed_work(dev_priv->wq,
1669                                            &dev_priv->mm.retire_work, HZ);
1670         }
1671         return 0;
1672 }
1673
1674 static inline void
1675 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
1676 {
1677         struct drm_i915_file_private *file_priv = request->file_priv;
1678
1679         if (!file_priv)
1680                 return;
1681
1682         spin_lock(&file_priv->mm.lock);
1683         if (request->file_priv) {
1684                 list_del(&request->client_list);
1685                 request->file_priv = NULL;
1686         }
1687         spin_unlock(&file_priv->mm.lock);
1688 }
1689
1690 static void i915_gem_reset_ring_lists(struct drm_i915_private *dev_priv,
1691                                       struct intel_ring_buffer *ring)
1692 {
1693         while (!list_empty(&ring->request_list)) {
1694                 struct drm_i915_gem_request *request;
1695
1696                 request = list_first_entry(&ring->request_list,
1697                                            struct drm_i915_gem_request,
1698                                            list);
1699
1700                 list_del(&request->list);
1701                 i915_gem_request_remove_from_client(request);
1702                 kfree(request);
1703         }
1704
1705         while (!list_empty(&ring->active_list)) {
1706                 struct drm_i915_gem_object *obj;
1707
1708                 obj = list_first_entry(&ring->active_list,
1709                                        struct drm_i915_gem_object,
1710                                        ring_list);
1711
1712                 obj->base.write_domain = 0;
1713                 list_del_init(&obj->gpu_write_list);
1714                 i915_gem_object_move_to_inactive(obj);
1715         }
1716 }
1717
1718 static void i915_gem_reset_fences(struct drm_device *dev)
1719 {
1720         struct drm_i915_private *dev_priv = dev->dev_private;
1721         int i;
1722
1723         for (i = 0; i < dev_priv->num_fence_regs; i++) {
1724                 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
1725                 struct drm_i915_gem_object *obj = reg->obj;
1726
1727                 if (!obj)
1728                         continue;
1729
1730                 if (obj->tiling_mode)
1731                         i915_gem_release_mmap(obj);
1732
1733                 reg->obj->fence_reg = I915_FENCE_REG_NONE;
1734                 reg->obj->fenced_gpu_access = false;
1735                 reg->obj->last_fenced_seqno = 0;
1736                 reg->obj->last_fenced_ring = NULL;
1737                 i915_gem_clear_fence_reg(dev, reg);
1738         }
1739 }
1740
1741 void i915_gem_reset(struct drm_device *dev)
1742 {
1743         struct drm_i915_private *dev_priv = dev->dev_private;
1744         struct drm_i915_gem_object *obj;
1745         int i;
1746
1747         for (i = 0; i < I915_NUM_RINGS; i++)
1748                 i915_gem_reset_ring_lists(dev_priv, &dev_priv->ring[i]);
1749
1750         /* Remove anything from the flushing lists. The GPU cache is likely
1751          * to be lost on reset along with the data, so simply move the
1752          * lost bo to the inactive list.
1753          */
1754         while (!list_empty(&dev_priv->mm.flushing_list)) {
1755                 obj = list_first_entry(&dev_priv->mm.flushing_list,
1756                                       struct drm_i915_gem_object,
1757                                       mm_list);
1758
1759                 obj->base.write_domain = 0;
1760                 list_del_init(&obj->gpu_write_list);
1761                 i915_gem_object_move_to_inactive(obj);
1762         }
1763
1764         /* Move everything out of the GPU domains to ensure we do any
1765          * necessary invalidation upon reuse.
1766          */
1767         list_for_each_entry(obj,
1768                             &dev_priv->mm.inactive_list,
1769                             mm_list)
1770         {
1771                 obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
1772         }
1773
1774         /* The fence registers are invalidated so clear them out */
1775         i915_gem_reset_fences(dev);
1776 }
1777
1778 /**
1779  * This function clears the request list as sequence numbers are passed.
1780  */
1781 void
1782 i915_gem_retire_requests_ring(struct intel_ring_buffer *ring)
1783 {
1784         uint32_t seqno;
1785         int i;
1786
1787         if (list_empty(&ring->request_list))
1788                 return;
1789
1790         WARN_ON(i915_verify_lists(ring->dev));
1791
1792         seqno = ring->get_seqno(ring);
1793
1794         for (i = 0; i < ARRAY_SIZE(ring->sync_seqno); i++)
1795                 if (seqno >= ring->sync_seqno[i])
1796                         ring->sync_seqno[i] = 0;
1797
1798         while (!list_empty(&ring->request_list)) {
1799                 struct drm_i915_gem_request *request;
1800
1801                 request = list_first_entry(&ring->request_list,
1802                                            struct drm_i915_gem_request,
1803                                            list);
1804
1805                 if (!i915_seqno_passed(seqno, request->seqno))
1806                         break;
1807
1808                 trace_i915_gem_request_retire(ring, request->seqno);
1809                 /* We know the GPU must have read the request to have
1810                  * sent us the seqno + interrupt, so use the position
1811                  * of tail of the request to update the last known position
1812                  * of the GPU head.
1813                  */
1814                 ring->last_retired_head = request->tail;
1815
1816                 list_del(&request->list);
1817                 i915_gem_request_remove_from_client(request);
1818                 kfree(request);
1819         }
1820
1821         /* Move any buffers on the active list that are no longer referenced
1822          * by the ringbuffer to the flushing/inactive lists as appropriate.
1823          */
1824         while (!list_empty(&ring->active_list)) {
1825                 struct drm_i915_gem_object *obj;
1826
1827                 obj = list_first_entry(&ring->active_list,
1828                                       struct drm_i915_gem_object,
1829                                       ring_list);
1830
1831                 if (!i915_seqno_passed(seqno, obj->last_rendering_seqno))
1832                         break;
1833
1834                 if (obj->base.write_domain != 0)
1835                         i915_gem_object_move_to_flushing(obj);
1836                 else
1837                         i915_gem_object_move_to_inactive(obj);
1838         }
1839
1840         if (unlikely(ring->trace_irq_seqno &&
1841                      i915_seqno_passed(seqno, ring->trace_irq_seqno))) {
1842                 ring->irq_put(ring);
1843                 ring->trace_irq_seqno = 0;
1844         }
1845
1846         WARN_ON(i915_verify_lists(ring->dev));
1847 }
1848
1849 void
1850 i915_gem_retire_requests(struct drm_device *dev)
1851 {
1852         drm_i915_private_t *dev_priv = dev->dev_private;
1853         int i;
1854
1855         if (!list_empty(&dev_priv->mm.deferred_free_list)) {
1856             struct drm_i915_gem_object *obj, *next;
1857
1858             /* We must be careful that during unbind() we do not
1859              * accidentally infinitely recurse into retire requests.
1860              * Currently:
1861              *   retire -> free -> unbind -> wait -> retire_ring
1862              */
1863             list_for_each_entry_safe(obj, next,
1864                                      &dev_priv->mm.deferred_free_list,
1865                                      mm_list)
1866                     i915_gem_free_object_tail(obj);
1867         }
1868
1869         for (i = 0; i < I915_NUM_RINGS; i++)
1870                 i915_gem_retire_requests_ring(&dev_priv->ring[i]);
1871 }
1872
1873 static void
1874 i915_gem_retire_work_handler(struct work_struct *work)
1875 {
1876         drm_i915_private_t *dev_priv;
1877         struct drm_device *dev;
1878         bool idle;
1879         int i;
1880
1881         dev_priv = container_of(work, drm_i915_private_t,
1882                                 mm.retire_work.work);
1883         dev = dev_priv->dev;
1884
1885         /* Come back later if the device is busy... */
1886         if (!mutex_trylock(&dev->struct_mutex)) {
1887                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
1888                 return;
1889         }
1890
1891         i915_gem_retire_requests(dev);
1892
1893         /* Send a periodic flush down the ring so we don't hold onto GEM
1894          * objects indefinitely.
1895          */
1896         idle = true;
1897         for (i = 0; i < I915_NUM_RINGS; i++) {
1898                 struct intel_ring_buffer *ring = &dev_priv->ring[i];
1899
1900                 if (!list_empty(&ring->gpu_write_list)) {
1901                         struct drm_i915_gem_request *request;
1902                         int ret;
1903
1904                         ret = i915_gem_flush_ring(ring,
1905                                                   0, I915_GEM_GPU_DOMAINS);
1906                         request = kzalloc(sizeof(*request), GFP_KERNEL);
1907                         if (ret || request == NULL ||
1908                             i915_add_request(ring, NULL, request))
1909                             kfree(request);
1910                 }
1911
1912                 idle &= list_empty(&ring->request_list);
1913         }
1914
1915         if (!dev_priv->mm.suspended && !idle)
1916                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, HZ);
1917
1918         mutex_unlock(&dev->struct_mutex);
1919 }
1920
1921 /**
1922  * Waits for a sequence number to be signaled, and cleans up the
1923  * request and object lists appropriately for that event.
1924  */
1925 int
1926 i915_wait_request(struct intel_ring_buffer *ring,
1927                   uint32_t seqno,
1928                   bool do_retire)
1929 {
1930         drm_i915_private_t *dev_priv = ring->dev->dev_private;
1931         u32 ier;
1932         int ret = 0;
1933
1934         BUG_ON(seqno == 0);
1935
1936         if (atomic_read(&dev_priv->mm.wedged)) {
1937                 struct completion *x = &dev_priv->error_completion;
1938                 bool recovery_complete;
1939                 unsigned long flags;
1940
1941                 /* Give the error handler a chance to run. */
1942                 spin_lock_irqsave(&x->wait.lock, flags);
1943                 recovery_complete = x->done > 0;
1944                 spin_unlock_irqrestore(&x->wait.lock, flags);
1945
1946                 return recovery_complete ? -EIO : -EAGAIN;
1947         }
1948
1949         if (seqno == ring->outstanding_lazy_request) {
1950                 struct drm_i915_gem_request *request;
1951
1952                 request = kzalloc(sizeof(*request), GFP_KERNEL);
1953                 if (request == NULL)
1954                         return -ENOMEM;
1955
1956                 ret = i915_add_request(ring, NULL, request);
1957                 if (ret) {
1958                         kfree(request);
1959                         return ret;
1960                 }
1961
1962                 seqno = request->seqno;
1963         }
1964
1965         if (!i915_seqno_passed(ring->get_seqno(ring), seqno)) {
1966                 if (HAS_PCH_SPLIT(ring->dev))
1967                         ier = I915_READ(DEIER) | I915_READ(GTIER);
1968                 else
1969                         ier = I915_READ(IER);
1970                 if (!ier) {
1971                         DRM_ERROR("something (likely vbetool) disabled "
1972                                   "interrupts, re-enabling\n");
1973                         ring->dev->driver->irq_preinstall(ring->dev);
1974                         ring->dev->driver->irq_postinstall(ring->dev);
1975                 }
1976
1977                 trace_i915_gem_request_wait_begin(ring, seqno);
1978
1979                 ring->waiting_seqno = seqno;
1980                 if (ring->irq_get(ring)) {
1981                         if (dev_priv->mm.interruptible)
1982                                 ret = wait_event_interruptible(ring->irq_queue,
1983                                                                i915_seqno_passed(ring->get_seqno(ring), seqno)
1984                                                                || atomic_read(&dev_priv->mm.wedged));
1985                         else
1986                                 wait_event(ring->irq_queue,
1987                                            i915_seqno_passed(ring->get_seqno(ring), seqno)
1988                                            || atomic_read(&dev_priv->mm.wedged));
1989
1990                         ring->irq_put(ring);
1991                 } else if (wait_for_atomic(i915_seqno_passed(ring->get_seqno(ring),
1992                                                              seqno) ||
1993                                            atomic_read(&dev_priv->mm.wedged), 3000))
1994                         ret = -EBUSY;
1995                 ring->waiting_seqno = 0;
1996
1997                 trace_i915_gem_request_wait_end(ring, seqno);
1998         }
1999         if (atomic_read(&dev_priv->mm.wedged))
2000                 ret = -EAGAIN;
2001
2002         /* Directly dispatch request retiring.  While we have the work queue
2003          * to handle this, the waiter on a request often wants an associated
2004          * buffer to have made it to the inactive list, and we would need
2005          * a separate wait queue to handle that.
2006          */
2007         if (ret == 0 && do_retire)
2008                 i915_gem_retire_requests_ring(ring);
2009
2010         return ret;
2011 }
2012
2013 /**
2014  * Ensures that all rendering to the object has completed and the object is
2015  * safe to unbind from the GTT or access from the CPU.
2016  */
2017 int
2018 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj)
2019 {
2020         int ret;
2021
2022         /* This function only exists to support waiting for existing rendering,
2023          * not for emitting required flushes.
2024          */
2025         BUG_ON((obj->base.write_domain & I915_GEM_GPU_DOMAINS) != 0);
2026
2027         /* If there is rendering queued on the buffer being evicted, wait for
2028          * it.
2029          */
2030         if (obj->active) {
2031                 ret = i915_wait_request(obj->ring, obj->last_rendering_seqno,
2032                                         true);
2033                 if (ret)
2034                         return ret;
2035         }
2036
2037         return 0;
2038 }
2039
2040 static void i915_gem_object_finish_gtt(struct drm_i915_gem_object *obj)
2041 {
2042         u32 old_write_domain, old_read_domains;
2043
2044         /* Act a barrier for all accesses through the GTT */
2045         mb();
2046
2047         /* Force a pagefault for domain tracking on next user access */
2048         i915_gem_release_mmap(obj);
2049
2050         if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
2051                 return;
2052
2053         old_read_domains = obj->base.read_domains;
2054         old_write_domain = obj->base.write_domain;
2055
2056         obj->base.read_domains &= ~I915_GEM_DOMAIN_GTT;
2057         obj->base.write_domain &= ~I915_GEM_DOMAIN_GTT;
2058
2059         trace_i915_gem_object_change_domain(obj,
2060                                             old_read_domains,
2061                                             old_write_domain);
2062 }
2063
2064 /**
2065  * Unbinds an object from the GTT aperture.
2066  */
2067 int
2068 i915_gem_object_unbind(struct drm_i915_gem_object *obj)
2069 {
2070         drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
2071         int ret = 0;
2072
2073         if (obj->gtt_space == NULL)
2074                 return 0;
2075
2076         if (obj->pin_count != 0) {
2077                 DRM_ERROR("Attempting to unbind pinned buffer\n");
2078                 return -EINVAL;
2079         }
2080
2081         ret = i915_gem_object_finish_gpu(obj);
2082         if (ret == -ERESTARTSYS)
2083                 return ret;
2084         /* Continue on if we fail due to EIO, the GPU is hung so we
2085          * should be safe and we need to cleanup or else we might
2086          * cause memory corruption through use-after-free.
2087          */
2088
2089         i915_gem_object_finish_gtt(obj);
2090
2091         /* Move the object to the CPU domain to ensure that
2092          * any possible CPU writes while it's not in the GTT
2093          * are flushed when we go to remap it.
2094          */
2095         if (ret == 0)
2096                 ret = i915_gem_object_set_to_cpu_domain(obj, 1);
2097         if (ret == -ERESTARTSYS)
2098                 return ret;
2099         if (ret) {
2100                 /* In the event of a disaster, abandon all caches and
2101                  * hope for the best.
2102                  */
2103                 i915_gem_clflush_object(obj);
2104                 obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
2105         }
2106
2107         /* release the fence reg _after_ flushing */
2108         ret = i915_gem_object_put_fence(obj);
2109         if (ret == -ERESTARTSYS)
2110                 return ret;
2111
2112         trace_i915_gem_object_unbind(obj);
2113
2114         i915_gem_gtt_unbind_object(obj);
2115         if (obj->has_aliasing_ppgtt_mapping) {
2116                 i915_ppgtt_unbind_object(dev_priv->mm.aliasing_ppgtt, obj);
2117                 obj->has_aliasing_ppgtt_mapping = 0;
2118         }
2119
2120         i915_gem_object_put_pages_gtt(obj);
2121
2122         list_del_init(&obj->gtt_list);
2123         list_del_init(&obj->mm_list);
2124         /* Avoid an unnecessary call to unbind on rebind. */
2125         obj->map_and_fenceable = true;
2126
2127         drm_mm_put_block(obj->gtt_space);
2128         obj->gtt_space = NULL;
2129         obj->gtt_offset = 0;
2130
2131         if (i915_gem_object_is_purgeable(obj))
2132                 i915_gem_object_truncate(obj);
2133
2134         return ret;
2135 }
2136
2137 int
2138 i915_gem_flush_ring(struct intel_ring_buffer *ring,
2139                     uint32_t invalidate_domains,
2140                     uint32_t flush_domains)
2141 {
2142         int ret;
2143
2144         if (((invalidate_domains | flush_domains) & I915_GEM_GPU_DOMAINS) == 0)
2145                 return 0;
2146
2147         trace_i915_gem_ring_flush(ring, invalidate_domains, flush_domains);
2148
2149         ret = ring->flush(ring, invalidate_domains, flush_domains);
2150         if (ret)
2151                 return ret;
2152
2153         if (flush_domains & I915_GEM_GPU_DOMAINS)
2154                 i915_gem_process_flushing_list(ring, flush_domains);
2155
2156         return 0;
2157 }
2158
2159 static int i915_ring_idle(struct intel_ring_buffer *ring, bool do_retire)
2160 {
2161         int ret;
2162
2163         if (list_empty(&ring->gpu_write_list) && list_empty(&ring->active_list))
2164                 return 0;
2165
2166         if (!list_empty(&ring->gpu_write_list)) {
2167                 ret = i915_gem_flush_ring(ring,
2168                                     I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
2169                 if (ret)
2170                         return ret;
2171         }
2172
2173         return i915_wait_request(ring, i915_gem_next_request_seqno(ring),
2174                                  do_retire);
2175 }
2176
2177 int i915_gpu_idle(struct drm_device *dev, bool do_retire)
2178 {
2179         drm_i915_private_t *dev_priv = dev->dev_private;
2180         int ret, i;
2181
2182         /* Flush everything onto the inactive list. */
2183         for (i = 0; i < I915_NUM_RINGS; i++) {
2184                 ret = i915_ring_idle(&dev_priv->ring[i], do_retire);
2185                 if (ret)
2186                         return ret;
2187         }
2188
2189         return 0;
2190 }
2191
2192 static int sandybridge_write_fence_reg(struct drm_i915_gem_object *obj,
2193                                        struct intel_ring_buffer *pipelined)
2194 {
2195         struct drm_device *dev = obj->base.dev;
2196         drm_i915_private_t *dev_priv = dev->dev_private;
2197         u32 size = obj->gtt_space->size;
2198         int regnum = obj->fence_reg;
2199         uint64_t val;
2200
2201         val = (uint64_t)((obj->gtt_offset + size - 4096) &
2202                          0xfffff000) << 32;
2203         val |= obj->gtt_offset & 0xfffff000;
2204         val |= (uint64_t)((obj->stride / 128) - 1) <<
2205                 SANDYBRIDGE_FENCE_PITCH_SHIFT;
2206
2207         if (obj->tiling_mode == I915_TILING_Y)
2208                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2209         val |= I965_FENCE_REG_VALID;
2210
2211         if (pipelined) {
2212                 int ret = intel_ring_begin(pipelined, 6);
2213                 if (ret)
2214                         return ret;
2215
2216                 intel_ring_emit(pipelined, MI_NOOP);
2217                 intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(2));
2218                 intel_ring_emit(pipelined, FENCE_REG_SANDYBRIDGE_0 + regnum*8);
2219                 intel_ring_emit(pipelined, (u32)val);
2220                 intel_ring_emit(pipelined, FENCE_REG_SANDYBRIDGE_0 + regnum*8 + 4);
2221                 intel_ring_emit(pipelined, (u32)(val >> 32));
2222                 intel_ring_advance(pipelined);
2223         } else
2224                 I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + regnum * 8, val);
2225
2226         return 0;
2227 }
2228
2229 static int i965_write_fence_reg(struct drm_i915_gem_object *obj,
2230                                 struct intel_ring_buffer *pipelined)
2231 {
2232         struct drm_device *dev = obj->base.dev;
2233         drm_i915_private_t *dev_priv = dev->dev_private;
2234         u32 size = obj->gtt_space->size;
2235         int regnum = obj->fence_reg;
2236         uint64_t val;
2237
2238         val = (uint64_t)((obj->gtt_offset + size - 4096) &
2239                     0xfffff000) << 32;
2240         val |= obj->gtt_offset & 0xfffff000;
2241         val |= ((obj->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
2242         if (obj->tiling_mode == I915_TILING_Y)
2243                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
2244         val |= I965_FENCE_REG_VALID;
2245
2246         if (pipelined) {
2247                 int ret = intel_ring_begin(pipelined, 6);
2248                 if (ret)
2249                         return ret;
2250
2251                 intel_ring_emit(pipelined, MI_NOOP);
2252                 intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(2));
2253                 intel_ring_emit(pipelined, FENCE_REG_965_0 + regnum*8);
2254                 intel_ring_emit(pipelined, (u32)val);
2255                 intel_ring_emit(pipelined, FENCE_REG_965_0 + regnum*8 + 4);
2256                 intel_ring_emit(pipelined, (u32)(val >> 32));
2257                 intel_ring_advance(pipelined);
2258         } else
2259                 I915_WRITE64(FENCE_REG_965_0 + regnum * 8, val);
2260
2261         return 0;
2262 }
2263
2264 static int i915_write_fence_reg(struct drm_i915_gem_object *obj,
2265                                 struct intel_ring_buffer *pipelined)
2266 {
2267         struct drm_device *dev = obj->base.dev;
2268         drm_i915_private_t *dev_priv = dev->dev_private;
2269         u32 size = obj->gtt_space->size;
2270         u32 fence_reg, val, pitch_val;
2271         int tile_width;
2272
2273         if (WARN((obj->gtt_offset & ~I915_FENCE_START_MASK) ||
2274                  (size & -size) != size ||
2275                  (obj->gtt_offset & (size - 1)),
2276                  "object 0x%08x [fenceable? %d] not 1M or pot-size (0x%08x) aligned\n",
2277                  obj->gtt_offset, obj->map_and_fenceable, size))
2278                 return -EINVAL;
2279
2280         if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
2281                 tile_width = 128;
2282         else
2283                 tile_width = 512;
2284
2285         /* Note: pitch better be a power of two tile widths */
2286         pitch_val = obj->stride / tile_width;
2287         pitch_val = ffs(pitch_val) - 1;
2288
2289         val = obj->gtt_offset;
2290         if (obj->tiling_mode == I915_TILING_Y)
2291                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2292         val |= I915_FENCE_SIZE_BITS(size);
2293         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2294         val |= I830_FENCE_REG_VALID;
2295
2296         fence_reg = obj->fence_reg;
2297         if (fence_reg < 8)
2298                 fence_reg = FENCE_REG_830_0 + fence_reg * 4;
2299         else
2300                 fence_reg = FENCE_REG_945_8 + (fence_reg - 8) * 4;
2301
2302         if (pipelined) {
2303                 int ret = intel_ring_begin(pipelined, 4);
2304                 if (ret)
2305                         return ret;
2306
2307                 intel_ring_emit(pipelined, MI_NOOP);
2308                 intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(1));
2309                 intel_ring_emit(pipelined, fence_reg);
2310                 intel_ring_emit(pipelined, val);
2311                 intel_ring_advance(pipelined);
2312         } else
2313                 I915_WRITE(fence_reg, val);
2314
2315         return 0;
2316 }
2317
2318 static int i830_write_fence_reg(struct drm_i915_gem_object *obj,
2319                                 struct intel_ring_buffer *pipelined)
2320 {
2321         struct drm_device *dev = obj->base.dev;
2322         drm_i915_private_t *dev_priv = dev->dev_private;
2323         u32 size = obj->gtt_space->size;
2324         int regnum = obj->fence_reg;
2325         uint32_t val;
2326         uint32_t pitch_val;
2327
2328         if (WARN((obj->gtt_offset & ~I830_FENCE_START_MASK) ||
2329                  (size & -size) != size ||
2330                  (obj->gtt_offset & (size - 1)),
2331                  "object 0x%08x not 512K or pot-size 0x%08x aligned\n",
2332                  obj->gtt_offset, size))
2333                 return -EINVAL;
2334
2335         pitch_val = obj->stride / 128;
2336         pitch_val = ffs(pitch_val) - 1;
2337
2338         val = obj->gtt_offset;
2339         if (obj->tiling_mode == I915_TILING_Y)
2340                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
2341         val |= I830_FENCE_SIZE_BITS(size);
2342         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
2343         val |= I830_FENCE_REG_VALID;
2344
2345         if (pipelined) {
2346                 int ret = intel_ring_begin(pipelined, 4);
2347                 if (ret)
2348                         return ret;
2349
2350                 intel_ring_emit(pipelined, MI_NOOP);
2351                 intel_ring_emit(pipelined, MI_LOAD_REGISTER_IMM(1));
2352                 intel_ring_emit(pipelined, FENCE_REG_830_0 + regnum*4);
2353                 intel_ring_emit(pipelined, val);
2354                 intel_ring_advance(pipelined);
2355         } else
2356                 I915_WRITE(FENCE_REG_830_0 + regnum * 4, val);
2357
2358         return 0;
2359 }
2360
2361 static bool ring_passed_seqno(struct intel_ring_buffer *ring, u32 seqno)
2362 {
2363         return i915_seqno_passed(ring->get_seqno(ring), seqno);
2364 }
2365
2366 static int
2367 i915_gem_object_flush_fence(struct drm_i915_gem_object *obj,
2368                             struct intel_ring_buffer *pipelined)
2369 {
2370         int ret;
2371
2372         if (obj->fenced_gpu_access) {
2373                 if (obj->base.write_domain & I915_GEM_GPU_DOMAINS) {
2374                         ret = i915_gem_flush_ring(obj->last_fenced_ring,
2375                                                   0, obj->base.write_domain);
2376                         if (ret)
2377                                 return ret;
2378                 }
2379
2380                 obj->fenced_gpu_access = false;
2381         }
2382
2383         if (obj->last_fenced_seqno && pipelined != obj->last_fenced_ring) {
2384                 if (!ring_passed_seqno(obj->last_fenced_ring,
2385                                        obj->last_fenced_seqno)) {
2386                         ret = i915_wait_request(obj->last_fenced_ring,
2387                                                 obj->last_fenced_seqno,
2388                                                 true);
2389                         if (ret)
2390                                 return ret;
2391                 }
2392
2393                 obj->last_fenced_seqno = 0;
2394                 obj->last_fenced_ring = NULL;
2395         }
2396
2397         /* Ensure that all CPU reads are completed before installing a fence
2398          * and all writes before removing the fence.
2399          */
2400         if (obj->base.read_domains & I915_GEM_DOMAIN_GTT)
2401                 mb();
2402
2403         return 0;
2404 }
2405
2406 int
2407 i915_gem_object_put_fence(struct drm_i915_gem_object *obj)
2408 {
2409         int ret;
2410
2411         if (obj->tiling_mode)
2412                 i915_gem_release_mmap(obj);
2413
2414         ret = i915_gem_object_flush_fence(obj, NULL);
2415         if (ret)
2416                 return ret;
2417
2418         if (obj->fence_reg != I915_FENCE_REG_NONE) {
2419                 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2420
2421                 WARN_ON(dev_priv->fence_regs[obj->fence_reg].pin_count);
2422                 i915_gem_clear_fence_reg(obj->base.dev,
2423                                          &dev_priv->fence_regs[obj->fence_reg]);
2424
2425                 obj->fence_reg = I915_FENCE_REG_NONE;
2426         }
2427
2428         return 0;
2429 }
2430
2431 static struct drm_i915_fence_reg *
2432 i915_find_fence_reg(struct drm_device *dev,
2433                     struct intel_ring_buffer *pipelined)
2434 {
2435         struct drm_i915_private *dev_priv = dev->dev_private;
2436         struct drm_i915_fence_reg *reg, *first, *avail;
2437         int i;
2438
2439         /* First try to find a free reg */
2440         avail = NULL;
2441         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
2442                 reg = &dev_priv->fence_regs[i];
2443                 if (!reg->obj)
2444                         return reg;
2445
2446                 if (!reg->pin_count)
2447                         avail = reg;
2448         }
2449
2450         if (avail == NULL)
2451                 return NULL;
2452
2453         /* None available, try to steal one or wait for a user to finish */
2454         avail = first = NULL;
2455         list_for_each_entry(reg, &dev_priv->mm.fence_list, lru_list) {
2456                 if (reg->pin_count)
2457                         continue;
2458
2459                 if (first == NULL)
2460                         first = reg;
2461
2462                 if (!pipelined ||
2463                     !reg->obj->last_fenced_ring ||
2464                     reg->obj->last_fenced_ring == pipelined) {
2465                         avail = reg;
2466                         break;
2467                 }
2468         }
2469
2470         if (avail == NULL)
2471                 avail = first;
2472
2473         return avail;
2474 }
2475
2476 /**
2477  * i915_gem_object_get_fence - set up a fence reg for an object
2478  * @obj: object to map through a fence reg
2479  * @pipelined: ring on which to queue the change, or NULL for CPU access
2480  * @interruptible: must we wait uninterruptibly for the register to retire?
2481  *
2482  * When mapping objects through the GTT, userspace wants to be able to write
2483  * to them without having to worry about swizzling if the object is tiled.
2484  *
2485  * This function walks the fence regs looking for a free one for @obj,
2486  * stealing one if it can't find any.
2487  *
2488  * It then sets up the reg based on the object's properties: address, pitch
2489  * and tiling format.
2490  */
2491 int
2492 i915_gem_object_get_fence(struct drm_i915_gem_object *obj,
2493                           struct intel_ring_buffer *pipelined)
2494 {
2495         struct drm_device *dev = obj->base.dev;
2496         struct drm_i915_private *dev_priv = dev->dev_private;
2497         struct drm_i915_fence_reg *reg;
2498         int ret;
2499
2500         /* XXX disable pipelining. There are bugs. Shocking. */
2501         pipelined = NULL;
2502
2503         /* Just update our place in the LRU if our fence is getting reused. */
2504         if (obj->fence_reg != I915_FENCE_REG_NONE) {
2505                 reg = &dev_priv->fence_regs[obj->fence_reg];
2506                 list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2507
2508                 if (obj->tiling_changed) {
2509                         ret = i915_gem_object_flush_fence(obj, pipelined);
2510                         if (ret)
2511                                 return ret;
2512
2513                         if (!obj->fenced_gpu_access && !obj->last_fenced_seqno)
2514                                 pipelined = NULL;
2515
2516                         if (pipelined) {
2517                                 reg->setup_seqno =
2518                                         i915_gem_next_request_seqno(pipelined);
2519                                 obj->last_fenced_seqno = reg->setup_seqno;
2520                                 obj->last_fenced_ring = pipelined;
2521                         }
2522
2523                         goto update;
2524                 }
2525
2526                 if (!pipelined) {
2527                         if (reg->setup_seqno) {
2528                                 if (!ring_passed_seqno(obj->last_fenced_ring,
2529                                                        reg->setup_seqno)) {
2530                                         ret = i915_wait_request(obj->last_fenced_ring,
2531                                                                 reg->setup_seqno,
2532                                                                 true);
2533                                         if (ret)
2534                                                 return ret;
2535                                 }
2536
2537                                 reg->setup_seqno = 0;
2538                         }
2539                 } else if (obj->last_fenced_ring &&
2540                            obj->last_fenced_ring != pipelined) {
2541                         ret = i915_gem_object_flush_fence(obj, pipelined);
2542                         if (ret)
2543                                 return ret;
2544                 }
2545
2546                 return 0;
2547         }
2548
2549         reg = i915_find_fence_reg(dev, pipelined);
2550         if (reg == NULL)
2551                 return -EDEADLK;
2552
2553         ret = i915_gem_object_flush_fence(obj, pipelined);
2554         if (ret)
2555                 return ret;
2556
2557         if (reg->obj) {
2558                 struct drm_i915_gem_object *old = reg->obj;
2559
2560                 drm_gem_object_reference(&old->base);
2561
2562                 if (old->tiling_mode)
2563                         i915_gem_release_mmap(old);
2564
2565                 ret = i915_gem_object_flush_fence(old, pipelined);
2566                 if (ret) {
2567                         drm_gem_object_unreference(&old->base);
2568                         return ret;
2569                 }
2570
2571                 if (old->last_fenced_seqno == 0 && obj->last_fenced_seqno == 0)
2572                         pipelined = NULL;
2573
2574                 old->fence_reg = I915_FENCE_REG_NONE;
2575                 old->last_fenced_ring = pipelined;
2576                 old->last_fenced_seqno =
2577                         pipelined ? i915_gem_next_request_seqno(pipelined) : 0;
2578
2579                 drm_gem_object_unreference(&old->base);
2580         } else if (obj->last_fenced_seqno == 0)
2581                 pipelined = NULL;
2582
2583         reg->obj = obj;
2584         list_move_tail(&reg->lru_list, &dev_priv->mm.fence_list);
2585         obj->fence_reg = reg - dev_priv->fence_regs;
2586         obj->last_fenced_ring = pipelined;
2587
2588         reg->setup_seqno =
2589                 pipelined ? i915_gem_next_request_seqno(pipelined) : 0;
2590         obj->last_fenced_seqno = reg->setup_seqno;
2591
2592 update:
2593         obj->tiling_changed = false;
2594         switch (INTEL_INFO(dev)->gen) {
2595         case 7:
2596         case 6:
2597                 ret = sandybridge_write_fence_reg(obj, pipelined);
2598                 break;
2599         case 5:
2600         case 4:
2601                 ret = i965_write_fence_reg(obj, pipelined);
2602                 break;
2603         case 3:
2604                 ret = i915_write_fence_reg(obj, pipelined);
2605                 break;
2606         case 2:
2607                 ret = i830_write_fence_reg(obj, pipelined);
2608                 break;
2609         }
2610
2611         return ret;
2612 }
2613
2614 /**
2615  * i915_gem_clear_fence_reg - clear out fence register info
2616  * @obj: object to clear
2617  *
2618  * Zeroes out the fence register itself and clears out the associated
2619  * data structures in dev_priv and obj.
2620  */
2621 static void
2622 i915_gem_clear_fence_reg(struct drm_device *dev,
2623                          struct drm_i915_fence_reg *reg)
2624 {
2625         drm_i915_private_t *dev_priv = dev->dev_private;
2626         uint32_t fence_reg = reg - dev_priv->fence_regs;
2627
2628         switch (INTEL_INFO(dev)->gen) {
2629         case 7:
2630         case 6:
2631                 I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + fence_reg*8, 0);
2632                 break;
2633         case 5:
2634         case 4:
2635                 I915_WRITE64(FENCE_REG_965_0 + fence_reg*8, 0);
2636                 break;
2637         case 3:
2638                 if (fence_reg >= 8)
2639                         fence_reg = FENCE_REG_945_8 + (fence_reg - 8) * 4;
2640                 else
2641         case 2:
2642                         fence_reg = FENCE_REG_830_0 + fence_reg * 4;
2643
2644                 I915_WRITE(fence_reg, 0);
2645                 break;
2646         }
2647
2648         list_del_init(&reg->lru_list);
2649         reg->obj = NULL;
2650         reg->setup_seqno = 0;
2651         reg->pin_count = 0;
2652 }
2653
2654 /**
2655  * Finds free space in the GTT aperture and binds the object there.
2656  */
2657 static int
2658 i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
2659                             unsigned alignment,
2660                             bool map_and_fenceable)
2661 {
2662         struct drm_device *dev = obj->base.dev;
2663         drm_i915_private_t *dev_priv = dev->dev_private;
2664         struct drm_mm_node *free_space;
2665         gfp_t gfpmask = __GFP_NORETRY | __GFP_NOWARN;
2666         u32 size, fence_size, fence_alignment, unfenced_alignment;
2667         bool mappable, fenceable;
2668         int ret;
2669
2670         if (obj->madv != I915_MADV_WILLNEED) {
2671                 DRM_ERROR("Attempting to bind a purgeable object\n");
2672                 return -EINVAL;
2673         }
2674
2675         fence_size = i915_gem_get_gtt_size(dev,
2676                                            obj->base.size,
2677                                            obj->tiling_mode);
2678         fence_alignment = i915_gem_get_gtt_alignment(dev,
2679                                                      obj->base.size,
2680                                                      obj->tiling_mode);
2681         unfenced_alignment =
2682                 i915_gem_get_unfenced_gtt_alignment(dev,
2683                                                     obj->base.size,
2684                                                     obj->tiling_mode);
2685
2686         if (alignment == 0)
2687                 alignment = map_and_fenceable ? fence_alignment :
2688                                                 unfenced_alignment;
2689         if (map_and_fenceable && alignment & (fence_alignment - 1)) {
2690                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
2691                 return -EINVAL;
2692         }
2693
2694         size = map_and_fenceable ? fence_size : obj->base.size;
2695
2696         /* If the object is bigger than the entire aperture, reject it early
2697          * before evicting everything in a vain attempt to find space.
2698          */
2699         if (obj->base.size >
2700             (map_and_fenceable ? dev_priv->mm.gtt_mappable_end : dev_priv->mm.gtt_total)) {
2701                 DRM_ERROR("Attempting to bind an object larger than the aperture\n");
2702                 return -E2BIG;
2703         }
2704
2705  search_free:
2706         if (map_and_fenceable)
2707                 free_space =
2708                         drm_mm_search_free_in_range(&dev_priv->mm.gtt_space,
2709                                                     size, alignment, 0,
2710                                                     dev_priv->mm.gtt_mappable_end,
2711                                                     0);
2712         else
2713                 free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
2714                                                 size, alignment, 0);
2715
2716         if (free_space != NULL) {
2717                 if (map_and_fenceable)
2718                         obj->gtt_space =
2719                                 drm_mm_get_block_range_generic(free_space,
2720                                                                size, alignment, 0,
2721                                                                dev_priv->mm.gtt_mappable_end,
2722                                                                0);
2723                 else
2724                         obj->gtt_space =
2725                                 drm_mm_get_block(free_space, size, alignment);
2726         }
2727         if (obj->gtt_space == NULL) {
2728                 /* If the gtt is empty and we're still having trouble
2729                  * fitting our object in, we're out of memory.
2730                  */
2731                 ret = i915_gem_evict_something(dev, size, alignment,
2732                                                map_and_fenceable);
2733                 if (ret)
2734                         return ret;
2735
2736                 goto search_free;
2737         }
2738
2739         ret = i915_gem_object_get_pages_gtt(obj, gfpmask);
2740         if (ret) {
2741                 drm_mm_put_block(obj->gtt_space);
2742                 obj->gtt_space = NULL;
2743
2744                 if (ret == -ENOMEM) {
2745                         /* first try to reclaim some memory by clearing the GTT */
2746                         ret = i915_gem_evict_everything(dev, false);
2747                         if (ret) {
2748                                 /* now try to shrink everyone else */
2749                                 if (gfpmask) {
2750                                         gfpmask = 0;
2751                                         goto search_free;
2752                                 }
2753
2754                                 return -ENOMEM;
2755                         }
2756
2757                         goto search_free;
2758                 }
2759
2760                 return ret;
2761         }
2762
2763         ret = i915_gem_gtt_bind_object(obj);
2764         if (ret) {
2765                 i915_gem_object_put_pages_gtt(obj);
2766                 drm_mm_put_block(obj->gtt_space);
2767                 obj->gtt_space = NULL;
2768
2769                 if (i915_gem_evict_everything(dev, false))
2770                         return ret;
2771
2772                 goto search_free;
2773         }
2774
2775         list_add_tail(&obj->gtt_list, &dev_priv->mm.gtt_list);
2776         list_add_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
2777
2778         /* Assert that the object is not currently in any GPU domain. As it
2779          * wasn't in the GTT, there shouldn't be any way it could have been in
2780          * a GPU cache
2781          */
2782         BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2783         BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2784
2785         obj->gtt_offset = obj->gtt_space->start;
2786
2787         fenceable =
2788                 obj->gtt_space->size == fence_size &&
2789                 (obj->gtt_space->start & (fence_alignment - 1)) == 0;
2790
2791         mappable =
2792                 obj->gtt_offset + obj->base.size <= dev_priv->mm.gtt_mappable_end;
2793
2794         obj->map_and_fenceable = mappable && fenceable;
2795
2796         trace_i915_gem_object_bind(obj, map_and_fenceable);
2797         return 0;
2798 }
2799
2800 void
2801 i915_gem_clflush_object(struct drm_i915_gem_object *obj)
2802 {
2803         /* If we don't have a page list set up, then we're not pinned
2804          * to GPU, and we can ignore the cache flush because it'll happen
2805          * again at bind time.
2806          */
2807         if (obj->pages == NULL)
2808                 return;
2809
2810         /* If the GPU is snooping the contents of the CPU cache,
2811          * we do not need to manually clear the CPU cache lines.  However,
2812          * the caches are only snooped when the render cache is
2813          * flushed/invalidated.  As we always have to emit invalidations
2814          * and flushes when moving into and out of the RENDER domain, correct
2815          * snooping behaviour occurs naturally as the result of our domain
2816          * tracking.
2817          */
2818         if (obj->cache_level != I915_CACHE_NONE)
2819                 return;
2820
2821         trace_i915_gem_object_clflush(obj);
2822
2823         drm_clflush_pages(obj->pages, obj->base.size / PAGE_SIZE);
2824 }
2825
2826 /** Flushes any GPU write domain for the object if it's dirty. */
2827 static int
2828 i915_gem_object_flush_gpu_write_domain(struct drm_i915_gem_object *obj)
2829 {
2830         if ((obj->base.write_domain & I915_GEM_GPU_DOMAINS) == 0)
2831                 return 0;
2832
2833         /* Queue the GPU write cache flushing we need. */
2834         return i915_gem_flush_ring(obj->ring, 0, obj->base.write_domain);
2835 }
2836
2837 /** Flushes the GTT write domain for the object if it's dirty. */
2838 static void
2839 i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
2840 {
2841         uint32_t old_write_domain;
2842
2843         if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
2844                 return;
2845
2846         /* No actual flushing is required for the GTT write domain.  Writes
2847          * to it immediately go to main memory as far as we know, so there's
2848          * no chipset flush.  It also doesn't land in render cache.
2849          *
2850          * However, we do have to enforce the order so that all writes through
2851          * the GTT land before any writes to the device, such as updates to
2852          * the GATT itself.
2853          */
2854         wmb();
2855
2856         old_write_domain = obj->base.write_domain;
2857         obj->base.write_domain = 0;
2858
2859         trace_i915_gem_object_change_domain(obj,
2860                                             obj->base.read_domains,
2861                                             old_write_domain);
2862 }
2863
2864 /** Flushes the CPU write domain for the object if it's dirty. */
2865 static void
2866 i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
2867 {
2868         uint32_t old_write_domain;
2869
2870         if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
2871                 return;
2872
2873         i915_gem_clflush_object(obj);
2874         intel_gtt_chipset_flush();
2875         old_write_domain = obj->base.write_domain;
2876         obj->base.write_domain = 0;
2877
2878         trace_i915_gem_object_change_domain(obj,
2879                                             obj->base.read_domains,
2880                                             old_write_domain);
2881 }
2882
2883 /**
2884  * Moves a single object to the GTT read, and possibly write domain.
2885  *
2886  * This function returns when the move is complete, including waiting on
2887  * flushes to occur.
2888  */
2889 int
2890 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
2891 {
2892         uint32_t old_write_domain, old_read_domains;
2893         int ret;
2894
2895         /* Not valid to be called on unbound objects. */
2896         if (obj->gtt_space == NULL)
2897                 return -EINVAL;
2898
2899         if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
2900                 return 0;
2901
2902         ret = i915_gem_object_flush_gpu_write_domain(obj);
2903         if (ret)
2904                 return ret;
2905
2906         if (obj->pending_gpu_write || write) {
2907                 ret = i915_gem_object_wait_rendering(obj);
2908                 if (ret)
2909                         return ret;
2910         }
2911
2912         i915_gem_object_flush_cpu_write_domain(obj);
2913
2914         old_write_domain = obj->base.write_domain;
2915         old_read_domains = obj->base.read_domains;
2916
2917         /* It should now be out of any other write domains, and we can update
2918          * the domain values for our changes.
2919          */
2920         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
2921         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
2922         if (write) {
2923                 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
2924                 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
2925                 obj->dirty = 1;
2926         }
2927
2928         trace_i915_gem_object_change_domain(obj,
2929                                             old_read_domains,
2930                                             old_write_domain);
2931
2932         return 0;
2933 }
2934
2935 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
2936                                     enum i915_cache_level cache_level)
2937 {
2938         struct drm_device *dev = obj->base.dev;
2939         drm_i915_private_t *dev_priv = dev->dev_private;
2940         int ret;
2941
2942         if (obj->cache_level == cache_level)
2943                 return 0;
2944
2945         if (obj->pin_count) {
2946                 DRM_DEBUG("can not change the cache level of pinned objects\n");
2947                 return -EBUSY;
2948         }
2949
2950         if (obj->gtt_space) {
2951                 ret = i915_gem_object_finish_gpu(obj);
2952                 if (ret)
2953                         return ret;
2954
2955                 i915_gem_object_finish_gtt(obj);
2956
2957                 /* Before SandyBridge, you could not use tiling or fence
2958                  * registers with snooped memory, so relinquish any fences
2959                  * currently pointing to our region in the aperture.
2960                  */
2961                 if (INTEL_INFO(obj->base.dev)->gen < 6) {
2962                         ret = i915_gem_object_put_fence(obj);
2963                         if (ret)
2964                                 return ret;
2965                 }
2966
2967                 i915_gem_gtt_rebind_object(obj, cache_level);
2968                 if (obj->has_aliasing_ppgtt_mapping)
2969                         i915_ppgtt_bind_object(dev_priv->mm.aliasing_ppgtt,
2970                                                obj, cache_level);
2971         }
2972
2973         if (cache_level == I915_CACHE_NONE) {
2974                 u32 old_read_domains, old_write_domain;
2975
2976                 /* If we're coming from LLC cached, then we haven't
2977                  * actually been tracking whether the data is in the
2978                  * CPU cache or not, since we only allow one bit set
2979                  * in obj->write_domain and have been skipping the clflushes.
2980                  * Just set it to the CPU cache for now.
2981                  */
2982                 WARN_ON(obj->base.write_domain & ~I915_GEM_DOMAIN_CPU);
2983                 WARN_ON(obj->base.read_domains & ~I915_GEM_DOMAIN_CPU);
2984
2985                 old_read_domains = obj->base.read_domains;
2986                 old_write_domain = obj->base.write_domain;
2987
2988                 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
2989                 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
2990
2991                 trace_i915_gem_object_change_domain(obj,
2992                                                     old_read_domains,
2993                                                     old_write_domain);
2994         }
2995
2996         obj->cache_level = cache_level;
2997         return 0;
2998 }
2999
3000 /*
3001  * Prepare buffer for display plane (scanout, cursors, etc).
3002  * Can be called from an uninterruptible phase (modesetting) and allows
3003  * any flushes to be pipelined (for pageflips).
3004  *
3005  * For the display plane, we want to be in the GTT but out of any write
3006  * domains. So in many ways this looks like set_to_gtt_domain() apart from the
3007  * ability to pipeline the waits, pinning and any additional subtleties
3008  * that may differentiate the display plane from ordinary buffers.
3009  */
3010 int
3011 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
3012                                      u32 alignment,
3013                                      struct intel_ring_buffer *pipelined)
3014 {
3015         u32 old_read_domains, old_write_domain;
3016         int ret;
3017
3018         ret = i915_gem_object_flush_gpu_write_domain(obj);
3019         if (ret)
3020                 return ret;
3021
3022         if (pipelined != obj->ring) {
3023                 ret = i915_gem_object_wait_rendering(obj);
3024                 if (ret == -ERESTARTSYS)
3025                         return ret;
3026         }
3027
3028         /* The display engine is not coherent with the LLC cache on gen6.  As
3029          * a result, we make sure that the pinning that is about to occur is
3030          * done with uncached PTEs. This is lowest common denominator for all
3031          * chipsets.
3032          *
3033          * However for gen6+, we could do better by using the GFDT bit instead
3034          * of uncaching, which would allow us to flush all the LLC-cached data
3035          * with that bit in the PTE to main memory with just one PIPE_CONTROL.
3036          */
3037         ret = i915_gem_object_set_cache_level(obj, I915_CACHE_NONE);
3038         if (ret)
3039                 return ret;
3040
3041         /* As the user may map the buffer once pinned in the display plane
3042          * (e.g. libkms for the bootup splash), we have to ensure that we
3043          * always use map_and_fenceable for all scanout buffers.
3044          */
3045         ret = i915_gem_object_pin(obj, alignment, true);
3046         if (ret)
3047                 return ret;
3048
3049         i915_gem_object_flush_cpu_write_domain(obj);
3050
3051         old_write_domain = obj->base.write_domain;
3052         old_read_domains = obj->base.read_domains;
3053
3054         /* It should now be out of any other write domains, and we can update
3055          * the domain values for our changes.
3056          */
3057         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
3058         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3059
3060         trace_i915_gem_object_change_domain(obj,
3061                                             old_read_domains,
3062                                             old_write_domain);
3063
3064         return 0;
3065 }
3066
3067 int
3068 i915_gem_object_finish_gpu(struct drm_i915_gem_object *obj)
3069 {
3070         int ret;
3071
3072         if ((obj->base.read_domains & I915_GEM_GPU_DOMAINS) == 0)
3073                 return 0;
3074
3075         if (obj->base.write_domain & I915_GEM_GPU_DOMAINS) {
3076                 ret = i915_gem_flush_ring(obj->ring, 0, obj->base.write_domain);
3077                 if (ret)
3078                         return ret;
3079         }
3080
3081         ret = i915_gem_object_wait_rendering(obj);
3082         if (ret)
3083                 return ret;
3084
3085         /* Ensure that we invalidate the GPU's caches and TLBs. */
3086         obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
3087         return 0;
3088 }
3089
3090 /**
3091  * Moves a single object to the CPU read, and possibly write domain.
3092  *
3093  * This function returns when the move is complete, including waiting on
3094  * flushes to occur.
3095  */
3096 static int
3097 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
3098 {
3099         uint32_t old_write_domain, old_read_domains;
3100         int ret;
3101
3102         if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
3103                 return 0;
3104
3105         ret = i915_gem_object_flush_gpu_write_domain(obj);
3106         if (ret)
3107                 return ret;
3108
3109         ret = i915_gem_object_wait_rendering(obj);
3110         if (ret)
3111                 return ret;
3112
3113         i915_gem_object_flush_gtt_write_domain(obj);
3114
3115         /* If we have a partially-valid cache of the object in the CPU,
3116          * finish invalidating it and free the per-page flags.
3117          */
3118         i915_gem_object_set_to_full_cpu_read_domain(obj);
3119
3120         old_write_domain = obj->base.write_domain;
3121         old_read_domains = obj->base.read_domains;
3122
3123         /* Flush the CPU cache if it's still invalid. */
3124         if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
3125                 i915_gem_clflush_object(obj);
3126
3127                 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3128         }
3129
3130         /* It should now be out of any other write domains, and we can update
3131          * the domain values for our changes.
3132          */
3133         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3134
3135         /* If we're writing through the CPU, then the GPU read domains will
3136          * need to be invalidated at next use.
3137          */
3138         if (write) {
3139                 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3140                 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3141         }
3142
3143         trace_i915_gem_object_change_domain(obj,
3144                                             old_read_domains,
3145                                             old_write_domain);
3146
3147         return 0;
3148 }
3149
3150 /**
3151  * Moves the object from a partially CPU read to a full one.
3152  *
3153  * Note that this only resolves i915_gem_object_set_cpu_read_domain_range(),
3154  * and doesn't handle transitioning from !(read_domains & I915_GEM_DOMAIN_CPU).
3155  */
3156 static void
3157 i915_gem_object_set_to_full_cpu_read_domain(struct drm_i915_gem_object *obj)
3158 {
3159         if (!obj->page_cpu_valid)
3160                 return;
3161
3162         /* If we're partially in the CPU read domain, finish moving it in.
3163          */
3164         if (obj->base.read_domains & I915_GEM_DOMAIN_CPU) {
3165                 int i;
3166
3167                 for (i = 0; i <= (obj->base.size - 1) / PAGE_SIZE; i++) {
3168                         if (obj->page_cpu_valid[i])
3169                                 continue;
3170                         drm_clflush_pages(obj->pages + i, 1);
3171                 }
3172         }
3173
3174         /* Free the page_cpu_valid mappings which are now stale, whether
3175          * or not we've got I915_GEM_DOMAIN_CPU.
3176          */
3177         kfree(obj->page_cpu_valid);
3178         obj->page_cpu_valid = NULL;
3179 }
3180
3181 /**
3182  * Set the CPU read domain on a range of the object.
3183  *
3184  * The object ends up with I915_GEM_DOMAIN_CPU in its read flags although it's
3185  * not entirely valid.  The page_cpu_valid member of the object flags which
3186  * pages have been flushed, and will be respected by
3187  * i915_gem_object_set_to_cpu_domain() if it's called on to get a valid mapping
3188  * of the whole object.
3189  *
3190  * This function returns when the move is complete, including waiting on
3191  * flushes to occur.
3192  */
3193 static int
3194 i915_gem_object_set_cpu_read_domain_range(struct drm_i915_gem_object *obj,
3195                                           uint64_t offset, uint64_t size)
3196 {
3197         uint32_t old_read_domains;
3198         int i, ret;
3199
3200         if (offset == 0 && size == obj->base.size)
3201                 return i915_gem_object_set_to_cpu_domain(obj, 0);
3202
3203         ret = i915_gem_object_flush_gpu_write_domain(obj);
3204         if (ret)
3205                 return ret;
3206
3207         ret = i915_gem_object_wait_rendering(obj);
3208         if (ret)
3209                 return ret;
3210
3211         i915_gem_object_flush_gtt_write_domain(obj);
3212
3213         /* If we're already fully in the CPU read domain, we're done. */
3214         if (obj->page_cpu_valid == NULL &&
3215             (obj->base.read_domains & I915_GEM_DOMAIN_CPU) != 0)
3216                 return 0;
3217
3218         /* Otherwise, create/clear the per-page CPU read domain flag if we're
3219          * newly adding I915_GEM_DOMAIN_CPU
3220          */
3221         if (obj->page_cpu_valid == NULL) {
3222                 obj->page_cpu_valid = kzalloc(obj->base.size / PAGE_SIZE,
3223                                               GFP_KERNEL);
3224                 if (obj->page_cpu_valid == NULL)
3225                         return -ENOMEM;
3226         } else if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0)
3227                 memset(obj->page_cpu_valid, 0, obj->base.size / PAGE_SIZE);
3228
3229         /* Flush the cache on any pages that are still invalid from the CPU's
3230          * perspective.
3231          */
3232         for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
3233              i++) {
3234                 if (obj->page_cpu_valid[i])
3235                         continue;
3236
3237                 drm_clflush_pages(obj->pages + i, 1);
3238
3239                 obj->page_cpu_valid[i] = 1;
3240         }
3241
3242         /* It should now be out of any other write domains, and we can update
3243          * the domain values for our changes.
3244          */
3245         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
3246
3247         old_read_domains = obj->base.read_domains;
3248         obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
3249
3250         trace_i915_gem_object_change_domain(obj,
3251                                             old_read_domains,
3252                                             obj->base.write_domain);
3253
3254         return 0;
3255 }
3256
3257 /* Throttle our rendering by waiting until the ring has completed our requests
3258  * emitted over 20 msec ago.
3259  *
3260  * Note that if we were to use the current jiffies each time around the loop,
3261  * we wouldn't escape the function with any frames outstanding if the time to
3262  * render a frame was over 20ms.
3263  *
3264  * This should get us reasonable parallelism between CPU and GPU but also
3265  * relatively low latency when blocking on a particular request to finish.
3266  */
3267 static int
3268 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
3269 {
3270         struct drm_i915_private *dev_priv = dev->dev_private;
3271         struct drm_i915_file_private *file_priv = file->driver_priv;
3272         unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
3273         struct drm_i915_gem_request *request;
3274         struct intel_ring_buffer *ring = NULL;
3275         u32 seqno = 0;
3276         int ret;
3277
3278         if (atomic_read(&dev_priv->mm.wedged))
3279                 return -EIO;
3280
3281         spin_lock(&file_priv->mm.lock);
3282         list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
3283                 if (time_after_eq(request->emitted_jiffies, recent_enough))
3284                         break;
3285
3286                 ring = request->ring;
3287                 seqno = request->seqno;
3288         }
3289         spin_unlock(&file_priv->mm.lock);
3290
3291         if (seqno == 0)
3292                 return 0;
3293
3294         ret = 0;
3295         if (!i915_seqno_passed(ring->get_seqno(ring), seqno)) {
3296                 /* And wait for the seqno passing without holding any locks and
3297                  * causing extra latency for others. This is safe as the irq
3298                  * generation is designed to be run atomically and so is
3299                  * lockless.
3300                  */
3301                 if (ring->irq_get(ring)) {
3302                         ret = wait_event_interruptible(ring->irq_queue,
3303                                                        i915_seqno_passed(ring->get_seqno(ring), seqno)
3304                                                        || atomic_read(&dev_priv->mm.wedged));
3305                         ring->irq_put(ring);
3306
3307                         if (ret == 0 && atomic_read(&dev_priv->mm.wedged))
3308                                 ret = -EIO;
3309                 } else if (wait_for_atomic(i915_seqno_passed(ring->get_seqno(ring),
3310                                                              seqno) ||
3311                                     atomic_read(&dev_priv->mm.wedged), 3000)) {
3312                         ret = -EBUSY;
3313                 }
3314         }
3315
3316         if (ret == 0)
3317                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
3318
3319         return ret;
3320 }
3321
3322 int
3323 i915_gem_object_pin(struct drm_i915_gem_object *obj,
3324                     uint32_t alignment,
3325                     bool map_and_fenceable)
3326 {
3327         struct drm_device *dev = obj->base.dev;
3328         struct drm_i915_private *dev_priv = dev->dev_private;
3329         int ret;
3330
3331         BUG_ON(obj->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT);
3332         WARN_ON(i915_verify_lists(dev));
3333
3334         if (obj->gtt_space != NULL) {
3335                 if ((alignment && obj->gtt_offset & (alignment - 1)) ||
3336                     (map_and_fenceable && !obj->map_and_fenceable)) {
3337                         WARN(obj->pin_count,
3338                              "bo is already pinned with incorrect alignment:"
3339                              " offset=%x, req.alignment=%x, req.map_and_fenceable=%d,"
3340                              " obj->map_and_fenceable=%d\n",
3341                              obj->gtt_offset, alignment,
3342                              map_and_fenceable,
3343                              obj->map_and_fenceable);
3344                         ret = i915_gem_object_unbind(obj);
3345                         if (ret)
3346                                 return ret;
3347                 }
3348         }
3349
3350         if (obj->gtt_space == NULL) {
3351                 ret = i915_gem_object_bind_to_gtt(obj, alignment,
3352                                                   map_and_fenceable);
3353                 if (ret)
3354                         return ret;
3355         }
3356
3357         if (obj->pin_count++ == 0) {
3358                 if (!obj->active)
3359                         list_move_tail(&obj->mm_list,
3360                                        &dev_priv->mm.pinned_list);
3361         }
3362         obj->pin_mappable |= map_and_fenceable;
3363
3364         WARN_ON(i915_verify_lists(dev));
3365         return 0;
3366 }
3367
3368 void
3369 i915_gem_object_unpin(struct drm_i915_gem_object *obj)
3370 {
3371         struct drm_device *dev = obj->base.dev;
3372         drm_i915_private_t *dev_priv = dev->dev_private;
3373
3374         WARN_ON(i915_verify_lists(dev));
3375         BUG_ON(obj->pin_count == 0);
3376         BUG_ON(obj->gtt_space == NULL);
3377
3378         if (--obj->pin_count == 0) {
3379                 if (!obj->active)
3380                         list_move_tail(&obj->mm_list,
3381                                        &dev_priv->mm.inactive_list);
3382                 obj->pin_mappable = false;
3383         }
3384         WARN_ON(i915_verify_lists(dev));
3385 }
3386
3387 int
3388 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
3389                    struct drm_file *file)
3390 {
3391         struct drm_i915_gem_pin *args = data;
3392         struct drm_i915_gem_object *obj;
3393         int ret;
3394
3395         ret = i915_mutex_lock_interruptible(dev);
3396         if (ret)
3397                 return ret;
3398
3399         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3400         if (&obj->base == NULL) {
3401                 ret = -ENOENT;
3402                 goto unlock;
3403         }
3404
3405         if (obj->madv != I915_MADV_WILLNEED) {
3406                 DRM_ERROR("Attempting to pin a purgeable buffer\n");
3407                 ret = -EINVAL;
3408                 goto out;
3409         }
3410
3411         if (obj->pin_filp != NULL && obj->pin_filp != file) {
3412                 DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
3413                           args->handle);
3414                 ret = -EINVAL;
3415                 goto out;
3416         }
3417
3418         obj->user_pin_count++;
3419         obj->pin_filp = file;
3420         if (obj->user_pin_count == 1) {
3421                 ret = i915_gem_object_pin(obj, args->alignment, true);
3422                 if (ret)
3423                         goto out;
3424         }
3425
3426         /* XXX - flush the CPU caches for pinned objects
3427          * as the X server doesn't manage domains yet
3428          */
3429         i915_gem_object_flush_cpu_write_domain(obj);
3430         args->offset = obj->gtt_offset;
3431 out:
3432         drm_gem_object_unreference(&obj->base);
3433 unlock:
3434         mutex_unlock(&dev->struct_mutex);
3435         return ret;
3436 }
3437
3438 int
3439 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
3440                      struct drm_file *file)
3441 {
3442         struct drm_i915_gem_pin *args = data;
3443         struct drm_i915_gem_object *obj;
3444         int ret;
3445
3446         ret = i915_mutex_lock_interruptible(dev);
3447         if (ret)
3448                 return ret;
3449
3450         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3451         if (&obj->base == NULL) {
3452                 ret = -ENOENT;
3453                 goto unlock;
3454         }
3455
3456         if (obj->pin_filp != file) {
3457                 DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
3458                           args->handle);
3459                 ret = -EINVAL;
3460                 goto out;
3461         }
3462         obj->user_pin_count--;
3463         if (obj->user_pin_count == 0) {
3464                 obj->pin_filp = NULL;
3465                 i915_gem_object_unpin(obj);
3466         }
3467
3468 out:
3469         drm_gem_object_unreference(&obj->base);
3470 unlock:
3471         mutex_unlock(&dev->struct_mutex);
3472         return ret;
3473 }
3474
3475 int
3476 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
3477                     struct drm_file *file)
3478 {
3479         struct drm_i915_gem_busy *args = data;
3480         struct drm_i915_gem_object *obj;
3481         int ret;
3482
3483         ret = i915_mutex_lock_interruptible(dev);
3484         if (ret)
3485                 return ret;
3486
3487         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3488         if (&obj->base == NULL) {
3489                 ret = -ENOENT;
3490                 goto unlock;
3491         }
3492
3493         /* Count all active objects as busy, even if they are currently not used
3494          * by the gpu. Users of this interface expect objects to eventually
3495          * become non-busy without any further actions, therefore emit any
3496          * necessary flushes here.
3497          */
3498         args->busy = obj->active;
3499         if (args->busy) {
3500                 /* Unconditionally flush objects, even when the gpu still uses this
3501                  * object. Userspace calling this function indicates that it wants to
3502                  * use this buffer rather sooner than later, so issuing the required
3503                  * flush earlier is beneficial.
3504                  */
3505                 if (obj->base.write_domain & I915_GEM_GPU_DOMAINS) {
3506                         ret = i915_gem_flush_ring(obj->ring,
3507                                                   0, obj->base.write_domain);
3508                 } else if (obj->ring->outstanding_lazy_request ==
3509                            obj->last_rendering_seqno) {
3510                         struct drm_i915_gem_request *request;
3511
3512                         /* This ring is not being cleared by active usage,
3513                          * so emit a request to do so.
3514                          */
3515                         request = kzalloc(sizeof(*request), GFP_KERNEL);
3516                         if (request) {
3517                                 ret = i915_add_request(obj->ring, NULL, request);
3518                                 if (ret)
3519                                         kfree(request);
3520                         } else
3521                                 ret = -ENOMEM;
3522                 }
3523
3524                 /* Update the active list for the hardware's current position.
3525                  * Otherwise this only updates on a delayed timer or when irqs
3526                  * are actually unmasked, and our working set ends up being
3527                  * larger than required.
3528                  */
3529                 i915_gem_retire_requests_ring(obj->ring);
3530
3531                 args->busy = obj->active;
3532         }
3533
3534         drm_gem_object_unreference(&obj->base);
3535 unlock:
3536         mutex_unlock(&dev->struct_mutex);
3537         return ret;
3538 }
3539
3540 int
3541 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
3542                         struct drm_file *file_priv)
3543 {
3544         return i915_gem_ring_throttle(dev, file_priv);
3545 }
3546
3547 int
3548 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
3549                        struct drm_file *file_priv)
3550 {
3551         struct drm_i915_gem_madvise *args = data;
3552         struct drm_i915_gem_object *obj;
3553         int ret;
3554
3555         switch (args->madv) {
3556         case I915_MADV_DONTNEED:
3557         case I915_MADV_WILLNEED:
3558             break;
3559         default:
3560             return -EINVAL;
3561         }
3562
3563         ret = i915_mutex_lock_interruptible(dev);
3564         if (ret)
3565                 return ret;
3566
3567         obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
3568         if (&obj->base == NULL) {
3569                 ret = -ENOENT;
3570                 goto unlock;
3571         }
3572
3573         if (obj->pin_count) {
3574                 ret = -EINVAL;
3575                 goto out;
3576         }
3577
3578         if (obj->madv != __I915_MADV_PURGED)
3579                 obj->madv = args->madv;
3580
3581         /* if the object is no longer bound, discard its backing storage */
3582         if (i915_gem_object_is_purgeable(obj) &&
3583             obj->gtt_space == NULL)
3584                 i915_gem_object_truncate(obj);
3585
3586         args->retained = obj->madv != __I915_MADV_PURGED;
3587
3588 out:
3589         drm_gem_object_unreference(&obj->base);
3590 unlock:
3591         mutex_unlock(&dev->struct_mutex);
3592         return ret;
3593 }
3594
3595 struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
3596                                                   size_t size)
3597 {
3598         struct drm_i915_private *dev_priv = dev->dev_private;
3599         struct drm_i915_gem_object *obj;
3600         struct address_space *mapping;
3601
3602         obj = kzalloc(sizeof(*obj), GFP_KERNEL);
3603         if (obj == NULL)
3604                 return NULL;
3605
3606         if (drm_gem_object_init(dev, &obj->base, size) != 0) {
3607                 kfree(obj);
3608                 return NULL;
3609         }
3610
3611         mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
3612         mapping_set_gfp_mask(mapping, GFP_HIGHUSER | __GFP_RECLAIMABLE);
3613
3614         i915_gem_info_add_obj(dev_priv, size);
3615
3616         obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3617         obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3618
3619         if (HAS_LLC(dev)) {
3620                 /* On some devices, we can have the GPU use the LLC (the CPU
3621                  * cache) for about a 10% performance improvement
3622                  * compared to uncached.  Graphics requests other than
3623                  * display scanout are coherent with the CPU in
3624                  * accessing this cache.  This means in this mode we
3625                  * don't need to clflush on the CPU side, and on the
3626                  * GPU side we only need to flush internal caches to
3627                  * get data visible to the CPU.
3628                  *
3629                  * However, we maintain the display planes as UC, and so
3630                  * need to rebind when first used as such.
3631                  */
3632                 obj->cache_level = I915_CACHE_LLC;
3633         } else
3634                 obj->cache_level = I915_CACHE_NONE;
3635
3636         obj->base.driver_private = NULL;
3637         obj->fence_reg = I915_FENCE_REG_NONE;
3638         INIT_LIST_HEAD(&obj->mm_list);
3639         INIT_LIST_HEAD(&obj->gtt_list);
3640         INIT_LIST_HEAD(&obj->ring_list);
3641         INIT_LIST_HEAD(&obj->exec_list);
3642         INIT_LIST_HEAD(&obj->gpu_write_list);
3643         obj->madv = I915_MADV_WILLNEED;
3644         /* Avoid an unnecessary call to unbind on the first bind. */
3645         obj->map_and_fenceable = true;
3646
3647         return obj;
3648 }
3649
3650 int i915_gem_init_object(struct drm_gem_object *obj)
3651 {
3652         BUG();
3653
3654         return 0;
3655 }
3656
3657 static void i915_gem_free_object_tail(struct drm_i915_gem_object *obj)
3658 {
3659         struct drm_device *dev = obj->base.dev;
3660         drm_i915_private_t *dev_priv = dev->dev_private;
3661         int ret;
3662
3663         ret = i915_gem_object_unbind(obj);
3664         if (ret == -ERESTARTSYS) {
3665                 list_move(&obj->mm_list,
3666                           &dev_priv->mm.deferred_free_list);
3667                 return;
3668         }
3669
3670         trace_i915_gem_object_destroy(obj);
3671
3672         if (obj->base.map_list.map)
3673                 drm_gem_free_mmap_offset(&obj->base);
3674
3675         drm_gem_object_release(&obj->base);
3676         i915_gem_info_remove_obj(dev_priv, obj->base.size);
3677
3678         kfree(obj->page_cpu_valid);
3679         kfree(obj->bit_17);
3680         kfree(obj);
3681 }
3682
3683 void i915_gem_free_object(struct drm_gem_object *gem_obj)
3684 {
3685         struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
3686         struct drm_device *dev = obj->base.dev;
3687
3688         while (obj->pin_count > 0)
3689                 i915_gem_object_unpin(obj);
3690
3691         if (obj->phys_obj)
3692                 i915_gem_detach_phys_object(dev, obj);
3693
3694         i915_gem_free_object_tail(obj);
3695 }
3696
3697 int
3698 i915_gem_idle(struct drm_device *dev)
3699 {
3700         drm_i915_private_t *dev_priv = dev->dev_private;
3701         int ret;
3702
3703         mutex_lock(&dev->struct_mutex);
3704
3705         if (dev_priv->mm.suspended) {
3706                 mutex_unlock(&dev->struct_mutex);
3707                 return 0;
3708         }
3709
3710         ret = i915_gpu_idle(dev, true);
3711         if (ret) {
3712                 mutex_unlock(&dev->struct_mutex);
3713                 return ret;
3714         }
3715
3716         /* Under UMS, be paranoid and evict. */
3717         if (!drm_core_check_feature(dev, DRIVER_MODESET)) {
3718                 ret = i915_gem_evict_inactive(dev, false);
3719                 if (ret) {
3720                         mutex_unlock(&dev->struct_mutex);
3721                         return ret;
3722                 }
3723         }
3724
3725         i915_gem_reset_fences(dev);
3726
3727         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
3728          * We need to replace this with a semaphore, or something.
3729          * And not confound mm.suspended!
3730          */
3731         dev_priv->mm.suspended = 1;
3732         del_timer_sync(&dev_priv->hangcheck_timer);
3733
3734         i915_kernel_lost_context(dev);
3735         i915_gem_cleanup_ringbuffer(dev);
3736
3737         mutex_unlock(&dev->struct_mutex);
3738
3739         /* Cancel the retire work handler, which should be idle now. */
3740         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
3741
3742         return 0;
3743 }
3744
3745 void i915_gem_init_swizzling(struct drm_device *dev)
3746 {
3747         drm_i915_private_t *dev_priv = dev->dev_private;
3748
3749         if (INTEL_INFO(dev)->gen < 5 ||
3750             dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
3751                 return;
3752
3753         I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
3754                                  DISP_TILE_SURFACE_SWIZZLING);
3755
3756         if (IS_GEN5(dev))
3757                 return;
3758
3759         I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
3760         if (IS_GEN6(dev))
3761                 I915_WRITE(ARB_MODE, ARB_MODE_ENABLE(ARB_MODE_SWIZZLE_SNB));
3762         else
3763                 I915_WRITE(ARB_MODE, ARB_MODE_ENABLE(ARB_MODE_SWIZZLE_IVB));
3764 }
3765
3766 void i915_gem_init_ppgtt(struct drm_device *dev)
3767 {
3768         drm_i915_private_t *dev_priv = dev->dev_private;
3769         uint32_t pd_offset;
3770         struct intel_ring_buffer *ring;
3771         struct i915_hw_ppgtt *ppgtt = dev_priv->mm.aliasing_ppgtt;
3772         uint32_t __iomem *pd_addr;
3773         uint32_t pd_entry;
3774         int i;
3775
3776         if (!dev_priv->mm.aliasing_ppgtt)
3777                 return;
3778
3779
3780         pd_addr = dev_priv->mm.gtt->gtt + ppgtt->pd_offset/sizeof(uint32_t);
3781         for (i = 0; i < ppgtt->num_pd_entries; i++) {
3782                 dma_addr_t pt_addr;
3783
3784                 if (dev_priv->mm.gtt->needs_dmar)
3785                         pt_addr = ppgtt->pt_dma_addr[i];
3786                 else
3787                         pt_addr = page_to_phys(ppgtt->pt_pages[i]);
3788
3789                 pd_entry = GEN6_PDE_ADDR_ENCODE(pt_addr);
3790                 pd_entry |= GEN6_PDE_VALID;
3791
3792                 writel(pd_entry, pd_addr + i);
3793         }
3794         readl(pd_addr);
3795
3796         pd_offset = ppgtt->pd_offset;
3797         pd_offset /= 64; /* in cachelines, */
3798         pd_offset <<= 16;
3799
3800         if (INTEL_INFO(dev)->gen == 6) {
3801                 uint32_t ecochk = I915_READ(GAM_ECOCHK);
3802                 I915_WRITE(GAM_ECOCHK, ecochk | ECOCHK_SNB_BIT |
3803                                        ECOCHK_PPGTT_CACHE64B);
3804                 I915_WRITE(GFX_MODE, GFX_MODE_ENABLE(GFX_PPGTT_ENABLE));
3805         } else if (INTEL_INFO(dev)->gen >= 7) {
3806                 I915_WRITE(GAM_ECOCHK, ECOCHK_PPGTT_CACHE64B);
3807                 /* GFX_MODE is per-ring on gen7+ */
3808         }
3809
3810         for (i = 0; i < I915_NUM_RINGS; i++) {
3811                 ring = &dev_priv->ring[i];
3812
3813                 if (INTEL_INFO(dev)->gen >= 7)
3814                         I915_WRITE(RING_MODE_GEN7(ring),
3815                                    GFX_MODE_ENABLE(GFX_PPGTT_ENABLE));
3816
3817                 I915_WRITE(RING_PP_DIR_DCLV(ring), PP_DIR_DCLV_2G);
3818                 I915_WRITE(RING_PP_DIR_BASE(ring), pd_offset);
3819         }
3820 }
3821
3822 int
3823 i915_gem_init_hw(struct drm_device *dev)
3824 {
3825         drm_i915_private_t *dev_priv = dev->dev_private;
3826         int ret;
3827
3828         i915_gem_init_swizzling(dev);
3829
3830         ret = intel_init_render_ring_buffer(dev);
3831         if (ret)
3832                 return ret;
3833
3834         if (HAS_BSD(dev)) {
3835                 ret = intel_init_bsd_ring_buffer(dev);
3836                 if (ret)
3837                         goto cleanup_render_ring;
3838         }
3839
3840         if (HAS_BLT(dev)) {
3841                 ret = intel_init_blt_ring_buffer(dev);
3842                 if (ret)
3843                         goto cleanup_bsd_ring;
3844         }
3845
3846         dev_priv->next_seqno = 1;
3847
3848         i915_gem_init_ppgtt(dev);
3849
3850         return 0;
3851
3852 cleanup_bsd_ring:
3853         intel_cleanup_ring_buffer(&dev_priv->ring[VCS]);
3854 cleanup_render_ring:
3855         intel_cleanup_ring_buffer(&dev_priv->ring[RCS]);
3856         return ret;
3857 }
3858
3859 void
3860 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
3861 {
3862         drm_i915_private_t *dev_priv = dev->dev_private;
3863         int i;
3864
3865         for (i = 0; i < I915_NUM_RINGS; i++)
3866                 intel_cleanup_ring_buffer(&dev_priv->ring[i]);
3867 }
3868
3869 int
3870 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
3871                        struct drm_file *file_priv)
3872 {
3873         drm_i915_private_t *dev_priv = dev->dev_private;
3874         int ret, i;
3875
3876         if (drm_core_check_feature(dev, DRIVER_MODESET))
3877                 return 0;
3878
3879         if (atomic_read(&dev_priv->mm.wedged)) {
3880                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
3881                 atomic_set(&dev_priv->mm.wedged, 0);
3882         }
3883
3884         mutex_lock(&dev->struct_mutex);
3885         dev_priv->mm.suspended = 0;
3886
3887         ret = i915_gem_init_hw(dev);
3888         if (ret != 0) {
3889                 mutex_unlock(&dev->struct_mutex);
3890                 return ret;
3891         }
3892
3893         BUG_ON(!list_empty(&dev_priv->mm.active_list));
3894         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
3895         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
3896         for (i = 0; i < I915_NUM_RINGS; i++) {
3897                 BUG_ON(!list_empty(&dev_priv->ring[i].active_list));
3898                 BUG_ON(!list_empty(&dev_priv->ring[i].request_list));
3899         }
3900         mutex_unlock(&dev->struct_mutex);
3901
3902         ret = drm_irq_install(dev);
3903         if (ret)
3904                 goto cleanup_ringbuffer;
3905
3906         return 0;
3907
3908 cleanup_ringbuffer:
3909         mutex_lock(&dev->struct_mutex);
3910         i915_gem_cleanup_ringbuffer(dev);
3911         dev_priv->mm.suspended = 1;
3912         mutex_unlock(&dev->struct_mutex);
3913
3914         return ret;
3915 }
3916
3917 int
3918 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
3919                        struct drm_file *file_priv)
3920 {
3921         if (drm_core_check_feature(dev, DRIVER_MODESET))
3922                 return 0;
3923
3924         drm_irq_uninstall(dev);
3925         return i915_gem_idle(dev);
3926 }
3927
3928 void
3929 i915_gem_lastclose(struct drm_device *dev)
3930 {
3931         int ret;
3932
3933         if (drm_core_check_feature(dev, DRIVER_MODESET))
3934                 return;
3935
3936         ret = i915_gem_idle(dev);
3937         if (ret)
3938                 DRM_ERROR("failed to idle hardware: %d\n", ret);
3939 }
3940
3941 static void
3942 init_ring_lists(struct intel_ring_buffer *ring)
3943 {
3944         INIT_LIST_HEAD(&ring->active_list);
3945         INIT_LIST_HEAD(&ring->request_list);
3946         INIT_LIST_HEAD(&ring->gpu_write_list);
3947 }
3948
3949 void
3950 i915_gem_load(struct drm_device *dev)
3951 {
3952         int i;
3953         drm_i915_private_t *dev_priv = dev->dev_private;
3954
3955         INIT_LIST_HEAD(&dev_priv->mm.active_list);
3956         INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
3957         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
3958         INIT_LIST_HEAD(&dev_priv->mm.pinned_list);
3959         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
3960         INIT_LIST_HEAD(&dev_priv->mm.deferred_free_list);
3961         INIT_LIST_HEAD(&dev_priv->mm.gtt_list);
3962         for (i = 0; i < I915_NUM_RINGS; i++)
3963                 init_ring_lists(&dev_priv->ring[i]);
3964         for (i = 0; i < I915_MAX_NUM_FENCES; i++)
3965                 INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
3966         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
3967                           i915_gem_retire_work_handler);
3968         init_completion(&dev_priv->error_completion);
3969
3970         /* On GEN3 we really need to make sure the ARB C3 LP bit is set */
3971         if (IS_GEN3(dev)) {
3972                 u32 tmp = I915_READ(MI_ARB_STATE);
3973                 if (!(tmp & MI_ARB_C3_LP_WRITE_ENABLE)) {
3974                         /* arb state is a masked write, so set bit + bit in mask */
3975                         tmp = MI_ARB_C3_LP_WRITE_ENABLE | (MI_ARB_C3_LP_WRITE_ENABLE << MI_ARB_MASK_SHIFT);
3976                         I915_WRITE(MI_ARB_STATE, tmp);
3977                 }
3978         }
3979
3980         dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
3981
3982         /* Old X drivers will take 0-2 for front, back, depth buffers */
3983         if (!drm_core_check_feature(dev, DRIVER_MODESET))
3984                 dev_priv->fence_reg_start = 3;
3985
3986         if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
3987                 dev_priv->num_fence_regs = 16;
3988         else
3989                 dev_priv->num_fence_regs = 8;
3990
3991         /* Initialize fence registers to zero */
3992         for (i = 0; i < dev_priv->num_fence_regs; i++) {
3993                 i915_gem_clear_fence_reg(dev, &dev_priv->fence_regs[i]);
3994         }
3995
3996         i915_gem_detect_bit_6_swizzle(dev);
3997         init_waitqueue_head(&dev_priv->pending_flip_queue);
3998
3999         dev_priv->mm.interruptible = true;
4000
4001         dev_priv->mm.inactive_shrinker.shrink = i915_gem_inactive_shrink;
4002         dev_priv->mm.inactive_shrinker.seeks = DEFAULT_SEEKS;
4003         register_shrinker(&dev_priv->mm.inactive_shrinker);
4004 }
4005
4006 /*
4007  * Create a physically contiguous memory object for this object
4008  * e.g. for cursor + overlay regs
4009  */
4010 static int i915_gem_init_phys_object(struct drm_device *dev,
4011                                      int id, int size, int align)
4012 {
4013         drm_i915_private_t *dev_priv = dev->dev_private;
4014         struct drm_i915_gem_phys_object *phys_obj;
4015         int ret;
4016
4017         if (dev_priv->mm.phys_objs[id - 1] || !size)
4018                 return 0;
4019
4020         phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
4021         if (!phys_obj)
4022                 return -ENOMEM;
4023
4024         phys_obj->id = id;
4025
4026         phys_obj->handle = drm_pci_alloc(dev, size, align);
4027         if (!phys_obj->handle) {
4028                 ret = -ENOMEM;
4029                 goto kfree_obj;
4030         }
4031 #ifdef CONFIG_X86
4032         set_memory_wc((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
4033 #endif
4034
4035         dev_priv->mm.phys_objs[id - 1] = phys_obj;
4036
4037         return 0;
4038 kfree_obj:
4039         kfree(phys_obj);
4040         return ret;
4041 }
4042
4043 static void i915_gem_free_phys_object(struct drm_device *dev, int id)
4044 {
4045         drm_i915_private_t *dev_priv = dev->dev_private;
4046         struct drm_i915_gem_phys_object *phys_obj;
4047
4048         if (!dev_priv->mm.phys_objs[id - 1])
4049                 return;
4050
4051         phys_obj = dev_priv->mm.phys_objs[id - 1];
4052         if (phys_obj->cur_obj) {
4053                 i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
4054         }
4055
4056 #ifdef CONFIG_X86
4057         set_memory_wb((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
4058 #endif
4059         drm_pci_free(dev, phys_obj->handle);
4060         kfree(phys_obj);
4061         dev_priv->mm.phys_objs[id - 1] = NULL;
4062 }
4063
4064 void i915_gem_free_all_phys_object(struct drm_device *dev)
4065 {
4066         int i;
4067
4068         for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
4069                 i915_gem_free_phys_object(dev, i);
4070 }
4071
4072 void i915_gem_detach_phys_object(struct drm_device *dev,
4073                                  struct drm_i915_gem_object *obj)
4074 {
4075         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
4076         char *vaddr;
4077         int i;
4078         int page_count;
4079
4080         if (!obj->phys_obj)
4081                 return;
4082         vaddr = obj->phys_obj->handle->vaddr;
4083
4084         page_count = obj->base.size / PAGE_SIZE;
4085         for (i = 0; i < page_count; i++) {
4086                 struct page *page = shmem_read_mapping_page(mapping, i);
4087                 if (!IS_ERR(page)) {
4088                         char *dst = kmap_atomic(page);
4089                         memcpy(dst, vaddr + i*PAGE_SIZE, PAGE_SIZE);
4090                         kunmap_atomic(dst);
4091
4092                         drm_clflush_pages(&page, 1);
4093
4094                         set_page_dirty(page);
4095                         mark_page_accessed(page);
4096                         page_cache_release(page);
4097                 }
4098         }
4099         intel_gtt_chipset_flush();
4100
4101         obj->phys_obj->cur_obj = NULL;
4102         obj->phys_obj = NULL;
4103 }
4104
4105 int
4106 i915_gem_attach_phys_object(struct drm_device *dev,
4107                             struct drm_i915_gem_object *obj,
4108                             int id,
4109                             int align)
4110 {
4111         struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
4112         drm_i915_private_t *dev_priv = dev->dev_private;
4113         int ret = 0;
4114         int page_count;
4115         int i;
4116
4117         if (id > I915_MAX_PHYS_OBJECT)
4118                 return -EINVAL;
4119
4120         if (obj->phys_obj) {
4121                 if (obj->phys_obj->id == id)
4122                         return 0;
4123                 i915_gem_detach_phys_object(dev, obj);
4124         }
4125
4126         /* create a new object */
4127         if (!dev_priv->mm.phys_objs[id - 1]) {
4128                 ret = i915_gem_init_phys_object(dev, id,
4129                                                 obj->base.size, align);
4130                 if (ret) {
4131                         DRM_ERROR("failed to init phys object %d size: %zu\n",
4132                                   id, obj->base.size);
4133                         return ret;
4134                 }
4135         }
4136
4137         /* bind to the object */
4138         obj->phys_obj = dev_priv->mm.phys_objs[id - 1];
4139         obj->phys_obj->cur_obj = obj;
4140
4141         page_count = obj->base.size / PAGE_SIZE;
4142
4143         for (i = 0; i < page_count; i++) {
4144                 struct page *page;
4145                 char *dst, *src;
4146
4147                 page = shmem_read_mapping_page(mapping, i);
4148                 if (IS_ERR(page))
4149                         return PTR_ERR(page);
4150
4151                 src = kmap_atomic(page);
4152                 dst = obj->phys_obj->handle->vaddr + (i * PAGE_SIZE);
4153                 memcpy(dst, src, PAGE_SIZE);
4154                 kunmap_atomic(src);
4155
4156                 mark_page_accessed(page);
4157                 page_cache_release(page);
4158         }
4159
4160         return 0;
4161 }
4162
4163 static int
4164 i915_gem_phys_pwrite(struct drm_device *dev,
4165                      struct drm_i915_gem_object *obj,
4166                      struct drm_i915_gem_pwrite *args,
4167                      struct drm_file *file_priv)
4168 {
4169         void *vaddr = obj->phys_obj->handle->vaddr + args->offset;
4170         char __user *user_data = (char __user *) (uintptr_t) args->data_ptr;
4171
4172         if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
4173                 unsigned long unwritten;
4174
4175                 /* The physical object once assigned is fixed for the lifetime
4176                  * of the obj, so we can safely drop the lock and continue
4177                  * to access vaddr.
4178                  */
4179                 mutex_unlock(&dev->struct_mutex);
4180                 unwritten = copy_from_user(vaddr, user_data, args->size);
4181                 mutex_lock(&dev->struct_mutex);
4182                 if (unwritten)
4183                         return -EFAULT;
4184         }
4185
4186         intel_gtt_chipset_flush();
4187         return 0;
4188 }
4189
4190 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
4191 {
4192         struct drm_i915_file_private *file_priv = file->driver_priv;
4193
4194         /* Clean up our request list when the client is going away, so that
4195          * later retire_requests won't dereference our soon-to-be-gone
4196          * file_priv.
4197          */
4198         spin_lock(&file_priv->mm.lock);
4199         while (!list_empty(&file_priv->mm.request_list)) {
4200                 struct drm_i915_gem_request *request;
4201
4202                 request = list_first_entry(&file_priv->mm.request_list,
4203                                            struct drm_i915_gem_request,
4204                                            client_list);
4205                 list_del(&request->client_list);
4206                 request->file_priv = NULL;
4207         }
4208         spin_unlock(&file_priv->mm.lock);
4209 }
4210
4211 static int
4212 i915_gpu_is_active(struct drm_device *dev)
4213 {
4214         drm_i915_private_t *dev_priv = dev->dev_private;
4215         int lists_empty;
4216
4217         lists_empty = list_empty(&dev_priv->mm.flushing_list) &&
4218                       list_empty(&dev_priv->mm.active_list);
4219
4220         return !lists_empty;
4221 }
4222
4223 static int
4224 i915_gem_inactive_shrink(struct shrinker *shrinker, struct shrink_control *sc)
4225 {
4226         struct drm_i915_private *dev_priv =
4227                 container_of(shrinker,
4228                              struct drm_i915_private,
4229                              mm.inactive_shrinker);
4230         struct drm_device *dev = dev_priv->dev;
4231         struct drm_i915_gem_object *obj, *next;
4232         int nr_to_scan = sc->nr_to_scan;
4233         int cnt;
4234
4235         if (!mutex_trylock(&dev->struct_mutex))
4236                 return 0;
4237
4238         /* "fast-path" to count number of available objects */
4239         if (nr_to_scan == 0) {
4240                 cnt = 0;
4241                 list_for_each_entry(obj,
4242                                     &dev_priv->mm.inactive_list,
4243                                     mm_list)
4244                         cnt++;
4245                 mutex_unlock(&dev->struct_mutex);
4246                 return cnt / 100 * sysctl_vfs_cache_pressure;
4247         }
4248
4249 rescan:
4250         /* first scan for clean buffers */
4251         i915_gem_retire_requests(dev);
4252
4253         list_for_each_entry_safe(obj, next,
4254                                  &dev_priv->mm.inactive_list,
4255                                  mm_list) {
4256                 if (i915_gem_object_is_purgeable(obj)) {
4257                         if (i915_gem_object_unbind(obj) == 0 &&
4258                             --nr_to_scan == 0)
4259                                 break;
4260                 }
4261         }
4262
4263         /* second pass, evict/count anything still on the inactive list */
4264         cnt = 0;
4265         list_for_each_entry_safe(obj, next,
4266                                  &dev_priv->mm.inactive_list,
4267                                  mm_list) {
4268                 if (nr_to_scan &&
4269                     i915_gem_object_unbind(obj) == 0)
4270                         nr_to_scan--;
4271                 else
4272                         cnt++;
4273         }
4274
4275         if (nr_to_scan && i915_gpu_is_active(dev)) {
4276                 /*
4277                  * We are desperate for pages, so as a last resort, wait
4278                  * for the GPU to finish and discard whatever we can.
4279                  * This has a dramatic impact to reduce the number of
4280                  * OOM-killer events whilst running the GPU aggressively.
4281                  */
4282                 if (i915_gpu_idle(dev, true) == 0)
4283                         goto rescan;
4284         }
4285         mutex_unlock(&dev->struct_mutex);
4286         return cnt / 100 * sysctl_vfs_cache_pressure;
4287 }