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