Merge drm/drm-next into drm-intel-next-queued
[sfrench/cifs-2.6.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/drm_vma_manager.h>
29 #include <drm/drm_pci.h>
30 #include <drm/i915_drm.h>
31 #include <linux/dma-fence-array.h>
32 #include <linux/kthread.h>
33 #include <linux/reservation.h>
34 #include <linux/shmem_fs.h>
35 #include <linux/slab.h>
36 #include <linux/stop_machine.h>
37 #include <linux/swap.h>
38 #include <linux/pci.h>
39 #include <linux/dma-buf.h>
40 #include <linux/mman.h>
41
42 #include "i915_drv.h"
43 #include "i915_gem_clflush.h"
44 #include "i915_gemfs.h"
45 #include "i915_globals.h"
46 #include "i915_reset.h"
47 #include "i915_trace.h"
48 #include "i915_vgpu.h"
49
50 #include "intel_drv.h"
51 #include "intel_frontbuffer.h"
52 #include "intel_mocs.h"
53 #include "intel_workarounds.h"
54
55 static void i915_gem_flush_free_objects(struct drm_i915_private *i915);
56
57 static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
58 {
59         if (obj->cache_dirty)
60                 return false;
61
62         if (!(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE))
63                 return true;
64
65         return obj->pin_global; /* currently in use by HW, keep flushed */
66 }
67
68 static int
69 insert_mappable_node(struct i915_ggtt *ggtt,
70                      struct drm_mm_node *node, u32 size)
71 {
72         memset(node, 0, sizeof(*node));
73         return drm_mm_insert_node_in_range(&ggtt->vm.mm, node,
74                                            size, 0, I915_COLOR_UNEVICTABLE,
75                                            0, ggtt->mappable_end,
76                                            DRM_MM_INSERT_LOW);
77 }
78
79 static void
80 remove_mappable_node(struct drm_mm_node *node)
81 {
82         drm_mm_remove_node(node);
83 }
84
85 /* some bookkeeping */
86 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
87                                   u64 size)
88 {
89         spin_lock(&dev_priv->mm.object_stat_lock);
90         dev_priv->mm.object_count++;
91         dev_priv->mm.object_memory += size;
92         spin_unlock(&dev_priv->mm.object_stat_lock);
93 }
94
95 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
96                                      u64 size)
97 {
98         spin_lock(&dev_priv->mm.object_stat_lock);
99         dev_priv->mm.object_count--;
100         dev_priv->mm.object_memory -= size;
101         spin_unlock(&dev_priv->mm.object_stat_lock);
102 }
103
104 static void __i915_gem_park(struct drm_i915_private *i915)
105 {
106         intel_wakeref_t wakeref;
107
108         GEM_TRACE("\n");
109
110         lockdep_assert_held(&i915->drm.struct_mutex);
111         GEM_BUG_ON(i915->gt.active_requests);
112         GEM_BUG_ON(!list_empty(&i915->gt.active_rings));
113
114         if (!i915->gt.awake)
115                 return;
116
117         /*
118          * Be paranoid and flush a concurrent interrupt to make sure
119          * we don't reactivate any irq tasklets after parking.
120          *
121          * FIXME: Note that even though we have waited for execlists to be idle,
122          * there may still be an in-flight interrupt even though the CSB
123          * is now empty. synchronize_irq() makes sure that a residual interrupt
124          * is completed before we continue, but it doesn't prevent the HW from
125          * raising a spurious interrupt later. To complete the shield we should
126          * coordinate disabling the CS irq with flushing the interrupts.
127          */
128         synchronize_irq(i915->drm.irq);
129
130         intel_engines_park(i915);
131         i915_timelines_park(i915);
132
133         i915_pmu_gt_parked(i915);
134         i915_vma_parked(i915);
135
136         wakeref = fetch_and_zero(&i915->gt.awake);
137         GEM_BUG_ON(!wakeref);
138
139         if (INTEL_GEN(i915) >= 6)
140                 gen6_rps_idle(i915);
141
142         intel_display_power_put(i915, POWER_DOMAIN_GT_IRQ, wakeref);
143
144         i915_globals_park();
145 }
146
147 void i915_gem_park(struct drm_i915_private *i915)
148 {
149         GEM_TRACE("\n");
150
151         lockdep_assert_held(&i915->drm.struct_mutex);
152         GEM_BUG_ON(i915->gt.active_requests);
153
154         if (!i915->gt.awake)
155                 return;
156
157         /* Defer the actual call to __i915_gem_park() to prevent ping-pongs */
158         mod_delayed_work(i915->wq, &i915->gt.idle_work, msecs_to_jiffies(100));
159 }
160
161 void i915_gem_unpark(struct drm_i915_private *i915)
162 {
163         GEM_TRACE("\n");
164
165         lockdep_assert_held(&i915->drm.struct_mutex);
166         GEM_BUG_ON(!i915->gt.active_requests);
167         assert_rpm_wakelock_held(i915);
168
169         if (i915->gt.awake)
170                 return;
171
172         /*
173          * It seems that the DMC likes to transition between the DC states a lot
174          * when there are no connected displays (no active power domains) during
175          * command submission.
176          *
177          * This activity has negative impact on the performance of the chip with
178          * huge latencies observed in the interrupt handler and elsewhere.
179          *
180          * Work around it by grabbing a GT IRQ power domain whilst there is any
181          * GT activity, preventing any DC state transitions.
182          */
183         i915->gt.awake = intel_display_power_get(i915, POWER_DOMAIN_GT_IRQ);
184         GEM_BUG_ON(!i915->gt.awake);
185
186         i915_globals_unpark();
187
188         intel_enable_gt_powersave(i915);
189         i915_update_gfx_val(i915);
190         if (INTEL_GEN(i915) >= 6)
191                 gen6_rps_busy(i915);
192         i915_pmu_gt_unparked(i915);
193
194         intel_engines_unpark(i915);
195
196         i915_queue_hangcheck(i915);
197
198         queue_delayed_work(i915->wq,
199                            &i915->gt.retire_work,
200                            round_jiffies_up_relative(HZ));
201 }
202
203 int
204 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
205                             struct drm_file *file)
206 {
207         struct i915_ggtt *ggtt = &to_i915(dev)->ggtt;
208         struct drm_i915_gem_get_aperture *args = data;
209         struct i915_vma *vma;
210         u64 pinned;
211
212         mutex_lock(&ggtt->vm.mutex);
213
214         pinned = ggtt->vm.reserved;
215         list_for_each_entry(vma, &ggtt->vm.bound_list, vm_link)
216                 if (i915_vma_is_pinned(vma))
217                         pinned += vma->node.size;
218
219         mutex_unlock(&ggtt->vm.mutex);
220
221         args->aper_size = ggtt->vm.total;
222         args->aper_available_size = args->aper_size - pinned;
223
224         return 0;
225 }
226
227 static int i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
228 {
229         struct address_space *mapping = obj->base.filp->f_mapping;
230         drm_dma_handle_t *phys;
231         struct sg_table *st;
232         struct scatterlist *sg;
233         char *vaddr;
234         int i;
235         int err;
236
237         if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
238                 return -EINVAL;
239
240         /* Always aligning to the object size, allows a single allocation
241          * to handle all possible callers, and given typical object sizes,
242          * the alignment of the buddy allocation will naturally match.
243          */
244         phys = drm_pci_alloc(obj->base.dev,
245                              roundup_pow_of_two(obj->base.size),
246                              roundup_pow_of_two(obj->base.size));
247         if (!phys)
248                 return -ENOMEM;
249
250         vaddr = phys->vaddr;
251         for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
252                 struct page *page;
253                 char *src;
254
255                 page = shmem_read_mapping_page(mapping, i);
256                 if (IS_ERR(page)) {
257                         err = PTR_ERR(page);
258                         goto err_phys;
259                 }
260
261                 src = kmap_atomic(page);
262                 memcpy(vaddr, src, PAGE_SIZE);
263                 drm_clflush_virt_range(vaddr, PAGE_SIZE);
264                 kunmap_atomic(src);
265
266                 put_page(page);
267                 vaddr += PAGE_SIZE;
268         }
269
270         i915_gem_chipset_flush(to_i915(obj->base.dev));
271
272         st = kmalloc(sizeof(*st), GFP_KERNEL);
273         if (!st) {
274                 err = -ENOMEM;
275                 goto err_phys;
276         }
277
278         if (sg_alloc_table(st, 1, GFP_KERNEL)) {
279                 kfree(st);
280                 err = -ENOMEM;
281                 goto err_phys;
282         }
283
284         sg = st->sgl;
285         sg->offset = 0;
286         sg->length = obj->base.size;
287
288         sg_dma_address(sg) = phys->busaddr;
289         sg_dma_len(sg) = obj->base.size;
290
291         obj->phys_handle = phys;
292
293         __i915_gem_object_set_pages(obj, st, sg->length);
294
295         return 0;
296
297 err_phys:
298         drm_pci_free(obj->base.dev, phys);
299
300         return err;
301 }
302
303 static void __start_cpu_write(struct drm_i915_gem_object *obj)
304 {
305         obj->read_domains = I915_GEM_DOMAIN_CPU;
306         obj->write_domain = I915_GEM_DOMAIN_CPU;
307         if (cpu_write_needs_clflush(obj))
308                 obj->cache_dirty = true;
309 }
310
311 static void
312 __i915_gem_object_release_shmem(struct drm_i915_gem_object *obj,
313                                 struct sg_table *pages,
314                                 bool needs_clflush)
315 {
316         GEM_BUG_ON(obj->mm.madv == __I915_MADV_PURGED);
317
318         if (obj->mm.madv == I915_MADV_DONTNEED)
319                 obj->mm.dirty = false;
320
321         if (needs_clflush &&
322             (obj->read_domains & I915_GEM_DOMAIN_CPU) == 0 &&
323             !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ))
324                 drm_clflush_sg(pages);
325
326         __start_cpu_write(obj);
327 }
328
329 static void
330 i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj,
331                                struct sg_table *pages)
332 {
333         __i915_gem_object_release_shmem(obj, pages, false);
334
335         if (obj->mm.dirty) {
336                 struct address_space *mapping = obj->base.filp->f_mapping;
337                 char *vaddr = obj->phys_handle->vaddr;
338                 int i;
339
340                 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
341                         struct page *page;
342                         char *dst;
343
344                         page = shmem_read_mapping_page(mapping, i);
345                         if (IS_ERR(page))
346                                 continue;
347
348                         dst = kmap_atomic(page);
349                         drm_clflush_virt_range(vaddr, PAGE_SIZE);
350                         memcpy(dst, vaddr, PAGE_SIZE);
351                         kunmap_atomic(dst);
352
353                         set_page_dirty(page);
354                         if (obj->mm.madv == I915_MADV_WILLNEED)
355                                 mark_page_accessed(page);
356                         put_page(page);
357                         vaddr += PAGE_SIZE;
358                 }
359                 obj->mm.dirty = false;
360         }
361
362         sg_free_table(pages);
363         kfree(pages);
364
365         drm_pci_free(obj->base.dev, obj->phys_handle);
366 }
367
368 static void
369 i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
370 {
371         i915_gem_object_unpin_pages(obj);
372 }
373
374 static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
375         .get_pages = i915_gem_object_get_pages_phys,
376         .put_pages = i915_gem_object_put_pages_phys,
377         .release = i915_gem_object_release_phys,
378 };
379
380 static const struct drm_i915_gem_object_ops i915_gem_object_ops;
381
382 int i915_gem_object_unbind(struct drm_i915_gem_object *obj)
383 {
384         struct i915_vma *vma;
385         LIST_HEAD(still_in_list);
386         int ret;
387
388         lockdep_assert_held(&obj->base.dev->struct_mutex);
389
390         /* Closed vma are removed from the obj->vma_list - but they may
391          * still have an active binding on the object. To remove those we
392          * must wait for all rendering to complete to the object (as unbinding
393          * must anyway), and retire the requests.
394          */
395         ret = i915_gem_object_set_to_cpu_domain(obj, false);
396         if (ret)
397                 return ret;
398
399         spin_lock(&obj->vma.lock);
400         while (!ret && (vma = list_first_entry_or_null(&obj->vma.list,
401                                                        struct i915_vma,
402                                                        obj_link))) {
403                 list_move_tail(&vma->obj_link, &still_in_list);
404                 spin_unlock(&obj->vma.lock);
405
406                 ret = i915_vma_unbind(vma);
407
408                 spin_lock(&obj->vma.lock);
409         }
410         list_splice(&still_in_list, &obj->vma.list);
411         spin_unlock(&obj->vma.lock);
412
413         return ret;
414 }
415
416 static long
417 i915_gem_object_wait_fence(struct dma_fence *fence,
418                            unsigned int flags,
419                            long timeout)
420 {
421         struct i915_request *rq;
422
423         BUILD_BUG_ON(I915_WAIT_INTERRUPTIBLE != 0x1);
424
425         if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
426                 return timeout;
427
428         if (!dma_fence_is_i915(fence))
429                 return dma_fence_wait_timeout(fence,
430                                               flags & I915_WAIT_INTERRUPTIBLE,
431                                               timeout);
432
433         rq = to_request(fence);
434         if (i915_request_completed(rq))
435                 goto out;
436
437         timeout = i915_request_wait(rq, flags, timeout);
438
439 out:
440         if (flags & I915_WAIT_LOCKED && i915_request_completed(rq))
441                 i915_request_retire_upto(rq);
442
443         return timeout;
444 }
445
446 static long
447 i915_gem_object_wait_reservation(struct reservation_object *resv,
448                                  unsigned int flags,
449                                  long timeout)
450 {
451         unsigned int seq = __read_seqcount_begin(&resv->seq);
452         struct dma_fence *excl;
453         bool prune_fences = false;
454
455         if (flags & I915_WAIT_ALL) {
456                 struct dma_fence **shared;
457                 unsigned int count, i;
458                 int ret;
459
460                 ret = reservation_object_get_fences_rcu(resv,
461                                                         &excl, &count, &shared);
462                 if (ret)
463                         return ret;
464
465                 for (i = 0; i < count; i++) {
466                         timeout = i915_gem_object_wait_fence(shared[i],
467                                                              flags, timeout);
468                         if (timeout < 0)
469                                 break;
470
471                         dma_fence_put(shared[i]);
472                 }
473
474                 for (; i < count; i++)
475                         dma_fence_put(shared[i]);
476                 kfree(shared);
477
478                 /*
479                  * If both shared fences and an exclusive fence exist,
480                  * then by construction the shared fences must be later
481                  * than the exclusive fence. If we successfully wait for
482                  * all the shared fences, we know that the exclusive fence
483                  * must all be signaled. If all the shared fences are
484                  * signaled, we can prune the array and recover the
485                  * floating references on the fences/requests.
486                  */
487                 prune_fences = count && timeout >= 0;
488         } else {
489                 excl = reservation_object_get_excl_rcu(resv);
490         }
491
492         if (excl && timeout >= 0)
493                 timeout = i915_gem_object_wait_fence(excl, flags, timeout);
494
495         dma_fence_put(excl);
496
497         /*
498          * Opportunistically prune the fences iff we know they have *all* been
499          * signaled and that the reservation object has not been changed (i.e.
500          * no new fences have been added).
501          */
502         if (prune_fences && !__read_seqcount_retry(&resv->seq, seq)) {
503                 if (reservation_object_trylock(resv)) {
504                         if (!__read_seqcount_retry(&resv->seq, seq))
505                                 reservation_object_add_excl_fence(resv, NULL);
506                         reservation_object_unlock(resv);
507                 }
508         }
509
510         return timeout;
511 }
512
513 static void __fence_set_priority(struct dma_fence *fence,
514                                  const struct i915_sched_attr *attr)
515 {
516         struct i915_request *rq;
517         struct intel_engine_cs *engine;
518
519         if (dma_fence_is_signaled(fence) || !dma_fence_is_i915(fence))
520                 return;
521
522         rq = to_request(fence);
523         engine = rq->engine;
524
525         local_bh_disable();
526         rcu_read_lock(); /* RCU serialisation for set-wedged protection */
527         if (engine->schedule)
528                 engine->schedule(rq, attr);
529         rcu_read_unlock();
530         local_bh_enable(); /* kick the tasklets if queues were reprioritised */
531 }
532
533 static void fence_set_priority(struct dma_fence *fence,
534                                const struct i915_sched_attr *attr)
535 {
536         /* Recurse once into a fence-array */
537         if (dma_fence_is_array(fence)) {
538                 struct dma_fence_array *array = to_dma_fence_array(fence);
539                 int i;
540
541                 for (i = 0; i < array->num_fences; i++)
542                         __fence_set_priority(array->fences[i], attr);
543         } else {
544                 __fence_set_priority(fence, attr);
545         }
546 }
547
548 int
549 i915_gem_object_wait_priority(struct drm_i915_gem_object *obj,
550                               unsigned int flags,
551                               const struct i915_sched_attr *attr)
552 {
553         struct dma_fence *excl;
554
555         if (flags & I915_WAIT_ALL) {
556                 struct dma_fence **shared;
557                 unsigned int count, i;
558                 int ret;
559
560                 ret = reservation_object_get_fences_rcu(obj->resv,
561                                                         &excl, &count, &shared);
562                 if (ret)
563                         return ret;
564
565                 for (i = 0; i < count; i++) {
566                         fence_set_priority(shared[i], attr);
567                         dma_fence_put(shared[i]);
568                 }
569
570                 kfree(shared);
571         } else {
572                 excl = reservation_object_get_excl_rcu(obj->resv);
573         }
574
575         if (excl) {
576                 fence_set_priority(excl, attr);
577                 dma_fence_put(excl);
578         }
579         return 0;
580 }
581
582 /**
583  * Waits for rendering to the object to be completed
584  * @obj: i915 gem object
585  * @flags: how to wait (under a lock, for all rendering or just for writes etc)
586  * @timeout: how long to wait
587  */
588 int
589 i915_gem_object_wait(struct drm_i915_gem_object *obj,
590                      unsigned int flags,
591                      long timeout)
592 {
593         might_sleep();
594         GEM_BUG_ON(timeout < 0);
595
596         timeout = i915_gem_object_wait_reservation(obj->resv, flags, timeout);
597         return timeout < 0 ? timeout : 0;
598 }
599
600 static int
601 i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
602                      struct drm_i915_gem_pwrite *args,
603                      struct drm_file *file)
604 {
605         void *vaddr = obj->phys_handle->vaddr + args->offset;
606         char __user *user_data = u64_to_user_ptr(args->data_ptr);
607
608         /* We manually control the domain here and pretend that it
609          * remains coherent i.e. in the GTT domain, like shmem_pwrite.
610          */
611         intel_fb_obj_invalidate(obj, ORIGIN_CPU);
612         if (copy_from_user(vaddr, user_data, args->size))
613                 return -EFAULT;
614
615         drm_clflush_virt_range(vaddr, args->size);
616         i915_gem_chipset_flush(to_i915(obj->base.dev));
617
618         intel_fb_obj_flush(obj, ORIGIN_CPU);
619         return 0;
620 }
621
622 static int
623 i915_gem_create(struct drm_file *file,
624                 struct drm_i915_private *dev_priv,
625                 u64 *size_p,
626                 u32 *handle_p)
627 {
628         struct drm_i915_gem_object *obj;
629         u32 handle;
630         u64 size;
631         int ret;
632
633         size = round_up(*size_p, PAGE_SIZE);
634         if (size == 0)
635                 return -EINVAL;
636
637         /* Allocate the new object */
638         obj = i915_gem_object_create(dev_priv, size);
639         if (IS_ERR(obj))
640                 return PTR_ERR(obj);
641
642         ret = drm_gem_handle_create(file, &obj->base, &handle);
643         /* drop reference from allocate - handle holds it now */
644         i915_gem_object_put(obj);
645         if (ret)
646                 return ret;
647
648         *handle_p = handle;
649         *size_p = obj->base.size;
650         return 0;
651 }
652
653 int
654 i915_gem_dumb_create(struct drm_file *file,
655                      struct drm_device *dev,
656                      struct drm_mode_create_dumb *args)
657 {
658         /* have to work out size/pitch and return them */
659         args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
660         args->size = args->pitch * args->height;
661         return i915_gem_create(file, to_i915(dev),
662                                &args->size, &args->handle);
663 }
664
665 static bool gpu_write_needs_clflush(struct drm_i915_gem_object *obj)
666 {
667         return !(obj->cache_level == I915_CACHE_NONE ||
668                  obj->cache_level == I915_CACHE_WT);
669 }
670
671 /**
672  * Creates a new mm object and returns a handle to it.
673  * @dev: drm device pointer
674  * @data: ioctl data blob
675  * @file: drm file pointer
676  */
677 int
678 i915_gem_create_ioctl(struct drm_device *dev, void *data,
679                       struct drm_file *file)
680 {
681         struct drm_i915_private *dev_priv = to_i915(dev);
682         struct drm_i915_gem_create *args = data;
683
684         i915_gem_flush_free_objects(dev_priv);
685
686         return i915_gem_create(file, dev_priv,
687                                &args->size, &args->handle);
688 }
689
690 static inline enum fb_op_origin
691 fb_write_origin(struct drm_i915_gem_object *obj, unsigned int domain)
692 {
693         return (domain == I915_GEM_DOMAIN_GTT ?
694                 obj->frontbuffer_ggtt_origin : ORIGIN_CPU);
695 }
696
697 void i915_gem_flush_ggtt_writes(struct drm_i915_private *dev_priv)
698 {
699         intel_wakeref_t wakeref;
700
701         /*
702          * No actual flushing is required for the GTT write domain for reads
703          * from the GTT domain. Writes to it "immediately" go to main memory
704          * as far as we know, so there's no chipset flush. It also doesn't
705          * land in the GPU render cache.
706          *
707          * However, we do have to enforce the order so that all writes through
708          * the GTT land before any writes to the device, such as updates to
709          * the GATT itself.
710          *
711          * We also have to wait a bit for the writes to land from the GTT.
712          * An uncached read (i.e. mmio) seems to be ideal for the round-trip
713          * timing. This issue has only been observed when switching quickly
714          * between GTT writes and CPU reads from inside the kernel on recent hw,
715          * and it appears to only affect discrete GTT blocks (i.e. on LLC
716          * system agents we cannot reproduce this behaviour, until Cannonlake
717          * that was!).
718          */
719
720         wmb();
721
722         if (INTEL_INFO(dev_priv)->has_coherent_ggtt)
723                 return;
724
725         i915_gem_chipset_flush(dev_priv);
726
727         with_intel_runtime_pm(dev_priv, wakeref) {
728                 spin_lock_irq(&dev_priv->uncore.lock);
729
730                 POSTING_READ_FW(RING_HEAD(RENDER_RING_BASE));
731
732                 spin_unlock_irq(&dev_priv->uncore.lock);
733         }
734 }
735
736 static void
737 flush_write_domain(struct drm_i915_gem_object *obj, unsigned int flush_domains)
738 {
739         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
740         struct i915_vma *vma;
741
742         if (!(obj->write_domain & flush_domains))
743                 return;
744
745         switch (obj->write_domain) {
746         case I915_GEM_DOMAIN_GTT:
747                 i915_gem_flush_ggtt_writes(dev_priv);
748
749                 intel_fb_obj_flush(obj,
750                                    fb_write_origin(obj, I915_GEM_DOMAIN_GTT));
751
752                 for_each_ggtt_vma(vma, obj) {
753                         if (vma->iomap)
754                                 continue;
755
756                         i915_vma_unset_ggtt_write(vma);
757                 }
758                 break;
759
760         case I915_GEM_DOMAIN_WC:
761                 wmb();
762                 break;
763
764         case I915_GEM_DOMAIN_CPU:
765                 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
766                 break;
767
768         case I915_GEM_DOMAIN_RENDER:
769                 if (gpu_write_needs_clflush(obj))
770                         obj->cache_dirty = true;
771                 break;
772         }
773
774         obj->write_domain = 0;
775 }
776
777 /*
778  * Pins the specified object's pages and synchronizes the object with
779  * GPU accesses. Sets needs_clflush to non-zero if the caller should
780  * flush the object from the CPU cache.
781  */
782 int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
783                                     unsigned int *needs_clflush)
784 {
785         int ret;
786
787         lockdep_assert_held(&obj->base.dev->struct_mutex);
788
789         *needs_clflush = 0;
790         if (!i915_gem_object_has_struct_page(obj))
791                 return -ENODEV;
792
793         ret = i915_gem_object_wait(obj,
794                                    I915_WAIT_INTERRUPTIBLE |
795                                    I915_WAIT_LOCKED,
796                                    MAX_SCHEDULE_TIMEOUT);
797         if (ret)
798                 return ret;
799
800         ret = i915_gem_object_pin_pages(obj);
801         if (ret)
802                 return ret;
803
804         if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ ||
805             !static_cpu_has(X86_FEATURE_CLFLUSH)) {
806                 ret = i915_gem_object_set_to_cpu_domain(obj, false);
807                 if (ret)
808                         goto err_unpin;
809                 else
810                         goto out;
811         }
812
813         flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
814
815         /* If we're not in the cpu read domain, set ourself into the gtt
816          * read domain and manually flush cachelines (if required). This
817          * optimizes for the case when the gpu will dirty the data
818          * anyway again before the next pread happens.
819          */
820         if (!obj->cache_dirty &&
821             !(obj->read_domains & I915_GEM_DOMAIN_CPU))
822                 *needs_clflush = CLFLUSH_BEFORE;
823
824 out:
825         /* return with the pages pinned */
826         return 0;
827
828 err_unpin:
829         i915_gem_object_unpin_pages(obj);
830         return ret;
831 }
832
833 int i915_gem_obj_prepare_shmem_write(struct drm_i915_gem_object *obj,
834                                      unsigned int *needs_clflush)
835 {
836         int ret;
837
838         lockdep_assert_held(&obj->base.dev->struct_mutex);
839
840         *needs_clflush = 0;
841         if (!i915_gem_object_has_struct_page(obj))
842                 return -ENODEV;
843
844         ret = i915_gem_object_wait(obj,
845                                    I915_WAIT_INTERRUPTIBLE |
846                                    I915_WAIT_LOCKED |
847                                    I915_WAIT_ALL,
848                                    MAX_SCHEDULE_TIMEOUT);
849         if (ret)
850                 return ret;
851
852         ret = i915_gem_object_pin_pages(obj);
853         if (ret)
854                 return ret;
855
856         if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE ||
857             !static_cpu_has(X86_FEATURE_CLFLUSH)) {
858                 ret = i915_gem_object_set_to_cpu_domain(obj, true);
859                 if (ret)
860                         goto err_unpin;
861                 else
862                         goto out;
863         }
864
865         flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
866
867         /* If we're not in the cpu write domain, set ourself into the
868          * gtt write domain and manually flush cachelines (as required).
869          * This optimizes for the case when the gpu will use the data
870          * right away and we therefore have to clflush anyway.
871          */
872         if (!obj->cache_dirty) {
873                 *needs_clflush |= CLFLUSH_AFTER;
874
875                 /*
876                  * Same trick applies to invalidate partially written
877                  * cachelines read before writing.
878                  */
879                 if (!(obj->read_domains & I915_GEM_DOMAIN_CPU))
880                         *needs_clflush |= CLFLUSH_BEFORE;
881         }
882
883 out:
884         intel_fb_obj_invalidate(obj, ORIGIN_CPU);
885         obj->mm.dirty = true;
886         /* return with the pages pinned */
887         return 0;
888
889 err_unpin:
890         i915_gem_object_unpin_pages(obj);
891         return ret;
892 }
893
894 static int
895 shmem_pread(struct page *page, int offset, int len, char __user *user_data,
896             bool needs_clflush)
897 {
898         char *vaddr;
899         int ret;
900
901         vaddr = kmap(page);
902
903         if (needs_clflush)
904                 drm_clflush_virt_range(vaddr + offset, len);
905
906         ret = __copy_to_user(user_data, vaddr + offset, len);
907
908         kunmap(page);
909
910         return ret ? -EFAULT : 0;
911 }
912
913 static int
914 i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
915                      struct drm_i915_gem_pread *args)
916 {
917         char __user *user_data;
918         u64 remain;
919         unsigned int needs_clflush;
920         unsigned int idx, offset;
921         int ret;
922
923         ret = mutex_lock_interruptible(&obj->base.dev->struct_mutex);
924         if (ret)
925                 return ret;
926
927         ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
928         mutex_unlock(&obj->base.dev->struct_mutex);
929         if (ret)
930                 return ret;
931
932         remain = args->size;
933         user_data = u64_to_user_ptr(args->data_ptr);
934         offset = offset_in_page(args->offset);
935         for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
936                 struct page *page = i915_gem_object_get_page(obj, idx);
937                 unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
938
939                 ret = shmem_pread(page, offset, length, user_data,
940                                   needs_clflush);
941                 if (ret)
942                         break;
943
944                 remain -= length;
945                 user_data += length;
946                 offset = 0;
947         }
948
949         i915_gem_obj_finish_shmem_access(obj);
950         return ret;
951 }
952
953 static inline bool
954 gtt_user_read(struct io_mapping *mapping,
955               loff_t base, int offset,
956               char __user *user_data, int length)
957 {
958         void __iomem *vaddr;
959         unsigned long unwritten;
960
961         /* We can use the cpu mem copy function because this is X86. */
962         vaddr = io_mapping_map_atomic_wc(mapping, base);
963         unwritten = __copy_to_user_inatomic(user_data,
964                                             (void __force *)vaddr + offset,
965                                             length);
966         io_mapping_unmap_atomic(vaddr);
967         if (unwritten) {
968                 vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
969                 unwritten = copy_to_user(user_data,
970                                          (void __force *)vaddr + offset,
971                                          length);
972                 io_mapping_unmap(vaddr);
973         }
974         return unwritten;
975 }
976
977 static int
978 i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
979                    const struct drm_i915_gem_pread *args)
980 {
981         struct drm_i915_private *i915 = to_i915(obj->base.dev);
982         struct i915_ggtt *ggtt = &i915->ggtt;
983         intel_wakeref_t wakeref;
984         struct drm_mm_node node;
985         struct i915_vma *vma;
986         void __user *user_data;
987         u64 remain, offset;
988         int ret;
989
990         ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
991         if (ret)
992                 return ret;
993
994         wakeref = intel_runtime_pm_get(i915);
995         vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
996                                        PIN_MAPPABLE |
997                                        PIN_NONFAULT |
998                                        PIN_NONBLOCK);
999         if (!IS_ERR(vma)) {
1000                 node.start = i915_ggtt_offset(vma);
1001                 node.allocated = false;
1002                 ret = i915_vma_put_fence(vma);
1003                 if (ret) {
1004                         i915_vma_unpin(vma);
1005                         vma = ERR_PTR(ret);
1006                 }
1007         }
1008         if (IS_ERR(vma)) {
1009                 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
1010                 if (ret)
1011                         goto out_unlock;
1012                 GEM_BUG_ON(!node.allocated);
1013         }
1014
1015         ret = i915_gem_object_set_to_gtt_domain(obj, false);
1016         if (ret)
1017                 goto out_unpin;
1018
1019         mutex_unlock(&i915->drm.struct_mutex);
1020
1021         user_data = u64_to_user_ptr(args->data_ptr);
1022         remain = args->size;
1023         offset = args->offset;
1024
1025         while (remain > 0) {
1026                 /* Operation in this page
1027                  *
1028                  * page_base = page offset within aperture
1029                  * page_offset = offset within page
1030                  * page_length = bytes to copy for this page
1031                  */
1032                 u32 page_base = node.start;
1033                 unsigned page_offset = offset_in_page(offset);
1034                 unsigned page_length = PAGE_SIZE - page_offset;
1035                 page_length = remain < page_length ? remain : page_length;
1036                 if (node.allocated) {
1037                         wmb();
1038                         ggtt->vm.insert_page(&ggtt->vm,
1039                                              i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1040                                              node.start, I915_CACHE_NONE, 0);
1041                         wmb();
1042                 } else {
1043                         page_base += offset & PAGE_MASK;
1044                 }
1045
1046                 if (gtt_user_read(&ggtt->iomap, page_base, page_offset,
1047                                   user_data, page_length)) {
1048                         ret = -EFAULT;
1049                         break;
1050                 }
1051
1052                 remain -= page_length;
1053                 user_data += page_length;
1054                 offset += page_length;
1055         }
1056
1057         mutex_lock(&i915->drm.struct_mutex);
1058 out_unpin:
1059         if (node.allocated) {
1060                 wmb();
1061                 ggtt->vm.clear_range(&ggtt->vm, node.start, node.size);
1062                 remove_mappable_node(&node);
1063         } else {
1064                 i915_vma_unpin(vma);
1065         }
1066 out_unlock:
1067         intel_runtime_pm_put(i915, wakeref);
1068         mutex_unlock(&i915->drm.struct_mutex);
1069
1070         return ret;
1071 }
1072
1073 /**
1074  * Reads data from the object referenced by handle.
1075  * @dev: drm device pointer
1076  * @data: ioctl data blob
1077  * @file: drm file pointer
1078  *
1079  * On error, the contents of *data are undefined.
1080  */
1081 int
1082 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
1083                      struct drm_file *file)
1084 {
1085         struct drm_i915_gem_pread *args = data;
1086         struct drm_i915_gem_object *obj;
1087         int ret;
1088
1089         if (args->size == 0)
1090                 return 0;
1091
1092         if (!access_ok(u64_to_user_ptr(args->data_ptr),
1093                        args->size))
1094                 return -EFAULT;
1095
1096         obj = i915_gem_object_lookup(file, args->handle);
1097         if (!obj)
1098                 return -ENOENT;
1099
1100         /* Bounds check source.  */
1101         if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
1102                 ret = -EINVAL;
1103                 goto out;
1104         }
1105
1106         trace_i915_gem_object_pread(obj, args->offset, args->size);
1107
1108         ret = i915_gem_object_wait(obj,
1109                                    I915_WAIT_INTERRUPTIBLE,
1110                                    MAX_SCHEDULE_TIMEOUT);
1111         if (ret)
1112                 goto out;
1113
1114         ret = i915_gem_object_pin_pages(obj);
1115         if (ret)
1116                 goto out;
1117
1118         ret = i915_gem_shmem_pread(obj, args);
1119         if (ret == -EFAULT || ret == -ENODEV)
1120                 ret = i915_gem_gtt_pread(obj, args);
1121
1122         i915_gem_object_unpin_pages(obj);
1123 out:
1124         i915_gem_object_put(obj);
1125         return ret;
1126 }
1127
1128 /* This is the fast write path which cannot handle
1129  * page faults in the source data
1130  */
1131
1132 static inline bool
1133 ggtt_write(struct io_mapping *mapping,
1134            loff_t base, int offset,
1135            char __user *user_data, int length)
1136 {
1137         void __iomem *vaddr;
1138         unsigned long unwritten;
1139
1140         /* We can use the cpu mem copy function because this is X86. */
1141         vaddr = io_mapping_map_atomic_wc(mapping, base);
1142         unwritten = __copy_from_user_inatomic_nocache((void __force *)vaddr + offset,
1143                                                       user_data, length);
1144         io_mapping_unmap_atomic(vaddr);
1145         if (unwritten) {
1146                 vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
1147                 unwritten = copy_from_user((void __force *)vaddr + offset,
1148                                            user_data, length);
1149                 io_mapping_unmap(vaddr);
1150         }
1151
1152         return unwritten;
1153 }
1154
1155 /**
1156  * This is the fast pwrite path, where we copy the data directly from the
1157  * user into the GTT, uncached.
1158  * @obj: i915 GEM object
1159  * @args: pwrite arguments structure
1160  */
1161 static int
1162 i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
1163                          const struct drm_i915_gem_pwrite *args)
1164 {
1165         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1166         struct i915_ggtt *ggtt = &i915->ggtt;
1167         intel_wakeref_t wakeref;
1168         struct drm_mm_node node;
1169         struct i915_vma *vma;
1170         u64 remain, offset;
1171         void __user *user_data;
1172         int ret;
1173
1174         ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1175         if (ret)
1176                 return ret;
1177
1178         if (i915_gem_object_has_struct_page(obj)) {
1179                 /*
1180                  * Avoid waking the device up if we can fallback, as
1181                  * waking/resuming is very slow (worst-case 10-100 ms
1182                  * depending on PCI sleeps and our own resume time).
1183                  * This easily dwarfs any performance advantage from
1184                  * using the cache bypass of indirect GGTT access.
1185                  */
1186                 wakeref = intel_runtime_pm_get_if_in_use(i915);
1187                 if (!wakeref) {
1188                         ret = -EFAULT;
1189                         goto out_unlock;
1190                 }
1191         } else {
1192                 /* No backing pages, no fallback, we must force GGTT access */
1193                 wakeref = intel_runtime_pm_get(i915);
1194         }
1195
1196         vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1197                                        PIN_MAPPABLE |
1198                                        PIN_NONFAULT |
1199                                        PIN_NONBLOCK);
1200         if (!IS_ERR(vma)) {
1201                 node.start = i915_ggtt_offset(vma);
1202                 node.allocated = false;
1203                 ret = i915_vma_put_fence(vma);
1204                 if (ret) {
1205                         i915_vma_unpin(vma);
1206                         vma = ERR_PTR(ret);
1207                 }
1208         }
1209         if (IS_ERR(vma)) {
1210                 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
1211                 if (ret)
1212                         goto out_rpm;
1213                 GEM_BUG_ON(!node.allocated);
1214         }
1215
1216         ret = i915_gem_object_set_to_gtt_domain(obj, true);
1217         if (ret)
1218                 goto out_unpin;
1219
1220         mutex_unlock(&i915->drm.struct_mutex);
1221
1222         intel_fb_obj_invalidate(obj, ORIGIN_CPU);
1223
1224         user_data = u64_to_user_ptr(args->data_ptr);
1225         offset = args->offset;
1226         remain = args->size;
1227         while (remain) {
1228                 /* Operation in this page
1229                  *
1230                  * page_base = page offset within aperture
1231                  * page_offset = offset within page
1232                  * page_length = bytes to copy for this page
1233                  */
1234                 u32 page_base = node.start;
1235                 unsigned int page_offset = offset_in_page(offset);
1236                 unsigned int page_length = PAGE_SIZE - page_offset;
1237                 page_length = remain < page_length ? remain : page_length;
1238                 if (node.allocated) {
1239                         wmb(); /* flush the write before we modify the GGTT */
1240                         ggtt->vm.insert_page(&ggtt->vm,
1241                                              i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1242                                              node.start, I915_CACHE_NONE, 0);
1243                         wmb(); /* flush modifications to the GGTT (insert_page) */
1244                 } else {
1245                         page_base += offset & PAGE_MASK;
1246                 }
1247                 /* If we get a fault while copying data, then (presumably) our
1248                  * source page isn't available.  Return the error and we'll
1249                  * retry in the slow path.
1250                  * If the object is non-shmem backed, we retry again with the
1251                  * path that handles page fault.
1252                  */
1253                 if (ggtt_write(&ggtt->iomap, page_base, page_offset,
1254                                user_data, page_length)) {
1255                         ret = -EFAULT;
1256                         break;
1257                 }
1258
1259                 remain -= page_length;
1260                 user_data += page_length;
1261                 offset += page_length;
1262         }
1263         intel_fb_obj_flush(obj, ORIGIN_CPU);
1264
1265         mutex_lock(&i915->drm.struct_mutex);
1266 out_unpin:
1267         if (node.allocated) {
1268                 wmb();
1269                 ggtt->vm.clear_range(&ggtt->vm, node.start, node.size);
1270                 remove_mappable_node(&node);
1271         } else {
1272                 i915_vma_unpin(vma);
1273         }
1274 out_rpm:
1275         intel_runtime_pm_put(i915, wakeref);
1276 out_unlock:
1277         mutex_unlock(&i915->drm.struct_mutex);
1278         return ret;
1279 }
1280
1281 /* Per-page copy function for the shmem pwrite fastpath.
1282  * Flushes invalid cachelines before writing to the target if
1283  * needs_clflush_before is set and flushes out any written cachelines after
1284  * writing if needs_clflush is set.
1285  */
1286 static int
1287 shmem_pwrite(struct page *page, int offset, int len, char __user *user_data,
1288              bool needs_clflush_before,
1289              bool needs_clflush_after)
1290 {
1291         char *vaddr;
1292         int ret;
1293
1294         vaddr = kmap(page);
1295
1296         if (needs_clflush_before)
1297                 drm_clflush_virt_range(vaddr + offset, len);
1298
1299         ret = __copy_from_user(vaddr + offset, user_data, len);
1300         if (!ret && needs_clflush_after)
1301                 drm_clflush_virt_range(vaddr + offset, len);
1302
1303         kunmap(page);
1304
1305         return ret ? -EFAULT : 0;
1306 }
1307
1308 static int
1309 i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
1310                       const struct drm_i915_gem_pwrite *args)
1311 {
1312         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1313         void __user *user_data;
1314         u64 remain;
1315         unsigned int partial_cacheline_write;
1316         unsigned int needs_clflush;
1317         unsigned int offset, idx;
1318         int ret;
1319
1320         ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1321         if (ret)
1322                 return ret;
1323
1324         ret = i915_gem_obj_prepare_shmem_write(obj, &needs_clflush);
1325         mutex_unlock(&i915->drm.struct_mutex);
1326         if (ret)
1327                 return ret;
1328
1329         /* If we don't overwrite a cacheline completely we need to be
1330          * careful to have up-to-date data by first clflushing. Don't
1331          * overcomplicate things and flush the entire patch.
1332          */
1333         partial_cacheline_write = 0;
1334         if (needs_clflush & CLFLUSH_BEFORE)
1335                 partial_cacheline_write = boot_cpu_data.x86_clflush_size - 1;
1336
1337         user_data = u64_to_user_ptr(args->data_ptr);
1338         remain = args->size;
1339         offset = offset_in_page(args->offset);
1340         for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
1341                 struct page *page = i915_gem_object_get_page(obj, idx);
1342                 unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
1343
1344                 ret = shmem_pwrite(page, offset, length, user_data,
1345                                    (offset | length) & partial_cacheline_write,
1346                                    needs_clflush & CLFLUSH_AFTER);
1347                 if (ret)
1348                         break;
1349
1350                 remain -= length;
1351                 user_data += length;
1352                 offset = 0;
1353         }
1354
1355         intel_fb_obj_flush(obj, ORIGIN_CPU);
1356         i915_gem_obj_finish_shmem_access(obj);
1357         return ret;
1358 }
1359
1360 /**
1361  * Writes data to the object referenced by handle.
1362  * @dev: drm device
1363  * @data: ioctl data blob
1364  * @file: drm file
1365  *
1366  * On error, the contents of the buffer that were to be modified are undefined.
1367  */
1368 int
1369 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
1370                       struct drm_file *file)
1371 {
1372         struct drm_i915_gem_pwrite *args = data;
1373         struct drm_i915_gem_object *obj;
1374         int ret;
1375
1376         if (args->size == 0)
1377                 return 0;
1378
1379         if (!access_ok(u64_to_user_ptr(args->data_ptr), args->size))
1380                 return -EFAULT;
1381
1382         obj = i915_gem_object_lookup(file, args->handle);
1383         if (!obj)
1384                 return -ENOENT;
1385
1386         /* Bounds check destination. */
1387         if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
1388                 ret = -EINVAL;
1389                 goto err;
1390         }
1391
1392         /* Writes not allowed into this read-only object */
1393         if (i915_gem_object_is_readonly(obj)) {
1394                 ret = -EINVAL;
1395                 goto err;
1396         }
1397
1398         trace_i915_gem_object_pwrite(obj, args->offset, args->size);
1399
1400         ret = -ENODEV;
1401         if (obj->ops->pwrite)
1402                 ret = obj->ops->pwrite(obj, args);
1403         if (ret != -ENODEV)
1404                 goto err;
1405
1406         ret = i915_gem_object_wait(obj,
1407                                    I915_WAIT_INTERRUPTIBLE |
1408                                    I915_WAIT_ALL,
1409                                    MAX_SCHEDULE_TIMEOUT);
1410         if (ret)
1411                 goto err;
1412
1413         ret = i915_gem_object_pin_pages(obj);
1414         if (ret)
1415                 goto err;
1416
1417         ret = -EFAULT;
1418         /* We can only do the GTT pwrite on untiled buffers, as otherwise
1419          * it would end up going through the fenced access, and we'll get
1420          * different detiling behavior between reading and writing.
1421          * pread/pwrite currently are reading and writing from the CPU
1422          * perspective, requiring manual detiling by the client.
1423          */
1424         if (!i915_gem_object_has_struct_page(obj) ||
1425             cpu_write_needs_clflush(obj))
1426                 /* Note that the gtt paths might fail with non-page-backed user
1427                  * pointers (e.g. gtt mappings when moving data between
1428                  * textures). Fallback to the shmem path in that case.
1429                  */
1430                 ret = i915_gem_gtt_pwrite_fast(obj, args);
1431
1432         if (ret == -EFAULT || ret == -ENOSPC) {
1433                 if (obj->phys_handle)
1434                         ret = i915_gem_phys_pwrite(obj, args, file);
1435                 else
1436                         ret = i915_gem_shmem_pwrite(obj, args);
1437         }
1438
1439         i915_gem_object_unpin_pages(obj);
1440 err:
1441         i915_gem_object_put(obj);
1442         return ret;
1443 }
1444
1445 static void i915_gem_object_bump_inactive_ggtt(struct drm_i915_gem_object *obj)
1446 {
1447         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1448         struct list_head *list;
1449         struct i915_vma *vma;
1450
1451         GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
1452
1453         mutex_lock(&i915->ggtt.vm.mutex);
1454         for_each_ggtt_vma(vma, obj) {
1455                 if (!drm_mm_node_allocated(&vma->node))
1456                         continue;
1457
1458                 list_move_tail(&vma->vm_link, &vma->vm->bound_list);
1459         }
1460         mutex_unlock(&i915->ggtt.vm.mutex);
1461
1462         spin_lock(&i915->mm.obj_lock);
1463         list = obj->bind_count ? &i915->mm.bound_list : &i915->mm.unbound_list;
1464         list_move_tail(&obj->mm.link, list);
1465         spin_unlock(&i915->mm.obj_lock);
1466 }
1467
1468 /**
1469  * Called when user space prepares to use an object with the CPU, either
1470  * through the mmap ioctl's mapping or a GTT mapping.
1471  * @dev: drm device
1472  * @data: ioctl data blob
1473  * @file: drm file
1474  */
1475 int
1476 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1477                           struct drm_file *file)
1478 {
1479         struct drm_i915_gem_set_domain *args = data;
1480         struct drm_i915_gem_object *obj;
1481         u32 read_domains = args->read_domains;
1482         u32 write_domain = args->write_domain;
1483         int err;
1484
1485         /* Only handle setting domains to types used by the CPU. */
1486         if ((write_domain | read_domains) & I915_GEM_GPU_DOMAINS)
1487                 return -EINVAL;
1488
1489         /*
1490          * Having something in the write domain implies it's in the read
1491          * domain, and only that read domain.  Enforce that in the request.
1492          */
1493         if (write_domain && read_domains != write_domain)
1494                 return -EINVAL;
1495
1496         if (!read_domains)
1497                 return 0;
1498
1499         obj = i915_gem_object_lookup(file, args->handle);
1500         if (!obj)
1501                 return -ENOENT;
1502
1503         /*
1504          * Already in the desired write domain? Nothing for us to do!
1505          *
1506          * We apply a little bit of cunning here to catch a broader set of
1507          * no-ops. If obj->write_domain is set, we must be in the same
1508          * obj->read_domains, and only that domain. Therefore, if that
1509          * obj->write_domain matches the request read_domains, we are
1510          * already in the same read/write domain and can skip the operation,
1511          * without having to further check the requested write_domain.
1512          */
1513         if (READ_ONCE(obj->write_domain) == read_domains) {
1514                 err = 0;
1515                 goto out;
1516         }
1517
1518         /*
1519          * Try to flush the object off the GPU without holding the lock.
1520          * We will repeat the flush holding the lock in the normal manner
1521          * to catch cases where we are gazumped.
1522          */
1523         err = i915_gem_object_wait(obj,
1524                                    I915_WAIT_INTERRUPTIBLE |
1525                                    I915_WAIT_PRIORITY |
1526                                    (write_domain ? I915_WAIT_ALL : 0),
1527                                    MAX_SCHEDULE_TIMEOUT);
1528         if (err)
1529                 goto out;
1530
1531         /*
1532          * Proxy objects do not control access to the backing storage, ergo
1533          * they cannot be used as a means to manipulate the cache domain
1534          * tracking for that backing storage. The proxy object is always
1535          * considered to be outside of any cache domain.
1536          */
1537         if (i915_gem_object_is_proxy(obj)) {
1538                 err = -ENXIO;
1539                 goto out;
1540         }
1541
1542         /*
1543          * Flush and acquire obj->pages so that we are coherent through
1544          * direct access in memory with previous cached writes through
1545          * shmemfs and that our cache domain tracking remains valid.
1546          * For example, if the obj->filp was moved to swap without us
1547          * being notified and releasing the pages, we would mistakenly
1548          * continue to assume that the obj remained out of the CPU cached
1549          * domain.
1550          */
1551         err = i915_gem_object_pin_pages(obj);
1552         if (err)
1553                 goto out;
1554
1555         err = i915_mutex_lock_interruptible(dev);
1556         if (err)
1557                 goto out_unpin;
1558
1559         if (read_domains & I915_GEM_DOMAIN_WC)
1560                 err = i915_gem_object_set_to_wc_domain(obj, write_domain);
1561         else if (read_domains & I915_GEM_DOMAIN_GTT)
1562                 err = i915_gem_object_set_to_gtt_domain(obj, write_domain);
1563         else
1564                 err = i915_gem_object_set_to_cpu_domain(obj, write_domain);
1565
1566         /* And bump the LRU for this access */
1567         i915_gem_object_bump_inactive_ggtt(obj);
1568
1569         mutex_unlock(&dev->struct_mutex);
1570
1571         if (write_domain != 0)
1572                 intel_fb_obj_invalidate(obj,
1573                                         fb_write_origin(obj, write_domain));
1574
1575 out_unpin:
1576         i915_gem_object_unpin_pages(obj);
1577 out:
1578         i915_gem_object_put(obj);
1579         return err;
1580 }
1581
1582 /**
1583  * Called when user space has done writes to this buffer
1584  * @dev: drm device
1585  * @data: ioctl data blob
1586  * @file: drm file
1587  */
1588 int
1589 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1590                          struct drm_file *file)
1591 {
1592         struct drm_i915_gem_sw_finish *args = data;
1593         struct drm_i915_gem_object *obj;
1594
1595         obj = i915_gem_object_lookup(file, args->handle);
1596         if (!obj)
1597                 return -ENOENT;
1598
1599         /*
1600          * Proxy objects are barred from CPU access, so there is no
1601          * need to ban sw_finish as it is a nop.
1602          */
1603
1604         /* Pinned buffers may be scanout, so flush the cache */
1605         i915_gem_object_flush_if_display(obj);
1606         i915_gem_object_put(obj);
1607
1608         return 0;
1609 }
1610
1611 static inline bool
1612 __vma_matches(struct vm_area_struct *vma, struct file *filp,
1613               unsigned long addr, unsigned long size)
1614 {
1615         if (vma->vm_file != filp)
1616                 return false;
1617
1618         return vma->vm_start == addr &&
1619                (vma->vm_end - vma->vm_start) == PAGE_ALIGN(size);
1620 }
1621
1622 /**
1623  * i915_gem_mmap_ioctl - Maps the contents of an object, returning the address
1624  *                       it is mapped to.
1625  * @dev: drm device
1626  * @data: ioctl data blob
1627  * @file: drm file
1628  *
1629  * While the mapping holds a reference on the contents of the object, it doesn't
1630  * imply a ref on the object itself.
1631  *
1632  * IMPORTANT:
1633  *
1634  * DRM driver writers who look a this function as an example for how to do GEM
1635  * mmap support, please don't implement mmap support like here. The modern way
1636  * to implement DRM mmap support is with an mmap offset ioctl (like
1637  * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
1638  * That way debug tooling like valgrind will understand what's going on, hiding
1639  * the mmap call in a driver private ioctl will break that. The i915 driver only
1640  * does cpu mmaps this way because we didn't know better.
1641  */
1642 int
1643 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1644                     struct drm_file *file)
1645 {
1646         struct drm_i915_gem_mmap *args = data;
1647         struct drm_i915_gem_object *obj;
1648         unsigned long addr;
1649
1650         if (args->flags & ~(I915_MMAP_WC))
1651                 return -EINVAL;
1652
1653         if (args->flags & I915_MMAP_WC && !boot_cpu_has(X86_FEATURE_PAT))
1654                 return -ENODEV;
1655
1656         obj = i915_gem_object_lookup(file, args->handle);
1657         if (!obj)
1658                 return -ENOENT;
1659
1660         /* prime objects have no backing filp to GEM mmap
1661          * pages from.
1662          */
1663         if (!obj->base.filp) {
1664                 addr = -ENXIO;
1665                 goto err;
1666         }
1667
1668         if (range_overflows(args->offset, args->size, (u64)obj->base.size)) {
1669                 addr = -EINVAL;
1670                 goto err;
1671         }
1672
1673         addr = vm_mmap(obj->base.filp, 0, args->size,
1674                        PROT_READ | PROT_WRITE, MAP_SHARED,
1675                        args->offset);
1676         if (IS_ERR_VALUE(addr))
1677                 goto err;
1678
1679         if (args->flags & I915_MMAP_WC) {
1680                 struct mm_struct *mm = current->mm;
1681                 struct vm_area_struct *vma;
1682
1683                 if (down_write_killable(&mm->mmap_sem)) {
1684                         addr = -EINTR;
1685                         goto err;
1686                 }
1687                 vma = find_vma(mm, addr);
1688                 if (vma && __vma_matches(vma, obj->base.filp, addr, args->size))
1689                         vma->vm_page_prot =
1690                                 pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1691                 else
1692                         addr = -ENOMEM;
1693                 up_write(&mm->mmap_sem);
1694                 if (IS_ERR_VALUE(addr))
1695                         goto err;
1696
1697                 /* This may race, but that's ok, it only gets set */
1698                 WRITE_ONCE(obj->frontbuffer_ggtt_origin, ORIGIN_CPU);
1699         }
1700         i915_gem_object_put(obj);
1701
1702         args->addr_ptr = (u64)addr;
1703         return 0;
1704
1705 err:
1706         i915_gem_object_put(obj);
1707         return addr;
1708 }
1709
1710 static unsigned int tile_row_pages(const struct drm_i915_gem_object *obj)
1711 {
1712         return i915_gem_object_get_tile_row_size(obj) >> PAGE_SHIFT;
1713 }
1714
1715 /**
1716  * i915_gem_mmap_gtt_version - report the current feature set for GTT mmaps
1717  *
1718  * A history of the GTT mmap interface:
1719  *
1720  * 0 - Everything had to fit into the GTT. Both parties of a memcpy had to
1721  *     aligned and suitable for fencing, and still fit into the available
1722  *     mappable space left by the pinned display objects. A classic problem
1723  *     we called the page-fault-of-doom where we would ping-pong between
1724  *     two objects that could not fit inside the GTT and so the memcpy
1725  *     would page one object in at the expense of the other between every
1726  *     single byte.
1727  *
1728  * 1 - Objects can be any size, and have any compatible fencing (X Y, or none
1729  *     as set via i915_gem_set_tiling() [DRM_I915_GEM_SET_TILING]). If the
1730  *     object is too large for the available space (or simply too large
1731  *     for the mappable aperture!), a view is created instead and faulted
1732  *     into userspace. (This view is aligned and sized appropriately for
1733  *     fenced access.)
1734  *
1735  * 2 - Recognise WC as a separate cache domain so that we can flush the
1736  *     delayed writes via GTT before performing direct access via WC.
1737  *
1738  * 3 - Remove implicit set-domain(GTT) and synchronisation on initial
1739  *     pagefault; swapin remains transparent.
1740  *
1741  * Restrictions:
1742  *
1743  *  * snoopable objects cannot be accessed via the GTT. It can cause machine
1744  *    hangs on some architectures, corruption on others. An attempt to service
1745  *    a GTT page fault from a snoopable object will generate a SIGBUS.
1746  *
1747  *  * the object must be able to fit into RAM (physical memory, though no
1748  *    limited to the mappable aperture).
1749  *
1750  *
1751  * Caveats:
1752  *
1753  *  * a new GTT page fault will synchronize rendering from the GPU and flush
1754  *    all data to system memory. Subsequent access will not be synchronized.
1755  *
1756  *  * all mappings are revoked on runtime device suspend.
1757  *
1758  *  * there are only 8, 16 or 32 fence registers to share between all users
1759  *    (older machines require fence register for display and blitter access
1760  *    as well). Contention of the fence registers will cause the previous users
1761  *    to be unmapped and any new access will generate new page faults.
1762  *
1763  *  * running out of memory while servicing a fault may generate a SIGBUS,
1764  *    rather than the expected SIGSEGV.
1765  */
1766 int i915_gem_mmap_gtt_version(void)
1767 {
1768         return 3;
1769 }
1770
1771 static inline struct i915_ggtt_view
1772 compute_partial_view(const struct drm_i915_gem_object *obj,
1773                      pgoff_t page_offset,
1774                      unsigned int chunk)
1775 {
1776         struct i915_ggtt_view view;
1777
1778         if (i915_gem_object_is_tiled(obj))
1779                 chunk = roundup(chunk, tile_row_pages(obj));
1780
1781         view.type = I915_GGTT_VIEW_PARTIAL;
1782         view.partial.offset = rounddown(page_offset, chunk);
1783         view.partial.size =
1784                 min_t(unsigned int, chunk,
1785                       (obj->base.size >> PAGE_SHIFT) - view.partial.offset);
1786
1787         /* If the partial covers the entire object, just create a normal VMA. */
1788         if (chunk >= obj->base.size >> PAGE_SHIFT)
1789                 view.type = I915_GGTT_VIEW_NORMAL;
1790
1791         return view;
1792 }
1793
1794 /**
1795  * i915_gem_fault - fault a page into the GTT
1796  * @vmf: fault info
1797  *
1798  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1799  * from userspace.  The fault handler takes care of binding the object to
1800  * the GTT (if needed), allocating and programming a fence register (again,
1801  * only if needed based on whether the old reg is still valid or the object
1802  * is tiled) and inserting a new PTE into the faulting process.
1803  *
1804  * Note that the faulting process may involve evicting existing objects
1805  * from the GTT and/or fence registers to make room.  So performance may
1806  * suffer if the GTT working set is large or there are few fence registers
1807  * left.
1808  *
1809  * The current feature set supported by i915_gem_fault() and thus GTT mmaps
1810  * is exposed via I915_PARAM_MMAP_GTT_VERSION (see i915_gem_mmap_gtt_version).
1811  */
1812 vm_fault_t i915_gem_fault(struct vm_fault *vmf)
1813 {
1814 #define MIN_CHUNK_PAGES (SZ_1M >> PAGE_SHIFT)
1815         struct vm_area_struct *area = vmf->vma;
1816         struct drm_i915_gem_object *obj = to_intel_bo(area->vm_private_data);
1817         struct drm_device *dev = obj->base.dev;
1818         struct drm_i915_private *dev_priv = to_i915(dev);
1819         struct i915_ggtt *ggtt = &dev_priv->ggtt;
1820         bool write = area->vm_flags & VM_WRITE;
1821         intel_wakeref_t wakeref;
1822         struct i915_vma *vma;
1823         pgoff_t page_offset;
1824         int srcu;
1825         int ret;
1826
1827         /* Sanity check that we allow writing into this object */
1828         if (i915_gem_object_is_readonly(obj) && write)
1829                 return VM_FAULT_SIGBUS;
1830
1831         /* We don't use vmf->pgoff since that has the fake offset */
1832         page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
1833
1834         trace_i915_gem_object_fault(obj, page_offset, true, write);
1835
1836         ret = i915_gem_object_pin_pages(obj);
1837         if (ret)
1838                 goto err;
1839
1840         wakeref = intel_runtime_pm_get(dev_priv);
1841
1842         srcu = i915_reset_trylock(dev_priv);
1843         if (srcu < 0) {
1844                 ret = srcu;
1845                 goto err_rpm;
1846         }
1847
1848         ret = i915_mutex_lock_interruptible(dev);
1849         if (ret)
1850                 goto err_reset;
1851
1852         /* Access to snoopable pages through the GTT is incoherent. */
1853         if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev_priv)) {
1854                 ret = -EFAULT;
1855                 goto err_unlock;
1856         }
1857
1858         /* Now pin it into the GTT as needed */
1859         vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1860                                        PIN_MAPPABLE |
1861                                        PIN_NONBLOCK |
1862                                        PIN_NONFAULT);
1863         if (IS_ERR(vma)) {
1864                 /* Use a partial view if it is bigger than available space */
1865                 struct i915_ggtt_view view =
1866                         compute_partial_view(obj, page_offset, MIN_CHUNK_PAGES);
1867                 unsigned int flags;
1868
1869                 flags = PIN_MAPPABLE;
1870                 if (view.type == I915_GGTT_VIEW_NORMAL)
1871                         flags |= PIN_NONBLOCK; /* avoid warnings for pinned */
1872
1873                 /*
1874                  * Userspace is now writing through an untracked VMA, abandon
1875                  * all hope that the hardware is able to track future writes.
1876                  */
1877                 obj->frontbuffer_ggtt_origin = ORIGIN_CPU;
1878
1879                 vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, flags);
1880                 if (IS_ERR(vma) && !view.type) {
1881                         flags = PIN_MAPPABLE;
1882                         view.type = I915_GGTT_VIEW_PARTIAL;
1883                         vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, flags);
1884                 }
1885         }
1886         if (IS_ERR(vma)) {
1887                 ret = PTR_ERR(vma);
1888                 goto err_unlock;
1889         }
1890
1891         ret = i915_vma_pin_fence(vma);
1892         if (ret)
1893                 goto err_unpin;
1894
1895         /* Finally, remap it using the new GTT offset */
1896         ret = remap_io_mapping(area,
1897                                area->vm_start + (vma->ggtt_view.partial.offset << PAGE_SHIFT),
1898                                (ggtt->gmadr.start + vma->node.start) >> PAGE_SHIFT,
1899                                min_t(u64, vma->size, area->vm_end - area->vm_start),
1900                                &ggtt->iomap);
1901         if (ret)
1902                 goto err_fence;
1903
1904         /* Mark as being mmapped into userspace for later revocation */
1905         assert_rpm_wakelock_held(dev_priv);
1906         if (!i915_vma_set_userfault(vma) && !obj->userfault_count++)
1907                 list_add(&obj->userfault_link, &dev_priv->mm.userfault_list);
1908         GEM_BUG_ON(!obj->userfault_count);
1909
1910         i915_vma_set_ggtt_write(vma);
1911
1912 err_fence:
1913         i915_vma_unpin_fence(vma);
1914 err_unpin:
1915         __i915_vma_unpin(vma);
1916 err_unlock:
1917         mutex_unlock(&dev->struct_mutex);
1918 err_reset:
1919         i915_reset_unlock(dev_priv, srcu);
1920 err_rpm:
1921         intel_runtime_pm_put(dev_priv, wakeref);
1922         i915_gem_object_unpin_pages(obj);
1923 err:
1924         switch (ret) {
1925         case -EIO:
1926                 /*
1927                  * We eat errors when the gpu is terminally wedged to avoid
1928                  * userspace unduly crashing (gl has no provisions for mmaps to
1929                  * fail). But any other -EIO isn't ours (e.g. swap in failure)
1930                  * and so needs to be reported.
1931                  */
1932                 if (!i915_terminally_wedged(dev_priv))
1933                         return VM_FAULT_SIGBUS;
1934                 /* else: fall through */
1935         case -EAGAIN:
1936                 /*
1937                  * EAGAIN means the gpu is hung and we'll wait for the error
1938                  * handler to reset everything when re-faulting in
1939                  * i915_mutex_lock_interruptible.
1940                  */
1941         case 0:
1942         case -ERESTARTSYS:
1943         case -EINTR:
1944         case -EBUSY:
1945                 /*
1946                  * EBUSY is ok: this just means that another thread
1947                  * already did the job.
1948                  */
1949                 return VM_FAULT_NOPAGE;
1950         case -ENOMEM:
1951                 return VM_FAULT_OOM;
1952         case -ENOSPC:
1953         case -EFAULT:
1954                 return VM_FAULT_SIGBUS;
1955         default:
1956                 WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
1957                 return VM_FAULT_SIGBUS;
1958         }
1959 }
1960
1961 static void __i915_gem_object_release_mmap(struct drm_i915_gem_object *obj)
1962 {
1963         struct i915_vma *vma;
1964
1965         GEM_BUG_ON(!obj->userfault_count);
1966
1967         obj->userfault_count = 0;
1968         list_del(&obj->userfault_link);
1969         drm_vma_node_unmap(&obj->base.vma_node,
1970                            obj->base.dev->anon_inode->i_mapping);
1971
1972         for_each_ggtt_vma(vma, obj)
1973                 i915_vma_unset_userfault(vma);
1974 }
1975
1976 /**
1977  * i915_gem_release_mmap - remove physical page mappings
1978  * @obj: obj in question
1979  *
1980  * Preserve the reservation of the mmapping with the DRM core code, but
1981  * relinquish ownership of the pages back to the system.
1982  *
1983  * It is vital that we remove the page mapping if we have mapped a tiled
1984  * object through the GTT and then lose the fence register due to
1985  * resource pressure. Similarly if the object has been moved out of the
1986  * aperture, than pages mapped into userspace must be revoked. Removing the
1987  * mapping will then trigger a page fault on the next user access, allowing
1988  * fixup by i915_gem_fault().
1989  */
1990 void
1991 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
1992 {
1993         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1994         intel_wakeref_t wakeref;
1995
1996         /* Serialisation between user GTT access and our code depends upon
1997          * revoking the CPU's PTE whilst the mutex is held. The next user
1998          * pagefault then has to wait until we release the mutex.
1999          *
2000          * Note that RPM complicates somewhat by adding an additional
2001          * requirement that operations to the GGTT be made holding the RPM
2002          * wakeref.
2003          */
2004         lockdep_assert_held(&i915->drm.struct_mutex);
2005         wakeref = intel_runtime_pm_get(i915);
2006
2007         if (!obj->userfault_count)
2008                 goto out;
2009
2010         __i915_gem_object_release_mmap(obj);
2011
2012         /* Ensure that the CPU's PTE are revoked and there are not outstanding
2013          * memory transactions from userspace before we return. The TLB
2014          * flushing implied above by changing the PTE above *should* be
2015          * sufficient, an extra barrier here just provides us with a bit
2016          * of paranoid documentation about our requirement to serialise
2017          * memory writes before touching registers / GSM.
2018          */
2019         wmb();
2020
2021 out:
2022         intel_runtime_pm_put(i915, wakeref);
2023 }
2024
2025 void i915_gem_runtime_suspend(struct drm_i915_private *dev_priv)
2026 {
2027         struct drm_i915_gem_object *obj, *on;
2028         int i;
2029
2030         /*
2031          * Only called during RPM suspend. All users of the userfault_list
2032          * must be holding an RPM wakeref to ensure that this can not
2033          * run concurrently with themselves (and use the struct_mutex for
2034          * protection between themselves).
2035          */
2036
2037         list_for_each_entry_safe(obj, on,
2038                                  &dev_priv->mm.userfault_list, userfault_link)
2039                 __i915_gem_object_release_mmap(obj);
2040
2041         /* The fence will be lost when the device powers down. If any were
2042          * in use by hardware (i.e. they are pinned), we should not be powering
2043          * down! All other fences will be reacquired by the user upon waking.
2044          */
2045         for (i = 0; i < dev_priv->num_fence_regs; i++) {
2046                 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
2047
2048                 /* Ideally we want to assert that the fence register is not
2049                  * live at this point (i.e. that no piece of code will be
2050                  * trying to write through fence + GTT, as that both violates
2051                  * our tracking of activity and associated locking/barriers,
2052                  * but also is illegal given that the hw is powered down).
2053                  *
2054                  * Previously we used reg->pin_count as a "liveness" indicator.
2055                  * That is not sufficient, and we need a more fine-grained
2056                  * tool if we want to have a sanity check here.
2057                  */
2058
2059                 if (!reg->vma)
2060                         continue;
2061
2062                 GEM_BUG_ON(i915_vma_has_userfault(reg->vma));
2063                 reg->dirty = true;
2064         }
2065 }
2066
2067 static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
2068 {
2069         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2070         int err;
2071
2072         err = drm_gem_create_mmap_offset(&obj->base);
2073         if (likely(!err))
2074                 return 0;
2075
2076         /* Attempt to reap some mmap space from dead objects */
2077         do {
2078                 err = i915_gem_wait_for_idle(dev_priv,
2079                                              I915_WAIT_INTERRUPTIBLE,
2080                                              MAX_SCHEDULE_TIMEOUT);
2081                 if (err)
2082                         break;
2083
2084                 i915_gem_drain_freed_objects(dev_priv);
2085                 err = drm_gem_create_mmap_offset(&obj->base);
2086                 if (!err)
2087                         break;
2088
2089         } while (flush_delayed_work(&dev_priv->gt.retire_work));
2090
2091         return err;
2092 }
2093
2094 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
2095 {
2096         drm_gem_free_mmap_offset(&obj->base);
2097 }
2098
2099 int
2100 i915_gem_mmap_gtt(struct drm_file *file,
2101                   struct drm_device *dev,
2102                   u32 handle,
2103                   u64 *offset)
2104 {
2105         struct drm_i915_gem_object *obj;
2106         int ret;
2107
2108         obj = i915_gem_object_lookup(file, handle);
2109         if (!obj)
2110                 return -ENOENT;
2111
2112         ret = i915_gem_object_create_mmap_offset(obj);
2113         if (ret == 0)
2114                 *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
2115
2116         i915_gem_object_put(obj);
2117         return ret;
2118 }
2119
2120 /**
2121  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
2122  * @dev: DRM device
2123  * @data: GTT mapping ioctl data
2124  * @file: GEM object info
2125  *
2126  * Simply returns the fake offset to userspace so it can mmap it.
2127  * The mmap call will end up in drm_gem_mmap(), which will set things
2128  * up so we can get faults in the handler above.
2129  *
2130  * The fault handler will take care of binding the object into the GTT
2131  * (since it may have been evicted to make room for something), allocating
2132  * a fence register, and mapping the appropriate aperture address into
2133  * userspace.
2134  */
2135 int
2136 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
2137                         struct drm_file *file)
2138 {
2139         struct drm_i915_gem_mmap_gtt *args = data;
2140
2141         return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
2142 }
2143
2144 /* Immediately discard the backing storage */
2145 static void
2146 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
2147 {
2148         i915_gem_object_free_mmap_offset(obj);
2149
2150         if (obj->base.filp == NULL)
2151                 return;
2152
2153         /* Our goal here is to return as much of the memory as
2154          * is possible back to the system as we are called from OOM.
2155          * To do this we must instruct the shmfs to drop all of its
2156          * backing pages, *now*.
2157          */
2158         shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
2159         obj->mm.madv = __I915_MADV_PURGED;
2160         obj->mm.pages = ERR_PTR(-EFAULT);
2161 }
2162
2163 /* Try to discard unwanted pages */
2164 void __i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
2165 {
2166         struct address_space *mapping;
2167
2168         lockdep_assert_held(&obj->mm.lock);
2169         GEM_BUG_ON(i915_gem_object_has_pages(obj));
2170
2171         switch (obj->mm.madv) {
2172         case I915_MADV_DONTNEED:
2173                 i915_gem_object_truncate(obj);
2174         case __I915_MADV_PURGED:
2175                 return;
2176         }
2177
2178         if (obj->base.filp == NULL)
2179                 return;
2180
2181         mapping = obj->base.filp->f_mapping,
2182         invalidate_mapping_pages(mapping, 0, (loff_t)-1);
2183 }
2184
2185 /*
2186  * Move pages to appropriate lru and release the pagevec, decrementing the
2187  * ref count of those pages.
2188  */
2189 static void check_release_pagevec(struct pagevec *pvec)
2190 {
2191         check_move_unevictable_pages(pvec);
2192         __pagevec_release(pvec);
2193         cond_resched();
2194 }
2195
2196 static void
2197 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj,
2198                               struct sg_table *pages)
2199 {
2200         struct sgt_iter sgt_iter;
2201         struct pagevec pvec;
2202         struct page *page;
2203
2204         __i915_gem_object_release_shmem(obj, pages, true);
2205
2206         i915_gem_gtt_finish_pages(obj, pages);
2207
2208         if (i915_gem_object_needs_bit17_swizzle(obj))
2209                 i915_gem_object_save_bit_17_swizzle(obj, pages);
2210
2211         mapping_clear_unevictable(file_inode(obj->base.filp)->i_mapping);
2212
2213         pagevec_init(&pvec);
2214         for_each_sgt_page(page, sgt_iter, pages) {
2215                 if (obj->mm.dirty)
2216                         set_page_dirty(page);
2217
2218                 if (obj->mm.madv == I915_MADV_WILLNEED)
2219                         mark_page_accessed(page);
2220
2221                 if (!pagevec_add(&pvec, page))
2222                         check_release_pagevec(&pvec);
2223         }
2224         if (pagevec_count(&pvec))
2225                 check_release_pagevec(&pvec);
2226         obj->mm.dirty = false;
2227
2228         sg_free_table(pages);
2229         kfree(pages);
2230 }
2231
2232 static void __i915_gem_object_reset_page_iter(struct drm_i915_gem_object *obj)
2233 {
2234         struct radix_tree_iter iter;
2235         void __rcu **slot;
2236
2237         rcu_read_lock();
2238         radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
2239                 radix_tree_delete(&obj->mm.get_page.radix, iter.index);
2240         rcu_read_unlock();
2241 }
2242
2243 static struct sg_table *
2244 __i915_gem_object_unset_pages(struct drm_i915_gem_object *obj)
2245 {
2246         struct drm_i915_private *i915 = to_i915(obj->base.dev);
2247         struct sg_table *pages;
2248
2249         pages = fetch_and_zero(&obj->mm.pages);
2250         if (IS_ERR_OR_NULL(pages))
2251                 return pages;
2252
2253         spin_lock(&i915->mm.obj_lock);
2254         list_del(&obj->mm.link);
2255         spin_unlock(&i915->mm.obj_lock);
2256
2257         if (obj->mm.mapping) {
2258                 void *ptr;
2259
2260                 ptr = page_mask_bits(obj->mm.mapping);
2261                 if (is_vmalloc_addr(ptr))
2262                         vunmap(ptr);
2263                 else
2264                         kunmap(kmap_to_page(ptr));
2265
2266                 obj->mm.mapping = NULL;
2267         }
2268
2269         __i915_gem_object_reset_page_iter(obj);
2270         obj->mm.page_sizes.phys = obj->mm.page_sizes.sg = 0;
2271
2272         return pages;
2273 }
2274
2275 int __i915_gem_object_put_pages(struct drm_i915_gem_object *obj,
2276                                 enum i915_mm_subclass subclass)
2277 {
2278         struct sg_table *pages;
2279         int ret;
2280
2281         if (i915_gem_object_has_pinned_pages(obj))
2282                 return -EBUSY;
2283
2284         GEM_BUG_ON(obj->bind_count);
2285
2286         /* May be called by shrinker from within get_pages() (on another bo) */
2287         mutex_lock_nested(&obj->mm.lock, subclass);
2288         if (unlikely(atomic_read(&obj->mm.pages_pin_count))) {
2289                 ret = -EBUSY;
2290                 goto unlock;
2291         }
2292
2293         /*
2294          * ->put_pages might need to allocate memory for the bit17 swizzle
2295          * array, hence protect them from being reaped by removing them from gtt
2296          * lists early.
2297          */
2298         pages = __i915_gem_object_unset_pages(obj);
2299
2300         /*
2301          * XXX Temporary hijinx to avoid updating all backends to handle
2302          * NULL pages. In the future, when we have more asynchronous
2303          * get_pages backends we should be better able to handle the
2304          * cancellation of the async task in a more uniform manner.
2305          */
2306         if (!pages && !i915_gem_object_needs_async_cancel(obj))
2307                 pages = ERR_PTR(-EINVAL);
2308
2309         if (!IS_ERR(pages))
2310                 obj->ops->put_pages(obj, pages);
2311
2312         ret = 0;
2313 unlock:
2314         mutex_unlock(&obj->mm.lock);
2315
2316         return ret;
2317 }
2318
2319 bool i915_sg_trim(struct sg_table *orig_st)
2320 {
2321         struct sg_table new_st;
2322         struct scatterlist *sg, *new_sg;
2323         unsigned int i;
2324
2325         if (orig_st->nents == orig_st->orig_nents)
2326                 return false;
2327
2328         if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL | __GFP_NOWARN))
2329                 return false;
2330
2331         new_sg = new_st.sgl;
2332         for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
2333                 sg_set_page(new_sg, sg_page(sg), sg->length, 0);
2334                 sg_dma_address(new_sg) = sg_dma_address(sg);
2335                 sg_dma_len(new_sg) = sg_dma_len(sg);
2336
2337                 new_sg = sg_next(new_sg);
2338         }
2339         GEM_BUG_ON(new_sg); /* Should walk exactly nents and hit the end */
2340
2341         sg_free_table(orig_st);
2342
2343         *orig_st = new_st;
2344         return true;
2345 }
2346
2347 static int i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
2348 {
2349         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2350         const unsigned long page_count = obj->base.size / PAGE_SIZE;
2351         unsigned long i;
2352         struct address_space *mapping;
2353         struct sg_table *st;
2354         struct scatterlist *sg;
2355         struct sgt_iter sgt_iter;
2356         struct page *page;
2357         unsigned long last_pfn = 0;     /* suppress gcc warning */
2358         unsigned int max_segment = i915_sg_segment_size();
2359         unsigned int sg_page_sizes;
2360         struct pagevec pvec;
2361         gfp_t noreclaim;
2362         int ret;
2363
2364         /*
2365          * Assert that the object is not currently in any GPU domain. As it
2366          * wasn't in the GTT, there shouldn't be any way it could have been in
2367          * a GPU cache
2368          */
2369         GEM_BUG_ON(obj->read_domains & I915_GEM_GPU_DOMAINS);
2370         GEM_BUG_ON(obj->write_domain & I915_GEM_GPU_DOMAINS);
2371
2372         /*
2373          * If there's no chance of allocating enough pages for the whole
2374          * object, bail early.
2375          */
2376         if (page_count > totalram_pages())
2377                 return -ENOMEM;
2378
2379         st = kmalloc(sizeof(*st), GFP_KERNEL);
2380         if (st == NULL)
2381                 return -ENOMEM;
2382
2383 rebuild_st:
2384         if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
2385                 kfree(st);
2386                 return -ENOMEM;
2387         }
2388
2389         /*
2390          * Get the list of pages out of our struct file.  They'll be pinned
2391          * at this point until we release them.
2392          *
2393          * Fail silently without starting the shrinker
2394          */
2395         mapping = obj->base.filp->f_mapping;
2396         mapping_set_unevictable(mapping);
2397         noreclaim = mapping_gfp_constraint(mapping, ~__GFP_RECLAIM);
2398         noreclaim |= __GFP_NORETRY | __GFP_NOWARN;
2399
2400         sg = st->sgl;
2401         st->nents = 0;
2402         sg_page_sizes = 0;
2403         for (i = 0; i < page_count; i++) {
2404                 const unsigned int shrink[] = {
2405                         I915_SHRINK_BOUND | I915_SHRINK_UNBOUND | I915_SHRINK_PURGEABLE,
2406                         0,
2407                 }, *s = shrink;
2408                 gfp_t gfp = noreclaim;
2409
2410                 do {
2411                         cond_resched();
2412                         page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2413                         if (!IS_ERR(page))
2414                                 break;
2415
2416                         if (!*s) {
2417                                 ret = PTR_ERR(page);
2418                                 goto err_sg;
2419                         }
2420
2421                         i915_gem_shrink(dev_priv, 2 * page_count, NULL, *s++);
2422
2423                         /*
2424                          * We've tried hard to allocate the memory by reaping
2425                          * our own buffer, now let the real VM do its job and
2426                          * go down in flames if truly OOM.
2427                          *
2428                          * However, since graphics tend to be disposable,
2429                          * defer the oom here by reporting the ENOMEM back
2430                          * to userspace.
2431                          */
2432                         if (!*s) {
2433                                 /* reclaim and warn, but no oom */
2434                                 gfp = mapping_gfp_mask(mapping);
2435
2436                                 /*
2437                                  * Our bo are always dirty and so we require
2438                                  * kswapd to reclaim our pages (direct reclaim
2439                                  * does not effectively begin pageout of our
2440                                  * buffers on its own). However, direct reclaim
2441                                  * only waits for kswapd when under allocation
2442                                  * congestion. So as a result __GFP_RECLAIM is
2443                                  * unreliable and fails to actually reclaim our
2444                                  * dirty pages -- unless you try over and over
2445                                  * again with !__GFP_NORETRY. However, we still
2446                                  * want to fail this allocation rather than
2447                                  * trigger the out-of-memory killer and for
2448                                  * this we want __GFP_RETRY_MAYFAIL.
2449                                  */
2450                                 gfp |= __GFP_RETRY_MAYFAIL;
2451                         }
2452                 } while (1);
2453
2454                 if (!i ||
2455                     sg->length >= max_segment ||
2456                     page_to_pfn(page) != last_pfn + 1) {
2457                         if (i) {
2458                                 sg_page_sizes |= sg->length;
2459                                 sg = sg_next(sg);
2460                         }
2461                         st->nents++;
2462                         sg_set_page(sg, page, PAGE_SIZE, 0);
2463                 } else {
2464                         sg->length += PAGE_SIZE;
2465                 }
2466                 last_pfn = page_to_pfn(page);
2467
2468                 /* Check that the i965g/gm workaround works. */
2469                 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
2470         }
2471         if (sg) { /* loop terminated early; short sg table */
2472                 sg_page_sizes |= sg->length;
2473                 sg_mark_end(sg);
2474         }
2475
2476         /* Trim unused sg entries to avoid wasting memory. */
2477         i915_sg_trim(st);
2478
2479         ret = i915_gem_gtt_prepare_pages(obj, st);
2480         if (ret) {
2481                 /*
2482                  * DMA remapping failed? One possible cause is that
2483                  * it could not reserve enough large entries, asking
2484                  * for PAGE_SIZE chunks instead may be helpful.
2485                  */
2486                 if (max_segment > PAGE_SIZE) {
2487                         for_each_sgt_page(page, sgt_iter, st)
2488                                 put_page(page);
2489                         sg_free_table(st);
2490
2491                         max_segment = PAGE_SIZE;
2492                         goto rebuild_st;
2493                 } else {
2494                         dev_warn(&dev_priv->drm.pdev->dev,
2495                                  "Failed to DMA remap %lu pages\n",
2496                                  page_count);
2497                         goto err_pages;
2498                 }
2499         }
2500
2501         if (i915_gem_object_needs_bit17_swizzle(obj))
2502                 i915_gem_object_do_bit_17_swizzle(obj, st);
2503
2504         __i915_gem_object_set_pages(obj, st, sg_page_sizes);
2505
2506         return 0;
2507
2508 err_sg:
2509         sg_mark_end(sg);
2510 err_pages:
2511         mapping_clear_unevictable(mapping);
2512         pagevec_init(&pvec);
2513         for_each_sgt_page(page, sgt_iter, st) {
2514                 if (!pagevec_add(&pvec, page))
2515                         check_release_pagevec(&pvec);
2516         }
2517         if (pagevec_count(&pvec))
2518                 check_release_pagevec(&pvec);
2519         sg_free_table(st);
2520         kfree(st);
2521
2522         /*
2523          * shmemfs first checks if there is enough memory to allocate the page
2524          * and reports ENOSPC should there be insufficient, along with the usual
2525          * ENOMEM for a genuine allocation failure.
2526          *
2527          * We use ENOSPC in our driver to mean that we have run out of aperture
2528          * space and so want to translate the error from shmemfs back to our
2529          * usual understanding of ENOMEM.
2530          */
2531         if (ret == -ENOSPC)
2532                 ret = -ENOMEM;
2533
2534         return ret;
2535 }
2536
2537 void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
2538                                  struct sg_table *pages,
2539                                  unsigned int sg_page_sizes)
2540 {
2541         struct drm_i915_private *i915 = to_i915(obj->base.dev);
2542         unsigned long supported = INTEL_INFO(i915)->page_sizes;
2543         int i;
2544
2545         lockdep_assert_held(&obj->mm.lock);
2546
2547         /* Make the pages coherent with the GPU (flushing any swapin). */
2548         if (obj->cache_dirty) {
2549                 obj->write_domain = 0;
2550                 if (i915_gem_object_has_struct_page(obj))
2551                         drm_clflush_sg(pages);
2552                 obj->cache_dirty = false;
2553         }
2554
2555         obj->mm.get_page.sg_pos = pages->sgl;
2556         obj->mm.get_page.sg_idx = 0;
2557
2558         obj->mm.pages = pages;
2559
2560         if (i915_gem_object_is_tiled(obj) &&
2561             i915->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
2562                 GEM_BUG_ON(obj->mm.quirked);
2563                 __i915_gem_object_pin_pages(obj);
2564                 obj->mm.quirked = true;
2565         }
2566
2567         GEM_BUG_ON(!sg_page_sizes);
2568         obj->mm.page_sizes.phys = sg_page_sizes;
2569
2570         /*
2571          * Calculate the supported page-sizes which fit into the given
2572          * sg_page_sizes. This will give us the page-sizes which we may be able
2573          * to use opportunistically when later inserting into the GTT. For
2574          * example if phys=2G, then in theory we should be able to use 1G, 2M,
2575          * 64K or 4K pages, although in practice this will depend on a number of
2576          * other factors.
2577          */
2578         obj->mm.page_sizes.sg = 0;
2579         for_each_set_bit(i, &supported, ilog2(I915_GTT_MAX_PAGE_SIZE) + 1) {
2580                 if (obj->mm.page_sizes.phys & ~0u << i)
2581                         obj->mm.page_sizes.sg |= BIT(i);
2582         }
2583         GEM_BUG_ON(!HAS_PAGE_SIZES(i915, obj->mm.page_sizes.sg));
2584
2585         spin_lock(&i915->mm.obj_lock);
2586         list_add(&obj->mm.link, &i915->mm.unbound_list);
2587         spin_unlock(&i915->mm.obj_lock);
2588 }
2589
2590 static int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2591 {
2592         int err;
2593
2594         if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
2595                 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2596                 return -EFAULT;
2597         }
2598
2599         err = obj->ops->get_pages(obj);
2600         GEM_BUG_ON(!err && !i915_gem_object_has_pages(obj));
2601
2602         return err;
2603 }
2604
2605 /* Ensure that the associated pages are gathered from the backing storage
2606  * and pinned into our object. i915_gem_object_pin_pages() may be called
2607  * multiple times before they are released by a single call to
2608  * i915_gem_object_unpin_pages() - once the pages are no longer referenced
2609  * either as a result of memory pressure (reaping pages under the shrinker)
2610  * or as the object is itself released.
2611  */
2612 int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2613 {
2614         int err;
2615
2616         err = mutex_lock_interruptible(&obj->mm.lock);
2617         if (err)
2618                 return err;
2619
2620         if (unlikely(!i915_gem_object_has_pages(obj))) {
2621                 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2622
2623                 err = ____i915_gem_object_get_pages(obj);
2624                 if (err)
2625                         goto unlock;
2626
2627                 smp_mb__before_atomic();
2628         }
2629         atomic_inc(&obj->mm.pages_pin_count);
2630
2631 unlock:
2632         mutex_unlock(&obj->mm.lock);
2633         return err;
2634 }
2635
2636 /* The 'mapping' part of i915_gem_object_pin_map() below */
2637 static void *i915_gem_object_map(const struct drm_i915_gem_object *obj,
2638                                  enum i915_map_type type)
2639 {
2640         unsigned long n_pages = obj->base.size >> PAGE_SHIFT;
2641         struct sg_table *sgt = obj->mm.pages;
2642         struct sgt_iter sgt_iter;
2643         struct page *page;
2644         struct page *stack_pages[32];
2645         struct page **pages = stack_pages;
2646         unsigned long i = 0;
2647         pgprot_t pgprot;
2648         void *addr;
2649
2650         /* A single page can always be kmapped */
2651         if (n_pages == 1 && type == I915_MAP_WB)
2652                 return kmap(sg_page(sgt->sgl));
2653
2654         if (n_pages > ARRAY_SIZE(stack_pages)) {
2655                 /* Too big for stack -- allocate temporary array instead */
2656                 pages = kvmalloc_array(n_pages, sizeof(*pages), GFP_KERNEL);
2657                 if (!pages)
2658                         return NULL;
2659         }
2660
2661         for_each_sgt_page(page, sgt_iter, sgt)
2662                 pages[i++] = page;
2663
2664         /* Check that we have the expected number of pages */
2665         GEM_BUG_ON(i != n_pages);
2666
2667         switch (type) {
2668         default:
2669                 MISSING_CASE(type);
2670                 /* fallthrough to use PAGE_KERNEL anyway */
2671         case I915_MAP_WB:
2672                 pgprot = PAGE_KERNEL;
2673                 break;
2674         case I915_MAP_WC:
2675                 pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
2676                 break;
2677         }
2678         addr = vmap(pages, n_pages, 0, pgprot);
2679
2680         if (pages != stack_pages)
2681                 kvfree(pages);
2682
2683         return addr;
2684 }
2685
2686 /* get, pin, and map the pages of the object into kernel space */
2687 void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
2688                               enum i915_map_type type)
2689 {
2690         enum i915_map_type has_type;
2691         bool pinned;
2692         void *ptr;
2693         int ret;
2694
2695         if (unlikely(!i915_gem_object_has_struct_page(obj)))
2696                 return ERR_PTR(-ENXIO);
2697
2698         ret = mutex_lock_interruptible(&obj->mm.lock);
2699         if (ret)
2700                 return ERR_PTR(ret);
2701
2702         pinned = !(type & I915_MAP_OVERRIDE);
2703         type &= ~I915_MAP_OVERRIDE;
2704
2705         if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
2706                 if (unlikely(!i915_gem_object_has_pages(obj))) {
2707                         GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2708
2709                         ret = ____i915_gem_object_get_pages(obj);
2710                         if (ret)
2711                                 goto err_unlock;
2712
2713                         smp_mb__before_atomic();
2714                 }
2715                 atomic_inc(&obj->mm.pages_pin_count);
2716                 pinned = false;
2717         }
2718         GEM_BUG_ON(!i915_gem_object_has_pages(obj));
2719
2720         ptr = page_unpack_bits(obj->mm.mapping, &has_type);
2721         if (ptr && has_type != type) {
2722                 if (pinned) {
2723                         ret = -EBUSY;
2724                         goto err_unpin;
2725                 }
2726
2727                 if (is_vmalloc_addr(ptr))
2728                         vunmap(ptr);
2729                 else
2730                         kunmap(kmap_to_page(ptr));
2731
2732                 ptr = obj->mm.mapping = NULL;
2733         }
2734
2735         if (!ptr) {
2736                 ptr = i915_gem_object_map(obj, type);
2737                 if (!ptr) {
2738                         ret = -ENOMEM;
2739                         goto err_unpin;
2740                 }
2741
2742                 obj->mm.mapping = page_pack_bits(ptr, type);
2743         }
2744
2745 out_unlock:
2746         mutex_unlock(&obj->mm.lock);
2747         return ptr;
2748
2749 err_unpin:
2750         atomic_dec(&obj->mm.pages_pin_count);
2751 err_unlock:
2752         ptr = ERR_PTR(ret);
2753         goto out_unlock;
2754 }
2755
2756 void __i915_gem_object_flush_map(struct drm_i915_gem_object *obj,
2757                                  unsigned long offset,
2758                                  unsigned long size)
2759 {
2760         enum i915_map_type has_type;
2761         void *ptr;
2762
2763         GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
2764         GEM_BUG_ON(range_overflows_t(typeof(obj->base.size),
2765                                      offset, size, obj->base.size));
2766
2767         obj->mm.dirty = true;
2768
2769         if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE)
2770                 return;
2771
2772         ptr = page_unpack_bits(obj->mm.mapping, &has_type);
2773         if (has_type == I915_MAP_WC)
2774                 return;
2775
2776         drm_clflush_virt_range(ptr + offset, size);
2777         if (size == obj->base.size) {
2778                 obj->write_domain &= ~I915_GEM_DOMAIN_CPU;
2779                 obj->cache_dirty = false;
2780         }
2781 }
2782
2783 static int
2784 i915_gem_object_pwrite_gtt(struct drm_i915_gem_object *obj,
2785                            const struct drm_i915_gem_pwrite *arg)
2786 {
2787         struct address_space *mapping = obj->base.filp->f_mapping;
2788         char __user *user_data = u64_to_user_ptr(arg->data_ptr);
2789         u64 remain, offset;
2790         unsigned int pg;
2791
2792         /* Before we instantiate/pin the backing store for our use, we
2793          * can prepopulate the shmemfs filp efficiently using a write into
2794          * the pagecache. We avoid the penalty of instantiating all the
2795          * pages, important if the user is just writing to a few and never
2796          * uses the object on the GPU, and using a direct write into shmemfs
2797          * allows it to avoid the cost of retrieving a page (either swapin
2798          * or clearing-before-use) before it is overwritten.
2799          */
2800         if (i915_gem_object_has_pages(obj))
2801                 return -ENODEV;
2802
2803         if (obj->mm.madv != I915_MADV_WILLNEED)
2804                 return -EFAULT;
2805
2806         /* Before the pages are instantiated the object is treated as being
2807          * in the CPU domain. The pages will be clflushed as required before
2808          * use, and we can freely write into the pages directly. If userspace
2809          * races pwrite with any other operation; corruption will ensue -
2810          * that is userspace's prerogative!
2811          */
2812
2813         remain = arg->size;
2814         offset = arg->offset;
2815         pg = offset_in_page(offset);
2816
2817         do {
2818                 unsigned int len, unwritten;
2819                 struct page *page;
2820                 void *data, *vaddr;
2821                 int err;
2822
2823                 len = PAGE_SIZE - pg;
2824                 if (len > remain)
2825                         len = remain;
2826
2827                 err = pagecache_write_begin(obj->base.filp, mapping,
2828                                             offset, len, 0,
2829                                             &page, &data);
2830                 if (err < 0)
2831                         return err;
2832
2833                 vaddr = kmap(page);
2834                 unwritten = copy_from_user(vaddr + pg, user_data, len);
2835                 kunmap(page);
2836
2837                 err = pagecache_write_end(obj->base.filp, mapping,
2838                                           offset, len, len - unwritten,
2839                                           page, data);
2840                 if (err < 0)
2841                         return err;
2842
2843                 if (unwritten)
2844                         return -EFAULT;
2845
2846                 remain -= len;
2847                 user_data += len;
2848                 offset += len;
2849                 pg = 0;
2850         } while (remain);
2851
2852         return 0;
2853 }
2854
2855 static void
2856 i915_gem_retire_work_handler(struct work_struct *work)
2857 {
2858         struct drm_i915_private *dev_priv =
2859                 container_of(work, typeof(*dev_priv), gt.retire_work.work);
2860         struct drm_device *dev = &dev_priv->drm;
2861
2862         /* Come back later if the device is busy... */
2863         if (mutex_trylock(&dev->struct_mutex)) {
2864                 i915_retire_requests(dev_priv);
2865                 mutex_unlock(&dev->struct_mutex);
2866         }
2867
2868         /*
2869          * Keep the retire handler running until we are finally idle.
2870          * We do not need to do this test under locking as in the worst-case
2871          * we queue the retire worker once too often.
2872          */
2873         if (READ_ONCE(dev_priv->gt.awake))
2874                 queue_delayed_work(dev_priv->wq,
2875                                    &dev_priv->gt.retire_work,
2876                                    round_jiffies_up_relative(HZ));
2877 }
2878
2879 static bool switch_to_kernel_context_sync(struct drm_i915_private *i915,
2880                                           unsigned long mask)
2881 {
2882         bool result = true;
2883
2884         /*
2885          * Even if we fail to switch, give whatever is running a small chance
2886          * to save itself before we report the failure. Yes, this may be a
2887          * false positive due to e.g. ENOMEM, caveat emptor!
2888          */
2889         if (i915_gem_switch_to_kernel_context(i915, mask))
2890                 result = false;
2891
2892         if (i915_gem_wait_for_idle(i915,
2893                                    I915_WAIT_LOCKED |
2894                                    I915_WAIT_FOR_IDLE_BOOST,
2895                                    I915_GEM_IDLE_TIMEOUT))
2896                 result = false;
2897
2898         if (!result) {
2899                 if (i915_modparams.reset) { /* XXX hide warning from gem_eio */
2900                         dev_err(i915->drm.dev,
2901                                 "Failed to idle engines, declaring wedged!\n");
2902                         GEM_TRACE_DUMP();
2903                 }
2904
2905                 /* Forcibly cancel outstanding work and leave the gpu quiet. */
2906                 i915_gem_set_wedged(i915);
2907         }
2908
2909         i915_retire_requests(i915); /* ensure we flush after wedging */
2910         return result;
2911 }
2912
2913 static bool load_power_context(struct drm_i915_private *i915)
2914 {
2915         /* Force loading the kernel context on all engines */
2916         if (!switch_to_kernel_context_sync(i915, ALL_ENGINES))
2917                 return false;
2918
2919         /*
2920          * Immediately park the GPU so that we enable powersaving and
2921          * treat it as idle. The next time we issue a request, we will
2922          * unpark and start using the engine->pinned_default_state, otherwise
2923          * it is in limbo and an early reset may fail.
2924          */
2925         __i915_gem_park(i915);
2926
2927         return true;
2928 }
2929
2930 static void
2931 i915_gem_idle_work_handler(struct work_struct *work)
2932 {
2933         struct drm_i915_private *i915 =
2934                 container_of(work, typeof(*i915), gt.idle_work.work);
2935         bool rearm_hangcheck;
2936
2937         if (!READ_ONCE(i915->gt.awake))
2938                 return;
2939
2940         if (READ_ONCE(i915->gt.active_requests))
2941                 return;
2942
2943         rearm_hangcheck =
2944                 cancel_delayed_work_sync(&i915->gpu_error.hangcheck_work);
2945
2946         if (!mutex_trylock(&i915->drm.struct_mutex)) {
2947                 /* Currently busy, come back later */
2948                 mod_delayed_work(i915->wq,
2949                                  &i915->gt.idle_work,
2950                                  msecs_to_jiffies(50));
2951                 goto out_rearm;
2952         }
2953
2954         /*
2955          * Flush out the last user context, leaving only the pinned
2956          * kernel context resident. Should anything unfortunate happen
2957          * while we are idle (such as the GPU being power cycled), no users
2958          * will be harmed.
2959          */
2960         if (!work_pending(&i915->gt.idle_work.work) &&
2961             !i915->gt.active_requests) {
2962                 ++i915->gt.active_requests; /* don't requeue idle */
2963
2964                 switch_to_kernel_context_sync(i915, i915->gt.active_engines);
2965
2966                 if (!--i915->gt.active_requests) {
2967                         __i915_gem_park(i915);
2968                         rearm_hangcheck = false;
2969                 }
2970         }
2971
2972         mutex_unlock(&i915->drm.struct_mutex);
2973
2974 out_rearm:
2975         if (rearm_hangcheck) {
2976                 GEM_BUG_ON(!i915->gt.awake);
2977                 i915_queue_hangcheck(i915);
2978         }
2979 }
2980
2981 void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
2982 {
2983         struct drm_i915_private *i915 = to_i915(gem->dev);
2984         struct drm_i915_gem_object *obj = to_intel_bo(gem);
2985         struct drm_i915_file_private *fpriv = file->driver_priv;
2986         struct i915_lut_handle *lut, *ln;
2987
2988         mutex_lock(&i915->drm.struct_mutex);
2989
2990         list_for_each_entry_safe(lut, ln, &obj->lut_list, obj_link) {
2991                 struct i915_gem_context *ctx = lut->ctx;
2992                 struct i915_vma *vma;
2993
2994                 GEM_BUG_ON(ctx->file_priv == ERR_PTR(-EBADF));
2995                 if (ctx->file_priv != fpriv)
2996                         continue;
2997
2998                 vma = radix_tree_delete(&ctx->handles_vma, lut->handle);
2999                 GEM_BUG_ON(vma->obj != obj);
3000
3001                 /* We allow the process to have multiple handles to the same
3002                  * vma, in the same fd namespace, by virtue of flink/open.
3003                  */
3004                 GEM_BUG_ON(!vma->open_count);
3005                 if (!--vma->open_count && !i915_vma_is_ggtt(vma))
3006                         i915_vma_close(vma);
3007
3008                 list_del(&lut->obj_link);
3009                 list_del(&lut->ctx_link);
3010
3011                 i915_lut_handle_free(lut);
3012                 __i915_gem_object_release_unless_active(obj);
3013         }
3014
3015         mutex_unlock(&i915->drm.struct_mutex);
3016 }
3017
3018 static unsigned long to_wait_timeout(s64 timeout_ns)
3019 {
3020         if (timeout_ns < 0)
3021                 return MAX_SCHEDULE_TIMEOUT;
3022
3023         if (timeout_ns == 0)
3024                 return 0;
3025
3026         return nsecs_to_jiffies_timeout(timeout_ns);
3027 }
3028
3029 /**
3030  * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
3031  * @dev: drm device pointer
3032  * @data: ioctl data blob
3033  * @file: drm file pointer
3034  *
3035  * Returns 0 if successful, else an error is returned with the remaining time in
3036  * the timeout parameter.
3037  *  -ETIME: object is still busy after timeout
3038  *  -ERESTARTSYS: signal interrupted the wait
3039  *  -ENONENT: object doesn't exist
3040  * Also possible, but rare:
3041  *  -EAGAIN: incomplete, restart syscall
3042  *  -ENOMEM: damn
3043  *  -ENODEV: Internal IRQ fail
3044  *  -E?: The add request failed
3045  *
3046  * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
3047  * non-zero timeout parameter the wait ioctl will wait for the given number of
3048  * nanoseconds on an object becoming unbusy. Since the wait itself does so
3049  * without holding struct_mutex the object may become re-busied before this
3050  * function completes. A similar but shorter * race condition exists in the busy
3051  * ioctl
3052  */
3053 int
3054 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
3055 {
3056         struct drm_i915_gem_wait *args = data;
3057         struct drm_i915_gem_object *obj;
3058         ktime_t start;
3059         long ret;
3060
3061         if (args->flags != 0)
3062                 return -EINVAL;
3063
3064         obj = i915_gem_object_lookup(file, args->bo_handle);
3065         if (!obj)
3066                 return -ENOENT;
3067
3068         start = ktime_get();
3069
3070         ret = i915_gem_object_wait(obj,
3071                                    I915_WAIT_INTERRUPTIBLE |
3072                                    I915_WAIT_PRIORITY |
3073                                    I915_WAIT_ALL,
3074                                    to_wait_timeout(args->timeout_ns));
3075
3076         if (args->timeout_ns > 0) {
3077                 args->timeout_ns -= ktime_to_ns(ktime_sub(ktime_get(), start));
3078                 if (args->timeout_ns < 0)
3079                         args->timeout_ns = 0;
3080
3081                 /*
3082                  * Apparently ktime isn't accurate enough and occasionally has a
3083                  * bit of mismatch in the jiffies<->nsecs<->ktime loop. So patch
3084                  * things up to make the test happy. We allow up to 1 jiffy.
3085                  *
3086                  * This is a regression from the timespec->ktime conversion.
3087                  */
3088                 if (ret == -ETIME && !nsecs_to_jiffies(args->timeout_ns))
3089                         args->timeout_ns = 0;
3090
3091                 /* Asked to wait beyond the jiffie/scheduler precision? */
3092                 if (ret == -ETIME && args->timeout_ns)
3093                         ret = -EAGAIN;
3094         }
3095
3096         i915_gem_object_put(obj);
3097         return ret;
3098 }
3099
3100 static int wait_for_engines(struct drm_i915_private *i915)
3101 {
3102         if (wait_for(intel_engines_are_idle(i915), I915_IDLE_ENGINES_TIMEOUT)) {
3103                 dev_err(i915->drm.dev,
3104                         "Failed to idle engines, declaring wedged!\n");
3105                 GEM_TRACE_DUMP();
3106                 i915_gem_set_wedged(i915);
3107                 return -EIO;
3108         }
3109
3110         return 0;
3111 }
3112
3113 static long
3114 wait_for_timelines(struct drm_i915_private *i915,
3115                    unsigned int flags, long timeout)
3116 {
3117         struct i915_gt_timelines *gt = &i915->gt.timelines;
3118         struct i915_timeline *tl;
3119
3120         if (!READ_ONCE(i915->gt.active_requests))
3121                 return timeout;
3122
3123         mutex_lock(&gt->mutex);
3124         list_for_each_entry(tl, &gt->active_list, link) {
3125                 struct i915_request *rq;
3126
3127                 rq = i915_active_request_get_unlocked(&tl->last_request);
3128                 if (!rq)
3129                         continue;
3130
3131                 mutex_unlock(&gt->mutex);
3132
3133                 /*
3134                  * "Race-to-idle".
3135                  *
3136                  * Switching to the kernel context is often used a synchronous
3137                  * step prior to idling, e.g. in suspend for flushing all
3138                  * current operations to memory before sleeping. These we
3139                  * want to complete as quickly as possible to avoid prolonged
3140                  * stalls, so allow the gpu to boost to maximum clocks.
3141                  */
3142                 if (flags & I915_WAIT_FOR_IDLE_BOOST)
3143                         gen6_rps_boost(rq);
3144
3145                 timeout = i915_request_wait(rq, flags, timeout);
3146                 i915_request_put(rq);
3147                 if (timeout < 0)
3148                         return timeout;
3149
3150                 /* restart after reacquiring the lock */
3151                 mutex_lock(&gt->mutex);
3152                 tl = list_entry(&gt->active_list, typeof(*tl), link);
3153         }
3154         mutex_unlock(&gt->mutex);
3155
3156         return timeout;
3157 }
3158
3159 int i915_gem_wait_for_idle(struct drm_i915_private *i915,
3160                            unsigned int flags, long timeout)
3161 {
3162         GEM_TRACE("flags=%x (%s), timeout=%ld%s\n",
3163                   flags, flags & I915_WAIT_LOCKED ? "locked" : "unlocked",
3164                   timeout, timeout == MAX_SCHEDULE_TIMEOUT ? " (forever)" : "");
3165
3166         /* If the device is asleep, we have no requests outstanding */
3167         if (!READ_ONCE(i915->gt.awake))
3168                 return 0;
3169
3170         timeout = wait_for_timelines(i915, flags, timeout);
3171         if (timeout < 0)
3172                 return timeout;
3173
3174         if (flags & I915_WAIT_LOCKED) {
3175                 int err;
3176
3177                 lockdep_assert_held(&i915->drm.struct_mutex);
3178
3179                 err = wait_for_engines(i915);
3180                 if (err)
3181                         return err;
3182
3183                 i915_retire_requests(i915);
3184         }
3185
3186         return 0;
3187 }
3188
3189 static void __i915_gem_object_flush_for_display(struct drm_i915_gem_object *obj)
3190 {