OSDN Git Service

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