drm/i915: Reserve shadow batch VMA analogue to others
[firefly-linux-kernel-4.4.55.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 <drm/drmP.h>
29 #include <drm/drm_vma_manager.h>
30 #include <drm/i915_drm.h>
31 #include "i915_drv.h"
32 #include "i915_trace.h"
33 #include "intel_drv.h"
34 #include <linux/oom.h>
35 #include <linux/shmem_fs.h>
36 #include <linux/slab.h>
37 #include <linux/swap.h>
38 #include <linux/pci.h>
39 #include <linux/dma-buf.h>
40
41 static void i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj);
42 static void i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj,
43                                                    bool force);
44 static __must_check int
45 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
46                                bool readonly);
47 static void
48 i915_gem_object_retire(struct drm_i915_gem_object *obj);
49
50 static void i915_gem_write_fence(struct drm_device *dev, int reg,
51                                  struct drm_i915_gem_object *obj);
52 static void i915_gem_object_update_fence(struct drm_i915_gem_object *obj,
53                                          struct drm_i915_fence_reg *fence,
54                                          bool enable);
55
56 static unsigned long i915_gem_shrinker_count(struct shrinker *shrinker,
57                                              struct shrink_control *sc);
58 static unsigned long i915_gem_shrinker_scan(struct shrinker *shrinker,
59                                             struct shrink_control *sc);
60 static int i915_gem_shrinker_oom(struct notifier_block *nb,
61                                  unsigned long event,
62                                  void *ptr);
63 static unsigned long i915_gem_shrink_all(struct drm_i915_private *dev_priv);
64
65 static bool cpu_cache_is_coherent(struct drm_device *dev,
66                                   enum i915_cache_level level)
67 {
68         return HAS_LLC(dev) || level != I915_CACHE_NONE;
69 }
70
71 static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
72 {
73         if (!cpu_cache_is_coherent(obj->base.dev, obj->cache_level))
74                 return true;
75
76         return obj->pin_display;
77 }
78
79 static inline void i915_gem_object_fence_lost(struct drm_i915_gem_object *obj)
80 {
81         if (obj->tiling_mode)
82                 i915_gem_release_mmap(obj);
83
84         /* As we do not have an associated fence register, we will force
85          * a tiling change if we ever need to acquire one.
86          */
87         obj->fence_dirty = false;
88         obj->fence_reg = I915_FENCE_REG_NONE;
89 }
90
91 /* some bookkeeping */
92 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
93                                   size_t size)
94 {
95         spin_lock(&dev_priv->mm.object_stat_lock);
96         dev_priv->mm.object_count++;
97         dev_priv->mm.object_memory += size;
98         spin_unlock(&dev_priv->mm.object_stat_lock);
99 }
100
101 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
102                                      size_t size)
103 {
104         spin_lock(&dev_priv->mm.object_stat_lock);
105         dev_priv->mm.object_count--;
106         dev_priv->mm.object_memory -= size;
107         spin_unlock(&dev_priv->mm.object_stat_lock);
108 }
109
110 static int
111 i915_gem_wait_for_error(struct i915_gpu_error *error)
112 {
113         int ret;
114
115 #define EXIT_COND (!i915_reset_in_progress(error) || \
116                    i915_terminally_wedged(error))
117         if (EXIT_COND)
118                 return 0;
119
120         /*
121          * Only wait 10 seconds for the gpu reset to complete to avoid hanging
122          * userspace. If it takes that long something really bad is going on and
123          * we should simply try to bail out and fail as gracefully as possible.
124          */
125         ret = wait_event_interruptible_timeout(error->reset_queue,
126                                                EXIT_COND,
127                                                10*HZ);
128         if (ret == 0) {
129                 DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
130                 return -EIO;
131         } else if (ret < 0) {
132                 return ret;
133         }
134 #undef EXIT_COND
135
136         return 0;
137 }
138
139 int i915_mutex_lock_interruptible(struct drm_device *dev)
140 {
141         struct drm_i915_private *dev_priv = dev->dev_private;
142         int ret;
143
144         ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
145         if (ret)
146                 return ret;
147
148         ret = mutex_lock_interruptible(&dev->struct_mutex);
149         if (ret)
150                 return ret;
151
152         WARN_ON(i915_verify_lists(dev));
153         return 0;
154 }
155
156 int
157 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
158                             struct drm_file *file)
159 {
160         struct drm_i915_private *dev_priv = dev->dev_private;
161         struct drm_i915_gem_get_aperture *args = data;
162         struct drm_i915_gem_object *obj;
163         size_t pinned;
164
165         pinned = 0;
166         mutex_lock(&dev->struct_mutex);
167         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list)
168                 if (i915_gem_obj_is_pinned(obj))
169                         pinned += i915_gem_obj_ggtt_size(obj);
170         mutex_unlock(&dev->struct_mutex);
171
172         args->aper_size = dev_priv->gtt.base.total;
173         args->aper_available_size = args->aper_size - pinned;
174
175         return 0;
176 }
177
178 static int
179 i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
180 {
181         struct address_space *mapping = file_inode(obj->base.filp)->i_mapping;
182         char *vaddr = obj->phys_handle->vaddr;
183         struct sg_table *st;
184         struct scatterlist *sg;
185         int i;
186
187         if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
188                 return -EINVAL;
189
190         for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
191                 struct page *page;
192                 char *src;
193
194                 page = shmem_read_mapping_page(mapping, i);
195                 if (IS_ERR(page))
196                         return PTR_ERR(page);
197
198                 src = kmap_atomic(page);
199                 memcpy(vaddr, src, PAGE_SIZE);
200                 drm_clflush_virt_range(vaddr, PAGE_SIZE);
201                 kunmap_atomic(src);
202
203                 page_cache_release(page);
204                 vaddr += PAGE_SIZE;
205         }
206
207         i915_gem_chipset_flush(obj->base.dev);
208
209         st = kmalloc(sizeof(*st), GFP_KERNEL);
210         if (st == NULL)
211                 return -ENOMEM;
212
213         if (sg_alloc_table(st, 1, GFP_KERNEL)) {
214                 kfree(st);
215                 return -ENOMEM;
216         }
217
218         sg = st->sgl;
219         sg->offset = 0;
220         sg->length = obj->base.size;
221
222         sg_dma_address(sg) = obj->phys_handle->busaddr;
223         sg_dma_len(sg) = obj->base.size;
224
225         obj->pages = st;
226         obj->has_dma_mapping = true;
227         return 0;
228 }
229
230 static void
231 i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj)
232 {
233         int ret;
234
235         BUG_ON(obj->madv == __I915_MADV_PURGED);
236
237         ret = i915_gem_object_set_to_cpu_domain(obj, true);
238         if (ret) {
239                 /* In the event of a disaster, abandon all caches and
240                  * hope for the best.
241                  */
242                 WARN_ON(ret != -EIO);
243                 obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
244         }
245
246         if (obj->madv == I915_MADV_DONTNEED)
247                 obj->dirty = 0;
248
249         if (obj->dirty) {
250                 struct address_space *mapping = file_inode(obj->base.filp)->i_mapping;
251                 char *vaddr = obj->phys_handle->vaddr;
252                 int i;
253
254                 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
255                         struct page *page;
256                         char *dst;
257
258                         page = shmem_read_mapping_page(mapping, i);
259                         if (IS_ERR(page))
260                                 continue;
261
262                         dst = kmap_atomic(page);
263                         drm_clflush_virt_range(vaddr, PAGE_SIZE);
264                         memcpy(dst, vaddr, PAGE_SIZE);
265                         kunmap_atomic(dst);
266
267                         set_page_dirty(page);
268                         if (obj->madv == I915_MADV_WILLNEED)
269                                 mark_page_accessed(page);
270                         page_cache_release(page);
271                         vaddr += PAGE_SIZE;
272                 }
273                 obj->dirty = 0;
274         }
275
276         sg_free_table(obj->pages);
277         kfree(obj->pages);
278
279         obj->has_dma_mapping = false;
280 }
281
282 static void
283 i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
284 {
285         drm_pci_free(obj->base.dev, obj->phys_handle);
286 }
287
288 static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
289         .get_pages = i915_gem_object_get_pages_phys,
290         .put_pages = i915_gem_object_put_pages_phys,
291         .release = i915_gem_object_release_phys,
292 };
293
294 static int
295 drop_pages(struct drm_i915_gem_object *obj)
296 {
297         struct i915_vma *vma, *next;
298         int ret;
299
300         drm_gem_object_reference(&obj->base);
301         list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link)
302                 if (i915_vma_unbind(vma))
303                         break;
304
305         ret = i915_gem_object_put_pages(obj);
306         drm_gem_object_unreference(&obj->base);
307
308         return ret;
309 }
310
311 int
312 i915_gem_object_attach_phys(struct drm_i915_gem_object *obj,
313                             int align)
314 {
315         drm_dma_handle_t *phys;
316         int ret;
317
318         if (obj->phys_handle) {
319                 if ((unsigned long)obj->phys_handle->vaddr & (align -1))
320                         return -EBUSY;
321
322                 return 0;
323         }
324
325         if (obj->madv != I915_MADV_WILLNEED)
326                 return -EFAULT;
327
328         if (obj->base.filp == NULL)
329                 return -EINVAL;
330
331         ret = drop_pages(obj);
332         if (ret)
333                 return ret;
334
335         /* create a new object */
336         phys = drm_pci_alloc(obj->base.dev, obj->base.size, align);
337         if (!phys)
338                 return -ENOMEM;
339
340         obj->phys_handle = phys;
341         obj->ops = &i915_gem_phys_ops;
342
343         return i915_gem_object_get_pages(obj);
344 }
345
346 static int
347 i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
348                      struct drm_i915_gem_pwrite *args,
349                      struct drm_file *file_priv)
350 {
351         struct drm_device *dev = obj->base.dev;
352         void *vaddr = obj->phys_handle->vaddr + args->offset;
353         char __user *user_data = to_user_ptr(args->data_ptr);
354         int ret;
355
356         /* We manually control the domain here and pretend that it
357          * remains coherent i.e. in the GTT domain, like shmem_pwrite.
358          */
359         ret = i915_gem_object_wait_rendering(obj, false);
360         if (ret)
361                 return ret;
362
363         if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
364                 unsigned long unwritten;
365
366                 /* The physical object once assigned is fixed for the lifetime
367                  * of the obj, so we can safely drop the lock and continue
368                  * to access vaddr.
369                  */
370                 mutex_unlock(&dev->struct_mutex);
371                 unwritten = copy_from_user(vaddr, user_data, args->size);
372                 mutex_lock(&dev->struct_mutex);
373                 if (unwritten)
374                         return -EFAULT;
375         }
376
377         drm_clflush_virt_range(vaddr, args->size);
378         i915_gem_chipset_flush(dev);
379         return 0;
380 }
381
382 void *i915_gem_object_alloc(struct drm_device *dev)
383 {
384         struct drm_i915_private *dev_priv = dev->dev_private;
385         return kmem_cache_zalloc(dev_priv->slab, GFP_KERNEL);
386 }
387
388 void i915_gem_object_free(struct drm_i915_gem_object *obj)
389 {
390         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
391         kmem_cache_free(dev_priv->slab, obj);
392 }
393
394 static int
395 i915_gem_create(struct drm_file *file,
396                 struct drm_device *dev,
397                 uint64_t size,
398                 bool dumb,
399                 uint32_t *handle_p)
400 {
401         struct drm_i915_gem_object *obj;
402         int ret;
403         u32 handle;
404
405         size = roundup(size, PAGE_SIZE);
406         if (size == 0)
407                 return -EINVAL;
408
409         /* Allocate the new object */
410         obj = i915_gem_alloc_object(dev, size);
411         if (obj == NULL)
412                 return -ENOMEM;
413
414         obj->base.dumb = dumb;
415         ret = drm_gem_handle_create(file, &obj->base, &handle);
416         /* drop reference from allocate - handle holds it now */
417         drm_gem_object_unreference_unlocked(&obj->base);
418         if (ret)
419                 return ret;
420
421         *handle_p = handle;
422         return 0;
423 }
424
425 int
426 i915_gem_dumb_create(struct drm_file *file,
427                      struct drm_device *dev,
428                      struct drm_mode_create_dumb *args)
429 {
430         /* have to work out size/pitch and return them */
431         args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
432         args->size = args->pitch * args->height;
433         return i915_gem_create(file, dev,
434                                args->size, true, &args->handle);
435 }
436
437 /**
438  * Creates a new mm object and returns a handle to it.
439  */
440 int
441 i915_gem_create_ioctl(struct drm_device *dev, void *data,
442                       struct drm_file *file)
443 {
444         struct drm_i915_gem_create *args = data;
445
446         return i915_gem_create(file, dev,
447                                args->size, false, &args->handle);
448 }
449
450 static inline int
451 __copy_to_user_swizzled(char __user *cpu_vaddr,
452                         const char *gpu_vaddr, int gpu_offset,
453                         int length)
454 {
455         int ret, cpu_offset = 0;
456
457         while (length > 0) {
458                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
459                 int this_length = min(cacheline_end - gpu_offset, length);
460                 int swizzled_gpu_offset = gpu_offset ^ 64;
461
462                 ret = __copy_to_user(cpu_vaddr + cpu_offset,
463                                      gpu_vaddr + swizzled_gpu_offset,
464                                      this_length);
465                 if (ret)
466                         return ret + length;
467
468                 cpu_offset += this_length;
469                 gpu_offset += this_length;
470                 length -= this_length;
471         }
472
473         return 0;
474 }
475
476 static inline int
477 __copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
478                           const char __user *cpu_vaddr,
479                           int length)
480 {
481         int ret, cpu_offset = 0;
482
483         while (length > 0) {
484                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
485                 int this_length = min(cacheline_end - gpu_offset, length);
486                 int swizzled_gpu_offset = gpu_offset ^ 64;
487
488                 ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
489                                        cpu_vaddr + cpu_offset,
490                                        this_length);
491                 if (ret)
492                         return ret + length;
493
494                 cpu_offset += this_length;
495                 gpu_offset += this_length;
496                 length -= this_length;
497         }
498
499         return 0;
500 }
501
502 /*
503  * Pins the specified object's pages and synchronizes the object with
504  * GPU accesses. Sets needs_clflush to non-zero if the caller should
505  * flush the object from the CPU cache.
506  */
507 int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
508                                     int *needs_clflush)
509 {
510         int ret;
511
512         *needs_clflush = 0;
513
514         if (!obj->base.filp)
515                 return -EINVAL;
516
517         if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU)) {
518                 /* If we're not in the cpu read domain, set ourself into the gtt
519                  * read domain and manually flush cachelines (if required). This
520                  * optimizes for the case when the gpu will dirty the data
521                  * anyway again before the next pread happens. */
522                 *needs_clflush = !cpu_cache_is_coherent(obj->base.dev,
523                                                         obj->cache_level);
524                 ret = i915_gem_object_wait_rendering(obj, true);
525                 if (ret)
526                         return ret;
527
528                 i915_gem_object_retire(obj);
529         }
530
531         ret = i915_gem_object_get_pages(obj);
532         if (ret)
533                 return ret;
534
535         i915_gem_object_pin_pages(obj);
536
537         return ret;
538 }
539
540 /* Per-page copy function for the shmem pread fastpath.
541  * Flushes invalid cachelines before reading the target if
542  * needs_clflush is set. */
543 static int
544 shmem_pread_fast(struct page *page, int shmem_page_offset, int page_length,
545                  char __user *user_data,
546                  bool page_do_bit17_swizzling, bool needs_clflush)
547 {
548         char *vaddr;
549         int ret;
550
551         if (unlikely(page_do_bit17_swizzling))
552                 return -EINVAL;
553
554         vaddr = kmap_atomic(page);
555         if (needs_clflush)
556                 drm_clflush_virt_range(vaddr + shmem_page_offset,
557                                        page_length);
558         ret = __copy_to_user_inatomic(user_data,
559                                       vaddr + shmem_page_offset,
560                                       page_length);
561         kunmap_atomic(vaddr);
562
563         return ret ? -EFAULT : 0;
564 }
565
566 static void
567 shmem_clflush_swizzled_range(char *addr, unsigned long length,
568                              bool swizzled)
569 {
570         if (unlikely(swizzled)) {
571                 unsigned long start = (unsigned long) addr;
572                 unsigned long end = (unsigned long) addr + length;
573
574                 /* For swizzling simply ensure that we always flush both
575                  * channels. Lame, but simple and it works. Swizzled
576                  * pwrite/pread is far from a hotpath - current userspace
577                  * doesn't use it at all. */
578                 start = round_down(start, 128);
579                 end = round_up(end, 128);
580
581                 drm_clflush_virt_range((void *)start, end - start);
582         } else {
583                 drm_clflush_virt_range(addr, length);
584         }
585
586 }
587
588 /* Only difference to the fast-path function is that this can handle bit17
589  * and uses non-atomic copy and kmap functions. */
590 static int
591 shmem_pread_slow(struct page *page, int shmem_page_offset, int page_length,
592                  char __user *user_data,
593                  bool page_do_bit17_swizzling, bool needs_clflush)
594 {
595         char *vaddr;
596         int ret;
597
598         vaddr = kmap(page);
599         if (needs_clflush)
600                 shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
601                                              page_length,
602                                              page_do_bit17_swizzling);
603
604         if (page_do_bit17_swizzling)
605                 ret = __copy_to_user_swizzled(user_data,
606                                               vaddr, shmem_page_offset,
607                                               page_length);
608         else
609                 ret = __copy_to_user(user_data,
610                                      vaddr + shmem_page_offset,
611                                      page_length);
612         kunmap(page);
613
614         return ret ? - EFAULT : 0;
615 }
616
617 static int
618 i915_gem_shmem_pread(struct drm_device *dev,
619                      struct drm_i915_gem_object *obj,
620                      struct drm_i915_gem_pread *args,
621                      struct drm_file *file)
622 {
623         char __user *user_data;
624         ssize_t remain;
625         loff_t offset;
626         int shmem_page_offset, page_length, ret = 0;
627         int obj_do_bit17_swizzling, page_do_bit17_swizzling;
628         int prefaulted = 0;
629         int needs_clflush = 0;
630         struct sg_page_iter sg_iter;
631
632         user_data = to_user_ptr(args->data_ptr);
633         remain = args->size;
634
635         obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
636
637         ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
638         if (ret)
639                 return ret;
640
641         offset = args->offset;
642
643         for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents,
644                          offset >> PAGE_SHIFT) {
645                 struct page *page = sg_page_iter_page(&sg_iter);
646
647                 if (remain <= 0)
648                         break;
649
650                 /* Operation in this page
651                  *
652                  * shmem_page_offset = offset within page in shmem file
653                  * page_length = bytes to copy for this page
654                  */
655                 shmem_page_offset = offset_in_page(offset);
656                 page_length = remain;
657                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
658                         page_length = PAGE_SIZE - shmem_page_offset;
659
660                 page_do_bit17_swizzling = obj_do_bit17_swizzling &&
661                         (page_to_phys(page) & (1 << 17)) != 0;
662
663                 ret = shmem_pread_fast(page, shmem_page_offset, page_length,
664                                        user_data, page_do_bit17_swizzling,
665                                        needs_clflush);
666                 if (ret == 0)
667                         goto next_page;
668
669                 mutex_unlock(&dev->struct_mutex);
670
671                 if (likely(!i915.prefault_disable) && !prefaulted) {
672                         ret = fault_in_multipages_writeable(user_data, remain);
673                         /* Userspace is tricking us, but we've already clobbered
674                          * its pages with the prefault and promised to write the
675                          * data up to the first fault. Hence ignore any errors
676                          * and just continue. */
677                         (void)ret;
678                         prefaulted = 1;
679                 }
680
681                 ret = shmem_pread_slow(page, shmem_page_offset, page_length,
682                                        user_data, page_do_bit17_swizzling,
683                                        needs_clflush);
684
685                 mutex_lock(&dev->struct_mutex);
686
687                 if (ret)
688                         goto out;
689
690 next_page:
691                 remain -= page_length;
692                 user_data += page_length;
693                 offset += page_length;
694         }
695
696 out:
697         i915_gem_object_unpin_pages(obj);
698
699         return ret;
700 }
701
702 /**
703  * Reads data from the object referenced by handle.
704  *
705  * On error, the contents of *data are undefined.
706  */
707 int
708 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
709                      struct drm_file *file)
710 {
711         struct drm_i915_gem_pread *args = data;
712         struct drm_i915_gem_object *obj;
713         int ret = 0;
714
715         if (args->size == 0)
716                 return 0;
717
718         if (!access_ok(VERIFY_WRITE,
719                        to_user_ptr(args->data_ptr),
720                        args->size))
721                 return -EFAULT;
722
723         ret = i915_mutex_lock_interruptible(dev);
724         if (ret)
725                 return ret;
726
727         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
728         if (&obj->base == NULL) {
729                 ret = -ENOENT;
730                 goto unlock;
731         }
732
733         /* Bounds check source.  */
734         if (args->offset > obj->base.size ||
735             args->size > obj->base.size - args->offset) {
736                 ret = -EINVAL;
737                 goto out;
738         }
739
740         /* prime objects have no backing filp to GEM pread/pwrite
741          * pages from.
742          */
743         if (!obj->base.filp) {
744                 ret = -EINVAL;
745                 goto out;
746         }
747
748         trace_i915_gem_object_pread(obj, args->offset, args->size);
749
750         ret = i915_gem_shmem_pread(dev, obj, args, file);
751
752 out:
753         drm_gem_object_unreference(&obj->base);
754 unlock:
755         mutex_unlock(&dev->struct_mutex);
756         return ret;
757 }
758
759 /* This is the fast write path which cannot handle
760  * page faults in the source data
761  */
762
763 static inline int
764 fast_user_write(struct io_mapping *mapping,
765                 loff_t page_base, int page_offset,
766                 char __user *user_data,
767                 int length)
768 {
769         void __iomem *vaddr_atomic;
770         void *vaddr;
771         unsigned long unwritten;
772
773         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
774         /* We can use the cpu mem copy function because this is X86. */
775         vaddr = (void __force*)vaddr_atomic + page_offset;
776         unwritten = __copy_from_user_inatomic_nocache(vaddr,
777                                                       user_data, length);
778         io_mapping_unmap_atomic(vaddr_atomic);
779         return unwritten;
780 }
781
782 /**
783  * This is the fast pwrite path, where we copy the data directly from the
784  * user into the GTT, uncached.
785  */
786 static int
787 i915_gem_gtt_pwrite_fast(struct drm_device *dev,
788                          struct drm_i915_gem_object *obj,
789                          struct drm_i915_gem_pwrite *args,
790                          struct drm_file *file)
791 {
792         struct drm_i915_private *dev_priv = dev->dev_private;
793         ssize_t remain;
794         loff_t offset, page_base;
795         char __user *user_data;
796         int page_offset, page_length, ret;
797
798         ret = i915_gem_obj_ggtt_pin(obj, 0, PIN_MAPPABLE | PIN_NONBLOCK);
799         if (ret)
800                 goto out;
801
802         ret = i915_gem_object_set_to_gtt_domain(obj, true);
803         if (ret)
804                 goto out_unpin;
805
806         ret = i915_gem_object_put_fence(obj);
807         if (ret)
808                 goto out_unpin;
809
810         user_data = to_user_ptr(args->data_ptr);
811         remain = args->size;
812
813         offset = i915_gem_obj_ggtt_offset(obj) + args->offset;
814
815         while (remain > 0) {
816                 /* Operation in this page
817                  *
818                  * page_base = page offset within aperture
819                  * page_offset = offset within page
820                  * page_length = bytes to copy for this page
821                  */
822                 page_base = offset & PAGE_MASK;
823                 page_offset = offset_in_page(offset);
824                 page_length = remain;
825                 if ((page_offset + remain) > PAGE_SIZE)
826                         page_length = PAGE_SIZE - page_offset;
827
828                 /* If we get a fault while copying data, then (presumably) our
829                  * source page isn't available.  Return the error and we'll
830                  * retry in the slow path.
831                  */
832                 if (fast_user_write(dev_priv->gtt.mappable, page_base,
833                                     page_offset, user_data, page_length)) {
834                         ret = -EFAULT;
835                         goto out_unpin;
836                 }
837
838                 remain -= page_length;
839                 user_data += page_length;
840                 offset += page_length;
841         }
842
843 out_unpin:
844         i915_gem_object_ggtt_unpin(obj);
845 out:
846         return ret;
847 }
848
849 /* Per-page copy function for the shmem pwrite fastpath.
850  * Flushes invalid cachelines before writing to the target if
851  * needs_clflush_before is set and flushes out any written cachelines after
852  * writing if needs_clflush is set. */
853 static int
854 shmem_pwrite_fast(struct page *page, int shmem_page_offset, int page_length,
855                   char __user *user_data,
856                   bool page_do_bit17_swizzling,
857                   bool needs_clflush_before,
858                   bool needs_clflush_after)
859 {
860         char *vaddr;
861         int ret;
862
863         if (unlikely(page_do_bit17_swizzling))
864                 return -EINVAL;
865
866         vaddr = kmap_atomic(page);
867         if (needs_clflush_before)
868                 drm_clflush_virt_range(vaddr + shmem_page_offset,
869                                        page_length);
870         ret = __copy_from_user_inatomic(vaddr + shmem_page_offset,
871                                         user_data, page_length);
872         if (needs_clflush_after)
873                 drm_clflush_virt_range(vaddr + shmem_page_offset,
874                                        page_length);
875         kunmap_atomic(vaddr);
876
877         return ret ? -EFAULT : 0;
878 }
879
880 /* Only difference to the fast-path function is that this can handle bit17
881  * and uses non-atomic copy and kmap functions. */
882 static int
883 shmem_pwrite_slow(struct page *page, int shmem_page_offset, int page_length,
884                   char __user *user_data,
885                   bool page_do_bit17_swizzling,
886                   bool needs_clflush_before,
887                   bool needs_clflush_after)
888 {
889         char *vaddr;
890         int ret;
891
892         vaddr = kmap(page);
893         if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
894                 shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
895                                              page_length,
896                                              page_do_bit17_swizzling);
897         if (page_do_bit17_swizzling)
898                 ret = __copy_from_user_swizzled(vaddr, shmem_page_offset,
899                                                 user_data,
900                                                 page_length);
901         else
902                 ret = __copy_from_user(vaddr + shmem_page_offset,
903                                        user_data,
904                                        page_length);
905         if (needs_clflush_after)
906                 shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
907                                              page_length,
908                                              page_do_bit17_swizzling);
909         kunmap(page);
910
911         return ret ? -EFAULT : 0;
912 }
913
914 static int
915 i915_gem_shmem_pwrite(struct drm_device *dev,
916                       struct drm_i915_gem_object *obj,
917                       struct drm_i915_gem_pwrite *args,
918                       struct drm_file *file)
919 {
920         ssize_t remain;
921         loff_t offset;
922         char __user *user_data;
923         int shmem_page_offset, page_length, ret = 0;
924         int obj_do_bit17_swizzling, page_do_bit17_swizzling;
925         int hit_slowpath = 0;
926         int needs_clflush_after = 0;
927         int needs_clflush_before = 0;
928         struct sg_page_iter sg_iter;
929
930         user_data = to_user_ptr(args->data_ptr);
931         remain = args->size;
932
933         obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
934
935         if (obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
936                 /* If we're not in the cpu write domain, set ourself into the gtt
937                  * write domain and manually flush cachelines (if required). This
938                  * optimizes for the case when the gpu will use the data
939                  * right away and we therefore have to clflush anyway. */
940                 needs_clflush_after = cpu_write_needs_clflush(obj);
941                 ret = i915_gem_object_wait_rendering(obj, false);
942                 if (ret)
943                         return ret;
944
945                 i915_gem_object_retire(obj);
946         }
947         /* Same trick applies to invalidate partially written cachelines read
948          * before writing. */
949         if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0)
950                 needs_clflush_before =
951                         !cpu_cache_is_coherent(dev, obj->cache_level);
952
953         ret = i915_gem_object_get_pages(obj);
954         if (ret)
955                 return ret;
956
957         i915_gem_object_pin_pages(obj);
958
959         offset = args->offset;
960         obj->dirty = 1;
961
962         for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents,
963                          offset >> PAGE_SHIFT) {
964                 struct page *page = sg_page_iter_page(&sg_iter);
965                 int partial_cacheline_write;
966
967                 if (remain <= 0)
968                         break;
969
970                 /* Operation in this page
971                  *
972                  * shmem_page_offset = offset within page in shmem file
973                  * page_length = bytes to copy for this page
974                  */
975                 shmem_page_offset = offset_in_page(offset);
976
977                 page_length = remain;
978                 if ((shmem_page_offset + page_length) > PAGE_SIZE)
979                         page_length = PAGE_SIZE - shmem_page_offset;
980
981                 /* If we don't overwrite a cacheline completely we need to be
982                  * careful to have up-to-date data by first clflushing. Don't
983                  * overcomplicate things and flush the entire patch. */
984                 partial_cacheline_write = needs_clflush_before &&
985                         ((shmem_page_offset | page_length)
986                                 & (boot_cpu_data.x86_clflush_size - 1));
987
988                 page_do_bit17_swizzling = obj_do_bit17_swizzling &&
989                         (page_to_phys(page) & (1 << 17)) != 0;
990
991                 ret = shmem_pwrite_fast(page, shmem_page_offset, page_length,
992                                         user_data, page_do_bit17_swizzling,
993                                         partial_cacheline_write,
994                                         needs_clflush_after);
995                 if (ret == 0)
996                         goto next_page;
997
998                 hit_slowpath = 1;
999                 mutex_unlock(&dev->struct_mutex);
1000                 ret = shmem_pwrite_slow(page, shmem_page_offset, page_length,
1001                                         user_data, page_do_bit17_swizzling,
1002                                         partial_cacheline_write,
1003                                         needs_clflush_after);
1004
1005                 mutex_lock(&dev->struct_mutex);
1006
1007                 if (ret)
1008                         goto out;
1009
1010 next_page:
1011                 remain -= page_length;
1012                 user_data += page_length;
1013                 offset += page_length;
1014         }
1015
1016 out:
1017         i915_gem_object_unpin_pages(obj);
1018
1019         if (hit_slowpath) {
1020                 /*
1021                  * Fixup: Flush cpu caches in case we didn't flush the dirty
1022                  * cachelines in-line while writing and the object moved
1023                  * out of the cpu write domain while we've dropped the lock.
1024                  */
1025                 if (!needs_clflush_after &&
1026                     obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
1027                         if (i915_gem_clflush_object(obj, obj->pin_display))
1028                                 i915_gem_chipset_flush(dev);
1029                 }
1030         }
1031
1032         if (needs_clflush_after)
1033                 i915_gem_chipset_flush(dev);
1034
1035         return ret;
1036 }
1037
1038 /**
1039  * Writes data to the object referenced by handle.
1040  *
1041  * On error, the contents of the buffer that were to be modified are undefined.
1042  */
1043 int
1044 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
1045                       struct drm_file *file)
1046 {
1047         struct drm_i915_gem_pwrite *args = data;
1048         struct drm_i915_gem_object *obj;
1049         int ret;
1050
1051         if (args->size == 0)
1052                 return 0;
1053
1054         if (!access_ok(VERIFY_READ,
1055                        to_user_ptr(args->data_ptr),
1056                        args->size))
1057                 return -EFAULT;
1058
1059         if (likely(!i915.prefault_disable)) {
1060                 ret = fault_in_multipages_readable(to_user_ptr(args->data_ptr),
1061                                                    args->size);
1062                 if (ret)
1063                         return -EFAULT;
1064         }
1065
1066         ret = i915_mutex_lock_interruptible(dev);
1067         if (ret)
1068                 return ret;
1069
1070         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1071         if (&obj->base == NULL) {
1072                 ret = -ENOENT;
1073                 goto unlock;
1074         }
1075
1076         /* Bounds check destination. */
1077         if (args->offset > obj->base.size ||
1078             args->size > obj->base.size - args->offset) {
1079                 ret = -EINVAL;
1080                 goto out;
1081         }
1082
1083         /* prime objects have no backing filp to GEM pread/pwrite
1084          * pages from.
1085          */
1086         if (!obj->base.filp) {
1087                 ret = -EINVAL;
1088                 goto out;
1089         }
1090
1091         trace_i915_gem_object_pwrite(obj, args->offset, args->size);
1092
1093         ret = -EFAULT;
1094         /* We can only do the GTT pwrite on untiled buffers, as otherwise
1095          * it would end up going through the fenced access, and we'll get
1096          * different detiling behavior between reading and writing.
1097          * pread/pwrite currently are reading and writing from the CPU
1098          * perspective, requiring manual detiling by the client.
1099          */
1100         if (obj->tiling_mode == I915_TILING_NONE &&
1101             obj->base.write_domain != I915_GEM_DOMAIN_CPU &&
1102             cpu_write_needs_clflush(obj)) {
1103                 ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file);
1104                 /* Note that the gtt paths might fail with non-page-backed user
1105                  * pointers (e.g. gtt mappings when moving data between
1106                  * textures). Fallback to the shmem path in that case. */
1107         }
1108
1109         if (ret == -EFAULT || ret == -ENOSPC) {
1110                 if (obj->phys_handle)
1111                         ret = i915_gem_phys_pwrite(obj, args, file);
1112                 else
1113                         ret = i915_gem_shmem_pwrite(dev, obj, args, file);
1114         }
1115
1116 out:
1117         drm_gem_object_unreference(&obj->base);
1118 unlock:
1119         mutex_unlock(&dev->struct_mutex);
1120         return ret;
1121 }
1122
1123 int
1124 i915_gem_check_wedge(struct i915_gpu_error *error,
1125                      bool interruptible)
1126 {
1127         if (i915_reset_in_progress(error)) {
1128                 /* Non-interruptible callers can't handle -EAGAIN, hence return
1129                  * -EIO unconditionally for these. */
1130                 if (!interruptible)
1131                         return -EIO;
1132
1133                 /* Recovery complete, but the reset failed ... */
1134                 if (i915_terminally_wedged(error))
1135                         return -EIO;
1136
1137                 /*
1138                  * Check if GPU Reset is in progress - we need intel_ring_begin
1139                  * to work properly to reinit the hw state while the gpu is
1140                  * still marked as reset-in-progress. Handle this with a flag.
1141                  */
1142                 if (!error->reload_in_reset)
1143                         return -EAGAIN;
1144         }
1145
1146         return 0;
1147 }
1148
1149 /*
1150  * Compare arbitrary request against outstanding lazy request. Emit on match.
1151  */
1152 int
1153 i915_gem_check_olr(struct drm_i915_gem_request *req)
1154 {
1155         int ret;
1156
1157         WARN_ON(!mutex_is_locked(&req->ring->dev->struct_mutex));
1158
1159         ret = 0;
1160         if (req == req->ring->outstanding_lazy_request)
1161                 ret = i915_add_request(req->ring);
1162
1163         return ret;
1164 }
1165
1166 static void fake_irq(unsigned long data)
1167 {
1168         wake_up_process((struct task_struct *)data);
1169 }
1170
1171 static bool missed_irq(struct drm_i915_private *dev_priv,
1172                        struct intel_engine_cs *ring)
1173 {
1174         return test_bit(ring->id, &dev_priv->gpu_error.missed_irq_rings);
1175 }
1176
1177 static bool can_wait_boost(struct drm_i915_file_private *file_priv)
1178 {
1179         if (file_priv == NULL)
1180                 return true;
1181
1182         return !atomic_xchg(&file_priv->rps_wait_boost, true);
1183 }
1184
1185 /**
1186  * __i915_wait_request - wait until execution of request has finished
1187  * @req: duh!
1188  * @reset_counter: reset sequence associated with the given request
1189  * @interruptible: do an interruptible wait (normally yes)
1190  * @timeout: in - how long to wait (NULL forever); out - how much time remaining
1191  *
1192  * Note: It is of utmost importance that the passed in seqno and reset_counter
1193  * values have been read by the caller in an smp safe manner. Where read-side
1194  * locks are involved, it is sufficient to read the reset_counter before
1195  * unlocking the lock that protects the seqno. For lockless tricks, the
1196  * reset_counter _must_ be read before, and an appropriate smp_rmb must be
1197  * inserted.
1198  *
1199  * Returns 0 if the request was found within the alloted time. Else returns the
1200  * errno with remaining time filled in timeout argument.
1201  */
1202 int __i915_wait_request(struct drm_i915_gem_request *req,
1203                         unsigned reset_counter,
1204                         bool interruptible,
1205                         s64 *timeout,
1206                         struct drm_i915_file_private *file_priv)
1207 {
1208         struct intel_engine_cs *ring = i915_gem_request_get_ring(req);
1209         struct drm_device *dev = ring->dev;
1210         struct drm_i915_private *dev_priv = dev->dev_private;
1211         const bool irq_test_in_progress =
1212                 ACCESS_ONCE(dev_priv->gpu_error.test_irq_rings) & intel_ring_flag(ring);
1213         DEFINE_WAIT(wait);
1214         unsigned long timeout_expire;
1215         s64 before, now;
1216         int ret;
1217
1218         WARN(!intel_irqs_enabled(dev_priv), "IRQs disabled");
1219
1220         if (i915_gem_request_completed(req, true))
1221                 return 0;
1222
1223         timeout_expire = timeout ? jiffies + nsecs_to_jiffies((u64)*timeout) : 0;
1224
1225         if (INTEL_INFO(dev)->gen >= 6 && ring->id == RCS && can_wait_boost(file_priv)) {
1226                 gen6_rps_boost(dev_priv);
1227                 if (file_priv)
1228                         mod_delayed_work(dev_priv->wq,
1229                                          &file_priv->mm.idle_work,
1230                                          msecs_to_jiffies(100));
1231         }
1232
1233         if (!irq_test_in_progress && WARN_ON(!ring->irq_get(ring)))
1234                 return -ENODEV;
1235
1236         /* Record current time in case interrupted by signal, or wedged */
1237         trace_i915_gem_request_wait_begin(req);
1238         before = ktime_get_raw_ns();
1239         for (;;) {
1240                 struct timer_list timer;
1241
1242                 prepare_to_wait(&ring->irq_queue, &wait,
1243                                 interruptible ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
1244
1245                 /* We need to check whether any gpu reset happened in between
1246                  * the caller grabbing the seqno and now ... */
1247                 if (reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter)) {
1248                         /* ... but upgrade the -EAGAIN to an -EIO if the gpu
1249                          * is truely gone. */
1250                         ret = i915_gem_check_wedge(&dev_priv->gpu_error, interruptible);
1251                         if (ret == 0)
1252                                 ret = -EAGAIN;
1253                         break;
1254                 }
1255
1256                 if (i915_gem_request_completed(req, false)) {
1257                         ret = 0;
1258                         break;
1259                 }
1260
1261                 if (interruptible && signal_pending(current)) {
1262                         ret = -ERESTARTSYS;
1263                         break;
1264                 }
1265
1266                 if (timeout && time_after_eq(jiffies, timeout_expire)) {
1267                         ret = -ETIME;
1268                         break;
1269                 }
1270
1271                 timer.function = NULL;
1272                 if (timeout || missed_irq(dev_priv, ring)) {
1273                         unsigned long expire;
1274
1275                         setup_timer_on_stack(&timer, fake_irq, (unsigned long)current);
1276                         expire = missed_irq(dev_priv, ring) ? jiffies + 1 : timeout_expire;
1277                         mod_timer(&timer, expire);
1278                 }
1279
1280                 io_schedule();
1281
1282                 if (timer.function) {
1283                         del_singleshot_timer_sync(&timer);
1284                         destroy_timer_on_stack(&timer);
1285                 }
1286         }
1287         now = ktime_get_raw_ns();
1288         trace_i915_gem_request_wait_end(req);
1289
1290         if (!irq_test_in_progress)
1291                 ring->irq_put(ring);
1292
1293         finish_wait(&ring->irq_queue, &wait);
1294
1295         if (timeout) {
1296                 s64 tres = *timeout - (now - before);
1297
1298                 *timeout = tres < 0 ? 0 : tres;
1299         }
1300
1301         return ret;
1302 }
1303
1304 /**
1305  * Waits for a request to be signaled, and cleans up the
1306  * request and object lists appropriately for that event.
1307  */
1308 int
1309 i915_wait_request(struct drm_i915_gem_request *req)
1310 {
1311         struct drm_device *dev;
1312         struct drm_i915_private *dev_priv;
1313         bool interruptible;
1314         unsigned reset_counter;
1315         int ret;
1316
1317         BUG_ON(req == NULL);
1318
1319         dev = req->ring->dev;
1320         dev_priv = dev->dev_private;
1321         interruptible = dev_priv->mm.interruptible;
1322
1323         BUG_ON(!mutex_is_locked(&dev->struct_mutex));
1324
1325         ret = i915_gem_check_wedge(&dev_priv->gpu_error, interruptible);
1326         if (ret)
1327                 return ret;
1328
1329         ret = i915_gem_check_olr(req);
1330         if (ret)
1331                 return ret;
1332
1333         reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
1334         i915_gem_request_reference(req);
1335         ret = __i915_wait_request(req, reset_counter,
1336                                   interruptible, NULL, NULL);
1337         i915_gem_request_unreference(req);
1338         return ret;
1339 }
1340
1341 static int
1342 i915_gem_object_wait_rendering__tail(struct drm_i915_gem_object *obj)
1343 {
1344         if (!obj->active)
1345                 return 0;
1346
1347         /* Manually manage the write flush as we may have not yet
1348          * retired the buffer.
1349          *
1350          * Note that the last_write_req is always the earlier of
1351          * the two (read/write) requests, so if we haved successfully waited,
1352          * we know we have passed the last write.
1353          */
1354         i915_gem_request_assign(&obj->last_write_req, NULL);
1355
1356         return 0;
1357 }
1358
1359 /**
1360  * Ensures that all rendering to the object has completed and the object is
1361  * safe to unbind from the GTT or access from the CPU.
1362  */
1363 static __must_check int
1364 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
1365                                bool readonly)
1366 {
1367         struct drm_i915_gem_request *req;
1368         int ret;
1369
1370         req = readonly ? obj->last_write_req : obj->last_read_req;
1371         if (!req)
1372                 return 0;
1373
1374         ret = i915_wait_request(req);
1375         if (ret)
1376                 return ret;
1377
1378         return i915_gem_object_wait_rendering__tail(obj);
1379 }
1380
1381 /* A nonblocking variant of the above wait. This is a highly dangerous routine
1382  * as the object state may change during this call.
1383  */
1384 static __must_check int
1385 i915_gem_object_wait_rendering__nonblocking(struct drm_i915_gem_object *obj,
1386                                             struct drm_i915_file_private *file_priv,
1387                                             bool readonly)
1388 {
1389         struct drm_i915_gem_request *req;
1390         struct drm_device *dev = obj->base.dev;
1391         struct drm_i915_private *dev_priv = dev->dev_private;
1392         unsigned reset_counter;
1393         int ret;
1394
1395         BUG_ON(!mutex_is_locked(&dev->struct_mutex));
1396         BUG_ON(!dev_priv->mm.interruptible);
1397
1398         req = readonly ? obj->last_write_req : obj->last_read_req;
1399         if (!req)
1400                 return 0;
1401
1402         ret = i915_gem_check_wedge(&dev_priv->gpu_error, true);
1403         if (ret)
1404                 return ret;
1405
1406         ret = i915_gem_check_olr(req);
1407         if (ret)
1408                 return ret;
1409
1410         reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
1411         i915_gem_request_reference(req);
1412         mutex_unlock(&dev->struct_mutex);
1413         ret = __i915_wait_request(req, reset_counter, true, NULL, file_priv);
1414         mutex_lock(&dev->struct_mutex);
1415         i915_gem_request_unreference(req);
1416         if (ret)
1417                 return ret;
1418
1419         return i915_gem_object_wait_rendering__tail(obj);
1420 }
1421
1422 /**
1423  * Called when user space prepares to use an object with the CPU, either
1424  * through the mmap ioctl's mapping or a GTT mapping.
1425  */
1426 int
1427 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1428                           struct drm_file *file)
1429 {
1430         struct drm_i915_gem_set_domain *args = data;
1431         struct drm_i915_gem_object *obj;
1432         uint32_t read_domains = args->read_domains;
1433         uint32_t write_domain = args->write_domain;
1434         int ret;
1435
1436         /* Only handle setting domains to types used by the CPU. */
1437         if (write_domain & I915_GEM_GPU_DOMAINS)
1438                 return -EINVAL;
1439
1440         if (read_domains & I915_GEM_GPU_DOMAINS)
1441                 return -EINVAL;
1442
1443         /* Having something in the write domain implies it's in the read
1444          * domain, and only that read domain.  Enforce that in the request.
1445          */
1446         if (write_domain != 0 && read_domains != write_domain)
1447                 return -EINVAL;
1448
1449         ret = i915_mutex_lock_interruptible(dev);
1450         if (ret)
1451                 return ret;
1452
1453         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1454         if (&obj->base == NULL) {
1455                 ret = -ENOENT;
1456                 goto unlock;
1457         }
1458
1459         /* Try to flush the object off the GPU without holding the lock.
1460          * We will repeat the flush holding the lock in the normal manner
1461          * to catch cases where we are gazumped.
1462          */
1463         ret = i915_gem_object_wait_rendering__nonblocking(obj,
1464                                                           file->driver_priv,
1465                                                           !write_domain);
1466         if (ret)
1467                 goto unref;
1468
1469         if (read_domains & I915_GEM_DOMAIN_GTT)
1470                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
1471         else
1472                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
1473
1474 unref:
1475         drm_gem_object_unreference(&obj->base);
1476 unlock:
1477         mutex_unlock(&dev->struct_mutex);
1478         return ret;
1479 }
1480
1481 /**
1482  * Called when user space has done writes to this buffer
1483  */
1484 int
1485 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1486                          struct drm_file *file)
1487 {
1488         struct drm_i915_gem_sw_finish *args = data;
1489         struct drm_i915_gem_object *obj;
1490         int ret = 0;
1491
1492         ret = i915_mutex_lock_interruptible(dev);
1493         if (ret)
1494                 return ret;
1495
1496         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
1497         if (&obj->base == NULL) {
1498                 ret = -ENOENT;
1499                 goto unlock;
1500         }
1501
1502         /* Pinned buffers may be scanout, so flush the cache */
1503         if (obj->pin_display)
1504                 i915_gem_object_flush_cpu_write_domain(obj, true);
1505
1506         drm_gem_object_unreference(&obj->base);
1507 unlock:
1508         mutex_unlock(&dev->struct_mutex);
1509         return ret;
1510 }
1511
1512 /**
1513  * Maps the contents of an object, returning the address it is mapped
1514  * into.
1515  *
1516  * While the mapping holds a reference on the contents of the object, it doesn't
1517  * imply a ref on the object itself.
1518  *
1519  * IMPORTANT:
1520  *
1521  * DRM driver writers who look a this function as an example for how to do GEM
1522  * mmap support, please don't implement mmap support like here. The modern way
1523  * to implement DRM mmap support is with an mmap offset ioctl (like
1524  * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
1525  * That way debug tooling like valgrind will understand what's going on, hiding
1526  * the mmap call in a driver private ioctl will break that. The i915 driver only
1527  * does cpu mmaps this way because we didn't know better.
1528  */
1529 int
1530 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1531                     struct drm_file *file)
1532 {
1533         struct drm_i915_gem_mmap *args = data;
1534         struct drm_gem_object *obj;
1535         unsigned long addr;
1536
1537         if (args->flags & ~(I915_MMAP_WC))
1538                 return -EINVAL;
1539
1540         if (args->flags & I915_MMAP_WC && !cpu_has_pat)
1541                 return -ENODEV;
1542
1543         obj = drm_gem_object_lookup(dev, file, args->handle);
1544         if (obj == NULL)
1545                 return -ENOENT;
1546
1547         /* prime objects have no backing filp to GEM mmap
1548          * pages from.
1549          */
1550         if (!obj->filp) {
1551                 drm_gem_object_unreference_unlocked(obj);
1552                 return -EINVAL;
1553         }
1554
1555         addr = vm_mmap(obj->filp, 0, args->size,
1556                        PROT_READ | PROT_WRITE, MAP_SHARED,
1557                        args->offset);
1558         if (args->flags & I915_MMAP_WC) {
1559                 struct mm_struct *mm = current->mm;
1560                 struct vm_area_struct *vma;
1561
1562                 down_write(&mm->mmap_sem);
1563                 vma = find_vma(mm, addr);
1564                 if (vma)
1565                         vma->vm_page_prot =
1566                                 pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1567                 else
1568                         addr = -ENOMEM;
1569                 up_write(&mm->mmap_sem);
1570         }
1571         drm_gem_object_unreference_unlocked(obj);
1572         if (IS_ERR((void *)addr))
1573                 return addr;
1574
1575         args->addr_ptr = (uint64_t) addr;
1576
1577         return 0;
1578 }
1579
1580 /**
1581  * i915_gem_fault - fault a page into the GTT
1582  * vma: VMA in question
1583  * vmf: fault info
1584  *
1585  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1586  * from userspace.  The fault handler takes care of binding the object to
1587  * the GTT (if needed), allocating and programming a fence register (again,
1588  * only if needed based on whether the old reg is still valid or the object
1589  * is tiled) and inserting a new PTE into the faulting process.
1590  *
1591  * Note that the faulting process may involve evicting existing objects
1592  * from the GTT and/or fence registers to make room.  So performance may
1593  * suffer if the GTT working set is large or there are few fence registers
1594  * left.
1595  */
1596 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
1597 {
1598         struct drm_i915_gem_object *obj = to_intel_bo(vma->vm_private_data);
1599         struct drm_device *dev = obj->base.dev;
1600         struct drm_i915_private *dev_priv = dev->dev_private;
1601         pgoff_t page_offset;
1602         unsigned long pfn;
1603         int ret = 0;
1604         bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1605
1606         intel_runtime_pm_get(dev_priv);
1607
1608         /* We don't use vmf->pgoff since that has the fake offset */
1609         page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
1610                 PAGE_SHIFT;
1611
1612         ret = i915_mutex_lock_interruptible(dev);
1613         if (ret)
1614                 goto out;
1615
1616         trace_i915_gem_object_fault(obj, page_offset, true, write);
1617
1618         /* Try to flush the object off the GPU first without holding the lock.
1619          * Upon reacquiring the lock, we will perform our sanity checks and then
1620          * repeat the flush holding the lock in the normal manner to catch cases
1621          * where we are gazumped.
1622          */
1623         ret = i915_gem_object_wait_rendering__nonblocking(obj, NULL, !write);
1624         if (ret)
1625                 goto unlock;
1626
1627         /* Access to snoopable pages through the GTT is incoherent. */
1628         if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev)) {
1629                 ret = -EFAULT;
1630                 goto unlock;
1631         }
1632
1633         /* Now bind it into the GTT if needed */
1634         ret = i915_gem_obj_ggtt_pin(obj, 0, PIN_MAPPABLE);
1635         if (ret)
1636                 goto unlock;
1637
1638         ret = i915_gem_object_set_to_gtt_domain(obj, write);
1639         if (ret)
1640                 goto unpin;
1641
1642         ret = i915_gem_object_get_fence(obj);
1643         if (ret)
1644                 goto unpin;
1645
1646         /* Finally, remap it using the new GTT offset */
1647         pfn = dev_priv->gtt.mappable_base + i915_gem_obj_ggtt_offset(obj);
1648         pfn >>= PAGE_SHIFT;
1649
1650         if (!obj->fault_mappable) {
1651                 unsigned long size = min_t(unsigned long,
1652                                            vma->vm_end - vma->vm_start,
1653                                            obj->base.size);
1654                 int i;
1655
1656                 for (i = 0; i < size >> PAGE_SHIFT; i++) {
1657                         ret = vm_insert_pfn(vma,
1658                                             (unsigned long)vma->vm_start + i * PAGE_SIZE,
1659                                             pfn + i);
1660                         if (ret)
1661                                 break;
1662                 }
1663
1664                 obj->fault_mappable = true;
1665         } else
1666                 ret = vm_insert_pfn(vma,
1667                                     (unsigned long)vmf->virtual_address,
1668                                     pfn + page_offset);
1669 unpin:
1670         i915_gem_object_ggtt_unpin(obj);
1671 unlock:
1672         mutex_unlock(&dev->struct_mutex);
1673 out:
1674         switch (ret) {
1675         case -EIO:
1676                 /*
1677                  * We eat errors when the gpu is terminally wedged to avoid
1678                  * userspace unduly crashing (gl has no provisions for mmaps to
1679                  * fail). But any other -EIO isn't ours (e.g. swap in failure)
1680                  * and so needs to be reported.
1681                  */
1682                 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
1683                         ret = VM_FAULT_SIGBUS;
1684                         break;
1685                 }
1686         case -EAGAIN:
1687                 /*
1688                  * EAGAIN means the gpu is hung and we'll wait for the error
1689                  * handler to reset everything when re-faulting in
1690                  * i915_mutex_lock_interruptible.
1691                  */
1692         case 0:
1693         case -ERESTARTSYS:
1694         case -EINTR:
1695         case -EBUSY:
1696                 /*
1697                  * EBUSY is ok: this just means that another thread
1698                  * already did the job.
1699                  */
1700                 ret = VM_FAULT_NOPAGE;
1701                 break;
1702         case -ENOMEM:
1703                 ret = VM_FAULT_OOM;
1704                 break;
1705         case -ENOSPC:
1706         case -EFAULT:
1707                 ret = VM_FAULT_SIGBUS;
1708                 break;
1709         default:
1710                 WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
1711                 ret = VM_FAULT_SIGBUS;
1712                 break;
1713         }
1714
1715         intel_runtime_pm_put(dev_priv);
1716         return ret;
1717 }
1718
1719 /**
1720  * i915_gem_release_mmap - remove physical page mappings
1721  * @obj: obj in question
1722  *
1723  * Preserve the reservation of the mmapping with the DRM core code, but
1724  * relinquish ownership of the pages back to the system.
1725  *
1726  * It is vital that we remove the page mapping if we have mapped a tiled
1727  * object through the GTT and then lose the fence register due to
1728  * resource pressure. Similarly if the object has been moved out of the
1729  * aperture, than pages mapped into userspace must be revoked. Removing the
1730  * mapping will then trigger a page fault on the next user access, allowing
1731  * fixup by i915_gem_fault().
1732  */
1733 void
1734 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
1735 {
1736         if (!obj->fault_mappable)
1737                 return;
1738
1739         drm_vma_node_unmap(&obj->base.vma_node,
1740                            obj->base.dev->anon_inode->i_mapping);
1741         obj->fault_mappable = false;
1742 }
1743
1744 void
1745 i915_gem_release_all_mmaps(struct drm_i915_private *dev_priv)
1746 {
1747         struct drm_i915_gem_object *obj;
1748
1749         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list)
1750                 i915_gem_release_mmap(obj);
1751 }
1752
1753 uint32_t
1754 i915_gem_get_gtt_size(struct drm_device *dev, uint32_t size, int tiling_mode)
1755 {
1756         uint32_t gtt_size;
1757
1758         if (INTEL_INFO(dev)->gen >= 4 ||
1759             tiling_mode == I915_TILING_NONE)
1760                 return size;
1761
1762         /* Previous chips need a power-of-two fence region when tiling */
1763         if (INTEL_INFO(dev)->gen == 3)
1764                 gtt_size = 1024*1024;
1765         else
1766                 gtt_size = 512*1024;
1767
1768         while (gtt_size < size)
1769                 gtt_size <<= 1;
1770
1771         return gtt_size;
1772 }
1773
1774 /**
1775  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
1776  * @obj: object to check
1777  *
1778  * Return the required GTT alignment for an object, taking into account
1779  * potential fence register mapping.
1780  */
1781 uint32_t
1782 i915_gem_get_gtt_alignment(struct drm_device *dev, uint32_t size,
1783                            int tiling_mode, bool fenced)
1784 {
1785         /*
1786          * Minimum alignment is 4k (GTT page size), but might be greater
1787          * if a fence register is needed for the object.
1788          */
1789         if (INTEL_INFO(dev)->gen >= 4 || (!fenced && IS_G33(dev)) ||
1790             tiling_mode == I915_TILING_NONE)
1791                 return 4096;
1792
1793         /*
1794          * Previous chips need to be aligned to the size of the smallest
1795          * fence register that can contain the object.
1796          */
1797         return i915_gem_get_gtt_size(dev, size, tiling_mode);
1798 }
1799
1800 static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
1801 {
1802         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
1803         int ret;
1804
1805         if (drm_vma_node_has_offset(&obj->base.vma_node))
1806                 return 0;
1807
1808         dev_priv->mm.shrinker_no_lock_stealing = true;
1809
1810         ret = drm_gem_create_mmap_offset(&obj->base);
1811         if (ret != -ENOSPC)
1812                 goto out;
1813
1814         /* Badly fragmented mmap space? The only way we can recover
1815          * space is by destroying unwanted objects. We can't randomly release
1816          * mmap_offsets as userspace expects them to be persistent for the
1817          * lifetime of the objects. The closest we can is to release the
1818          * offsets on purgeable objects by truncating it and marking it purged,
1819          * which prevents userspace from ever using that object again.
1820          */
1821         i915_gem_shrink(dev_priv,
1822                         obj->base.size >> PAGE_SHIFT,
1823                         I915_SHRINK_BOUND |
1824                         I915_SHRINK_UNBOUND |
1825                         I915_SHRINK_PURGEABLE);
1826         ret = drm_gem_create_mmap_offset(&obj->base);
1827         if (ret != -ENOSPC)
1828                 goto out;
1829
1830         i915_gem_shrink_all(dev_priv);
1831         ret = drm_gem_create_mmap_offset(&obj->base);
1832 out:
1833         dev_priv->mm.shrinker_no_lock_stealing = false;
1834
1835         return ret;
1836 }
1837
1838 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
1839 {
1840         drm_gem_free_mmap_offset(&obj->base);
1841 }
1842
1843 static int
1844 i915_gem_mmap_gtt(struct drm_file *file,
1845                   struct drm_device *dev,
1846                   uint32_t handle, bool dumb,
1847                   uint64_t *offset)
1848 {
1849         struct drm_i915_private *dev_priv = dev->dev_private;
1850         struct drm_i915_gem_object *obj;
1851         int ret;
1852
1853         ret = i915_mutex_lock_interruptible(dev);
1854         if (ret)
1855                 return ret;
1856
1857         obj = to_intel_bo(drm_gem_object_lookup(dev, file, handle));
1858         if (&obj->base == NULL) {
1859                 ret = -ENOENT;
1860                 goto unlock;
1861         }
1862
1863         /*
1864          * We don't allow dumb mmaps on objects created using another
1865          * interface.
1866          */
1867         WARN_ONCE(dumb && !(obj->base.dumb || obj->base.import_attach),
1868                   "Illegal dumb map of accelerated buffer.\n");
1869
1870         if (obj->base.size > dev_priv->gtt.mappable_end) {
1871                 ret = -E2BIG;
1872                 goto out;
1873         }
1874
1875         if (obj->madv != I915_MADV_WILLNEED) {
1876                 DRM_DEBUG("Attempting to mmap a purgeable buffer\n");
1877                 ret = -EFAULT;
1878                 goto out;
1879         }
1880
1881         ret = i915_gem_object_create_mmap_offset(obj);
1882         if (ret)
1883                 goto out;
1884
1885         *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
1886
1887 out:
1888         drm_gem_object_unreference(&obj->base);
1889 unlock:
1890         mutex_unlock(&dev->struct_mutex);
1891         return ret;
1892 }
1893
1894 int
1895 i915_gem_dumb_map_offset(struct drm_file *file,
1896                          struct drm_device *dev,
1897                          uint32_t handle,
1898                          uint64_t *offset)
1899 {
1900         return i915_gem_mmap_gtt(file, dev, handle, true, offset);
1901 }
1902
1903 /**
1904  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
1905  * @dev: DRM device
1906  * @data: GTT mapping ioctl data
1907  * @file: GEM object info
1908  *
1909  * Simply returns the fake offset to userspace so it can mmap it.
1910  * The mmap call will end up in drm_gem_mmap(), which will set things
1911  * up so we can get faults in the handler above.
1912  *
1913  * The fault handler will take care of binding the object into the GTT
1914  * (since it may have been evicted to make room for something), allocating
1915  * a fence register, and mapping the appropriate aperture address into
1916  * userspace.
1917  */
1918 int
1919 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
1920                         struct drm_file *file)
1921 {
1922         struct drm_i915_gem_mmap_gtt *args = data;
1923
1924         return i915_gem_mmap_gtt(file, dev, args->handle, false, &args->offset);
1925 }
1926
1927 static inline int
1928 i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj)
1929 {
1930         return obj->madv == I915_MADV_DONTNEED;
1931 }
1932
1933 /* Immediately discard the backing storage */
1934 static void
1935 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
1936 {
1937         i915_gem_object_free_mmap_offset(obj);
1938
1939         if (obj->base.filp == NULL)
1940                 return;
1941
1942         /* Our goal here is to return as much of the memory as
1943          * is possible back to the system as we are called from OOM.
1944          * To do this we must instruct the shmfs to drop all of its
1945          * backing pages, *now*.
1946          */
1947         shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
1948         obj->madv = __I915_MADV_PURGED;
1949 }
1950
1951 /* Try to discard unwanted pages */
1952 static void
1953 i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
1954 {
1955         struct address_space *mapping;
1956
1957         switch (obj->madv) {
1958         case I915_MADV_DONTNEED:
1959                 i915_gem_object_truncate(obj);
1960         case __I915_MADV_PURGED:
1961                 return;
1962         }
1963
1964         if (obj->base.filp == NULL)
1965                 return;
1966
1967         mapping = file_inode(obj->base.filp)->i_mapping,
1968         invalidate_mapping_pages(mapping, 0, (loff_t)-1);
1969 }
1970
1971 static void
1972 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
1973 {
1974         struct sg_page_iter sg_iter;
1975         int ret;
1976
1977         BUG_ON(obj->madv == __I915_MADV_PURGED);
1978
1979         ret = i915_gem_object_set_to_cpu_domain(obj, true);
1980         if (ret) {
1981                 /* In the event of a disaster, abandon all caches and
1982                  * hope for the best.
1983                  */
1984                 WARN_ON(ret != -EIO);
1985                 i915_gem_clflush_object(obj, true);
1986                 obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
1987         }
1988
1989         if (i915_gem_object_needs_bit17_swizzle(obj))
1990                 i915_gem_object_save_bit_17_swizzle(obj);
1991
1992         if (obj->madv == I915_MADV_DONTNEED)
1993                 obj->dirty = 0;
1994
1995         for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents, 0) {
1996                 struct page *page = sg_page_iter_page(&sg_iter);
1997
1998                 if (obj->dirty)
1999                         set_page_dirty(page);
2000
2001                 if (obj->madv == I915_MADV_WILLNEED)
2002                         mark_page_accessed(page);
2003
2004                 page_cache_release(page);
2005         }
2006         obj->dirty = 0;
2007
2008         sg_free_table(obj->pages);
2009         kfree(obj->pages);
2010 }
2011
2012 int
2013 i915_gem_object_put_pages(struct drm_i915_gem_object *obj)
2014 {
2015         const struct drm_i915_gem_object_ops *ops = obj->ops;
2016
2017         if (obj->pages == NULL)
2018                 return 0;
2019
2020         if (obj->pages_pin_count)
2021                 return -EBUSY;
2022
2023         BUG_ON(i915_gem_obj_bound_any(obj));
2024
2025         /* ->put_pages might need to allocate memory for the bit17 swizzle
2026          * array, hence protect them from being reaped by removing them from gtt
2027          * lists early. */
2028         list_del(&obj->global_list);
2029
2030         ops->put_pages(obj);
2031         obj->pages = NULL;
2032
2033         i915_gem_object_invalidate(obj);
2034
2035         return 0;
2036 }
2037
2038 unsigned long
2039 i915_gem_shrink(struct drm_i915_private *dev_priv,
2040                 long target, unsigned flags)
2041 {
2042         const struct {
2043                 struct list_head *list;
2044                 unsigned int bit;
2045         } phases[] = {
2046                 { &dev_priv->mm.unbound_list, I915_SHRINK_UNBOUND },
2047                 { &dev_priv->mm.bound_list, I915_SHRINK_BOUND },
2048                 { NULL, 0 },
2049         }, *phase;
2050         unsigned long count = 0;
2051
2052         /*
2053          * As we may completely rewrite the (un)bound list whilst unbinding
2054          * (due to retiring requests) we have to strictly process only
2055          * one element of the list at the time, and recheck the list
2056          * on every iteration.
2057          *
2058          * In particular, we must hold a reference whilst removing the
2059          * object as we may end up waiting for and/or retiring the objects.
2060          * This might release the final reference (held by the active list)
2061          * and result in the object being freed from under us. This is
2062          * similar to the precautions the eviction code must take whilst
2063          * removing objects.
2064          *
2065          * Also note that although these lists do not hold a reference to
2066          * the object we can safely grab one here: The final object
2067          * unreferencing and the bound_list are both protected by the
2068          * dev->struct_mutex and so we won't ever be able to observe an
2069          * object on the bound_list with a reference count equals 0.
2070          */
2071         for (phase = phases; phase->list; phase++) {
2072                 struct list_head still_in_list;
2073
2074                 if ((flags & phase->bit) == 0)
2075                         continue;
2076
2077                 INIT_LIST_HEAD(&still_in_list);
2078                 while (count < target && !list_empty(phase->list)) {
2079                         struct drm_i915_gem_object *obj;
2080                         struct i915_vma *vma, *v;
2081
2082                         obj = list_first_entry(phase->list,
2083                                                typeof(*obj), global_list);
2084                         list_move_tail(&obj->global_list, &still_in_list);
2085
2086                         if (flags & I915_SHRINK_PURGEABLE &&
2087                             !i915_gem_object_is_purgeable(obj))
2088                                 continue;
2089
2090                         drm_gem_object_reference(&obj->base);
2091
2092                         /* For the unbound phase, this should be a no-op! */
2093                         list_for_each_entry_safe(vma, v,
2094                                                  &obj->vma_list, vma_link)
2095                                 if (i915_vma_unbind(vma))
2096                                         break;
2097
2098                         if (i915_gem_object_put_pages(obj) == 0)
2099                                 count += obj->base.size >> PAGE_SHIFT;
2100
2101                         drm_gem_object_unreference(&obj->base);
2102                 }
2103                 list_splice(&still_in_list, phase->list);
2104         }
2105
2106         return count;
2107 }
2108
2109 static unsigned long
2110 i915_gem_shrink_all(struct drm_i915_private *dev_priv)
2111 {
2112         i915_gem_evict_everything(dev_priv->dev);
2113         return i915_gem_shrink(dev_priv, LONG_MAX,
2114                                I915_SHRINK_BOUND | I915_SHRINK_UNBOUND);
2115 }
2116
2117 static int
2118 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
2119 {
2120         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2121         int page_count, i;
2122         struct address_space *mapping;
2123         struct sg_table *st;
2124         struct scatterlist *sg;
2125         struct sg_page_iter sg_iter;
2126         struct page *page;
2127         unsigned long last_pfn = 0;     /* suppress gcc warning */
2128         gfp_t gfp;
2129
2130         /* Assert that the object is not currently in any GPU domain. As it
2131          * wasn't in the GTT, there shouldn't be any way it could have been in
2132          * a GPU cache
2133          */
2134         BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2135         BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2136
2137         st = kmalloc(sizeof(*st), GFP_KERNEL);
2138         if (st == NULL)
2139                 return -ENOMEM;
2140
2141         page_count = obj->base.size / PAGE_SIZE;
2142         if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
2143                 kfree(st);
2144                 return -ENOMEM;
2145         }
2146
2147         /* Get the list of pages out of our struct file.  They'll be pinned
2148          * at this point until we release them.
2149          *
2150          * Fail silently without starting the shrinker
2151          */
2152         mapping = file_inode(obj->base.filp)->i_mapping;
2153         gfp = mapping_gfp_mask(mapping);
2154         gfp |= __GFP_NORETRY | __GFP_NOWARN | __GFP_NO_KSWAPD;
2155         gfp &= ~(__GFP_IO | __GFP_WAIT);
2156         sg = st->sgl;
2157         st->nents = 0;
2158         for (i = 0; i < page_count; i++) {
2159                 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2160                 if (IS_ERR(page)) {
2161                         i915_gem_shrink(dev_priv,
2162                                         page_count,
2163                                         I915_SHRINK_BOUND |
2164                                         I915_SHRINK_UNBOUND |
2165                                         I915_SHRINK_PURGEABLE);
2166                         page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2167                 }
2168                 if (IS_ERR(page)) {
2169                         /* We've tried hard to allocate the memory by reaping
2170                          * our own buffer, now let the real VM do its job and
2171                          * go down in flames if truly OOM.
2172                          */
2173                         i915_gem_shrink_all(dev_priv);
2174                         page = shmem_read_mapping_page(mapping, i);
2175                         if (IS_ERR(page))
2176                                 goto err_pages;
2177                 }
2178 #ifdef CONFIG_SWIOTLB
2179                 if (swiotlb_nr_tbl()) {
2180                         st->nents++;
2181                         sg_set_page(sg, page, PAGE_SIZE, 0);
2182                         sg = sg_next(sg);
2183                         continue;
2184                 }
2185 #endif
2186                 if (!i || page_to_pfn(page) != last_pfn + 1) {
2187                         if (i)
2188                                 sg = sg_next(sg);
2189                         st->nents++;
2190                         sg_set_page(sg, page, PAGE_SIZE, 0);
2191                 } else {
2192                         sg->length += PAGE_SIZE;
2193                 }
2194                 last_pfn = page_to_pfn(page);
2195
2196                 /* Check that the i965g/gm workaround works. */
2197                 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
2198         }
2199 #ifdef CONFIG_SWIOTLB
2200         if (!swiotlb_nr_tbl())
2201 #endif
2202                 sg_mark_end(sg);
2203         obj->pages = st;
2204
2205         if (i915_gem_object_needs_bit17_swizzle(obj))
2206                 i915_gem_object_do_bit_17_swizzle(obj);
2207
2208         if (obj->tiling_mode != I915_TILING_NONE &&
2209             dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES)
2210                 i915_gem_object_pin_pages(obj);
2211
2212         return 0;
2213
2214 err_pages:
2215         sg_mark_end(sg);
2216         for_each_sg_page(st->sgl, &sg_iter, st->nents, 0)
2217                 page_cache_release(sg_page_iter_page(&sg_iter));
2218         sg_free_table(st);
2219         kfree(st);
2220
2221         /* shmemfs first checks if there is enough memory to allocate the page
2222          * and reports ENOSPC should there be insufficient, along with the usual
2223          * ENOMEM for a genuine allocation failure.
2224          *
2225          * We use ENOSPC in our driver to mean that we have run out of aperture
2226          * space and so want to translate the error from shmemfs back to our
2227          * usual understanding of ENOMEM.
2228          */
2229         if (PTR_ERR(page) == -ENOSPC)
2230                 return -ENOMEM;
2231         else
2232                 return PTR_ERR(page);
2233 }
2234
2235 /* Ensure that the associated pages are gathered from the backing storage
2236  * and pinned into our object. i915_gem_object_get_pages() may be called
2237  * multiple times before they are released by a single call to
2238  * i915_gem_object_put_pages() - once the pages are no longer referenced
2239  * either as a result of memory pressure (reaping pages under the shrinker)
2240  * or as the object is itself released.
2241  */
2242 int
2243 i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2244 {
2245         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2246         const struct drm_i915_gem_object_ops *ops = obj->ops;
2247         int ret;
2248
2249         if (obj->pages)
2250                 return 0;
2251
2252         if (obj->madv != I915_MADV_WILLNEED) {
2253                 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2254                 return -EFAULT;
2255         }
2256
2257         BUG_ON(obj->pages_pin_count);
2258
2259         ret = ops->get_pages(obj);
2260         if (ret)
2261                 return ret;
2262
2263         list_add_tail(&obj->global_list, &dev_priv->mm.unbound_list);
2264         return 0;
2265 }
2266
2267 static void
2268 i915_gem_object_move_to_active(struct drm_i915_gem_object *obj,
2269                                struct intel_engine_cs *ring)
2270 {
2271         struct drm_i915_gem_request *req;
2272         struct intel_engine_cs *old_ring;
2273
2274         BUG_ON(ring == NULL);
2275
2276         req = intel_ring_get_request(ring);
2277         old_ring = i915_gem_request_get_ring(obj->last_read_req);
2278
2279         if (old_ring != ring && obj->last_write_req) {
2280                 /* Keep the request relative to the current ring */
2281                 i915_gem_request_assign(&obj->last_write_req, req);
2282         }
2283
2284         /* Add a reference if we're newly entering the active list. */
2285         if (!obj->active) {
2286                 drm_gem_object_reference(&obj->base);
2287                 obj->active = 1;
2288         }
2289
2290         list_move_tail(&obj->ring_list, &ring->active_list);
2291
2292         i915_gem_request_assign(&obj->last_read_req, req);
2293 }
2294
2295 void i915_vma_move_to_active(struct i915_vma *vma,
2296                              struct intel_engine_cs *ring)
2297 {
2298         list_move_tail(&vma->mm_list, &vma->vm->active_list);
2299         return i915_gem_object_move_to_active(vma->obj, ring);
2300 }
2301
2302 static void
2303 i915_gem_object_move_to_inactive(struct drm_i915_gem_object *obj)
2304 {
2305         struct i915_vma *vma;
2306
2307         BUG_ON(obj->base.write_domain & ~I915_GEM_GPU_DOMAINS);
2308         BUG_ON(!obj->active);
2309
2310         list_for_each_entry(vma, &obj->vma_list, vma_link) {
2311                 if (!list_empty(&vma->mm_list))
2312                         list_move_tail(&vma->mm_list, &vma->vm->inactive_list);
2313         }
2314
2315         intel_fb_obj_flush(obj, true);
2316
2317         list_del_init(&obj->ring_list);
2318
2319         i915_gem_request_assign(&obj->last_read_req, NULL);
2320         i915_gem_request_assign(&obj->last_write_req, NULL);
2321         obj->base.write_domain = 0;
2322
2323         i915_gem_request_assign(&obj->last_fenced_req, NULL);
2324
2325         obj->active = 0;
2326         drm_gem_object_unreference(&obj->base);
2327
2328         WARN_ON(i915_verify_lists(dev));
2329 }
2330
2331 static void
2332 i915_gem_object_retire(struct drm_i915_gem_object *obj)
2333 {
2334         if (obj->last_read_req == NULL)
2335                 return;
2336
2337         if (i915_gem_request_completed(obj->last_read_req, true))
2338                 i915_gem_object_move_to_inactive(obj);
2339 }
2340
2341 static int
2342 i915_gem_init_seqno(struct drm_device *dev, u32 seqno)
2343 {
2344         struct drm_i915_private *dev_priv = dev->dev_private;
2345         struct intel_engine_cs *ring;
2346         int ret, i, j;
2347
2348         /* Carefully retire all requests without writing to the rings */
2349         for_each_ring(ring, dev_priv, i) {
2350                 ret = intel_ring_idle(ring);
2351                 if (ret)
2352                         return ret;
2353         }
2354         i915_gem_retire_requests(dev);
2355
2356         /* Finally reset hw state */
2357         for_each_ring(ring, dev_priv, i) {
2358                 intel_ring_init_seqno(ring, seqno);
2359
2360                 for (j = 0; j < ARRAY_SIZE(ring->semaphore.sync_seqno); j++)
2361                         ring->semaphore.sync_seqno[j] = 0;
2362         }
2363
2364         return 0;
2365 }
2366
2367 int i915_gem_set_seqno(struct drm_device *dev, u32 seqno)
2368 {
2369         struct drm_i915_private *dev_priv = dev->dev_private;
2370         int ret;
2371
2372         if (seqno == 0)
2373                 return -EINVAL;
2374
2375         /* HWS page needs to be set less than what we
2376          * will inject to ring
2377          */
2378         ret = i915_gem_init_seqno(dev, seqno - 1);
2379         if (ret)
2380                 return ret;
2381
2382         /* Carefully set the last_seqno value so that wrap
2383          * detection still works
2384          */
2385         dev_priv->next_seqno = seqno;
2386         dev_priv->last_seqno = seqno - 1;
2387         if (dev_priv->last_seqno == 0)
2388                 dev_priv->last_seqno--;
2389
2390         return 0;
2391 }
2392
2393 int
2394 i915_gem_get_seqno(struct drm_device *dev, u32 *seqno)
2395 {
2396         struct drm_i915_private *dev_priv = dev->dev_private;
2397
2398         /* reserve 0 for non-seqno */
2399         if (dev_priv->next_seqno == 0) {
2400                 int ret = i915_gem_init_seqno(dev, 0);
2401                 if (ret)
2402                         return ret;
2403
2404                 dev_priv->next_seqno = 1;
2405         }
2406
2407         *seqno = dev_priv->last_seqno = dev_priv->next_seqno++;
2408         return 0;
2409 }
2410
2411 int __i915_add_request(struct intel_engine_cs *ring,
2412                        struct drm_file *file,
2413                        struct drm_i915_gem_object *obj)
2414 {
2415         struct drm_i915_private *dev_priv = ring->dev->dev_private;
2416         struct drm_i915_gem_request *request;
2417         struct intel_ringbuffer *ringbuf;
2418         u32 request_ring_position, request_start;
2419         int ret;
2420
2421         request = ring->outstanding_lazy_request;
2422         if (WARN_ON(request == NULL))
2423                 return -ENOMEM;
2424
2425         if (i915.enable_execlists) {
2426                 struct intel_context *ctx = request->ctx;
2427                 ringbuf = ctx->engine[ring->id].ringbuf;
2428         } else
2429                 ringbuf = ring->buffer;
2430
2431         request_start = intel_ring_get_tail(ringbuf);
2432         /*
2433          * Emit any outstanding flushes - execbuf can fail to emit the flush
2434          * after having emitted the batchbuffer command. Hence we need to fix
2435          * things up similar to emitting the lazy request. The difference here
2436          * is that the flush _must_ happen before the next request, no matter
2437          * what.
2438          */
2439         if (i915.enable_execlists) {
2440                 ret = logical_ring_flush_all_caches(ringbuf);
2441                 if (ret)
2442                         return ret;
2443         } else {
2444                 ret = intel_ring_flush_all_caches(ring);
2445                 if (ret)
2446                         return ret;
2447         }
2448
2449         /* Record the position of the start of the request so that
2450          * should we detect the updated seqno part-way through the
2451          * GPU processing the request, we never over-estimate the
2452          * position of the head.
2453          */
2454         request_ring_position = intel_ring_get_tail(ringbuf);
2455
2456         if (i915.enable_execlists) {
2457                 ret = ring->emit_request(ringbuf);
2458                 if (ret)
2459                         return ret;
2460         } else {
2461                 ret = ring->add_request(ring);
2462                 if (ret)
2463                         return ret;
2464         }
2465
2466         request->head = request_start;
2467         request->tail = request_ring_position;
2468
2469         /* Whilst this request exists, batch_obj will be on the
2470          * active_list, and so will hold the active reference. Only when this
2471          * request is retired will the the batch_obj be moved onto the
2472          * inactive_list and lose its active reference. Hence we do not need
2473          * to explicitly hold another reference here.
2474          */
2475         request->batch_obj = obj;
2476
2477         if (!i915.enable_execlists) {
2478                 /* Hold a reference to the current context so that we can inspect
2479                  * it later in case a hangcheck error event fires.
2480                  */
2481                 request->ctx = ring->last_context;
2482                 if (request->ctx)
2483                         i915_gem_context_reference(request->ctx);
2484         }
2485
2486         request->emitted_jiffies = jiffies;
2487         list_add_tail(&request->list, &ring->request_list);
2488         request->file_priv = NULL;
2489
2490         if (file) {
2491                 struct drm_i915_file_private *file_priv = file->driver_priv;
2492
2493                 spin_lock(&file_priv->mm.lock);
2494                 request->file_priv = file_priv;
2495                 list_add_tail(&request->client_list,
2496                               &file_priv->mm.request_list);
2497                 spin_unlock(&file_priv->mm.lock);
2498         }
2499
2500         trace_i915_gem_request_add(request);
2501         ring->outstanding_lazy_request = NULL;
2502
2503         i915_queue_hangcheck(ring->dev);
2504
2505         cancel_delayed_work_sync(&dev_priv->mm.idle_work);
2506         queue_delayed_work(dev_priv->wq,
2507                            &dev_priv->mm.retire_work,
2508                            round_jiffies_up_relative(HZ));
2509         intel_mark_busy(dev_priv->dev);
2510
2511         return 0;
2512 }
2513
2514 static inline void
2515 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
2516 {
2517         struct drm_i915_file_private *file_priv = request->file_priv;
2518
2519         if (!file_priv)
2520                 return;
2521
2522         spin_lock(&file_priv->mm.lock);
2523         list_del(&request->client_list);
2524         request->file_priv = NULL;
2525         spin_unlock(&file_priv->mm.lock);
2526 }
2527
2528 static bool i915_context_is_banned(struct drm_i915_private *dev_priv,
2529                                    const struct intel_context *ctx)
2530 {
2531         unsigned long elapsed;
2532
2533         elapsed = get_seconds() - ctx->hang_stats.guilty_ts;
2534
2535         if (ctx->hang_stats.banned)
2536                 return true;
2537
2538         if (ctx->hang_stats.ban_period_seconds &&
2539             elapsed <= ctx->hang_stats.ban_period_seconds) {
2540                 if (!i915_gem_context_is_default(ctx)) {
2541                         DRM_DEBUG("context hanging too fast, banning!\n");
2542                         return true;
2543                 } else if (i915_stop_ring_allow_ban(dev_priv)) {
2544                         if (i915_stop_ring_allow_warn(dev_priv))
2545                                 DRM_ERROR("gpu hanging too fast, banning!\n");
2546                         return true;
2547                 }
2548         }
2549
2550         return false;
2551 }
2552
2553 static void i915_set_reset_status(struct drm_i915_private *dev_priv,
2554                                   struct intel_context *ctx,
2555                                   const bool guilty)
2556 {
2557         struct i915_ctx_hang_stats *hs;
2558
2559         if (WARN_ON(!ctx))
2560                 return;
2561
2562         hs = &ctx->hang_stats;
2563
2564         if (guilty) {
2565                 hs->banned = i915_context_is_banned(dev_priv, ctx);
2566                 hs->batch_active++;
2567                 hs->guilty_ts = get_seconds();
2568         } else {
2569                 hs->batch_pending++;
2570         }
2571 }
2572
2573 static void i915_gem_free_request(struct drm_i915_gem_request *request)
2574 {
2575         list_del(&request->list);
2576         i915_gem_request_remove_from_client(request);
2577
2578         i915_gem_request_unreference(request);
2579 }
2580
2581 void i915_gem_request_free(struct kref *req_ref)
2582 {
2583         struct drm_i915_gem_request *req = container_of(req_ref,
2584                                                  typeof(*req), ref);
2585         struct intel_context *ctx = req->ctx;
2586
2587         if (ctx) {
2588                 if (i915.enable_execlists) {
2589                         struct intel_engine_cs *ring = req->ring;
2590
2591                         if (ctx != ring->default_context)
2592                                 intel_lr_context_unpin(ring, ctx);
2593                 }
2594
2595                 i915_gem_context_unreference(ctx);
2596         }
2597
2598         kfree(req);
2599 }
2600
2601 struct drm_i915_gem_request *
2602 i915_gem_find_active_request(struct intel_engine_cs *ring)
2603 {
2604         struct drm_i915_gem_request *request;
2605
2606         list_for_each_entry(request, &ring->request_list, list) {
2607                 if (i915_gem_request_completed(request, false))
2608                         continue;
2609
2610                 return request;
2611         }
2612
2613         return NULL;
2614 }
2615
2616 static void i915_gem_reset_ring_status(struct drm_i915_private *dev_priv,
2617                                        struct intel_engine_cs *ring)
2618 {
2619         struct drm_i915_gem_request *request;
2620         bool ring_hung;
2621
2622         request = i915_gem_find_active_request(ring);
2623
2624         if (request == NULL)
2625                 return;
2626
2627         ring_hung = ring->hangcheck.score >= HANGCHECK_SCORE_RING_HUNG;
2628
2629         i915_set_reset_status(dev_priv, request->ctx, ring_hung);
2630
2631         list_for_each_entry_continue(request, &ring->request_list, list)
2632                 i915_set_reset_status(dev_priv, request->ctx, false);
2633 }
2634
2635 static void i915_gem_reset_ring_cleanup(struct drm_i915_private *dev_priv,
2636                                         struct intel_engine_cs *ring)
2637 {
2638         while (!list_empty(&ring->active_list)) {
2639                 struct drm_i915_gem_object *obj;
2640
2641                 obj = list_first_entry(&ring->active_list,
2642                                        struct drm_i915_gem_object,
2643                                        ring_list);
2644
2645                 i915_gem_object_move_to_inactive(obj);
2646         }
2647
2648         /*
2649          * Clear the execlists queue up before freeing the requests, as those
2650          * are the ones that keep the context and ringbuffer backing objects
2651          * pinned in place.
2652          */
2653         while (!list_empty(&ring->execlist_queue)) {
2654                 struct intel_ctx_submit_request *submit_req;
2655
2656                 submit_req = list_first_entry(&ring->execlist_queue,
2657                                 struct intel_ctx_submit_request,
2658                                 execlist_link);
2659                 list_del(&submit_req->execlist_link);
2660                 intel_runtime_pm_put(dev_priv);
2661                 i915_gem_context_unreference(submit_req->ctx);
2662                 kfree(submit_req);
2663         }
2664
2665         /*
2666          * We must free the requests after all the corresponding objects have
2667          * been moved off active lists. Which is the same order as the normal
2668          * retire_requests function does. This is important if object hold
2669          * implicit references on things like e.g. ppgtt address spaces through
2670          * the request.
2671          */
2672         while (!list_empty(&ring->request_list)) {
2673                 struct drm_i915_gem_request *request;
2674
2675                 request = list_first_entry(&ring->request_list,
2676                                            struct drm_i915_gem_request,
2677                                            list);
2678
2679                 i915_gem_free_request(request);
2680         }
2681
2682         /* This may not have been flushed before the reset, so clean it now */
2683         i915_gem_request_assign(&ring->outstanding_lazy_request, NULL);
2684 }
2685
2686 void i915_gem_restore_fences(struct drm_device *dev)
2687 {
2688         struct drm_i915_private *dev_priv = dev->dev_private;
2689         int i;
2690
2691         for (i = 0; i < dev_priv->num_fence_regs; i++) {
2692                 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
2693
2694                 /*
2695                  * Commit delayed tiling changes if we have an object still
2696                  * attached to the fence, otherwise just clear the fence.
2697                  */
2698                 if (reg->obj) {
2699                         i915_gem_object_update_fence(reg->obj, reg,
2700                                                      reg->obj->tiling_mode);
2701                 } else {
2702                         i915_gem_write_fence(dev, i, NULL);
2703                 }
2704         }
2705 }
2706
2707 void i915_gem_reset(struct drm_device *dev)
2708 {
2709         struct drm_i915_private *dev_priv = dev->dev_private;
2710         struct intel_engine_cs *ring;
2711         int i;
2712
2713         /*
2714          * Before we free the objects from the requests, we need to inspect
2715          * them for finding the guilty party. As the requests only borrow
2716          * their reference to the objects, the inspection must be done first.
2717          */
2718         for_each_ring(ring, dev_priv, i)
2719                 i915_gem_reset_ring_status(dev_priv, ring);
2720
2721         for_each_ring(ring, dev_priv, i)
2722                 i915_gem_reset_ring_cleanup(dev_priv, ring);
2723
2724         i915_gem_context_reset(dev);
2725
2726         i915_gem_restore_fences(dev);
2727 }
2728
2729 /**
2730  * This function clears the request list as sequence numbers are passed.
2731  */
2732 void
2733 i915_gem_retire_requests_ring(struct intel_engine_cs *ring)
2734 {
2735         if (list_empty(&ring->request_list))
2736                 return;
2737
2738         WARN_ON(i915_verify_lists(ring->dev));
2739
2740         /* Move any buffers on the active list that are no longer referenced
2741          * by the ringbuffer to the flushing/inactive lists as appropriate,
2742          * before we free the context associated with the requests.
2743          */
2744         while (!list_empty(&ring->active_list)) {
2745                 struct drm_i915_gem_object *obj;
2746
2747                 obj = list_first_entry(&ring->active_list,
2748                                       struct drm_i915_gem_object,
2749                                       ring_list);
2750
2751                 if (!i915_gem_request_completed(obj->last_read_req, true))
2752                         break;
2753
2754                 i915_gem_object_move_to_inactive(obj);
2755         }
2756
2757
2758         while (!list_empty(&ring->request_list)) {
2759                 struct drm_i915_gem_request *request;
2760                 struct intel_ringbuffer *ringbuf;
2761
2762                 request = list_first_entry(&ring->request_list,
2763                                            struct drm_i915_gem_request,
2764                                            list);
2765
2766                 if (!i915_gem_request_completed(request, true))
2767                         break;
2768
2769                 trace_i915_gem_request_retire(request);
2770
2771                 /* This is one of the few common intersection points
2772                  * between legacy ringbuffer submission and execlists:
2773                  * we need to tell them apart in order to find the correct
2774                  * ringbuffer to which the request belongs to.
2775                  */
2776                 if (i915.enable_execlists) {
2777                         struct intel_context *ctx = request->ctx;
2778                         ringbuf = ctx->engine[ring->id].ringbuf;
2779                 } else
2780                         ringbuf = ring->buffer;
2781
2782                 /* We know the GPU must have read the request to have
2783                  * sent us the seqno + interrupt, so use the position
2784                  * of tail of the request to update the last known position
2785                  * of the GPU head.
2786                  */
2787                 ringbuf->last_retired_head = request->tail;
2788
2789                 i915_gem_free_request(request);
2790         }
2791
2792         if (unlikely(ring->trace_irq_req &&
2793                      i915_gem_request_completed(ring->trace_irq_req, true))) {
2794                 ring->irq_put(ring);
2795                 i915_gem_request_assign(&ring->trace_irq_req, NULL);
2796         }
2797
2798         WARN_ON(i915_verify_lists(ring->dev));
2799 }
2800
2801 bool
2802 i915_gem_retire_requests(struct drm_device *dev)
2803 {
2804         struct drm_i915_private *dev_priv = dev->dev_private;
2805         struct intel_engine_cs *ring;
2806         bool idle = true;
2807         int i;
2808
2809         for_each_ring(ring, dev_priv, i) {
2810                 i915_gem_retire_requests_ring(ring);
2811                 idle &= list_empty(&ring->request_list);
2812                 if (i915.enable_execlists) {
2813                         unsigned long flags;
2814
2815                         spin_lock_irqsave(&ring->execlist_lock, flags);
2816                         idle &= list_empty(&ring->execlist_queue);
2817                         spin_unlock_irqrestore(&ring->execlist_lock, flags);
2818
2819                         intel_execlists_retire_requests(ring);
2820                 }
2821         }
2822
2823         if (idle)
2824                 mod_delayed_work(dev_priv->wq,
2825                                    &dev_priv->mm.idle_work,
2826                                    msecs_to_jiffies(100));
2827
2828         return idle;
2829 }
2830
2831 static void
2832 i915_gem_retire_work_handler(struct work_struct *work)
2833 {
2834         struct drm_i915_private *dev_priv =
2835                 container_of(work, typeof(*dev_priv), mm.retire_work.work);
2836         struct drm_device *dev = dev_priv->dev;
2837         bool idle;
2838
2839         /* Come back later if the device is busy... */
2840         idle = false;
2841         if (mutex_trylock(&dev->struct_mutex)) {
2842                 idle = i915_gem_retire_requests(dev);
2843                 mutex_unlock(&dev->struct_mutex);
2844         }
2845         if (!idle)
2846                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
2847                                    round_jiffies_up_relative(HZ));
2848 }
2849
2850 static void
2851 i915_gem_idle_work_handler(struct work_struct *work)
2852 {
2853         struct drm_i915_private *dev_priv =
2854                 container_of(work, typeof(*dev_priv), mm.idle_work.work);
2855
2856         intel_mark_idle(dev_priv->dev);
2857 }
2858
2859 /**
2860  * Ensures that an object will eventually get non-busy by flushing any required
2861  * write domains, emitting any outstanding lazy request and retiring and
2862  * completed requests.
2863  */
2864 static int
2865 i915_gem_object_flush_active(struct drm_i915_gem_object *obj)
2866 {
2867         struct intel_engine_cs *ring;
2868         int ret;
2869
2870         if (obj->active) {
2871                 ring = i915_gem_request_get_ring(obj->last_read_req);
2872
2873                 ret = i915_gem_check_olr(obj->last_read_req);
2874                 if (ret)
2875                         return ret;
2876
2877                 i915_gem_retire_requests_ring(ring);
2878         }
2879
2880         return 0;
2881 }
2882
2883 /**
2884  * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
2885  * @DRM_IOCTL_ARGS: standard ioctl arguments
2886  *
2887  * Returns 0 if successful, else an error is returned with the remaining time in
2888  * the timeout parameter.
2889  *  -ETIME: object is still busy after timeout
2890  *  -ERESTARTSYS: signal interrupted the wait
2891  *  -ENONENT: object doesn't exist
2892  * Also possible, but rare:
2893  *  -EAGAIN: GPU wedged
2894  *  -ENOMEM: damn
2895  *  -ENODEV: Internal IRQ fail
2896  *  -E?: The add request failed
2897  *
2898  * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
2899  * non-zero timeout parameter the wait ioctl will wait for the given number of
2900  * nanoseconds on an object becoming unbusy. Since the wait itself does so
2901  * without holding struct_mutex the object may become re-busied before this
2902  * function completes. A similar but shorter * race condition exists in the busy
2903  * ioctl
2904  */
2905 int
2906 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
2907 {
2908         struct drm_i915_private *dev_priv = dev->dev_private;
2909         struct drm_i915_gem_wait *args = data;
2910         struct drm_i915_gem_object *obj;
2911         struct drm_i915_gem_request *req;
2912         unsigned reset_counter;
2913         int ret = 0;
2914
2915         if (args->flags != 0)
2916                 return -EINVAL;
2917
2918         ret = i915_mutex_lock_interruptible(dev);
2919         if (ret)
2920                 return ret;
2921
2922         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->bo_handle));
2923         if (&obj->base == NULL) {
2924                 mutex_unlock(&dev->struct_mutex);
2925                 return -ENOENT;
2926         }
2927
2928         /* Need to make sure the object gets inactive eventually. */
2929         ret = i915_gem_object_flush_active(obj);
2930         if (ret)
2931                 goto out;
2932
2933         if (!obj->active || !obj->last_read_req)
2934                 goto out;
2935
2936         req = obj->last_read_req;
2937
2938         /* Do this after OLR check to make sure we make forward progress polling
2939          * on this IOCTL with a timeout <=0 (like busy ioctl)
2940          */
2941         if (args->timeout_ns <= 0) {
2942                 ret = -ETIME;
2943                 goto out;
2944         }
2945
2946         drm_gem_object_unreference(&obj->base);
2947         reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
2948         i915_gem_request_reference(req);
2949         mutex_unlock(&dev->struct_mutex);
2950
2951         ret = __i915_wait_request(req, reset_counter, true, &args->timeout_ns,
2952                                   file->driver_priv);
2953         mutex_lock(&dev->struct_mutex);
2954         i915_gem_request_unreference(req);
2955         mutex_unlock(&dev->struct_mutex);
2956         return ret;
2957
2958 out:
2959         drm_gem_object_unreference(&obj->base);
2960         mutex_unlock(&dev->struct_mutex);
2961         return ret;
2962 }
2963
2964 /**
2965  * i915_gem_object_sync - sync an object to a ring.
2966  *
2967  * @obj: object which may be in use on another ring.
2968  * @to: ring we wish to use the object on. May be NULL.
2969  *
2970  * This code is meant to abstract object synchronization with the GPU.
2971  * Calling with NULL implies synchronizing the object with the CPU
2972  * rather than a particular GPU ring.
2973  *
2974  * Returns 0 if successful, else propagates up the lower layer error.
2975  */
2976 int
2977 i915_gem_object_sync(struct drm_i915_gem_object *obj,
2978                      struct intel_engine_cs *to)
2979 {
2980         struct intel_engine_cs *from;
2981         u32 seqno;
2982         int ret, idx;
2983
2984         from = i915_gem_request_get_ring(obj->last_read_req);
2985
2986         if (from == NULL || to == from)
2987                 return 0;
2988
2989         if (to == NULL || !i915_semaphore_is_enabled(obj->base.dev))
2990                 return i915_gem_object_wait_rendering(obj, false);
2991
2992         idx = intel_ring_sync_index(from, to);
2993
2994         seqno = i915_gem_request_get_seqno(obj->last_read_req);
2995         /* Optimization: Avoid semaphore sync when we are sure we already
2996          * waited for an object with higher seqno */
2997         if (seqno <= from->semaphore.sync_seqno[idx])
2998                 return 0;
2999
3000         ret = i915_gem_check_olr(obj->last_read_req);
3001         if (ret)
3002                 return ret;
3003
3004         trace_i915_gem_ring_sync_to(from, to, obj->last_read_req);
3005         ret = to->semaphore.sync_to(to, from, seqno);
3006         if (!ret)
3007                 /* We use last_read_req because sync_to()
3008                  * might have just caused seqno wrap under
3009                  * the radar.
3010                  */
3011                 from->semaphore.sync_seqno[idx] =
3012                                 i915_gem_request_get_seqno(obj->last_read_req);
3013
3014         return ret;
3015 }
3016
3017 static void i915_gem_object_finish_gtt(struct drm_i915_gem_object *obj)
3018 {
3019         u32 old_write_domain, old_read_domains;
3020
3021         /* Force a pagefault for domain tracking on next user access */
3022         i915_gem_release_mmap(obj);
3023
3024         if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3025                 return;
3026
3027         /* Wait for any direct GTT access to complete */
3028         mb();
3029
3030         old_read_domains = obj->base.read_domains;
3031         old_write_domain = obj->base.write_domain;
3032
3033         obj->base.read_domains &= ~I915_GEM_DOMAIN_GTT;
3034         obj->base.write_domain &= ~I915_GEM_DOMAIN_GTT;
3035
3036         trace_i915_gem_object_change_domain(obj,
3037                                             old_read_domains,
3038                                             old_write_domain);
3039 }
3040
3041 int i915_vma_unbind(struct i915_vma *vma)
3042 {
3043         struct drm_i915_gem_object *obj = vma->obj;
3044         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
3045         int ret;
3046
3047         if (list_empty(&vma->vma_link))
3048                 return 0;
3049
3050         if (!drm_mm_node_allocated(&vma->node)) {
3051                 i915_gem_vma_destroy(vma);
3052                 return 0;
3053         }
3054
3055         if (vma->pin_count)
3056                 return -EBUSY;
3057
3058         BUG_ON(obj->pages == NULL);
3059
3060         ret = i915_gem_object_finish_gpu(obj);
3061         if (ret)
3062                 return ret;
3063         /* Continue on if we fail due to EIO, the GPU is hung so we
3064          * should be safe and we need to cleanup or else we might
3065          * cause memory corruption through use-after-free.
3066          */
3067
3068         if (i915_is_ggtt(vma->vm) &&
3069             vma->ggtt_view.type == I915_GGTT_VIEW_NORMAL) {
3070                 i915_gem_object_finish_gtt(obj);
3071
3072                 /* release the fence reg _after_ flushing */
3073                 ret = i915_gem_object_put_fence(obj);
3074                 if (ret)
3075                         return ret;
3076         }
3077
3078         trace_i915_vma_unbind(vma);
3079
3080         vma->unbind_vma(vma);
3081
3082         list_del_init(&vma->mm_list);
3083         if (i915_is_ggtt(vma->vm)) {
3084                 if (vma->ggtt_view.type == I915_GGTT_VIEW_NORMAL) {
3085                         obj->map_and_fenceable = false;
3086                 } else if (vma->ggtt_view.pages) {
3087                         sg_free_table(vma->ggtt_view.pages);
3088                         kfree(vma->ggtt_view.pages);
3089                         vma->ggtt_view.pages = NULL;
3090                 }
3091         }
3092
3093         drm_mm_remove_node(&vma->node);
3094         i915_gem_vma_destroy(vma);
3095
3096         /* Since the unbound list is global, only move to that list if
3097          * no more VMAs exist. */
3098         if (list_empty(&obj->vma_list)) {
3099                 /* Throw away the active reference before
3100                  * moving to the unbound list. */
3101                 i915_gem_object_retire(obj);
3102
3103                 i915_gem_gtt_finish_object(obj);
3104                 list_move_tail(&obj->global_list, &dev_priv->mm.unbound_list);
3105         }
3106
3107         /* And finally now the object is completely decoupled from this vma,
3108          * we can drop its hold on the backing storage and allow it to be
3109          * reaped by the shrinker.
3110          */
3111         i915_gem_object_unpin_pages(obj);
3112
3113         return 0;
3114 }
3115
3116 int i915_gpu_idle(struct drm_device *dev)
3117 {
3118         struct drm_i915_private *dev_priv = dev->dev_private;
3119         struct intel_engine_cs *ring;
3120         int ret, i;
3121
3122         /* Flush everything onto the inactive list. */
3123         for_each_ring(ring, dev_priv, i) {
3124                 if (!i915.enable_execlists) {
3125                         ret = i915_switch_context(ring, ring->default_context);
3126                         if (ret)
3127                                 return ret;
3128                 }
3129
3130                 ret = intel_ring_idle(ring);
3131                 if (ret)
3132                         return ret;
3133         }
3134
3135         return 0;
3136 }
3137
3138 static void i965_write_fence_reg(struct drm_device *dev, int reg,
3139                                  struct drm_i915_gem_object *obj)
3140 {
3141         struct drm_i915_private *dev_priv = dev->dev_private;
3142         int fence_reg;
3143         int fence_pitch_shift;
3144
3145         if (INTEL_INFO(dev)->gen >= 6) {
3146                 fence_reg = FENCE_REG_SANDYBRIDGE_0;
3147                 fence_pitch_shift = SANDYBRIDGE_FENCE_PITCH_SHIFT;
3148         } else {
3149                 fence_reg = FENCE_REG_965_0;
3150                 fence_pitch_shift = I965_FENCE_PITCH_SHIFT;
3151         }
3152
3153         fence_reg += reg * 8;
3154
3155         /* To w/a incoherency with non-atomic 64-bit register updates,
3156          * we split the 64-bit update into two 32-bit writes. In order
3157          * for a partial fence not to be evaluated between writes, we
3158          * precede the update with write to turn off the fence register,
3159          * and only enable the fence as the last step.
3160          *
3161          * For extra levels of paranoia, we make sure each step lands
3162          * before applying the next step.
3163          */
3164         I915_WRITE(fence_reg, 0);
3165         POSTING_READ(fence_reg);
3166
3167         if (obj) {
3168                 u32 size = i915_gem_obj_ggtt_size(obj);
3169                 uint64_t val;
3170
3171                 val = (uint64_t)((i915_gem_obj_ggtt_offset(obj) + size - 4096) &
3172                                  0xfffff000) << 32;
3173                 val |= i915_gem_obj_ggtt_offset(obj) & 0xfffff000;
3174                 val |= (uint64_t)((obj->stride / 128) - 1) << fence_pitch_shift;
3175                 if (obj->tiling_mode == I915_TILING_Y)
3176                         val |= 1 << I965_FENCE_TILING_Y_SHIFT;
3177                 val |= I965_FENCE_REG_VALID;
3178
3179                 I915_WRITE(fence_reg + 4, val >> 32);
3180                 POSTING_READ(fence_reg + 4);
3181
3182                 I915_WRITE(fence_reg + 0, val);
3183                 POSTING_READ(fence_reg);
3184         } else {
3185                 I915_WRITE(fence_reg + 4, 0);
3186                 POSTING_READ(fence_reg + 4);
3187         }
3188 }
3189
3190 static void i915_write_fence_reg(struct drm_device *dev, int reg,
3191                                  struct drm_i915_gem_object *obj)
3192 {
3193         struct drm_i915_private *dev_priv = dev->dev_private;
3194         u32 val;
3195
3196         if (obj) {
3197                 u32 size = i915_gem_obj_ggtt_size(obj);
3198                 int pitch_val;
3199                 int tile_width;
3200
3201                 WARN((i915_gem_obj_ggtt_offset(obj) & ~I915_FENCE_START_MASK) ||
3202                      (size & -size) != size ||
3203                      (i915_gem_obj_ggtt_offset(obj) & (size - 1)),
3204                      "object 0x%08lx [fenceable? %d] not 1M or pot-size (0x%08x) aligned\n",
3205                      i915_gem_obj_ggtt_offset(obj), obj->map_and_fenceable, size);
3206
3207                 if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
3208                         tile_width = 128;
3209                 else
3210                         tile_width = 512;
3211
3212                 /* Note: pitch better be a power of two tile widths */
3213                 pitch_val = obj->stride / tile_width;
3214                 pitch_val = ffs(pitch_val) - 1;
3215
3216                 val = i915_gem_obj_ggtt_offset(obj);
3217                 if (obj->tiling_mode == I915_TILING_Y)
3218                         val |= 1 << I830_FENCE_TILING_Y_SHIFT;
3219                 val |= I915_FENCE_SIZE_BITS(size);
3220                 val |= pitch_val << I830_FENCE_PITCH_SHIFT;
3221                 val |= I830_FENCE_REG_VALID;
3222         } else
3223                 val = 0;
3224
3225         if (reg < 8)
3226                 reg = FENCE_REG_830_0 + reg * 4;
3227         else
3228                 reg = FENCE_REG_945_8 + (reg - 8) * 4;
3229
3230         I915_WRITE(reg, val);
3231         POSTING_READ(reg);
3232 }
3233
3234 static void i830_write_fence_reg(struct drm_device *dev, int reg,
3235                                 struct drm_i915_gem_object *obj)
3236 {
3237         struct drm_i915_private *dev_priv = dev->dev_private;
3238         uint32_t val;
3239
3240         if (obj) {
3241                 u32 size = i915_gem_obj_ggtt_size(obj);
3242                 uint32_t pitch_val;
3243
3244                 WARN((i915_gem_obj_ggtt_offset(obj) & ~I830_FENCE_START_MASK) ||
3245                      (size & -size) != size ||
3246                      (i915_gem_obj_ggtt_offset(obj) & (size - 1)),
3247                      "object 0x%08lx not 512K or pot-size 0x%08x aligned\n",
3248                      i915_gem_obj_ggtt_offset(obj), size);
3249
3250                 pitch_val = obj->stride / 128;
3251                 pitch_val = ffs(pitch_val) - 1;
3252
3253                 val = i915_gem_obj_ggtt_offset(obj);
3254                 if (obj->tiling_mode == I915_TILING_Y)
3255                         val |= 1 << I830_FENCE_TILING_Y_SHIFT;
3256                 val |= I830_FENCE_SIZE_BITS(size);
3257                 val |= pitch_val << I830_FENCE_PITCH_SHIFT;
3258                 val |= I830_FENCE_REG_VALID;
3259         } else
3260                 val = 0;
3261
3262         I915_WRITE(FENCE_REG_830_0 + reg * 4, val);
3263         POSTING_READ(FENCE_REG_830_0 + reg * 4);
3264 }
3265
3266 inline static bool i915_gem_object_needs_mb(struct drm_i915_gem_object *obj)
3267 {
3268         return obj && obj->base.read_domains & I915_GEM_DOMAIN_GTT;
3269 }
3270
3271 static void i915_gem_write_fence(struct drm_device *dev, int reg,
3272                                  struct drm_i915_gem_object *obj)
3273 {
3274         struct drm_i915_private *dev_priv = dev->dev_private;
3275
3276         /* Ensure that all CPU reads are completed before installing a fence
3277          * and all writes before removing the fence.
3278          */
3279         if (i915_gem_object_needs_mb(dev_priv->fence_regs[reg].obj))
3280                 mb();
3281
3282         WARN(obj && (!obj->stride || !obj->tiling_mode),
3283              "bogus fence setup with stride: 0x%x, tiling mode: %i\n",
3284              obj->stride, obj->tiling_mode);
3285
3286         if (IS_GEN2(dev))
3287                 i830_write_fence_reg(dev, reg, obj);
3288         else if (IS_GEN3(dev))
3289                 i915_write_fence_reg(dev, reg, obj);
3290         else if (INTEL_INFO(dev)->gen >= 4)
3291                 i965_write_fence_reg(dev, reg, obj);
3292
3293         /* And similarly be paranoid that no direct access to this region
3294          * is reordered to before the fence is installed.
3295          */
3296         if (i915_gem_object_needs_mb(obj))
3297                 mb();
3298 }
3299
3300 static inline int fence_number(struct drm_i915_private *dev_priv,
3301                                struct drm_i915_fence_reg *fence)
3302 {
3303         return fence - dev_priv->fence_regs;
3304 }
3305
3306 static void i915_gem_object_update_fence(struct drm_i915_gem_object *obj,
3307                                          struct drm_i915_fence_reg *fence,
3308                                          bool enable)
3309 {
3310         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
3311         int reg = fence_number(dev_priv, fence);
3312
3313         i915_gem_write_fence(obj->base.dev, reg, enable ? obj : NULL);
3314
3315         if (enable) {
3316                 obj->fence_reg = reg;
3317                 fence->obj = obj;
3318                 list_move_tail(&fence->lru_list, &dev_priv->mm.fence_list);
3319         } else {
3320                 obj->fence_reg = I915_FENCE_REG_NONE;
3321                 fence->obj = NULL;
3322                 list_del_init(&fence->lru_list);
3323         }
3324         obj->fence_dirty = false;
3325 }
3326
3327 static int
3328 i915_gem_object_wait_fence(struct drm_i915_gem_object *obj)
3329 {
3330         if (obj->last_fenced_req) {
3331                 int ret = i915_wait_request(obj->last_fenced_req);
3332                 if (ret)
3333                         return ret;
3334
3335                 i915_gem_request_assign(&obj->last_fenced_req, NULL);
3336         }
3337
3338         return 0;
3339 }
3340
3341 int
3342 i915_gem_object_put_fence(struct drm_i915_gem_object *obj)
3343 {
3344         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
3345         struct drm_i915_fence_reg *fence;
3346         int ret;
3347
3348         ret = i915_gem_object_wait_fence(obj);
3349         if (ret)
3350                 return ret;
3351
3352         if (obj->fence_reg == I915_FENCE_REG_NONE)
3353                 return 0;
3354
3355         fence = &dev_priv->fence_regs[obj->fence_reg];
3356
3357         if (WARN_ON(fence->pin_count))
3358                 return -EBUSY;
3359
3360         i915_gem_object_fence_lost(obj);
3361         i915_gem_object_update_fence(obj, fence, false);
3362
3363         return 0;
3364 }
3365
3366 static struct drm_i915_fence_reg *
3367 i915_find_fence_reg(struct drm_device *dev)
3368 {
3369         struct drm_i915_private *dev_priv = dev->dev_private;
3370         struct drm_i915_fence_reg *reg, *avail;
3371         int i;
3372
3373         /* First try to find a free reg */
3374         avail = NULL;
3375         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
3376                 reg = &dev_priv->fence_regs[i];
3377                 if (!reg->obj)
3378                         return reg;
3379
3380                 if (!reg->pin_count)
3381                         avail = reg;
3382         }
3383
3384         if (avail == NULL)
3385                 goto deadlock;
3386
3387         /* None available, try to steal one or wait for a user to finish */
3388         list_for_each_entry(reg, &dev_priv->mm.fence_list, lru_list) {
3389                 if (reg->pin_count)
3390                         continue;
3391
3392                 return reg;
3393         }
3394
3395 deadlock:
3396         /* Wait for completion of pending flips which consume fences */
3397         if (intel_has_pending_fb_unpin(dev))
3398                 return ERR_PTR(-EAGAIN);
3399
3400         return ERR_PTR(-EDEADLK);
3401 }
3402
3403 /**
3404  * i915_gem_object_get_fence - set up fencing for an object
3405  * @obj: object to map through a fence reg
3406  *
3407  * When mapping objects through the GTT, userspace wants to be able to write
3408  * to them without having to worry about swizzling if the object is tiled.
3409  * This function walks the fence regs looking for a free one for @obj,
3410  * stealing one if it can't find any.
3411  *
3412  * It then sets up the reg based on the object's properties: address, pitch
3413  * and tiling format.
3414  *
3415  * For an untiled surface, this removes any existing fence.
3416  */
3417 int
3418 i915_gem_object_get_fence(struct drm_i915_gem_object *obj)
3419 {
3420         struct drm_device *dev = obj->base.dev;
3421         struct drm_i915_private *dev_priv = dev->dev_private;
3422         bool enable = obj->tiling_mode != I915_TILING_NONE;
3423         struct drm_i915_fence_reg *reg;
3424         int ret;
3425
3426         /* Have we updated the tiling parameters upon the object and so
3427          * will need to serialise the write to the associated fence register?
3428          */
3429         if (obj->fence_dirty) {
3430                 ret = i915_gem_object_wait_fence(obj);
3431                 if (ret)
3432                         return ret;
3433         }
3434
3435         /* Just update our place in the LRU if our fence is getting reused. */
3436         if (obj->fence_reg != I915_FENCE_REG_NONE) {
3437                 reg = &dev_priv->fence_regs[obj->fence_reg];
3438                 if (!obj->fence_dirty) {
3439                         list_move_tail(&reg->lru_list,
3440                                        &dev_priv->mm.fence_list);
3441                         return 0;
3442                 }
3443         } else if (enable) {
3444                 if (WARN_ON(!obj->map_and_fenceable))
3445                         return -EINVAL;
3446
3447                 reg = i915_find_fence_reg(dev);
3448                 if (IS_ERR(reg))
3449                         return PTR_ERR(reg);
3450
3451                 if (reg->obj) {
3452                         struct drm_i915_gem_object *old = reg->obj;
3453
3454                         ret = i915_gem_object_wait_fence(old);
3455                         if (ret)
3456                                 return ret;
3457
3458                         i915_gem_object_fence_lost(old);
3459                 }
3460         } else
3461                 return 0;
3462
3463         i915_gem_object_update_fence(obj, reg, enable);
3464
3465         return 0;
3466 }
3467
3468 static bool i915_gem_valid_gtt_space(struct i915_vma *vma,
3469                                      unsigned long cache_level)
3470 {
3471         struct drm_mm_node *gtt_space = &vma->node;
3472         struct drm_mm_node *other;
3473
3474         /*
3475          * On some machines we have to be careful when putting differing types
3476          * of snoopable memory together to avoid the prefetcher crossing memory
3477          * domains and dying. During vm initialisation, we decide whether or not
3478          * these constraints apply and set the drm_mm.color_adjust
3479          * appropriately.
3480          */
3481         if (vma->vm->mm.color_adjust == NULL)
3482                 return true;
3483
3484         if (!drm_mm_node_allocated(gtt_space))
3485                 return true;
3486
3487         if (list_empty(&gtt_space->node_list))
3488                 return true;
3489
3490         other = list_entry(gtt_space->node_list.prev, struct drm_mm_node, node_list);
3491         if (other->allocated && !other->hole_follows && other->color != cache_level)
3492                 return false;
3493
3494         other = list_entry(gtt_space->node_list.next, struct drm_mm_node, node_list);
3495         if (other->allocated && !gtt_space->hole_follows && other->color != cache_level)
3496                 return false;
3497
3498         return true;
3499 }
3500
3501 /**
3502  * Finds free space in the GTT aperture and binds the object there.
3503  */
3504 static struct i915_vma *
3505 i915_gem_object_bind_to_vm(struct drm_i915_gem_object *obj,
3506                            struct i915_address_space *vm,
3507                            unsigned alignment,
3508                            uint64_t flags,
3509                            const struct i915_ggtt_view *view)
3510 {
3511         struct drm_device *dev = obj->base.dev;
3512         struct drm_i915_private *dev_priv = dev->dev_private;
3513         u32 size, fence_size, fence_alignment, unfenced_alignment;
3514         unsigned long start =
3515                 flags & PIN_OFFSET_BIAS ? flags & PIN_OFFSET_MASK : 0;
3516         unsigned long end =
3517                 flags & PIN_MAPPABLE ? dev_priv->gtt.mappable_end : vm->total;
3518         struct i915_vma *vma;
3519         int ret;
3520
3521         fence_size = i915_gem_get_gtt_size(dev,
3522                                            obj->base.size,
3523                                            obj->tiling_mode);
3524         fence_alignment = i915_gem_get_gtt_alignment(dev,
3525                                                      obj->base.size,
3526                                                      obj->tiling_mode, true);
3527         unfenced_alignment =
3528                 i915_gem_get_gtt_alignment(dev,
3529                                            obj->base.size,
3530                                            obj->tiling_mode, false);
3531
3532         if (alignment == 0)
3533                 alignment = flags & PIN_MAPPABLE ? fence_alignment :
3534                                                 unfenced_alignment;
3535         if (flags & PIN_MAPPABLE && alignment & (fence_alignment - 1)) {
3536                 DRM_DEBUG("Invalid object alignment requested %u\n", alignment);
3537                 return ERR_PTR(-EINVAL);
3538         }
3539
3540         size = flags & PIN_MAPPABLE ? fence_size : obj->base.size;
3541
3542         /* If the object is bigger than the entire aperture, reject it early
3543          * before evicting everything in a vain attempt to find space.
3544          */
3545         if (obj->base.size > end) {
3546                 DRM_DEBUG("Attempting to bind an object larger than the aperture: object=%zd > %s aperture=%lu\n",
3547                           obj->base.size,
3548                           flags & PIN_MAPPABLE ? "mappable" : "total",
3549                           end);
3550                 return ERR_PTR(-E2BIG);
3551         }
3552
3553         ret = i915_gem_object_get_pages(obj);
3554         if (ret)
3555                 return ERR_PTR(ret);
3556
3557         i915_gem_object_pin_pages(obj);
3558
3559         vma = i915_gem_obj_lookup_or_create_vma_view(obj, vm, view);
3560         if (IS_ERR(vma))
3561                 goto err_unpin;
3562
3563 search_free:
3564         ret = drm_mm_insert_node_in_range_generic(&vm->mm, &vma->node,
3565                                                   size, alignment,
3566                                                   obj->cache_level,
3567                                                   start, end,
3568                                                   DRM_MM_SEARCH_DEFAULT,
3569                                                   DRM_MM_CREATE_DEFAULT);
3570         if (ret) {
3571                 ret = i915_gem_evict_something(dev, vm, size, alignment,
3572                                                obj->cache_level,
3573                                                start, end,
3574                                                flags);
3575                 if (ret == 0)
3576                         goto search_free;
3577
3578                 goto err_free_vma;
3579         }
3580         if (WARN_ON(!i915_gem_valid_gtt_space(vma, obj->cache_level))) {
3581                 ret = -EINVAL;
3582                 goto err_remove_node;
3583         }
3584
3585         ret = i915_gem_gtt_prepare_object(obj);
3586         if (ret)
3587                 goto err_remove_node;
3588
3589         trace_i915_vma_bind(vma, flags);
3590         ret = i915_vma_bind(vma, obj->cache_level,
3591                             flags & PIN_GLOBAL ? GLOBAL_BIND : 0);
3592         if (ret)
3593                 goto err_finish_gtt;
3594
3595         list_move_tail(&obj->global_list, &dev_priv->mm.bound_list);
3596         list_add_tail(&vma->mm_list, &vm->inactive_list);
3597
3598         return vma;
3599
3600 err_finish_gtt:
3601         i915_gem_gtt_finish_object(obj);
3602 err_remove_node:
3603         drm_mm_remove_node(&vma->node);
3604 err_free_vma:
3605         i915_gem_vma_destroy(vma);
3606         vma = ERR_PTR(ret);
3607 err_unpin:
3608         i915_gem_object_unpin_pages(obj);
3609         return vma;
3610 }
3611
3612 bool
3613 i915_gem_clflush_object(struct drm_i915_gem_object *obj,
3614                         bool force)
3615 {
3616         /* If we don't have a page list set up, then we're not pinned
3617          * to GPU, and we can ignore the cache flush because it'll happen
3618          * again at bind time.
3619          */
3620         if (obj->pages == NULL)
3621                 return false;
3622
3623         /*
3624          * Stolen memory is always coherent with the GPU as it is explicitly
3625          * marked as wc by the system, or the system is cache-coherent.
3626          */
3627         if (obj->stolen || obj->phys_handle)
3628                 return false;
3629
3630         /* If the GPU is snooping the contents of the CPU cache,
3631          * we do not need to manually clear the CPU cache lines.  However,
3632          * the caches are only snooped when the render cache is
3633          * flushed/invalidated.  As we always have to emit invalidations
3634          * and flushes when moving into and out of the RENDER domain, correct
3635          * snooping behaviour occurs naturally as the result of our domain
3636          * tracking.
3637          */
3638         if (!force && cpu_cache_is_coherent(obj->base.dev, obj->cache_level))
3639                 return false;
3640
3641         trace_i915_gem_object_clflush(obj);
3642         drm_clflush_sg(obj->pages);
3643
3644         return true;
3645 }
3646
3647 /** Flushes the GTT write domain for the object if it's dirty. */
3648 static void
3649 i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
3650 {
3651         uint32_t old_write_domain;
3652
3653         if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
3654                 return;
3655
3656         /* No actual flushing is required for the GTT write domain.  Writes
3657          * to it immediately go to main memory as far as we know, so there's
3658          * no chipset flush.  It also doesn't land in render cache.
3659          *
3660          * However, we do have to enforce the order so that all writes through
3661          * the GTT land before any writes to the device, such as updates to
3662          * the GATT itself.
3663          */
3664         wmb();
3665
3666         old_write_domain = obj->base.write_domain;
3667         obj->base.write_domain = 0;
3668
3669         intel_fb_obj_flush(obj, false);
3670
3671         trace_i915_gem_object_change_domain(obj,
3672                                             obj->base.read_domains,
3673                                             old_write_domain);
3674 }
3675
3676 /** Flushes the CPU write domain for the object if it's dirty. */
3677 static void
3678 i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj,
3679                                        bool force)
3680 {
3681         uint32_t old_write_domain;
3682
3683         if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
3684                 return;
3685
3686         if (i915_gem_clflush_object(obj, force))
3687                 i915_gem_chipset_flush(obj->base.dev);
3688
3689         old_write_domain = obj->base.write_domain;
3690         obj->base.write_domain = 0;
3691
3692         intel_fb_obj_flush(obj, false);
3693
3694         trace_i915_gem_object_change_domain(obj,
3695                                             obj->base.read_domains,
3696                                             old_write_domain);
3697 }
3698
3699 /**
3700  * Moves a single object to the GTT read, and possibly write domain.
3701  *
3702  * This function returns when the move is complete, including waiting on
3703  * flushes to occur.
3704  */
3705 int
3706 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
3707 {
3708         uint32_t old_write_domain, old_read_domains;
3709         struct i915_vma *vma;
3710         int ret;
3711
3712         if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
3713                 return 0;
3714
3715         ret = i915_gem_object_wait_rendering(obj, !write);
3716         if (ret)
3717                 return ret;
3718
3719         i915_gem_object_retire(obj);
3720
3721         /* Flush and acquire obj->pages so that we are coherent through
3722          * direct access in memory with previous cached writes through
3723          * shmemfs and that our cache domain tracking remains valid.
3724          * For example, if the obj->filp was moved to swap without us
3725          * being notified and releasing the pages, we would mistakenly
3726          * continue to assume that the obj remained out of the CPU cached
3727          * domain.
3728          */
3729         ret = i915_gem_object_get_pages(obj);
3730         if (ret)
3731                 return ret;
3732
3733         i915_gem_object_flush_cpu_write_domain(obj, false);
3734
3735         /* Serialise direct access to this object with the barriers for
3736          * coherent writes from the GPU, by effectively invalidating the
3737          * GTT domain upon first access.
3738          */
3739         if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3740                 mb();
3741
3742         old_write_domain = obj->base.write_domain;
3743         old_read_domains = obj->base.read_domains;
3744
3745         /* It should now be out of any other write domains, and we can update
3746          * the domain values for our changes.
3747          */
3748         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
3749         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3750         if (write) {
3751                 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
3752                 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
3753                 obj->dirty = 1;
3754         }
3755
3756         if (write)
3757                 intel_fb_obj_invalidate(obj, NULL);
3758
3759         trace_i915_gem_object_change_domain(obj,
3760                                             old_read_domains,
3761                                             old_write_domain);
3762
3763         /* And bump the LRU for this access */
3764         vma = i915_gem_obj_to_ggtt(obj);
3765         if (vma && drm_mm_node_allocated(&vma->node) && !obj->active)
3766                 list_move_tail(&vma->mm_list,
3767                                &to_i915(obj->base.dev)->gtt.base.inactive_list);
3768
3769         return 0;
3770 }
3771
3772 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3773                                     enum i915_cache_level cache_level)
3774 {
3775         struct drm_device *dev = obj->base.dev;
3776         struct i915_vma *vma, *next;
3777         int ret;
3778
3779         if (obj->cache_level == cache_level)
3780                 return 0;
3781
3782         if (i915_gem_obj_is_pinned(obj)) {
3783                 DRM_DEBUG("can not change the cache level of pinned objects\n");
3784                 return -EBUSY;
3785         }
3786
3787         list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link) {
3788                 if (!i915_gem_valid_gtt_space(vma, cache_level)) {
3789                         ret = i915_vma_unbind(vma);
3790                         if (ret)
3791                                 return ret;
3792                 }
3793         }
3794
3795         if (i915_gem_obj_bound_any(obj)) {
3796                 ret = i915_gem_object_finish_gpu(obj);
3797                 if (ret)
3798                         return ret;
3799
3800                 i915_gem_object_finish_gtt(obj);
3801
3802                 /* Before SandyBridge, you could not use tiling or fence
3803                  * registers with snooped memory, so relinquish any fences
3804                  * currently pointing to our region in the aperture.
3805                  */
3806                 if (INTEL_INFO(dev)->gen < 6) {
3807                         ret = i915_gem_object_put_fence(obj);
3808                         if (ret)
3809                                 return ret;
3810                 }
3811
3812                 list_for_each_entry(vma, &obj->vma_list, vma_link)
3813                         if (drm_mm_node_allocated(&vma->node)) {
3814                                 ret = i915_vma_bind(vma, cache_level,
3815                                                     vma->bound & GLOBAL_BIND);
3816                                 if (ret)
3817                                         return ret;
3818                         }
3819         }
3820
3821         list_for_each_entry(vma, &obj->vma_list, vma_link)
3822                 vma->node.color = cache_level;
3823         obj->cache_level = cache_level;
3824
3825         if (cpu_write_needs_clflush(obj)) {
3826                 u32 old_read_domains, old_write_domain;
3827
3828                 /* If we're coming from LLC cached, then we haven't
3829                  * actually been tracking whether the data is in the
3830                  * CPU cache or not, since we only allow one bit set
3831                  * in obj->write_domain and have been skipping the clflushes.
3832                  * Just set it to the CPU cache for now.
3833                  */
3834                 i915_gem_object_retire(obj);
3835                 WARN_ON(obj->base.write_domain & ~I915_GEM_DOMAIN_CPU);
3836
3837                 old_read_domains = obj->base.read_domains;
3838                 old_write_domain = obj->base.write_domain;
3839
3840                 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
3841                 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
3842
3843                 trace_i915_gem_object_change_domain(obj,
3844                                                     old_read_domains,
3845                                                     old_write_domain);
3846         }
3847
3848         return 0;
3849 }
3850
3851 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
3852                                struct drm_file *file)
3853 {
3854         struct drm_i915_gem_caching *args = data;
3855         struct drm_i915_gem_object *obj;
3856         int ret;
3857
3858         ret = i915_mutex_lock_interruptible(dev);
3859         if (ret)
3860                 return ret;
3861
3862         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3863         if (&obj->base == NULL) {
3864                 ret = -ENOENT;
3865                 goto unlock;
3866         }
3867
3868         switch (obj->cache_level) {
3869         case I915_CACHE_LLC:
3870         case I915_CACHE_L3_LLC:
3871                 args->caching = I915_CACHING_CACHED;
3872                 break;
3873
3874         case I915_CACHE_WT:
3875                 args->caching = I915_CACHING_DISPLAY;
3876                 break;
3877
3878         default:
3879                 args->caching = I915_CACHING_NONE;
3880                 break;
3881         }
3882
3883         drm_gem_object_unreference(&obj->base);
3884 unlock:
3885         mutex_unlock(&dev->struct_mutex);
3886         return ret;
3887 }
3888
3889 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
3890                                struct drm_file *file)
3891 {
3892         struct drm_i915_gem_caching *args = data;
3893         struct drm_i915_gem_object *obj;
3894         enum i915_cache_level level;
3895         int ret;
3896
3897         switch (args->caching) {
3898         case I915_CACHING_NONE:
3899                 level = I915_CACHE_NONE;
3900                 break;
3901         case I915_CACHING_CACHED:
3902                 level = I915_CACHE_LLC;
3903                 break;
3904         case I915_CACHING_DISPLAY:
3905                 level = HAS_WT(dev) ? I915_CACHE_WT : I915_CACHE_NONE;
3906                 break;
3907         default:
3908                 return -EINVAL;
3909         }
3910
3911         ret = i915_mutex_lock_interruptible(dev);
3912         if (ret)
3913                 return ret;
3914
3915         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
3916         if (&obj->base == NULL) {
3917                 ret = -ENOENT;
3918                 goto unlock;
3919         }
3920
3921         ret = i915_gem_object_set_cache_level(obj, level);
3922
3923         drm_gem_object_unreference(&obj->base);
3924 unlock:
3925         mutex_unlock(&dev->struct_mutex);
3926         return ret;
3927 }
3928
3929 static bool is_pin_display(struct drm_i915_gem_object *obj)
3930 {
3931         struct i915_vma *vma;
3932
3933         vma = i915_gem_obj_to_ggtt(obj);
3934         if (!vma)
3935                 return false;
3936
3937         /* There are 2 sources that pin objects:
3938          *   1. The display engine (scanouts, sprites, cursors);
3939          *   2. Reservations for execbuffer;
3940          *
3941          * We can ignore reservations as we hold the struct_mutex and
3942          * are only called outside of the reservation path.
3943          */
3944         return vma->pin_count;
3945 }
3946
3947 /*
3948  * Prepare buffer for display plane (scanout, cursors, etc).
3949  * Can be called from an uninterruptible phase (modesetting) and allows
3950  * any flushes to be pipelined (for pageflips).
3951  */
3952 int
3953 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
3954                                      u32 alignment,
3955                                      struct intel_engine_cs *pipelined)
3956 {
3957         u32 old_read_domains, old_write_domain;
3958         bool was_pin_display;
3959         int ret;
3960
3961         if (pipelined != i915_gem_request_get_ring(obj->last_read_req)) {
3962                 ret = i915_gem_object_sync(obj, pipelined);
3963                 if (ret)
3964                         return ret;
3965         }
3966
3967         /* Mark the pin_display early so that we account for the
3968          * display coherency whilst setting up the cache domains.
3969          */
3970         was_pin_display = obj->pin_display;
3971         obj->pin_display = true;
3972
3973         /* The display engine is not coherent with the LLC cache on gen6.  As
3974          * a result, we make sure that the pinning that is about to occur is
3975          * done with uncached PTEs. This is lowest common denominator for all
3976          * chipsets.
3977          *
3978          * However for gen6+, we could do better by using the GFDT bit instead
3979          * of uncaching, which would allow us to flush all the LLC-cached data
3980          * with that bit in the PTE to main memory with just one PIPE_CONTROL.
3981          */
3982         ret = i915_gem_object_set_cache_level(obj,
3983                                               HAS_WT(obj->base.dev) ? I915_CACHE_WT : I915_CACHE_NONE);
3984         if (ret)
3985                 goto err_unpin_display;
3986
3987         /* As the user may map the buffer once pinned in the display plane
3988          * (e.g. libkms for the bootup splash), we have to ensure that we
3989          * always use map_and_fenceable for all scanout buffers.
3990          */
3991         ret = i915_gem_obj_ggtt_pin(obj, alignment, PIN_MAPPABLE);
3992         if (ret)
3993                 goto err_unpin_display;
3994
3995         i915_gem_object_flush_cpu_write_domain(obj, true);
3996
3997         old_write_domain = obj->base.write_domain;
3998         old_read_domains = obj->base.read_domains;
3999
4000         /* It should now be out of any other write domains, and we can update
4001          * the domain values for our changes.
4002          */
4003         obj->base.write_domain = 0;
4004         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
4005
4006         trace_i915_gem_object_change_domain(obj,
4007                                             old_read_domains,
4008                                             old_write_domain);
4009
4010         return 0;
4011
4012 err_unpin_display:
4013         WARN_ON(was_pin_display != is_pin_display(obj));
4014         obj->pin_display = was_pin_display;
4015         return ret;
4016 }
4017
4018 void
4019 i915_gem_object_unpin_from_display_plane(struct drm_i915_gem_object *obj)
4020 {
4021         i915_gem_object_ggtt_unpin(obj);
4022         obj->pin_display = is_pin_display(obj);
4023 }
4024
4025 int
4026 i915_gem_object_finish_gpu(struct drm_i915_gem_object *obj)
4027 {
4028         int ret;
4029
4030         if ((obj->base.read_domains & I915_GEM_GPU_DOMAINS) == 0)
4031                 return 0;
4032
4033         ret = i915_gem_object_wait_rendering(obj, false);
4034         if (ret)
4035                 return ret;
4036
4037         /* Ensure that we invalidate the GPU's caches and TLBs. */
4038         obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
4039         return 0;
4040 }
4041
4042 /**
4043  * Moves a single object to the CPU read, and possibly write domain.
4044  *
4045  * This function returns when the move is complete, including waiting on
4046  * flushes to occur.
4047  */
4048 int
4049 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
4050 {
4051         uint32_t old_write_domain, old_read_domains;
4052         int ret;
4053
4054         if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
4055                 return 0;
4056
4057         ret = i915_gem_object_wait_rendering(obj, !write);
4058         if (ret)
4059                 return ret;
4060
4061         i915_gem_object_retire(obj);
4062         i915_gem_object_flush_gtt_write_domain(obj);
4063
4064         old_write_domain = obj->base.write_domain;
4065         old_read_domains = obj->base.read_domains;
4066
4067         /* Flush the CPU cache if it's still invalid. */
4068         if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
4069                 i915_gem_clflush_object(obj, false);
4070
4071                 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
4072         }
4073
4074         /* It should now be out of any other write domains, and we can update
4075          * the domain values for our changes.
4076          */
4077         BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
4078
4079         /* If we're writing through the CPU, then the GPU read domains will
4080          * need to be invalidated at next use.
4081          */
4082         if (write) {
4083                 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4084                 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4085         }
4086
4087         if (write)
4088                 intel_fb_obj_invalidate(obj, NULL);
4089
4090         trace_i915_gem_object_change_domain(obj,
4091                                             old_read_domains,
4092                                             old_write_domain);
4093
4094         return 0;
4095 }
4096
4097 /* Throttle our rendering by waiting until the ring has completed our requests
4098  * emitted over 20 msec ago.
4099  *
4100  * Note that if we were to use the current jiffies each time around the loop,
4101  * we wouldn't escape the function with any frames outstanding if the time to
4102  * render a frame was over 20ms.
4103  *
4104  * This should get us reasonable parallelism between CPU and GPU but also
4105  * relatively low latency when blocking on a particular request to finish.
4106  */
4107 static int
4108 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
4109 {
4110         struct drm_i915_private *dev_priv = dev->dev_private;
4111         struct drm_i915_file_private *file_priv = file->driver_priv;
4112         unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
4113         struct drm_i915_gem_request *request, *target = NULL;
4114         unsigned reset_counter;
4115         int ret;
4116
4117         ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
4118         if (ret)
4119                 return ret;
4120
4121         ret = i915_gem_check_wedge(&dev_priv->gpu_error, false);
4122         if (ret)
4123                 return ret;
4124
4125         spin_lock(&file_priv->mm.lock);
4126         list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
4127                 if (time_after_eq(request->emitted_jiffies, recent_enough))
4128                         break;
4129
4130                 target = request;
4131         }
4132         reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
4133         if (target)
4134                 i915_gem_request_reference(target);
4135         spin_unlock(&file_priv->mm.lock);
4136
4137         if (target == NULL)
4138                 return 0;
4139
4140         ret = __i915_wait_request(target, reset_counter, true, NULL, NULL);
4141         if (ret == 0)
4142                 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
4143
4144         mutex_lock(&dev->struct_mutex);
4145         i915_gem_request_unreference(target);
4146         mutex_unlock(&dev->struct_mutex);
4147
4148         return ret;
4149 }
4150
4151 static bool
4152 i915_vma_misplaced(struct i915_vma *vma, uint32_t alignment, uint64_t flags)
4153 {
4154         struct drm_i915_gem_object *obj = vma->obj;
4155
4156         if (alignment &&
4157             vma->node.start & (alignment - 1))
4158                 return true;
4159
4160         if (flags & PIN_MAPPABLE && !obj->map_and_fenceable)
4161                 return true;
4162
4163         if (flags & PIN_OFFSET_BIAS &&
4164             vma->node.start < (flags & PIN_OFFSET_MASK))
4165                 return true;
4166
4167         return false;
4168 }
4169
4170 int
4171 i915_gem_object_pin_view(struct drm_i915_gem_object *obj,
4172                          struct i915_address_space *vm,
4173                          uint32_t alignment,
4174                          uint64_t flags,
4175                          const struct i915_ggtt_view *view)
4176 {
4177         struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
4178         struct i915_vma *vma;
4179         unsigned bound;
4180         int ret;
4181
4182         if (WARN_ON(vm == &dev_priv->mm.aliasing_ppgtt->base))
4183                 return -ENODEV;
4184
4185         if (WARN_ON(flags & (PIN_GLOBAL | PIN_MAPPABLE) && !i915_is_ggtt(vm)))
4186                 return -EINVAL;
4187
4188         if (WARN_ON((flags & (PIN_MAPPABLE | PIN_GLOBAL)) == PIN_MAPPABLE))
4189                 return -EINVAL;
4190
4191         vma = i915_gem_obj_to_vma_view(obj, vm, view);
4192         if (vma) {
4193                 if (WARN_ON(vma->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT))
4194                         return -EBUSY;
4195
4196                 if (i915_vma_misplaced(vma, alignment, flags)) {
4197                         WARN(vma->pin_count,
4198                              "bo is already pinned with incorrect alignment:"
4199                              " offset=%lx, req.alignment=%x, req.map_and_fenceable=%d,"
4200                              " obj->map_and_fenceable=%d\n",
4201                              i915_gem_obj_offset_view(obj, vm, view->type),
4202                              alignment,
4203                              !!(flags & PIN_MAPPABLE),
4204                              obj->map_and_fenceable);
4205                         ret = i915_vma_unbind(vma);
4206                         if (ret)
4207                                 return ret;
4208
4209                         vma = NULL;
4210                 }
4211         }
4212
4213         bound = vma ? vma->bound : 0;
4214         if (vma == NULL || !drm_mm_node_allocated(&vma->node)) {
4215                 vma = i915_gem_object_bind_to_vm(obj, vm, alignment,
4216                                                  flags, view);
4217                 if (IS_ERR(vma))
4218                         return PTR_ERR(vma);
4219         }
4220
4221         if (flags & PIN_GLOBAL && !(vma->bound & GLOBAL_BIND)) {
4222                 ret = i915_vma_bind(vma, obj->cache_level, GLOBAL_BIND);
4223                 if (ret)
4224                         return ret;
4225         }
4226
4227         if ((bound ^ vma->bound) & GLOBAL_BIND) {
4228                 bool mappable, fenceable;
4229                 u32 fence_size, fence_alignment;
4230
4231                 fence_size = i915_gem_get_gtt_size(obj->base.dev,
4232                                                    obj->base.size,
4233                                                    obj->tiling_mode);
4234                 fence_alignment = i915_gem_get_gtt_alignment(obj->base.dev,
4235                                                              obj->base.size,
4236                                                              obj->tiling_mode,
4237                                                              true);
4238
4239                 fenceable = (vma->node.size == fence_size &&
4240                              (vma->node.start & (fence_alignment - 1)) == 0);
4241
4242                 mappable = (vma->node.start + obj->base.size <=
4243                             dev_priv->gtt.mappable_end);
4244
4245                 obj->map_and_fenceable = mappable && fenceable;
4246         }
4247
4248         WARN_ON(flags & PIN_MAPPABLE && !obj->map_and_fenceable);
4249
4250         vma->pin_count++;
4251         if (flags & PIN_MAPPABLE)
4252                 obj->pin_mappable |= true;
4253
4254         return 0;
4255 }
4256
4257 void
4258 i915_gem_object_ggtt_unpin(struct drm_i915_gem_object *obj)
4259 {
4260         struct i915_vma *vma = i915_gem_obj_to_ggtt(obj);
4261
4262         BUG_ON(!vma);
4263         BUG_ON(vma->pin_count == 0);
4264         BUG_ON(!i915_gem_obj_ggtt_bound(obj));
4265
4266         if (--vma->pin_count == 0)
4267                 obj->pin_mappable = false;
4268 }
4269
4270 bool
4271 i915_gem_object_pin_fence(struct drm_i915_gem_object *obj)
4272 {
4273         if (obj->fence_reg != I915_FENCE_REG_NONE) {
4274                 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
4275                 struct i915_vma *ggtt_vma = i915_gem_obj_to_ggtt(obj);
4276
4277                 WARN_ON(!ggtt_vma ||
4278                         dev_priv->fence_regs[obj->fence_reg].pin_count >
4279                         ggtt_vma->pin_count);
4280                 dev_priv->fence_regs[obj->fence_reg].pin_count++;
4281                 return true;
4282         } else
4283                 return false;
4284 }
4285
4286 void
4287 i915_gem_object_unpin_fence(struct drm_i915_gem_object *obj)
4288 {
4289         if (obj->fence_reg != I915_FENCE_REG_NONE) {
4290                 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
4291                 WARN_ON(dev_priv->fence_regs[obj->fence_reg].pin_count <= 0);
4292                 dev_priv->fence_regs[obj->fence_reg].pin_count--;
4293         }
4294 }
4295
4296 int
4297 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4298                     struct drm_file *file)
4299 {
4300         struct drm_i915_gem_busy *args = data;
4301         struct drm_i915_gem_object *obj;
4302         int ret;
4303
4304         ret = i915_mutex_lock_interruptible(dev);
4305         if (ret)
4306                 return ret;
4307
4308         obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
4309         if (&obj->base == NULL) {
4310                 ret = -ENOENT;
4311                 goto unlock;
4312         }
4313
4314         /* Count all active objects as busy, even if they are currently not used
4315          * by the gpu. Users of this interface expect objects to eventually
4316          * become non-busy without any further actions, therefore emit any
4317          * necessary flushes here.
4318          */
4319         ret = i915_gem_object_flush_active(obj);
4320
4321         args->busy = obj->active;
4322         if (obj->last_read_req) {
4323                 struct intel_engine_cs *ring;
4324                 BUILD_BUG_ON(I915_NUM_RINGS > 16);
4325                 ring = i915_gem_request_get_ring(obj->last_read_req);
4326                 args->busy |= intel_ring_flag(ring) << 16;
4327         }
4328
4329         drm_gem_object_unreference(&obj->base);
4330 unlock:
4331         mutex_unlock(&dev->struct_mutex);
4332         return ret;
4333 }
4334
4335 int
4336 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
4337                         struct drm_file *file_priv)
4338 {
4339         return i915_gem_ring_throttle(dev, file_priv);
4340 }
4341
4342 int
4343 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
4344                        struct drm_file *file_priv)
4345 {
4346         struct drm_i915_private *dev_priv = dev->dev_private;
4347         struct drm_i915_gem_madvise *args = data;
4348         struct drm_i915_gem_object *obj;
4349         int ret;
4350
4351         switch (args->madv) {
4352         case I915_MADV_DONTNEED:
4353         case I915_MADV_WILLNEED:
4354             break;
4355         default:
4356             return -EINVAL;
4357         }
4358
4359         ret = i915_mutex_lock_interruptible(dev);
4360         if (ret)
4361                 return ret;
4362
4363         obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
4364         if (&obj->base == NULL) {
4365                 ret = -ENOENT;
4366                 goto unlock;
4367         }
4368
4369         if (i915_gem_obj_is_pinned(obj)) {
4370                 ret = -EINVAL;
4371                 goto out;
4372         }
4373
4374         if (obj->pages &&
4375             obj->tiling_mode != I915_TILING_NONE &&
4376             dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
4377                 if (obj->madv == I915_MADV_WILLNEED)
4378                         i915_gem_object_unpin_pages(obj);
4379                 if (args->madv == I915_MADV_WILLNEED)
4380                         i915_gem_object_pin_pages(obj);
4381         }
4382
4383         if (obj->madv != __I915_MADV_PURGED)
4384                 obj->madv = args->madv;
4385
4386         /* if the object is no longer attached, discard its backing storage */
4387         if (i915_gem_object_is_purgeable(obj) && obj->pages == NULL)
4388                 i915_gem_object_truncate(obj);
4389
4390         args->retained = obj->madv != __I915_MADV_PURGED;
4391
4392 out:
4393         drm_gem_object_unreference(&obj->base);
4394 unlock:
4395         mutex_unlock(&dev->struct_mutex);
4396         return ret;
4397 }
4398
4399 void i915_gem_object_init(struct drm_i915_gem_object *obj,
4400                           const struct drm_i915_gem_object_ops *ops)
4401 {
4402         INIT_LIST_HEAD(&obj->global_list);
4403         INIT_LIST_HEAD(&obj->ring_list);
4404         INIT_LIST_HEAD(&obj->obj_exec_link);
4405         INIT_LIST_HEAD(&obj->vma_list);
4406         INIT_LIST_HEAD(&obj->batch_pool_list);
4407
4408         obj->ops = ops;
4409
4410         obj->fence_reg = I915_FENCE_REG_NONE;
4411         obj->madv = I915_MADV_WILLNEED;
4412
4413         i915_gem_info_add_obj(obj->base.dev->dev_private, obj->base.size);
4414 }
4415
4416 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
4417         .get_pages = i915_gem_object_get_pages_gtt,
4418         .put_pages = i915_gem_object_put_pages_gtt,
4419 };
4420
4421 struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
4422                                                   size_t size)
4423 {
4424         struct drm_i915_gem_object *obj;
4425         struct address_space *mapping;
4426         gfp_t mask;
4427
4428         obj = i915_gem_object_alloc(dev);
4429         if (obj == NULL)
4430                 return NULL;
4431
4432         if (drm_gem_object_init(dev, &obj->base, size) != 0) {
4433                 i915_gem_object_free(obj);
4434                 return NULL;
4435         }
4436
4437         mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
4438         if (IS_CRESTLINE(dev) || IS_BROADWATER(dev)) {
4439                 /* 965gm cannot relocate objects above 4GiB. */
4440                 mask &= ~__GFP_HIGHMEM;
4441                 mask |= __GFP_DMA32;
4442         }
4443
4444         mapping = file_inode(obj->base.filp)->i_mapping;
4445         mapping_set_gfp_mask(mapping, mask);
4446
4447         i915_gem_object_init(obj, &i915_gem_object_ops);
4448
4449         obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4450         obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4451
4452         if (HAS_LLC(dev)) {
4453                 /* On some devices, we can have the GPU use the LLC (the CPU
4454                  * cache) for about a 10% performance improvement
4455                  * compared to uncached.  Graphics requests other than
4456                  * display scanout are coherent with the CPU in
4457                  * accessing this cache.  This means in this mode we
4458                  * don't need to clflush on the CPU side, and on the
4459                  * GPU side we only need to flush internal caches to
4460                  * get data visible to the CPU.
4461                  *
4462                  * However, we maintain the display planes as UC, and so
4463                  * need to rebind when first used as such.
4464                  */
4465                 obj->cache_level = I915_CACHE_LLC;
4466         } else
4467                 obj->cache_level = I915_CACHE_NONE;
4468
4469         trace_i915_gem_object_create(obj);
4470
4471         return obj;
4472 }
4473
4474 static bool discard_backing_storage(struct drm_i915_gem_object *obj)
4475 {
4476         /* If we are the last user of the backing storage (be it shmemfs
4477          * pages or stolen etc), we know that the pages are going to be
4478          * immediately released. In this case, we can then skip copying
4479          * back the contents from the GPU.
4480          */
4481
4482         if (obj->madv != I915_MADV_WILLNEED)
4483                 return false;
4484
4485         if (obj->base.filp == NULL)
4486                 return true;
4487
4488         /* At first glance, this looks racy, but then again so would be
4489          * userspace racing mmap against close. However, the first external
4490          * reference to the filp can only be obtained through the
4491          * i915_gem_mmap_ioctl() which safeguards us against the user
4492          * acquiring such a reference whilst we are in the middle of
4493          * freeing the object.
4494          */
4495         return atomic_long_read(&obj->base.filp->f_count) == 1;
4496 }
4497
4498 void i915_gem_free_object(struct drm_gem_object *gem_obj)
4499 {
4500         struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
4501         struct drm_device *dev = obj->base.dev;
4502         struct drm_i915_private *dev_priv = dev->dev_private;
4503         struct i915_vma *vma, *next;
4504
4505         intel_runtime_pm_get(dev_priv);
4506
4507         trace_i915_gem_object_destroy(obj);
4508
4509         list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link) {
4510                 int ret;
4511
4512                 vma->pin_count = 0;
4513                 ret = i915_vma_unbind(vma);
4514                 if (WARN_ON(ret == -ERESTARTSYS)) {
4515                         bool was_interruptible;
4516
4517                         was_interruptible = dev_priv->mm.interruptible;
4518                         dev_priv->mm.interruptible = false;
4519
4520                         WARN_ON(i915_vma_unbind(vma));
4521
4522                         dev_priv->mm.interruptible = was_interruptible;
4523                 }
4524         }
4525
4526         /* Stolen objects don't hold a ref, but do hold pin count. Fix that up
4527          * before progressing. */
4528         if (obj->stolen)
4529                 i915_gem_object_unpin_pages(obj);
4530
4531         WARN_ON(obj->frontbuffer_bits);
4532
4533         if (obj->pages && obj->madv == I915_MADV_WILLNEED &&
4534             dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES &&
4535             obj->tiling_mode != I915_TILING_NONE)
4536                 i915_gem_object_unpin_pages(obj);
4537
4538         if (WARN_ON(obj->pages_pin_count))
4539                 obj->pages_pin_count = 0;
4540         if (discard_backing_storage(obj))
4541                 obj->madv = I915_MADV_DONTNEED;
4542         i915_gem_object_put_pages(obj);
4543         i915_gem_object_free_mmap_offset(obj);
4544
4545         BUG_ON(obj->pages);
4546
4547         if (obj->base.import_attach)
4548                 drm_prime_gem_destroy(&obj->base, NULL);
4549
4550         if (obj->ops->release)
4551                 obj->ops->release(obj);
4552
4553         drm_gem_object_release(&obj->base);
4554         i915_gem_info_remove_obj(dev_priv, obj->base.size);
4555
4556         kfree(obj->bit_17);
4557         i915_gem_object_free(obj);
4558
4559         intel_runtime_pm_put(dev_priv);
4560 }
4561
4562 struct i915_vma *i915_gem_obj_to_vma_view(struct drm_i915_gem_object *obj,
4563                                           struct i915_address_space *vm,
4564                                           const struct i915_ggtt_view *view)
4565 {
4566         struct i915_vma *vma;
4567         list_for_each_entry(vma, &obj->vma_list, vma_link)
4568                 if (vma->vm == vm && vma->ggtt_view.type == view->type)
4569                         return vma;
4570
4571         return NULL;
4572 }
4573
4574 void i915_gem_vma_destroy(struct i915_vma *vma)
4575 {
4576         struct i915_address_space *vm = NULL;
4577         WARN_ON(vma->node.allocated);
4578
4579         /* Keep the vma as a placeholder in the execbuffer reservation lists */
4580         if (!list_empty(&vma->exec_list))
4581                 return;
4582
4583         vm = vma->vm;
4584
4585         if (!i915_is_ggtt(vm))
4586                 i915_ppgtt_put(i915_vm_to_ppgtt(vm));
4587
4588         list_del(&vma->vma_link);
4589
4590         kfree(vma);
4591 }
4592
4593 static void
4594 i915_gem_stop_ringbuffers(struct drm_device *dev)
4595 {
4596         struct drm_i915_private *dev_priv = dev->dev_private;
4597         struct intel_engine_cs *ring;
4598         int i;
4599
4600         for_each_ring(ring, dev_priv, i)
4601                 dev_priv->gt.stop_ring(ring);
4602 }
4603
4604 int
4605 i915_gem_suspend(struct drm_device *dev)
4606 {
4607         struct drm_i915_private *dev_priv = dev->dev_private;
4608         int ret = 0;
4609
4610         mutex_lock(&dev->struct_mutex);
4611         ret = i915_gpu_idle(dev);
4612         if (ret)
4613                 goto err;
4614
4615         i915_gem_retire_requests(dev);
4616
4617         /* Under UMS, be paranoid and evict. */
4618         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4619                 i915_gem_evict_everything(dev);
4620
4621         i915_gem_stop_ringbuffers(dev);
4622         mutex_unlock(&dev->struct_mutex);
4623
4624         del_timer_sync(&dev_priv->gpu_error.hangcheck_timer);
4625         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
4626         flush_delayed_work(&dev_priv->mm.idle_work);
4627
4628         /* Assert that we sucessfully flushed all the work and
4629          * reset the GPU back to its idle, low power state.
4630          */
4631         WARN_ON(dev_priv->mm.busy);
4632
4633         return 0;
4634
4635 err:
4636         mutex_unlock(&dev->struct_mutex);
4637         return ret;
4638 }
4639
4640 int i915_gem_l3_remap(struct intel_engine_cs *ring, int slice)
4641 {
4642         struct drm_device *dev = ring->dev;
4643         struct drm_i915_private *dev_priv = dev->dev_private;
4644         u32 reg_base = GEN7_L3LOG_BASE + (slice * 0x200);
4645         u32 *remap_info = dev_priv->l3_parity.remap_info[slice];
4646         int i, ret;
4647
4648         if (!HAS_L3_DPF(dev) || !remap_info)
4649                 return 0;
4650
4651         ret = intel_ring_begin(ring, GEN7_L3LOG_SIZE / 4 * 3);
4652         if (ret)
4653                 return ret;
4654
4655         /*
4656          * Note: We do not worry about the concurrent register cacheline hang
4657          * here because no other code should access these registers other than
4658          * at initialization time.
4659          */
4660         for (i = 0; i < GEN7_L3LOG_SIZE; i += 4) {
4661                 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
4662                 intel_ring_emit(ring, reg_base + i);
4663                 intel_ring_emit(ring, remap_info[i/4]);
4664         }
4665
4666         intel_ring_advance(ring);
4667
4668         return ret;
4669 }
4670
4671 void i915_gem_init_swizzling(struct drm_device *dev)
4672 {
4673         struct drm_i915_private *dev_priv = dev->dev_private;
4674
4675         if (INTEL_INFO(dev)->gen < 5 ||
4676             dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
4677                 return;
4678
4679         I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
4680                                  DISP_TILE_SURFACE_SWIZZLING);
4681
4682         if (IS_GEN5(dev))
4683                 return;
4684
4685         I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
4686         if (IS_GEN6(dev))
4687                 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
4688         else if (IS_GEN7(dev))
4689                 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
4690         else if (IS_GEN8(dev))
4691                 I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
4692         else
4693                 BUG();
4694 }
4695
4696 static bool
4697 intel_enable_blt(struct drm_device *dev)
4698 {
4699         if (!HAS_BLT(dev))
4700                 return false;
4701
4702         /* The blitter was dysfunctional on early prototypes */
4703         if (IS_GEN6(dev) && dev->pdev->revision < 8) {
4704                 DRM_INFO("BLT not supported on this pre-production hardware;"
4705                          " graphics performance will be degraded.\n");
4706                 return false;
4707         }
4708
4709         return true;
4710 }
4711
4712 static void init_unused_ring(struct drm_device *dev, u32 base)
4713 {
4714         struct drm_i915_private *dev_priv = dev->dev_private;
4715
4716         I915_WRITE(RING_CTL(base), 0);
4717         I915_WRITE(RING_HEAD(base), 0);
4718         I915_WRITE(RING_TAIL(base), 0);
4719         I915_WRITE(RING_START(base), 0);
4720 }
4721
4722 static void init_unused_rings(struct drm_device *dev)
4723 {
4724         if (IS_I830(dev)) {
4725                 init_unused_ring(dev, PRB1_BASE);
4726                 init_unused_ring(dev, SRB0_BASE);
4727                 init_unused_ring(dev, SRB1_BASE);
4728                 init_unused_ring(dev, SRB2_BASE);
4729                 init_unused_ring(dev, SRB3_BASE);
4730         } else if (IS_GEN2(dev)) {
4731                 init_unused_ring(dev, SRB0_BASE);
4732                 init_unused_ring(dev, SRB1_BASE);
4733         } else if (IS_GEN3(dev)) {
4734                 init_unused_ring(dev, PRB1_BASE);
4735                 init_unused_ring(dev, PRB2_BASE);
4736         }
4737 }
4738
4739 int i915_gem_init_rings(struct drm_device *dev)
4740 {
4741         struct drm_i915_private *dev_priv = dev->dev_private;
4742         int ret;
4743
4744         ret = intel_init_render_ring_buffer(dev);
4745         if (ret)
4746                 return ret;
4747
4748         if (HAS_BSD(dev)) {
4749                 ret = intel_init_bsd_ring_buffer(dev);
4750                 if (ret)
4751                         goto cleanup_render_ring;
4752         }
4753
4754         if (intel_enable_blt(dev)) {
4755                 ret = intel_init_blt_ring_buffer(dev);
4756                 if (ret)
4757                         goto cleanup_bsd_ring;
4758         }
4759
4760         if (HAS_VEBOX(dev)) {
4761                 ret = intel_init_vebox_ring_buffer(dev);
4762                 if (ret)
4763                         goto cleanup_blt_ring;
4764         }
4765
4766         if (HAS_BSD2(dev)) {
4767                 ret = intel_init_bsd2_ring_buffer(dev);
4768                 if (ret)
4769                         goto cleanup_vebox_ring;
4770         }
4771
4772         ret = i915_gem_set_seqno(dev, ((u32)~0 - 0x1000));
4773         if (ret)
4774                 goto cleanup_bsd2_ring;
4775
4776         return 0;
4777
4778 cleanup_bsd2_ring:
4779         intel_cleanup_ring_buffer(&dev_priv->ring[VCS2]);
4780 cleanup_vebox_ring:
4781         intel_cleanup_ring_buffer(&dev_priv->ring[VECS]);
4782 cleanup_blt_ring:
4783         intel_cleanup_ring_buffer(&dev_priv->ring[BCS]);
4784 cleanup_bsd_ring:
4785         intel_cleanup_ring_buffer(&dev_priv->ring[VCS]);
4786 cleanup_render_ring:
4787         intel_cleanup_ring_buffer(&dev_priv->ring[RCS]);
4788
4789         return ret;
4790 }
4791
4792 int
4793 i915_gem_init_hw(struct drm_device *dev)
4794 {
4795         struct drm_i915_private *dev_priv = dev->dev_private;
4796         struct intel_engine_cs *ring;
4797         int ret, i;
4798
4799         if (INTEL_INFO(dev)->gen < 6 && !intel_enable_gtt())
4800                 return -EIO;
4801
4802         if (dev_priv->ellc_size)
4803                 I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
4804
4805         if (IS_HASWELL(dev))
4806                 I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev) ?
4807                            LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
4808
4809         if (HAS_PCH_NOP(dev)) {
4810                 if (IS_IVYBRIDGE(dev)) {
4811                         u32 temp = I915_READ(GEN7_MSG_CTL);
4812                         temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
4813                         I915_WRITE(GEN7_MSG_CTL, temp);
4814                 } else if (INTEL_INFO(dev)->gen >= 7) {
4815                         u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
4816                         temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
4817                         I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
4818                 }
4819         }
4820
4821         i915_gem_init_swizzling(dev);
4822
4823         /*
4824          * At least 830 can leave some of the unused rings
4825          * "active" (ie. head != tail) after resume which
4826          * will prevent c3 entry. Makes sure all unused rings
4827          * are totally idle.
4828          */
4829         init_unused_rings(dev);
4830
4831         for_each_ring(ring, dev_priv, i) {
4832                 ret = ring->init_hw(ring);
4833                 if (ret)
4834                         return ret;
4835         }
4836
4837         for (i = 0; i < NUM_L3_SLICES(dev); i++)
4838                 i915_gem_l3_remap(&dev_priv->ring[RCS], i);
4839
4840         /*
4841          * XXX: Contexts should only be initialized once. Doing a switch to the
4842          * default context switch however is something we'd like to do after
4843          * reset or thaw (the latter may not actually be necessary for HW, but
4844          * goes with our code better). Context switching requires rings (for
4845          * the do_switch), but before enabling PPGTT. So don't move this.
4846          */
4847         ret = i915_gem_context_enable(dev_priv);
4848         if (ret && ret != -EIO) {
4849                 DRM_ERROR("Context enable failed %d\n", ret);
4850                 i915_gem_cleanup_ringbuffer(dev);
4851
4852                 return ret;
4853         }
4854
4855         ret = i915_ppgtt_init_hw(dev);
4856         if (ret && ret != -EIO) {
4857                 DRM_ERROR("PPGTT enable failed %d\n", ret);
4858                 i915_gem_cleanup_ringbuffer(dev);
4859         }
4860
4861         return ret;
4862 }
4863
4864 int i915_gem_init(struct drm_device *dev)
4865 {
4866         struct drm_i915_private *dev_priv = dev->dev_private;
4867         int ret;
4868
4869         i915.enable_execlists = intel_sanitize_enable_execlists(dev,
4870                         i915.enable_execlists);
4871
4872         mutex_lock(&dev->struct_mutex);
4873
4874         if (IS_VALLEYVIEW(dev)) {
4875                 /* VLVA0 (potential hack), BIOS isn't actually waking us */
4876                 I915_WRITE(VLV_GTLC_WAKE_CTRL, VLV_GTLC_ALLOWWAKEREQ);
4877                 if (wait_for((I915_READ(VLV_GTLC_PW_STATUS) &
4878                               VLV_GTLC_ALLOWWAKEACK), 10))
4879                         DRM_DEBUG_DRIVER("allow wake ack timed out\n");
4880         }
4881
4882         if (!i915.enable_execlists) {
4883                 dev_priv->gt.do_execbuf = i915_gem_ringbuffer_submission;
4884                 dev_priv->gt.init_rings = i915_gem_init_rings;
4885                 dev_priv->gt.cleanup_ring = intel_cleanup_ring_buffer;
4886                 dev_priv->gt.stop_ring = intel_stop_ring_buffer;
4887         } else {
4888                 dev_priv->gt.do_execbuf = intel_execlists_submission;
4889                 dev_priv->gt.init_rings = intel_logical_rings_init;
4890                 dev_priv->gt.cleanup_ring = intel_logical_ring_cleanup;
4891                 dev_priv->gt.stop_ring = intel_logical_ring_stop;
4892         }
4893
4894         ret = i915_gem_init_userptr(dev);
4895         if (ret)
4896                 goto out_unlock;
4897
4898         i915_gem_init_global_gtt(dev);
4899
4900         ret = i915_gem_context_init(dev);
4901         if (ret)
4902                 goto out_unlock;
4903
4904         ret = dev_priv->gt.init_rings(dev);
4905         if (ret)
4906                 goto out_unlock;
4907
4908         ret = i915_gem_init_hw(dev);
4909         if (ret == -EIO) {
4910                 /* Allow ring initialisation to fail by marking the GPU as
4911                  * wedged. But we only want to do this where the GPU is angry,
4912                  * for all other failure, such as an allocation failure, bail.
4913                  */
4914                 DRM_ERROR("Failed to initialize GPU, declaring it wedged\n");
4915                 atomic_set_mask(I915_WEDGED, &dev_priv->gpu_error.reset_counter);
4916                 ret = 0;
4917         }
4918
4919 out_unlock:
4920         mutex_unlock(&dev->struct_mutex);
4921
4922         return ret;
4923 }
4924
4925 void
4926 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
4927 {
4928         struct drm_i915_private *dev_priv = dev->dev_private;
4929         struct intel_engine_cs *ring;
4930         int i;
4931
4932         for_each_ring(ring, dev_priv, i)
4933                 dev_priv->gt.cleanup_ring(ring);
4934 }
4935
4936 static void
4937 init_ring_lists(struct intel_engine_cs *ring)
4938 {
4939         INIT_LIST_HEAD(&ring->active_list);
4940         INIT_LIST_HEAD(&ring->request_list);
4941 }
4942
4943 void i915_init_vm(struct drm_i915_private *dev_priv,
4944                   struct i915_address_space *vm)
4945 {
4946         if (!i915_is_ggtt(vm))
4947                 drm_mm_init(&vm->mm, vm->start, vm->total);
4948         vm->dev = dev_priv->dev;
4949         INIT_LIST_HEAD(&vm->active_list);
4950         INIT_LIST_HEAD(&vm->inactive_list);
4951         INIT_LIST_HEAD(&vm->global_link);
4952         list_add_tail(&vm->global_link, &dev_priv->vm_list);
4953 }
4954
4955 void
4956 i915_gem_load(struct drm_device *dev)
4957 {
4958         struct drm_i915_private *dev_priv = dev->dev_private;
4959         int i;
4960
4961         dev_priv->slab =
4962                 kmem_cache_create("i915_gem_object",
4963                                   sizeof(struct drm_i915_gem_object), 0,
4964                                   SLAB_HWCACHE_ALIGN,
4965                                   NULL);
4966
4967         INIT_LIST_HEAD(&dev_priv->vm_list);
4968         i915_init_vm(dev_priv, &dev_priv->gtt.base);
4969
4970         INIT_LIST_HEAD(&dev_priv->context_list);
4971         INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
4972         INIT_LIST_HEAD(&dev_priv->mm.bound_list);
4973         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
4974         for (i = 0; i < I915_NUM_RINGS; i++)
4975                 init_ring_lists(&dev_priv->ring[i]);
4976         for (i = 0; i < I915_MAX_NUM_FENCES; i++)
4977                 INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
4978         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
4979                           i915_gem_retire_work_handler);
4980         INIT_DELAYED_WORK(&dev_priv->mm.idle_work,
4981                           i915_gem_idle_work_handler);
4982         init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
4983
4984         /* On GEN3 we really need to make sure the ARB C3 LP bit is set */
4985         if (!drm_core_check_feature(dev, DRIVER_MODESET) && IS_GEN3(dev)) {
4986                 I915_WRITE(MI_ARB_STATE,
4987                            _MASKED_BIT_ENABLE(MI_ARB_C3_LP_WRITE_ENABLE));
4988         }
4989
4990         dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
4991
4992         /* Old X drivers will take 0-2 for front, back, depth buffers */
4993         if (!drm_core_check_feature(dev, DRIVER_MODESET))
4994                 dev_priv->fence_reg_start = 3;
4995
4996         if (INTEL_INFO(dev)->gen >= 7 && !IS_VALLEYVIEW(dev))
4997                 dev_priv->num_fence_regs = 32;
4998         else if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
4999                 dev_priv->num_fence_regs = 16;
5000         else
5001                 dev_priv->num_fence_regs = 8;
5002
5003         /* Initialize fence registers to zero */
5004         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
5005         i915_gem_restore_fences(dev);
5006
5007         i915_gem_detect_bit_6_swizzle(dev);
5008         init_waitqueue_head(&dev_priv->pending_flip_queue);
5009
5010         dev_priv->mm.interruptible = true;
5011
5012         dev_priv->mm.shrinker.scan_objects = i915_gem_shrinker_scan;
5013         dev_priv->mm.shrinker.count_objects = i915_gem_shrinker_count;
5014         dev_priv->mm.shrinker.seeks = DEFAULT_SEEKS;
5015         register_shrinker(&dev_priv->mm.shrinker);
5016
5017         dev_priv->mm.oom_notifier.notifier_call = i915_gem_shrinker_oom;
5018         register_oom_notifier(&dev_priv->mm.oom_notifier);
5019
5020         i915_gem_batch_pool_init(dev, &dev_priv->mm.batch_pool);
5021
5022         mutex_init(&dev_priv->fb_tracking.lock);
5023 }
5024
5025 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
5026 {
5027         struct drm_i915_file_private *file_priv = file->driver_priv;
5028
5029         cancel_delayed_work_sync(&file_priv->mm.idle_work);
5030
5031         /* Clean up our request list when the client is going away, so that
5032          * later retire_requests won't dereference our soon-to-be-gone
5033          * file_priv.
5034          */
5035         spin_lock(&file_priv->mm.lock);
5036         while (!list_empty(&file_priv->mm.request_list)) {
5037                 struct drm_i915_gem_request *request;
5038
5039                 request = list_first_entry(&file_priv->mm.request_list,
5040                                            struct drm_i915_gem_request,
5041                                            client_list);
5042                 list_del(&request->client_list);
5043                 request->file_priv = NULL;
5044         }
5045         spin_unlock(&file_priv->mm.lock);
5046 }
5047
5048 static void
5049 i915_gem_file_idle_work_handler(struct work_struct *work)
5050 {
5051         struct drm_i915_file_private *file_priv =
5052                 container_of(work, typeof(*file_priv), mm.idle_work.work);
5053
5054         atomic_set(&file_priv->rps_wait_boost, false);
5055 }
5056
5057 int i915_gem_open(struct drm_device *dev, struct drm_file *file)
5058 {
5059         struct drm_i915_file_private *file_priv;
5060         int ret;
5061
5062         DRM_DEBUG_DRIVER("\n");
5063
5064         file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
5065         if (!file_priv)
5066                 return -ENOMEM;
5067
5068         file->driver_priv = file_priv;
5069         file_priv->dev_priv = dev->dev_private;
5070         file_priv->file = file;
5071
5072         spin_lock_init(&file_priv->mm.lock);
5073         INIT_LIST_HEAD(&file_priv->mm.request_list);
5074         INIT_DELAYED_WORK(&file_priv->mm.idle_work,
5075                           i915_gem_file_idle_work_handler);
5076
5077         ret = i915_gem_context_open(dev, file);
5078         if (ret)
5079                 kfree(file_priv);
5080
5081         return ret;
5082 }
5083
5084 /**
5085  * i915_gem_track_fb - update frontbuffer tracking
5086  * old: current GEM buffer for the frontbuffer slots
5087  * new: new GEM buffer for the frontbuffer slots
5088  * frontbuffer_bits: bitmask of frontbuffer slots
5089  *
5090  * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
5091  * from @old and setting them in @new. Both @old and @new can be NULL.
5092  */
5093 void i915_gem_track_fb(struct drm_i915_gem_object *old,
5094                        struct drm_i915_gem_object *new,
5095                        unsigned frontbuffer_bits)
5096 {
5097         if (old) {
5098                 WARN_ON(!mutex_is_locked(&old->base.dev->struct_mutex));
5099                 WARN_ON(!(old->frontbuffer_bits & frontbuffer_bits));
5100                 old->frontbuffer_bits &= ~frontbuffer_bits;
5101         }
5102
5103         if (new) {
5104                 WARN_ON(!mutex_is_locked(&new->base.dev->struct_mutex));
5105                 WARN_ON(new->frontbuffer_bits & frontbuffer_bits);
5106                 new->frontbuffer_bits |= frontbuffer_bits;
5107         }
5108 }
5109
5110 static bool mutex_is_locked_by(struct mutex *mutex, struct task_struct *task)
5111 {
5112         if (!mutex_is_locked(mutex))
5113                 return false;
5114
5115 #if defined(CONFIG_SMP) || defined(CONFIG_DEBUG_MUTEXES)
5116         return mutex->owner == task;
5117 #else
5118         /* Since UP may be pre-empted, we cannot assume that we own the lock */
5119         return false;
5120 #endif
5121 }
5122
5123 static bool i915_gem_shrinker_lock(struct drm_device *dev, bool *unlock)
5124 {
5125         if (!mutex_trylock(&dev->struct_mutex)) {
5126                 if (!mutex_is_locked_by(&dev->struct_mutex, current))
5127                         return false;
5128
5129                 if (to_i915(dev)->mm.shrinker_no_lock_stealing)
5130                         return false;
5131
5132                 *unlock = false;
5133         } else
5134                 *unlock = true;
5135
5136         return true;
5137 }
5138
5139 static int num_vma_bound(struct drm_i915_gem_object *obj)
5140 {
5141         struct i915_vma *vma;
5142         int count = 0;
5143
5144         list_for_each_entry(vma, &obj->vma_list, vma_link)
5145                 if (drm_mm_node_allocated(&vma->node))
5146                         count++;
5147
5148         return count;
5149 }
5150
5151 static unsigned long
5152 i915_gem_shrinker_count(struct shrinker *shrinker, struct shrink_control *sc)
5153 {
5154         struct drm_i915_private *dev_priv =
5155                 container_of(shrinker, struct drm_i915_private, mm.shrinker);
5156         struct drm_device *dev = dev_priv->dev;
5157         struct drm_i915_gem_object *obj;
5158         unsigned long count;
5159         bool unlock;
5160
5161         if (!i915_gem_shrinker_lock(dev, &unlock))
5162                 return 0;
5163
5164         count = 0;
5165         list_for_each_entry(obj, &dev_priv->mm.unbound_list, global_list)
5166                 if (obj->pages_pin_count == 0)
5167                         count += obj->base.size >> PAGE_SHIFT;
5168
5169         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
5170                 if (!i915_gem_obj_is_pinned(obj) &&
5171                     obj->pages_pin_count == num_vma_bound(obj))
5172                         count += obj->base.size >> PAGE_SHIFT;
5173         }
5174
5175         if (unlock)
5176                 mutex_unlock(&dev->struct_mutex);
5177
5178         return count;
5179 }
5180
5181 /* All the new VM stuff */
5182 unsigned long i915_gem_obj_offset_view(struct drm_i915_gem_object *o,
5183                                        struct i915_address_space *vm,
5184                                        enum i915_ggtt_view_type view)
5185 {
5186         struct drm_i915_private *dev_priv = o->base.dev->dev_private;
5187         struct i915_vma *vma;
5188
5189         WARN_ON(vm == &dev_priv->mm.aliasing_ppgtt->base);
5190
5191         list_for_each_entry(vma, &o->vma_list, vma_link) {
5192                 if (vma->vm == vm && vma->ggtt_view.type == view)
5193                         return vma->node.start;
5194
5195         }
5196         WARN(1, "%s vma for this object not found.\n",
5197              i915_is_ggtt(vm) ? "global" : "ppgtt");
5198         return -1;
5199 }
5200
5201 bool i915_gem_obj_bound_view(struct drm_i915_gem_object *o,
5202                              struct i915_address_space *vm,
5203                              enum i915_ggtt_view_type view)
5204 {
5205         struct i915_vma *vma;
5206
5207         list_for_each_entry(vma, &o->vma_list, vma_link)
5208                 if (vma->vm == vm &&
5209                     vma->ggtt_view.type == view &&
5210                     drm_mm_node_allocated(&vma->node))
5211                         return true;
5212
5213         return false;
5214 }
5215
5216 bool i915_gem_obj_bound_any(struct drm_i915_gem_object *o)
5217 {
5218         struct i915_vma *vma;
5219
5220         list_for_each_entry(vma, &o->vma_list, vma_link)
5221                 if (drm_mm_node_allocated(&vma->node))
5222                         return true;
5223
5224         return false;
5225 }
5226
5227 unsigned long i915_gem_obj_size(struct drm_i915_gem_object *o,
5228                                 struct i915_address_space *vm)
5229 {
5230         struct drm_i915_private *dev_priv = o->base.dev->dev_private;
5231         struct i915_vma *vma;
5232
5233         WARN_ON(vm == &dev_priv->mm.aliasing_ppgtt->base);
5234
5235         BUG_ON(list_empty(&o->vma_list));
5236
5237         list_for_each_entry(vma, &o->vma_list, vma_link)
5238                 if (vma->vm == vm)
5239                         return vma->node.size;
5240
5241         return 0;
5242 }
5243
5244 static unsigned long
5245 i915_gem_shrinker_scan(struct shrinker *shrinker, struct shrink_control *sc)
5246 {
5247         struct drm_i915_private *dev_priv =
5248                 container_of(shrinker, struct drm_i915_private, mm.shrinker);
5249         struct drm_device *dev = dev_priv->dev;
5250         unsigned long freed;
5251         bool unlock;
5252
5253         if (!i915_gem_shrinker_lock(dev, &unlock))
5254                 return SHRINK_STOP;
5255
5256         freed = i915_gem_shrink(dev_priv,
5257                                 sc->nr_to_scan,
5258                                 I915_SHRINK_BOUND |
5259                                 I915_SHRINK_UNBOUND |
5260                                 I915_SHRINK_PURGEABLE);
5261         if (freed < sc->nr_to_scan)
5262                 freed += i915_gem_shrink(dev_priv,
5263                                          sc->nr_to_scan - freed,
5264                                          I915_SHRINK_BOUND |
5265                                          I915_SHRINK_UNBOUND);
5266         if (unlock)
5267                 mutex_unlock(&dev->struct_mutex);
5268
5269         return freed;
5270 }
5271
5272 static int
5273 i915_gem_shrinker_oom(struct notifier_block *nb, unsigned long event, void *ptr)
5274 {
5275         struct drm_i915_private *dev_priv =
5276                 container_of(nb, struct drm_i915_private, mm.oom_notifier);
5277         struct drm_device *dev = dev_priv->dev;
5278         struct drm_i915_gem_object *obj;
5279         unsigned long timeout = msecs_to_jiffies(5000) + 1;
5280         unsigned long pinned, bound, unbound, freed_pages;
5281         bool was_interruptible;
5282         bool unlock;
5283
5284         while (!i915_gem_shrinker_lock(dev, &unlock) && --timeout) {
5285                 schedule_timeout_killable(1);
5286                 if (fatal_signal_pending(current))
5287                         return NOTIFY_DONE;
5288         }
5289         if (timeout == 0) {
5290                 pr_err("Unable to purge GPU memory due lock contention.\n");
5291                 return NOTIFY_DONE;
5292         }
5293
5294         was_interruptible = dev_priv->mm.interruptible;
5295         dev_priv->mm.interruptible = false;
5296
5297         freed_pages = i915_gem_shrink_all(dev_priv);
5298
5299         dev_priv->mm.interruptible = was_interruptible;
5300
5301         /* Because we may be allocating inside our own driver, we cannot
5302          * assert that there are no objects with pinned pages that are not
5303          * being pointed to by hardware.
5304          */
5305         unbound = bound = pinned = 0;
5306         list_for_each_entry(obj, &dev_priv->mm.unbound_list, global_list) {
5307                 if (!obj->base.filp) /* not backed by a freeable object */
5308                         continue;
5309
5310                 if (obj->pages_pin_count)
5311                         pinned += obj->base.size;
5312                 else
5313                         unbound += obj->base.size;
5314         }
5315         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
5316                 if (!obj->base.filp)
5317                         continue;
5318
5319                 if (obj->pages_pin_count)
5320                         pinned += obj->base.size;
5321                 else
5322                         bound += obj->base.size;
5323         }
5324
5325         if (unlock)
5326                 mutex_unlock(&dev->struct_mutex);
5327
5328         if (freed_pages || unbound || bound)
5329                 pr_info("Purging GPU memory, %lu bytes freed, %lu bytes still pinned.\n",
5330                         freed_pages << PAGE_SHIFT, pinned);
5331         if (unbound || bound)
5332                 pr_err("%lu and %lu bytes still available in the "
5333                        "bound and unbound GPU page lists.\n",
5334                        bound, unbound);
5335
5336         *(unsigned long *)ptr += freed_pages;
5337         return NOTIFY_DONE;
5338 }
5339
5340 struct i915_vma *i915_gem_obj_to_ggtt(struct drm_i915_gem_object *obj)
5341 {
5342         struct i915_address_space *ggtt = i915_obj_to_ggtt(obj);
5343         struct i915_vma *vma;
5344
5345         list_for_each_entry(vma, &obj->vma_list, vma_link)
5346                 if (vma->vm == ggtt &&
5347                     vma->ggtt_view.type == I915_GGTT_VIEW_NORMAL)
5348                         return vma;
5349
5350         return NULL;
5351 }