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