GNU Linux-libre 4.14.328-gnu1
[releases.git] / drivers / gpu / drm / i915 / i915_gem.c
1 /*
2  * Copyright © 2008-2015 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *
26  */
27
28 #include <drm/drmP.h>
29 #include <drm/drm_vma_manager.h>
30 #include <drm/i915_drm.h>
31 #include "i915_drv.h"
32 #include "i915_gem_clflush.h"
33 #include "i915_vgpu.h"
34 #include "i915_trace.h"
35 #include "intel_drv.h"
36 #include "intel_frontbuffer.h"
37 #include "intel_mocs.h"
38 #include <linux/dma-fence-array.h>
39 #include <linux/kthread.h>
40 #include <linux/reservation.h>
41 #include <linux/shmem_fs.h>
42 #include <linux/slab.h>
43 #include <linux/stop_machine.h>
44 #include <linux/swap.h>
45 #include <linux/pci.h>
46 #include <linux/dma-buf.h>
47
48 static void i915_gem_flush_free_objects(struct drm_i915_private *i915);
49
50 static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
51 {
52         if (obj->cache_dirty)
53                 return false;
54
55         if (!(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE))
56                 return true;
57
58         return obj->pin_display;
59 }
60
61 static int
62 insert_mappable_node(struct i915_ggtt *ggtt,
63                      struct drm_mm_node *node, u32 size)
64 {
65         memset(node, 0, sizeof(*node));
66         return drm_mm_insert_node_in_range(&ggtt->base.mm, node,
67                                            size, 0, I915_COLOR_UNEVICTABLE,
68                                            0, ggtt->mappable_end,
69                                            DRM_MM_INSERT_LOW);
70 }
71
72 static void
73 remove_mappable_node(struct drm_mm_node *node)
74 {
75         drm_mm_remove_node(node);
76 }
77
78 /* some bookkeeping */
79 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
80                                   u64 size)
81 {
82         spin_lock(&dev_priv->mm.object_stat_lock);
83         dev_priv->mm.object_count++;
84         dev_priv->mm.object_memory += size;
85         spin_unlock(&dev_priv->mm.object_stat_lock);
86 }
87
88 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
89                                      u64 size)
90 {
91         spin_lock(&dev_priv->mm.object_stat_lock);
92         dev_priv->mm.object_count--;
93         dev_priv->mm.object_memory -= size;
94         spin_unlock(&dev_priv->mm.object_stat_lock);
95 }
96
97 static int
98 i915_gem_wait_for_error(struct i915_gpu_error *error)
99 {
100         int ret;
101
102         might_sleep();
103
104         /*
105          * Only wait 10 seconds for the gpu reset to complete to avoid hanging
106          * userspace. If it takes that long something really bad is going on and
107          * we should simply try to bail out and fail as gracefully as possible.
108          */
109         ret = wait_event_interruptible_timeout(error->reset_queue,
110                                                !i915_reset_backoff(error),
111                                                I915_RESET_TIMEOUT);
112         if (ret == 0) {
113                 DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
114                 return -EIO;
115         } else if (ret < 0) {
116                 return ret;
117         } else {
118                 return 0;
119         }
120 }
121
122 int i915_mutex_lock_interruptible(struct drm_device *dev)
123 {
124         struct drm_i915_private *dev_priv = to_i915(dev);
125         int ret;
126
127         ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
128         if (ret)
129                 return ret;
130
131         ret = mutex_lock_interruptible(&dev->struct_mutex);
132         if (ret)
133                 return ret;
134
135         return 0;
136 }
137
138 int
139 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
140                             struct drm_file *file)
141 {
142         struct drm_i915_private *dev_priv = to_i915(dev);
143         struct i915_ggtt *ggtt = &dev_priv->ggtt;
144         struct drm_i915_gem_get_aperture *args = data;
145         struct i915_vma *vma;
146         u64 pinned;
147
148         pinned = ggtt->base.reserved;
149         mutex_lock(&dev->struct_mutex);
150         list_for_each_entry(vma, &ggtt->base.active_list, vm_link)
151                 if (i915_vma_is_pinned(vma))
152                         pinned += vma->node.size;
153         list_for_each_entry(vma, &ggtt->base.inactive_list, vm_link)
154                 if (i915_vma_is_pinned(vma))
155                         pinned += vma->node.size;
156         mutex_unlock(&dev->struct_mutex);
157
158         args->aper_size = ggtt->base.total;
159         args->aper_available_size = args->aper_size - pinned;
160
161         return 0;
162 }
163
164 static struct sg_table *
165 i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
166 {
167         struct address_space *mapping = obj->base.filp->f_mapping;
168         drm_dma_handle_t *phys;
169         struct sg_table *st;
170         struct scatterlist *sg;
171         char *vaddr;
172         int i;
173
174         if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
175                 return ERR_PTR(-EINVAL);
176
177         /* Always aligning to the object size, allows a single allocation
178          * to handle all possible callers, and given typical object sizes,
179          * the alignment of the buddy allocation will naturally match.
180          */
181         phys = drm_pci_alloc(obj->base.dev,
182                              obj->base.size,
183                              roundup_pow_of_two(obj->base.size));
184         if (!phys)
185                 return ERR_PTR(-ENOMEM);
186
187         vaddr = phys->vaddr;
188         for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
189                 struct page *page;
190                 char *src;
191
192                 page = shmem_read_mapping_page(mapping, i);
193                 if (IS_ERR(page)) {
194                         st = ERR_CAST(page);
195                         goto err_phys;
196                 }
197
198                 src = kmap_atomic(page);
199                 memcpy(vaddr, src, PAGE_SIZE);
200                 drm_clflush_virt_range(vaddr, PAGE_SIZE);
201                 kunmap_atomic(src);
202
203                 put_page(page);
204                 vaddr += PAGE_SIZE;
205         }
206
207         i915_gem_chipset_flush(to_i915(obj->base.dev));
208
209         st = kmalloc(sizeof(*st), GFP_KERNEL);
210         if (!st) {
211                 st = ERR_PTR(-ENOMEM);
212                 goto err_phys;
213         }
214
215         if (sg_alloc_table(st, 1, GFP_KERNEL)) {
216                 kfree(st);
217                 st = ERR_PTR(-ENOMEM);
218                 goto err_phys;
219         }
220
221         sg = st->sgl;
222         sg->offset = 0;
223         sg->length = obj->base.size;
224
225         sg_dma_address(sg) = phys->busaddr;
226         sg_dma_len(sg) = obj->base.size;
227
228         obj->phys_handle = phys;
229         return st;
230
231 err_phys:
232         drm_pci_free(obj->base.dev, phys);
233         return st;
234 }
235
236 static void __start_cpu_write(struct drm_i915_gem_object *obj)
237 {
238         obj->base.read_domains = I915_GEM_DOMAIN_CPU;
239         obj->base.write_domain = I915_GEM_DOMAIN_CPU;
240         if (cpu_write_needs_clflush(obj))
241                 obj->cache_dirty = true;
242 }
243
244 static void
245 __i915_gem_object_release_shmem(struct drm_i915_gem_object *obj,
246                                 struct sg_table *pages,
247                                 bool needs_clflush)
248 {
249         GEM_BUG_ON(obj->mm.madv == __I915_MADV_PURGED);
250
251         if (obj->mm.madv == I915_MADV_DONTNEED)
252                 obj->mm.dirty = false;
253
254         if (needs_clflush &&
255             (obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0 &&
256             !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ))
257                 drm_clflush_sg(pages);
258
259         __start_cpu_write(obj);
260 }
261
262 static void
263 i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj,
264                                struct sg_table *pages)
265 {
266         __i915_gem_object_release_shmem(obj, pages, false);
267
268         if (obj->mm.dirty) {
269                 struct address_space *mapping = obj->base.filp->f_mapping;
270                 char *vaddr = obj->phys_handle->vaddr;
271                 int i;
272
273                 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
274                         struct page *page;
275                         char *dst;
276
277                         page = shmem_read_mapping_page(mapping, i);
278                         if (IS_ERR(page))
279                                 continue;
280
281                         dst = kmap_atomic(page);
282                         drm_clflush_virt_range(vaddr, PAGE_SIZE);
283                         memcpy(dst, vaddr, PAGE_SIZE);
284                         kunmap_atomic(dst);
285
286                         set_page_dirty(page);
287                         if (obj->mm.madv == I915_MADV_WILLNEED)
288                                 mark_page_accessed(page);
289                         put_page(page);
290                         vaddr += PAGE_SIZE;
291                 }
292                 obj->mm.dirty = false;
293         }
294
295         sg_free_table(pages);
296         kfree(pages);
297
298         drm_pci_free(obj->base.dev, obj->phys_handle);
299 }
300
301 static void
302 i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
303 {
304         i915_gem_object_unpin_pages(obj);
305 }
306
307 static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
308         .get_pages = i915_gem_object_get_pages_phys,
309         .put_pages = i915_gem_object_put_pages_phys,
310         .release = i915_gem_object_release_phys,
311 };
312
313 static const struct drm_i915_gem_object_ops i915_gem_object_ops;
314
315 int i915_gem_object_unbind(struct drm_i915_gem_object *obj)
316 {
317         struct i915_vma *vma;
318         LIST_HEAD(still_in_list);
319         int ret;
320
321         lockdep_assert_held(&obj->base.dev->struct_mutex);
322
323         /* Closed vma are removed from the obj->vma_list - but they may
324          * still have an active binding on the object. To remove those we
325          * must wait for all rendering to complete to the object (as unbinding
326          * must anyway), and retire the requests.
327          */
328         ret = i915_gem_object_set_to_cpu_domain(obj, false);
329         if (ret)
330                 return ret;
331
332         while ((vma = list_first_entry_or_null(&obj->vma_list,
333                                                struct i915_vma,
334                                                obj_link))) {
335                 list_move_tail(&vma->obj_link, &still_in_list);
336                 ret = i915_vma_unbind(vma);
337                 if (ret)
338                         break;
339         }
340         list_splice(&still_in_list, &obj->vma_list);
341
342         return ret;
343 }
344
345 static long
346 i915_gem_object_wait_fence(struct dma_fence *fence,
347                            unsigned int flags,
348                            long timeout,
349                            struct intel_rps_client *rps)
350 {
351         struct drm_i915_gem_request *rq;
352
353         BUILD_BUG_ON(I915_WAIT_INTERRUPTIBLE != 0x1);
354
355         if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
356                 return timeout;
357
358         if (!dma_fence_is_i915(fence))
359                 return dma_fence_wait_timeout(fence,
360                                               flags & I915_WAIT_INTERRUPTIBLE,
361                                               timeout);
362
363         rq = to_request(fence);
364         if (i915_gem_request_completed(rq))
365                 goto out;
366
367         /* This client is about to stall waiting for the GPU. In many cases
368          * this is undesirable and limits the throughput of the system, as
369          * many clients cannot continue processing user input/output whilst
370          * blocked. RPS autotuning may take tens of milliseconds to respond
371          * to the GPU load and thus incurs additional latency for the client.
372          * We can circumvent that by promoting the GPU frequency to maximum
373          * before we wait. This makes the GPU throttle up much more quickly
374          * (good for benchmarks and user experience, e.g. window animations),
375          * but at a cost of spending more power processing the workload
376          * (bad for battery). Not all clients even want their results
377          * immediately and for them we should just let the GPU select its own
378          * frequency to maximise efficiency. To prevent a single client from
379          * forcing the clocks too high for the whole system, we only allow
380          * each client to waitboost once in a busy period.
381          */
382         if (rps) {
383                 if (INTEL_GEN(rq->i915) >= 6)
384                         gen6_rps_boost(rq, rps);
385                 else
386                         rps = NULL;
387         }
388
389         timeout = i915_wait_request(rq, flags, timeout);
390
391 out:
392         if (flags & I915_WAIT_LOCKED && i915_gem_request_completed(rq))
393                 i915_gem_request_retire_upto(rq);
394
395         return timeout;
396 }
397
398 static long
399 i915_gem_object_wait_reservation(struct reservation_object *resv,
400                                  unsigned int flags,
401                                  long timeout,
402                                  struct intel_rps_client *rps)
403 {
404         unsigned int seq = __read_seqcount_begin(&resv->seq);
405         struct dma_fence *excl;
406         bool prune_fences = false;
407
408         if (flags & I915_WAIT_ALL) {
409                 struct dma_fence **shared;
410                 unsigned int count, i;
411                 int ret;
412
413                 ret = reservation_object_get_fences_rcu(resv,
414                                                         &excl, &count, &shared);
415                 if (ret)
416                         return ret;
417
418                 for (i = 0; i < count; i++) {
419                         timeout = i915_gem_object_wait_fence(shared[i],
420                                                              flags, timeout,
421                                                              rps);
422                         if (timeout < 0)
423                                 break;
424
425                         dma_fence_put(shared[i]);
426                 }
427
428                 for (; i < count; i++)
429                         dma_fence_put(shared[i]);
430                 kfree(shared);
431
432                 prune_fences = count && timeout >= 0;
433         } else {
434                 excl = reservation_object_get_excl_rcu(resv);
435         }
436
437         if (excl && timeout >= 0) {
438                 timeout = i915_gem_object_wait_fence(excl, flags, timeout, rps);
439                 prune_fences = timeout >= 0;
440         }
441
442         dma_fence_put(excl);
443
444         /* Oportunistically prune the fences iff we know they have *all* been
445          * signaled and that the reservation object has not been changed (i.e.
446          * no new fences have been added).
447          */
448         if (prune_fences && !__read_seqcount_retry(&resv->seq, seq)) {
449                 if (reservation_object_trylock(resv)) {
450                         if (!__read_seqcount_retry(&resv->seq, seq))
451                                 reservation_object_add_excl_fence(resv, NULL);
452                         reservation_object_unlock(resv);
453                 }
454         }
455
456         return timeout;
457 }
458
459 static void __fence_set_priority(struct dma_fence *fence, int prio)
460 {
461         struct drm_i915_gem_request *rq;
462         struct intel_engine_cs *engine;
463
464         if (!dma_fence_is_i915(fence))
465                 return;
466
467         rq = to_request(fence);
468         engine = rq->engine;
469         if (!engine->schedule)
470                 return;
471
472         engine->schedule(rq, prio);
473 }
474
475 static void fence_set_priority(struct dma_fence *fence, int prio)
476 {
477         /* Recurse once into a fence-array */
478         if (dma_fence_is_array(fence)) {
479                 struct dma_fence_array *array = to_dma_fence_array(fence);
480                 int i;
481
482                 for (i = 0; i < array->num_fences; i++)
483                         __fence_set_priority(array->fences[i], prio);
484         } else {
485                 __fence_set_priority(fence, prio);
486         }
487 }
488
489 int
490 i915_gem_object_wait_priority(struct drm_i915_gem_object *obj,
491                               unsigned int flags,
492                               int prio)
493 {
494         struct dma_fence *excl;
495
496         if (flags & I915_WAIT_ALL) {
497                 struct dma_fence **shared;
498                 unsigned int count, i;
499                 int ret;
500
501                 ret = reservation_object_get_fences_rcu(obj->resv,
502                                                         &excl, &count, &shared);
503                 if (ret)
504                         return ret;
505
506                 for (i = 0; i < count; i++) {
507                         fence_set_priority(shared[i], prio);
508                         dma_fence_put(shared[i]);
509                 }
510
511                 kfree(shared);
512         } else {
513                 excl = reservation_object_get_excl_rcu(obj->resv);
514         }
515
516         if (excl) {
517                 fence_set_priority(excl, prio);
518                 dma_fence_put(excl);
519         }
520         return 0;
521 }
522
523 /**
524  * Waits for rendering to the object to be completed
525  * @obj: i915 gem object
526  * @flags: how to wait (under a lock, for all rendering or just for writes etc)
527  * @timeout: how long to wait
528  * @rps: client (user process) to charge for any waitboosting
529  */
530 int
531 i915_gem_object_wait(struct drm_i915_gem_object *obj,
532                      unsigned int flags,
533                      long timeout,
534                      struct intel_rps_client *rps)
535 {
536         might_sleep();
537 #if IS_ENABLED(CONFIG_LOCKDEP)
538         GEM_BUG_ON(debug_locks &&
539                    !!lockdep_is_held(&obj->base.dev->struct_mutex) !=
540                    !!(flags & I915_WAIT_LOCKED));
541 #endif
542         GEM_BUG_ON(timeout < 0);
543
544         timeout = i915_gem_object_wait_reservation(obj->resv,
545                                                    flags, timeout,
546                                                    rps);
547         return timeout < 0 ? timeout : 0;
548 }
549
550 static struct intel_rps_client *to_rps_client(struct drm_file *file)
551 {
552         struct drm_i915_file_private *fpriv = file->driver_priv;
553
554         return &fpriv->rps;
555 }
556
557 static int
558 i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
559                      struct drm_i915_gem_pwrite *args,
560                      struct drm_file *file)
561 {
562         void *vaddr = obj->phys_handle->vaddr + args->offset;
563         char __user *user_data = u64_to_user_ptr(args->data_ptr);
564
565         /* We manually control the domain here and pretend that it
566          * remains coherent i.e. in the GTT domain, like shmem_pwrite.
567          */
568         intel_fb_obj_invalidate(obj, ORIGIN_CPU);
569         if (copy_from_user(vaddr, user_data, args->size))
570                 return -EFAULT;
571
572         drm_clflush_virt_range(vaddr, args->size);
573         i915_gem_chipset_flush(to_i915(obj->base.dev));
574
575         intel_fb_obj_flush(obj, ORIGIN_CPU);
576         return 0;
577 }
578
579 void *i915_gem_object_alloc(struct drm_i915_private *dev_priv)
580 {
581         return kmem_cache_zalloc(dev_priv->objects, GFP_KERNEL);
582 }
583
584 void i915_gem_object_free(struct drm_i915_gem_object *obj)
585 {
586         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
587         kmem_cache_free(dev_priv->objects, obj);
588 }
589
590 static int
591 i915_gem_create(struct drm_file *file,
592                 struct drm_i915_private *dev_priv,
593                 uint64_t size,
594                 uint32_t *handle_p)
595 {
596         struct drm_i915_gem_object *obj;
597         int ret;
598         u32 handle;
599
600         size = roundup(size, PAGE_SIZE);
601         if (size == 0)
602                 return -EINVAL;
603
604         /* Allocate the new object */
605         obj = i915_gem_object_create(dev_priv, size);
606         if (IS_ERR(obj))
607                 return PTR_ERR(obj);
608
609         ret = drm_gem_handle_create(file, &obj->base, &handle);
610         /* drop reference from allocate - handle holds it now */
611         i915_gem_object_put(obj);
612         if (ret)
613                 return ret;
614
615         *handle_p = handle;
616         return 0;
617 }
618
619 int
620 i915_gem_dumb_create(struct drm_file *file,
621                      struct drm_device *dev,
622                      struct drm_mode_create_dumb *args)
623 {
624         /* have to work out size/pitch and return them */
625         args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
626         args->size = args->pitch * args->height;
627         return i915_gem_create(file, to_i915(dev),
628                                args->size, &args->handle);
629 }
630
631 static bool gpu_write_needs_clflush(struct drm_i915_gem_object *obj)
632 {
633         return !(obj->cache_level == I915_CACHE_NONE ||
634                  obj->cache_level == I915_CACHE_WT);
635 }
636
637 /**
638  * Creates a new mm object and returns a handle to it.
639  * @dev: drm device pointer
640  * @data: ioctl data blob
641  * @file: drm file pointer
642  */
643 int
644 i915_gem_create_ioctl(struct drm_device *dev, void *data,
645                       struct drm_file *file)
646 {
647         struct drm_i915_private *dev_priv = to_i915(dev);
648         struct drm_i915_gem_create *args = data;
649
650         i915_gem_flush_free_objects(dev_priv);
651
652         return i915_gem_create(file, dev_priv,
653                                args->size, &args->handle);
654 }
655
656 static inline enum fb_op_origin
657 fb_write_origin(struct drm_i915_gem_object *obj, unsigned int domain)
658 {
659         return (domain == I915_GEM_DOMAIN_GTT ?
660                 obj->frontbuffer_ggtt_origin : ORIGIN_CPU);
661 }
662
663 static void
664 flush_write_domain(struct drm_i915_gem_object *obj, unsigned int flush_domains)
665 {
666         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
667
668         if (!(obj->base.write_domain & flush_domains))
669                 return;
670
671         /* No actual flushing is required for the GTT write domain.  Writes
672          * to it "immediately" go to main memory as far as we know, so there's
673          * no chipset flush.  It also doesn't land in render cache.
674          *
675          * However, we do have to enforce the order so that all writes through
676          * the GTT land before any writes to the device, such as updates to
677          * the GATT itself.
678          *
679          * We also have to wait a bit for the writes to land from the GTT.
680          * An uncached read (i.e. mmio) seems to be ideal for the round-trip
681          * timing. This issue has only been observed when switching quickly
682          * between GTT writes and CPU reads from inside the kernel on recent hw,
683          * and it appears to only affect discrete GTT blocks (i.e. on LLC
684          * system agents we cannot reproduce this behaviour).
685          */
686         wmb();
687
688         switch (obj->base.write_domain) {
689         case I915_GEM_DOMAIN_GTT:
690                 if (!HAS_LLC(dev_priv)) {
691                         intel_runtime_pm_get(dev_priv);
692                         spin_lock_irq(&dev_priv->uncore.lock);
693                         POSTING_READ_FW(RING_HEAD(dev_priv->engine[RCS]->mmio_base));
694                         spin_unlock_irq(&dev_priv->uncore.lock);
695                         intel_runtime_pm_put(dev_priv);
696                 }
697
698                 intel_fb_obj_flush(obj,
699                                    fb_write_origin(obj, I915_GEM_DOMAIN_GTT));
700                 break;
701
702         case I915_GEM_DOMAIN_CPU:
703                 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
704                 break;
705
706         case I915_GEM_DOMAIN_RENDER:
707                 if (gpu_write_needs_clflush(obj))
708                         obj->cache_dirty = true;
709                 break;
710         }
711
712         obj->base.write_domain = 0;
713 }
714
715 static inline int
716 __copy_to_user_swizzled(char __user *cpu_vaddr,
717                         const char *gpu_vaddr, int gpu_offset,
718                         int length)
719 {
720         int ret, cpu_offset = 0;
721
722         while (length > 0) {
723                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
724                 int this_length = min(cacheline_end - gpu_offset, length);
725                 int swizzled_gpu_offset = gpu_offset ^ 64;
726
727                 ret = __copy_to_user(cpu_vaddr + cpu_offset,
728                                      gpu_vaddr + swizzled_gpu_offset,
729                                      this_length);
730                 if (ret)
731                         return ret + length;
732
733                 cpu_offset += this_length;
734                 gpu_offset += this_length;
735                 length -= this_length;
736         }
737
738         return 0;
739 }
740
741 static inline int
742 __copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
743                           const char __user *cpu_vaddr,
744                           int length)
745 {
746         int ret, cpu_offset = 0;
747
748         while (length > 0) {
749                 int cacheline_end = ALIGN(gpu_offset + 1, 64);
750                 int this_length = min(cacheline_end - gpu_offset, length);
751                 int swizzled_gpu_offset = gpu_offset ^ 64;
752
753                 ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
754                                        cpu_vaddr + cpu_offset,
755                                        this_length);
756                 if (ret)
757                         return ret + length;
758
759                 cpu_offset += this_length;
760                 gpu_offset += this_length;
761                 length -= this_length;
762         }
763
764         return 0;
765 }
766
767 /*
768  * Pins the specified object's pages and synchronizes the object with
769  * GPU accesses. Sets needs_clflush to non-zero if the caller should
770  * flush the object from the CPU cache.
771  */
772 int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
773                                     unsigned int *needs_clflush)
774 {
775         int ret;
776
777         lockdep_assert_held(&obj->base.dev->struct_mutex);
778
779         *needs_clflush = 0;
780         if (!i915_gem_object_has_struct_page(obj))
781                 return -ENODEV;
782
783         ret = i915_gem_object_wait(obj,
784                                    I915_WAIT_INTERRUPTIBLE |
785                                    I915_WAIT_LOCKED,
786                                    MAX_SCHEDULE_TIMEOUT,
787                                    NULL);
788         if (ret)
789                 return ret;
790
791         ret = i915_gem_object_pin_pages(obj);
792         if (ret)
793                 return ret;
794
795         if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ ||
796             !static_cpu_has(X86_FEATURE_CLFLUSH)) {
797                 ret = i915_gem_object_set_to_cpu_domain(obj, false);
798                 if (ret)
799                         goto err_unpin;
800                 else
801                         goto out;
802         }
803
804         flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
805
806         /* If we're not in the cpu read domain, set ourself into the gtt
807          * read domain and manually flush cachelines (if required). This
808          * optimizes for the case when the gpu will dirty the data
809          * anyway again before the next pread happens.
810          */
811         if (!obj->cache_dirty &&
812             !(obj->base.read_domains & I915_GEM_DOMAIN_CPU))
813                 *needs_clflush = CLFLUSH_BEFORE;
814
815 out:
816         /* return with the pages pinned */
817         return 0;
818
819 err_unpin:
820         i915_gem_object_unpin_pages(obj);
821         return ret;
822 }
823
824 int i915_gem_obj_prepare_shmem_write(struct drm_i915_gem_object *obj,
825                                      unsigned int *needs_clflush)
826 {
827         int ret;
828
829         lockdep_assert_held(&obj->base.dev->struct_mutex);
830
831         *needs_clflush = 0;
832         if (!i915_gem_object_has_struct_page(obj))
833                 return -ENODEV;
834
835         ret = i915_gem_object_wait(obj,
836                                    I915_WAIT_INTERRUPTIBLE |
837                                    I915_WAIT_LOCKED |
838                                    I915_WAIT_ALL,
839                                    MAX_SCHEDULE_TIMEOUT,
840                                    NULL);
841         if (ret)
842                 return ret;
843
844         ret = i915_gem_object_pin_pages(obj);
845         if (ret)
846                 return ret;
847
848         if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE ||
849             !static_cpu_has(X86_FEATURE_CLFLUSH)) {
850                 ret = i915_gem_object_set_to_cpu_domain(obj, true);
851                 if (ret)
852                         goto err_unpin;
853                 else
854                         goto out;
855         }
856
857         flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
858
859         /* If we're not in the cpu write domain, set ourself into the
860          * gtt write domain and manually flush cachelines (as required).
861          * This optimizes for the case when the gpu will use the data
862          * right away and we therefore have to clflush anyway.
863          */
864         if (!obj->cache_dirty) {
865                 *needs_clflush |= CLFLUSH_AFTER;
866
867                 /*
868                  * Same trick applies to invalidate partially written
869                  * cachelines read before writing.
870                  */
871                 if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU))
872                         *needs_clflush |= CLFLUSH_BEFORE;
873         }
874
875 out:
876         intel_fb_obj_invalidate(obj, ORIGIN_CPU);
877         obj->mm.dirty = true;
878         /* return with the pages pinned */
879         return 0;
880
881 err_unpin:
882         i915_gem_object_unpin_pages(obj);
883         return ret;
884 }
885
886 static void
887 shmem_clflush_swizzled_range(char *addr, unsigned long length,
888                              bool swizzled)
889 {
890         if (unlikely(swizzled)) {
891                 unsigned long start = (unsigned long) addr;
892                 unsigned long end = (unsigned long) addr + length;
893
894                 /* For swizzling simply ensure that we always flush both
895                  * channels. Lame, but simple and it works. Swizzled
896                  * pwrite/pread is far from a hotpath - current userspace
897                  * doesn't use it at all. */
898                 start = round_down(start, 128);
899                 end = round_up(end, 128);
900
901                 drm_clflush_virt_range((void *)start, end - start);
902         } else {
903                 drm_clflush_virt_range(addr, length);
904         }
905
906 }
907
908 /* Only difference to the fast-path function is that this can handle bit17
909  * and uses non-atomic copy and kmap functions. */
910 static int
911 shmem_pread_slow(struct page *page, int offset, int length,
912                  char __user *user_data,
913                  bool page_do_bit17_swizzling, bool needs_clflush)
914 {
915         char *vaddr;
916         int ret;
917
918         vaddr = kmap(page);
919         if (needs_clflush)
920                 shmem_clflush_swizzled_range(vaddr + offset, length,
921                                              page_do_bit17_swizzling);
922
923         if (page_do_bit17_swizzling)
924                 ret = __copy_to_user_swizzled(user_data, vaddr, offset, length);
925         else
926                 ret = __copy_to_user(user_data, vaddr + offset, length);
927         kunmap(page);
928
929         return ret ? - EFAULT : 0;
930 }
931
932 static int
933 shmem_pread(struct page *page, int offset, int length, char __user *user_data,
934             bool page_do_bit17_swizzling, bool needs_clflush)
935 {
936         int ret;
937
938         ret = -ENODEV;
939         if (!page_do_bit17_swizzling) {
940                 char *vaddr = kmap_atomic(page);
941
942                 if (needs_clflush)
943                         drm_clflush_virt_range(vaddr + offset, length);
944                 ret = __copy_to_user_inatomic(user_data, vaddr + offset, length);
945                 kunmap_atomic(vaddr);
946         }
947         if (ret == 0)
948                 return 0;
949
950         return shmem_pread_slow(page, offset, length, user_data,
951                                 page_do_bit17_swizzling, needs_clflush);
952 }
953
954 static int
955 i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
956                      struct drm_i915_gem_pread *args)
957 {
958         char __user *user_data;
959         u64 remain;
960         unsigned int obj_do_bit17_swizzling;
961         unsigned int needs_clflush;
962         unsigned int idx, offset;
963         int ret;
964
965         obj_do_bit17_swizzling = 0;
966         if (i915_gem_object_needs_bit17_swizzle(obj))
967                 obj_do_bit17_swizzling = BIT(17);
968
969         ret = mutex_lock_interruptible(&obj->base.dev->struct_mutex);
970         if (ret)
971                 return ret;
972
973         ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
974         mutex_unlock(&obj->base.dev->struct_mutex);
975         if (ret)
976                 return ret;
977
978         remain = args->size;
979         user_data = u64_to_user_ptr(args->data_ptr);
980         offset = offset_in_page(args->offset);
981         for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
982                 struct page *page = i915_gem_object_get_page(obj, idx);
983                 unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
984
985                 ret = shmem_pread(page, offset, length, user_data,
986                                   page_to_phys(page) & obj_do_bit17_swizzling,
987                                   needs_clflush);
988                 if (ret)
989                         break;
990
991                 remain -= length;
992                 user_data += length;
993                 offset = 0;
994         }
995
996         i915_gem_obj_finish_shmem_access(obj);
997         return ret;
998 }
999
1000 static inline bool
1001 gtt_user_read(struct io_mapping *mapping,
1002               loff_t base, int offset,
1003               char __user *user_data, int length)
1004 {
1005         void *vaddr;
1006         unsigned long unwritten;
1007
1008         /* We can use the cpu mem copy function because this is X86. */
1009         vaddr = (void __force *)io_mapping_map_atomic_wc(mapping, base);
1010         unwritten = __copy_to_user_inatomic(user_data, vaddr + offset, length);
1011         io_mapping_unmap_atomic(vaddr);
1012         if (unwritten) {
1013                 vaddr = (void __force *)
1014                         io_mapping_map_wc(mapping, base, PAGE_SIZE);
1015                 unwritten = copy_to_user(user_data, vaddr + offset, length);
1016                 io_mapping_unmap(vaddr);
1017         }
1018         return unwritten;
1019 }
1020
1021 static int
1022 i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
1023                    const struct drm_i915_gem_pread *args)
1024 {
1025         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1026         struct i915_ggtt *ggtt = &i915->ggtt;
1027         struct drm_mm_node node;
1028         struct i915_vma *vma;
1029         void __user *user_data;
1030         u64 remain, offset;
1031         int ret;
1032
1033         ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1034         if (ret)
1035                 return ret;
1036
1037         intel_runtime_pm_get(i915);
1038         vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1039                                        PIN_MAPPABLE | PIN_NONBLOCK);
1040         if (!IS_ERR(vma)) {
1041                 node.start = i915_ggtt_offset(vma);
1042                 node.allocated = false;
1043                 ret = i915_vma_put_fence(vma);
1044                 if (ret) {
1045                         i915_vma_unpin(vma);
1046                         vma = ERR_PTR(ret);
1047                 }
1048         }
1049         if (IS_ERR(vma)) {
1050                 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
1051                 if (ret)
1052                         goto out_unlock;
1053                 GEM_BUG_ON(!node.allocated);
1054         }
1055
1056         ret = i915_gem_object_set_to_gtt_domain(obj, false);
1057         if (ret)
1058                 goto out_unpin;
1059
1060         mutex_unlock(&i915->drm.struct_mutex);
1061
1062         user_data = u64_to_user_ptr(args->data_ptr);
1063         remain = args->size;
1064         offset = args->offset;
1065
1066         while (remain > 0) {
1067                 /* Operation in this page
1068                  *
1069                  * page_base = page offset within aperture
1070                  * page_offset = offset within page
1071                  * page_length = bytes to copy for this page
1072                  */
1073                 u32 page_base = node.start;
1074                 unsigned page_offset = offset_in_page(offset);
1075                 unsigned page_length = PAGE_SIZE - page_offset;
1076                 page_length = remain < page_length ? remain : page_length;
1077                 if (node.allocated) {
1078                         wmb();
1079                         ggtt->base.insert_page(&ggtt->base,
1080                                                i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1081                                                node.start, I915_CACHE_NONE, 0);
1082                         wmb();
1083                 } else {
1084                         page_base += offset & PAGE_MASK;
1085                 }
1086
1087                 if (gtt_user_read(&ggtt->mappable, page_base, page_offset,
1088                                   user_data, page_length)) {
1089                         ret = -EFAULT;
1090                         break;
1091                 }
1092
1093                 remain -= page_length;
1094                 user_data += page_length;
1095                 offset += page_length;
1096         }
1097
1098         mutex_lock(&i915->drm.struct_mutex);
1099 out_unpin:
1100         if (node.allocated) {
1101                 wmb();
1102                 ggtt->base.clear_range(&ggtt->base,
1103                                        node.start, node.size);
1104                 remove_mappable_node(&node);
1105         } else {
1106                 i915_vma_unpin(vma);
1107         }
1108 out_unlock:
1109         intel_runtime_pm_put(i915);
1110         mutex_unlock(&i915->drm.struct_mutex);
1111
1112         return ret;
1113 }
1114
1115 /**
1116  * Reads data from the object referenced by handle.
1117  * @dev: drm device pointer
1118  * @data: ioctl data blob
1119  * @file: drm file pointer
1120  *
1121  * On error, the contents of *data are undefined.
1122  */
1123 int
1124 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
1125                      struct drm_file *file)
1126 {
1127         struct drm_i915_gem_pread *args = data;
1128         struct drm_i915_gem_object *obj;
1129         int ret;
1130
1131         if (args->size == 0)
1132                 return 0;
1133
1134         if (!access_ok(VERIFY_WRITE,
1135                        u64_to_user_ptr(args->data_ptr),
1136                        args->size))
1137                 return -EFAULT;
1138
1139         obj = i915_gem_object_lookup(file, args->handle);
1140         if (!obj)
1141                 return -ENOENT;
1142
1143         /* Bounds check source.  */
1144         if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
1145                 ret = -EINVAL;
1146                 goto out;
1147         }
1148
1149         trace_i915_gem_object_pread(obj, args->offset, args->size);
1150
1151         ret = i915_gem_object_wait(obj,
1152                                    I915_WAIT_INTERRUPTIBLE,
1153                                    MAX_SCHEDULE_TIMEOUT,
1154                                    to_rps_client(file));
1155         if (ret)
1156                 goto out;
1157
1158         ret = i915_gem_object_pin_pages(obj);
1159         if (ret)
1160                 goto out;
1161
1162         ret = i915_gem_shmem_pread(obj, args);
1163         if (ret == -EFAULT || ret == -ENODEV)
1164                 ret = i915_gem_gtt_pread(obj, args);
1165
1166         i915_gem_object_unpin_pages(obj);
1167 out:
1168         i915_gem_object_put(obj);
1169         return ret;
1170 }
1171
1172 /* This is the fast write path which cannot handle
1173  * page faults in the source data
1174  */
1175
1176 static inline bool
1177 ggtt_write(struct io_mapping *mapping,
1178            loff_t base, int offset,
1179            char __user *user_data, int length)
1180 {
1181         void *vaddr;
1182         unsigned long unwritten;
1183
1184         /* We can use the cpu mem copy function because this is X86. */
1185         vaddr = (void __force *)io_mapping_map_atomic_wc(mapping, base);
1186         unwritten = __copy_from_user_inatomic_nocache(vaddr + offset,
1187                                                       user_data, length);
1188         io_mapping_unmap_atomic(vaddr);
1189         if (unwritten) {
1190                 vaddr = (void __force *)
1191                         io_mapping_map_wc(mapping, base, PAGE_SIZE);
1192                 unwritten = copy_from_user(vaddr + offset, user_data, length);
1193                 io_mapping_unmap(vaddr);
1194         }
1195
1196         return unwritten;
1197 }
1198
1199 /**
1200  * This is the fast pwrite path, where we copy the data directly from the
1201  * user into the GTT, uncached.
1202  * @obj: i915 GEM object
1203  * @args: pwrite arguments structure
1204  */
1205 static int
1206 i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
1207                          const struct drm_i915_gem_pwrite *args)
1208 {
1209         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1210         struct i915_ggtt *ggtt = &i915->ggtt;
1211         struct drm_mm_node node;
1212         struct i915_vma *vma;
1213         u64 remain, offset;
1214         void __user *user_data;
1215         int ret;
1216
1217         ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1218         if (ret)
1219                 return ret;
1220
1221         intel_runtime_pm_get(i915);
1222         vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
1223                                        PIN_MAPPABLE | PIN_NONBLOCK);
1224         if (!IS_ERR(vma)) {
1225                 node.start = i915_ggtt_offset(vma);
1226                 node.allocated = false;
1227                 ret = i915_vma_put_fence(vma);
1228                 if (ret) {
1229                         i915_vma_unpin(vma);
1230                         vma = ERR_PTR(ret);
1231                 }
1232         }
1233         if (IS_ERR(vma)) {
1234                 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
1235                 if (ret)
1236                         goto out_unlock;
1237                 GEM_BUG_ON(!node.allocated);
1238         }
1239
1240         ret = i915_gem_object_set_to_gtt_domain(obj, true);
1241         if (ret)
1242                 goto out_unpin;
1243
1244         mutex_unlock(&i915->drm.struct_mutex);
1245
1246         intel_fb_obj_invalidate(obj, ORIGIN_CPU);
1247
1248         user_data = u64_to_user_ptr(args->data_ptr);
1249         offset = args->offset;
1250         remain = args->size;
1251         while (remain) {
1252                 /* Operation in this page
1253                  *
1254                  * page_base = page offset within aperture
1255                  * page_offset = offset within page
1256                  * page_length = bytes to copy for this page
1257                  */
1258                 u32 page_base = node.start;
1259                 unsigned int page_offset = offset_in_page(offset);
1260                 unsigned int page_length = PAGE_SIZE - page_offset;
1261                 page_length = remain < page_length ? remain : page_length;
1262                 if (node.allocated) {
1263                         wmb(); /* flush the write before we modify the GGTT */
1264                         ggtt->base.insert_page(&ggtt->base,
1265                                                i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1266                                                node.start, I915_CACHE_NONE, 0);
1267                         wmb(); /* flush modifications to the GGTT (insert_page) */
1268                 } else {
1269                         page_base += offset & PAGE_MASK;
1270                 }
1271                 /* If we get a fault while copying data, then (presumably) our
1272                  * source page isn't available.  Return the error and we'll
1273                  * retry in the slow path.
1274                  * If the object is non-shmem backed, we retry again with the
1275                  * path that handles page fault.
1276                  */
1277                 if (ggtt_write(&ggtt->mappable, page_base, page_offset,
1278                                user_data, page_length)) {
1279                         ret = -EFAULT;
1280                         break;
1281                 }
1282
1283                 remain -= page_length;
1284                 user_data += page_length;
1285                 offset += page_length;
1286         }
1287         intel_fb_obj_flush(obj, ORIGIN_CPU);
1288
1289         mutex_lock(&i915->drm.struct_mutex);
1290 out_unpin:
1291         if (node.allocated) {
1292                 wmb();
1293                 ggtt->base.clear_range(&ggtt->base,
1294                                        node.start, node.size);
1295                 remove_mappable_node(&node);
1296         } else {
1297                 i915_vma_unpin(vma);
1298         }
1299 out_unlock:
1300         intel_runtime_pm_put(i915);
1301         mutex_unlock(&i915->drm.struct_mutex);
1302         return ret;
1303 }
1304
1305 static int
1306 shmem_pwrite_slow(struct page *page, int offset, int length,
1307                   char __user *user_data,
1308                   bool page_do_bit17_swizzling,
1309                   bool needs_clflush_before,
1310                   bool needs_clflush_after)
1311 {
1312         char *vaddr;
1313         int ret;
1314
1315         vaddr = kmap(page);
1316         if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
1317                 shmem_clflush_swizzled_range(vaddr + offset, length,
1318                                              page_do_bit17_swizzling);
1319         if (page_do_bit17_swizzling)
1320                 ret = __copy_from_user_swizzled(vaddr, offset, user_data,
1321                                                 length);
1322         else
1323                 ret = __copy_from_user(vaddr + offset, user_data, length);
1324         if (needs_clflush_after)
1325                 shmem_clflush_swizzled_range(vaddr + offset, length,
1326                                              page_do_bit17_swizzling);
1327         kunmap(page);
1328
1329         return ret ? -EFAULT : 0;
1330 }
1331
1332 /* Per-page copy function for the shmem pwrite fastpath.
1333  * Flushes invalid cachelines before writing to the target if
1334  * needs_clflush_before is set and flushes out any written cachelines after
1335  * writing if needs_clflush is set.
1336  */
1337 static int
1338 shmem_pwrite(struct page *page, int offset, int len, char __user *user_data,
1339              bool page_do_bit17_swizzling,
1340              bool needs_clflush_before,
1341              bool needs_clflush_after)
1342 {
1343         int ret;
1344
1345         ret = -ENODEV;
1346         if (!page_do_bit17_swizzling) {
1347                 char *vaddr = kmap_atomic(page);
1348
1349                 if (needs_clflush_before)
1350                         drm_clflush_virt_range(vaddr + offset, len);
1351                 ret = __copy_from_user_inatomic(vaddr + offset, user_data, len);
1352                 if (needs_clflush_after)
1353                         drm_clflush_virt_range(vaddr + offset, len);
1354
1355                 kunmap_atomic(vaddr);
1356         }
1357         if (ret == 0)
1358                 return ret;
1359
1360         return shmem_pwrite_slow(page, offset, len, user_data,
1361                                  page_do_bit17_swizzling,
1362                                  needs_clflush_before,
1363                                  needs_clflush_after);
1364 }
1365
1366 static int
1367 i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
1368                       const struct drm_i915_gem_pwrite *args)
1369 {
1370         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1371         void __user *user_data;
1372         u64 remain;
1373         unsigned int obj_do_bit17_swizzling;
1374         unsigned int partial_cacheline_write;
1375         unsigned int needs_clflush;
1376         unsigned int offset, idx;
1377         int ret;
1378
1379         ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1380         if (ret)
1381                 return ret;
1382
1383         ret = i915_gem_obj_prepare_shmem_write(obj, &needs_clflush);
1384         mutex_unlock(&i915->drm.struct_mutex);
1385         if (ret)
1386                 return ret;
1387
1388         obj_do_bit17_swizzling = 0;
1389         if (i915_gem_object_needs_bit17_swizzle(obj))
1390                 obj_do_bit17_swizzling = BIT(17);
1391
1392         /* If we don't overwrite a cacheline completely we need to be
1393          * careful to have up-to-date data by first clflushing. Don't
1394          * overcomplicate things and flush the entire patch.
1395          */
1396         partial_cacheline_write = 0;
1397         if (needs_clflush & CLFLUSH_BEFORE)
1398                 partial_cacheline_write = boot_cpu_data.x86_clflush_size - 1;
1399
1400         user_data = u64_to_user_ptr(args->data_ptr);
1401         remain = args->size;
1402         offset = offset_in_page(args->offset);
1403         for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
1404                 struct page *page = i915_gem_object_get_page(obj, idx);
1405                 unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
1406
1407                 ret = shmem_pwrite(page, offset, length, user_data,
1408                                    page_to_phys(page) & obj_do_bit17_swizzling,
1409                                    (offset | length) & partial_cacheline_write,
1410                                    needs_clflush & CLFLUSH_AFTER);
1411                 if (ret)
1412                         break;
1413
1414                 remain -= length;
1415                 user_data += length;
1416                 offset = 0;
1417         }
1418
1419         intel_fb_obj_flush(obj, ORIGIN_CPU);
1420         i915_gem_obj_finish_shmem_access(obj);
1421         return ret;
1422 }
1423
1424 /**
1425  * Writes data to the object referenced by handle.
1426  * @dev: drm device
1427  * @data: ioctl data blob
1428  * @file: drm file
1429  *
1430  * On error, the contents of the buffer that were to be modified are undefined.
1431  */
1432 int
1433 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
1434                       struct drm_file *file)
1435 {
1436         struct drm_i915_gem_pwrite *args = data;
1437         struct drm_i915_gem_object *obj;
1438         int ret;
1439
1440         if (args->size == 0)
1441                 return 0;
1442
1443         if (!access_ok(VERIFY_READ,
1444                        u64_to_user_ptr(args->data_ptr),
1445                        args->size))
1446                 return -EFAULT;
1447
1448         obj = i915_gem_object_lookup(file, args->handle);
1449         if (!obj)
1450                 return -ENOENT;
1451
1452         /* Bounds check destination. */
1453         if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
1454                 ret = -EINVAL;
1455                 goto err;
1456         }
1457
1458         trace_i915_gem_object_pwrite(obj, args->offset, args->size);
1459
1460         ret = -ENODEV;
1461         if (obj->ops->pwrite)
1462                 ret = obj->ops->pwrite(obj, args);
1463         if (ret != -ENODEV)
1464                 goto err;
1465
1466         ret = i915_gem_object_wait(obj,
1467                                    I915_WAIT_INTERRUPTIBLE |
1468                                    I915_WAIT_ALL,
1469                                    MAX_SCHEDULE_TIMEOUT,
1470                                    to_rps_client(file));
1471         if (ret)
1472                 goto err;
1473
1474         ret = i915_gem_object_pin_pages(obj);
1475         if (ret)
1476                 goto err;
1477
1478         ret = -EFAULT;
1479         /* We can only do the GTT pwrite on untiled buffers, as otherwise
1480          * it would end up going through the fenced access, and we'll get
1481          * different detiling behavior between reading and writing.
1482          * pread/pwrite currently are reading and writing from the CPU
1483          * perspective, requiring manual detiling by the client.
1484          */
1485         if (!i915_gem_object_has_struct_page(obj) ||
1486             cpu_write_needs_clflush(obj))
1487                 /* Note that the gtt paths might fail with non-page-backed user
1488                  * pointers (e.g. gtt mappings when moving data between
1489                  * textures). Fallback to the shmem path in that case.
1490                  */
1491                 ret = i915_gem_gtt_pwrite_fast(obj, args);
1492
1493         if (ret == -EFAULT || ret == -ENOSPC) {
1494                 if (obj->phys_handle)
1495                         ret = i915_gem_phys_pwrite(obj, args, file);
1496                 else
1497                         ret = i915_gem_shmem_pwrite(obj, args);
1498         }
1499
1500         i915_gem_object_unpin_pages(obj);
1501 err:
1502         i915_gem_object_put(obj);
1503         return ret;
1504 }
1505
1506 static void i915_gem_object_bump_inactive_ggtt(struct drm_i915_gem_object *obj)
1507 {
1508         struct drm_i915_private *i915;
1509         struct list_head *list;
1510         struct i915_vma *vma;
1511
1512         list_for_each_entry(vma, &obj->vma_list, obj_link) {
1513                 if (!i915_vma_is_ggtt(vma))
1514                         break;
1515
1516                 if (i915_vma_is_active(vma))
1517                         continue;
1518
1519                 if (!drm_mm_node_allocated(&vma->node))
1520                         continue;
1521
1522                 list_move_tail(&vma->vm_link, &vma->vm->inactive_list);
1523         }
1524
1525         i915 = to_i915(obj->base.dev);
1526         list = obj->bind_count ? &i915->mm.bound_list : &i915->mm.unbound_list;
1527         list_move_tail(&obj->global_link, list);
1528 }
1529
1530 /**
1531  * Called when user space prepares to use an object with the CPU, either
1532  * through the mmap ioctl's mapping or a GTT mapping.
1533  * @dev: drm device
1534  * @data: ioctl data blob
1535  * @file: drm file
1536  */
1537 int
1538 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1539                           struct drm_file *file)
1540 {
1541         struct drm_i915_gem_set_domain *args = data;
1542         struct drm_i915_gem_object *obj;
1543         uint32_t read_domains = args->read_domains;
1544         uint32_t write_domain = args->write_domain;
1545         int err;
1546
1547         /* Only handle setting domains to types used by the CPU. */
1548         if ((write_domain | read_domains) & I915_GEM_GPU_DOMAINS)
1549                 return -EINVAL;
1550
1551         /* Having something in the write domain implies it's in the read
1552          * domain, and only that read domain.  Enforce that in the request.
1553          */
1554         if (write_domain != 0 && read_domains != write_domain)
1555                 return -EINVAL;
1556
1557         obj = i915_gem_object_lookup(file, args->handle);
1558         if (!obj)
1559                 return -ENOENT;
1560
1561         /* Try to flush the object off the GPU without holding the lock.
1562          * We will repeat the flush holding the lock in the normal manner
1563          * to catch cases where we are gazumped.
1564          */
1565         err = i915_gem_object_wait(obj,
1566                                    I915_WAIT_INTERRUPTIBLE |
1567                                    (write_domain ? I915_WAIT_ALL : 0),
1568                                    MAX_SCHEDULE_TIMEOUT,
1569                                    to_rps_client(file));
1570         if (err)
1571                 goto out;
1572
1573         /* Flush and acquire obj->pages so that we are coherent through
1574          * direct access in memory with previous cached writes through
1575          * shmemfs and that our cache domain tracking remains valid.
1576          * For example, if the obj->filp was moved to swap without us
1577          * being notified and releasing the pages, we would mistakenly
1578          * continue to assume that the obj remained out of the CPU cached
1579          * domain.
1580          */
1581         err = i915_gem_object_pin_pages(obj);
1582         if (err)
1583                 goto out;
1584
1585         err = i915_mutex_lock_interruptible(dev);
1586         if (err)
1587                 goto out_unpin;
1588
1589         if (read_domains & I915_GEM_DOMAIN_WC)
1590                 err = i915_gem_object_set_to_wc_domain(obj, write_domain);
1591         else if (read_domains & I915_GEM_DOMAIN_GTT)
1592                 err = i915_gem_object_set_to_gtt_domain(obj, write_domain);
1593         else
1594                 err = i915_gem_object_set_to_cpu_domain(obj, write_domain);
1595
1596         /* And bump the LRU for this access */
1597         i915_gem_object_bump_inactive_ggtt(obj);
1598
1599         mutex_unlock(&dev->struct_mutex);
1600
1601         if (write_domain != 0)
1602                 intel_fb_obj_invalidate(obj,
1603                                         fb_write_origin(obj, write_domain));
1604
1605 out_unpin:
1606         i915_gem_object_unpin_pages(obj);
1607 out:
1608         i915_gem_object_put(obj);
1609         return err;
1610 }
1611
1612 /**
1613  * Called when user space has done writes to this buffer
1614  * @dev: drm device
1615  * @data: ioctl data blob
1616  * @file: drm file
1617  */
1618 int
1619 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1620                          struct drm_file *file)
1621 {
1622         struct drm_i915_gem_sw_finish *args = data;
1623         struct drm_i915_gem_object *obj;
1624
1625         obj = i915_gem_object_lookup(file, args->handle);
1626         if (!obj)
1627                 return -ENOENT;
1628
1629         /* Pinned buffers may be scanout, so flush the cache */
1630         i915_gem_object_flush_if_display(obj);
1631         i915_gem_object_put(obj);
1632
1633         return 0;
1634 }
1635
1636 static inline bool
1637 __vma_matches(struct vm_area_struct *vma, struct file *filp,
1638               unsigned long addr, unsigned long size)
1639 {
1640         if (vma->vm_file != filp)
1641                 return false;
1642
1643         return vma->vm_start == addr &&
1644                (vma->vm_end - vma->vm_start) == PAGE_ALIGN(size);
1645 }
1646
1647 /**
1648  * i915_gem_mmap_ioctl - Maps the contents of an object, returning the address
1649  *                       it is mapped to.
1650  * @dev: drm device
1651  * @data: ioctl data blob
1652  * @file: drm file
1653  *
1654  * While the mapping holds a reference on the contents of the object, it doesn't
1655  * imply a ref on the object itself.
1656  *
1657  * IMPORTANT:
1658  *
1659  * DRM driver writers who look a this function as an example for how to do GEM
1660  * mmap support, please don't implement mmap support like here. The modern way
1661  * to implement DRM mmap support is with an mmap offset ioctl (like
1662  * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
1663  * That way debug tooling like valgrind will understand what's going on, hiding
1664  * the mmap call in a driver private ioctl will break that. The i915 driver only
1665  * does cpu mmaps this way because we didn't know better.
1666  */
1667 int
1668 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1669                     struct drm_file *file)
1670 {
1671         struct drm_i915_gem_mmap *args = data;
1672         struct drm_i915_gem_object *obj;
1673         unsigned long addr;
1674
1675         if (args->flags & ~(I915_MMAP_WC))
1676                 return -EINVAL;
1677
1678         if (args->flags & I915_MMAP_WC && !boot_cpu_has(X86_FEATURE_PAT))
1679                 return -ENODEV;
1680
1681         obj = i915_gem_object_lookup(file, args->handle);
1682         if (!obj)
1683                 return -ENOENT;
1684
1685         /* prime objects have no backing filp to GEM mmap
1686          * pages from.
1687          */
1688         if (!obj->base.filp) {
1689                 i915_gem_object_put(obj);
1690                 return -EINVAL;
1691         }
1692
1693         addr = vm_mmap(obj->base.filp, 0, args->size,
1694                        PROT_READ | PROT_WRITE, MAP_SHARED,
1695                        args->offset);
1696         if (args->flags & I915_MMAP_WC) {
1697                 struct mm_struct *mm = current->mm;
1698                 struct vm_area_struct *vma;
1699
1700                 if (down_write_killable(&mm->mmap_sem)) {
1701                         i915_gem_object_put(obj);
1702                         return -EINTR;
1703                 }
1704                 vma = find_vma(mm, addr);
1705                 if (vma && __vma_matches(vma, obj->base.filp, addr, args->size))
1706                         vma->vm_page_prot =
1707                                 pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1708                 else
1709                         addr = -ENOMEM;
1710                 up_write(&mm->mmap_sem);
1711
1712                 /* This may race, but that's ok, it only gets set */
1713                 WRITE_ONCE(obj->frontbuffer_ggtt_origin, ORIGIN_CPU);
1714         }
1715         i915_gem_object_put(obj);
1716         if (IS_ERR((void *)addr))
1717                 return addr;
1718
1719         args->addr_ptr = (uint64_t) addr;
1720
1721         return 0;
1722 }
1723
1724 static unsigned int tile_row_pages(struct drm_i915_gem_object *obj)
1725 {
1726         return i915_gem_object_get_tile_row_size(obj) >> PAGE_SHIFT;
1727 }
1728
1729 /**
1730  * i915_gem_mmap_gtt_version - report the current feature set for GTT mmaps
1731  *
1732  * A history of the GTT mmap interface:
1733  *
1734  * 0 - Everything had to fit into the GTT. Both parties of a memcpy had to
1735  *     aligned and suitable for fencing, and still fit into the available
1736  *     mappable space left by the pinned display objects. A classic problem
1737  *     we called the page-fault-of-doom where we would ping-pong between
1738  *     two objects that could not fit inside the GTT and so the memcpy
1739  *     would page one object in at the expense of the other between every
1740  *     single byte.
1741  *
1742  * 1 - Objects can be any size, and have any compatible fencing (X Y, or none
1743  *     as set via i915_gem_set_tiling() [DRM_I915_GEM_SET_TILING]). If the
1744  *     object is too large for the available space (or simply too large
1745  *     for the mappable aperture!), a view is created instead and faulted
1746  *     into userspace. (This view is aligned and sized appropriately for
1747  *     fenced access.)
1748  *
1749  * 2 - Recognise WC as a separate cache domain so that we can flush the
1750  *     delayed writes via GTT before performing direct access via WC.
1751  *
1752  * Restrictions:
1753  *
1754  *  * snoopable objects cannot be accessed via the GTT. It can cause machine
1755  *    hangs on some architectures, corruption on others. An attempt to service
1756  *    a GTT page fault from a snoopable object will generate a SIGBUS.
1757  *
1758  *  * the object must be able to fit into RAM (physical memory, though no
1759  *    limited to the mappable aperture).
1760  *
1761  *
1762  * Caveats:
1763  *
1764  *  * a new GTT page fault will synchronize rendering from the GPU and flush
1765  *    all data to system memory. Subsequent access will not be synchronized.
1766  *
1767  *  * all mappings are revoked on runtime device suspend.
1768  *
1769  *  * there are only 8, 16 or 32 fence registers to share between all users
1770  *    (older machines require fence register for display and blitter access
1771  *    as well). Contention of the fence registers will cause the previous users
1772  *    to be unmapped and any new access will generate new page faults.
1773  *
1774  *  * running out of memory while servicing a fault may generate a SIGBUS,
1775  *    rather than the expected SIGSEGV.
1776  */
1777 int i915_gem_mmap_gtt_version(void)
1778 {
1779         return 2;
1780 }
1781
1782 static inline struct i915_ggtt_view
1783 compute_partial_view(struct drm_i915_gem_object *obj,
1784                      pgoff_t page_offset,
1785                      unsigned int chunk)
1786 {
1787         struct i915_ggtt_view view;
1788
1789         if (i915_gem_object_is_tiled(obj))
1790                 chunk = roundup(chunk, tile_row_pages(obj));
1791
1792         view.type = I915_GGTT_VIEW_PARTIAL;
1793         view.partial.offset = rounddown(page_offset, chunk);
1794         view.partial.size =
1795                 min_t(unsigned int, chunk,
1796                       (obj->base.size >> PAGE_SHIFT) - view.partial.offset);
1797
1798         /* If the partial covers the entire object, just create a normal VMA. */
1799         if (chunk >= obj->base.size >> PAGE_SHIFT)
1800                 view.type = I915_GGTT_VIEW_NORMAL;
1801
1802         return view;
1803 }
1804
1805 /**
1806  * i915_gem_fault - fault a page into the GTT
1807  * @vmf: fault info
1808  *
1809  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1810  * from userspace.  The fault handler takes care of binding the object to
1811  * the GTT (if needed), allocating and programming a fence register (again,
1812  * only if needed based on whether the old reg is still valid or the object
1813  * is tiled) and inserting a new PTE into the faulting process.
1814  *
1815  * Note that the faulting process may involve evicting existing objects
1816  * from the GTT and/or fence registers to make room.  So performance may
1817  * suffer if the GTT working set is large or there are few fence registers
1818  * left.
1819  *
1820  * The current feature set supported by i915_gem_fault() and thus GTT mmaps
1821  * is exposed via I915_PARAM_MMAP_GTT_VERSION (see i915_gem_mmap_gtt_version).
1822  */
1823 int i915_gem_fault(struct vm_fault *vmf)
1824 {
1825 #define MIN_CHUNK_PAGES ((1 << 20) >> PAGE_SHIFT) /* 1 MiB */
1826         struct vm_area_struct *area = vmf->vma;
1827         struct drm_i915_gem_object *obj = to_intel_bo(area->vm_private_data);
1828         struct drm_device *dev = obj->base.dev;
1829         struct drm_i915_private *dev_priv = to_i915(dev);
1830         struct i915_ggtt *ggtt = &dev_priv->ggtt;
1831         bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
1832         struct i915_vma *vma;
1833         pgoff_t page_offset;
1834         unsigned int flags;
1835         int ret;
1836
1837         /* Sanity check that we allow writing into this object */
1838         if (i915_gem_object_is_readonly(obj) && write)
1839                 return VM_FAULT_SIGBUS;
1840
1841         /* We don't use vmf->pgoff since that has the fake offset */
1842         page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
1843
1844         trace_i915_gem_object_fault(obj, page_offset, true, write);
1845
1846         /* Try to flush the object off the GPU first without holding the lock.
1847          * Upon acquiring the lock, we will perform our sanity checks and then
1848          * repeat the flush holding the lock in the normal manner to catch cases
1849          * where we are gazumped.
1850          */
1851         ret = i915_gem_object_wait(obj,
1852                                    I915_WAIT_INTERRUPTIBLE,
1853                                    MAX_SCHEDULE_TIMEOUT,
1854                                    NULL);
1855         if (ret)
1856                 goto err;
1857
1858         ret = i915_gem_object_pin_pages(obj);
1859         if (ret)
1860                 goto err;
1861
1862         intel_runtime_pm_get(dev_priv);
1863
1864         ret = i915_mutex_lock_interruptible(dev);
1865         if (ret)
1866                 goto err_rpm;
1867
1868         /* Access to snoopable pages through the GTT is incoherent. */
1869         if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev_priv)) {
1870                 ret = -EFAULT;
1871                 goto err_unlock;
1872         }
1873
1874         /* If the object is smaller than a couple of partial vma, it is
1875          * not worth only creating a single partial vma - we may as well
1876          * clear enough space for the full object.
1877          */
1878         flags = PIN_MAPPABLE;
1879         if (obj->base.size > 2 * MIN_CHUNK_PAGES << PAGE_SHIFT)
1880                 flags |= PIN_NONBLOCK | PIN_NONFAULT;
1881
1882         /* Now pin it into the GTT as needed */
1883         vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, flags);
1884         if (IS_ERR(vma)) {
1885                 /* Use a partial view if it is bigger than available space */
1886                 struct i915_ggtt_view view =
1887                         compute_partial_view(obj, page_offset, MIN_CHUNK_PAGES);
1888
1889                 /* Userspace is now writing through an untracked VMA, abandon
1890                  * all hope that the hardware is able to track future writes.
1891                  */
1892                 obj->frontbuffer_ggtt_origin = ORIGIN_CPU;
1893
1894                 vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
1895         }
1896         if (IS_ERR(vma)) {
1897                 ret = PTR_ERR(vma);
1898                 goto err_unlock;
1899         }
1900
1901         ret = i915_gem_object_set_to_gtt_domain(obj, write);
1902         if (ret)
1903                 goto err_unpin;
1904
1905         ret = i915_vma_get_fence(vma);
1906         if (ret)
1907                 goto err_unpin;
1908
1909         /* Mark as being mmapped into userspace for later revocation */
1910         assert_rpm_wakelock_held(dev_priv);
1911         if (list_empty(&obj->userfault_link))
1912                 list_add(&obj->userfault_link, &dev_priv->mm.userfault_list);
1913
1914         /* Finally, remap it using the new GTT offset */
1915         ret = remap_io_mapping(area,
1916                                area->vm_start + (vma->ggtt_view.partial.offset << PAGE_SHIFT),
1917                                (ggtt->mappable_base + vma->node.start) >> PAGE_SHIFT,
1918                                min_t(u64, vma->size, area->vm_end - area->vm_start),
1919                                &ggtt->mappable);
1920
1921 err_unpin:
1922         __i915_vma_unpin(vma);
1923 err_unlock:
1924         mutex_unlock(&dev->struct_mutex);
1925 err_rpm:
1926         intel_runtime_pm_put(dev_priv);
1927         i915_gem_object_unpin_pages(obj);
1928 err:
1929         switch (ret) {
1930         case -EIO:
1931                 /*
1932                  * We eat errors when the gpu is terminally wedged to avoid
1933                  * userspace unduly crashing (gl has no provisions for mmaps to
1934                  * fail). But any other -EIO isn't ours (e.g. swap in failure)
1935                  * and so needs to be reported.
1936                  */
1937                 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
1938                         ret = VM_FAULT_SIGBUS;
1939                         break;
1940                 }
1941         case -EAGAIN:
1942                 /*
1943                  * EAGAIN means the gpu is hung and we'll wait for the error
1944                  * handler to reset everything when re-faulting in
1945                  * i915_mutex_lock_interruptible.
1946                  */
1947         case 0:
1948         case -ERESTARTSYS:
1949         case -EINTR:
1950         case -EBUSY:
1951                 /*
1952                  * EBUSY is ok: this just means that another thread
1953                  * already did the job.
1954                  */
1955                 ret = VM_FAULT_NOPAGE;
1956                 break;
1957         case -ENOMEM:
1958                 ret = VM_FAULT_OOM;
1959                 break;
1960         case -ENOSPC:
1961         case -EFAULT:
1962                 ret = VM_FAULT_SIGBUS;
1963                 break;
1964         default:
1965                 WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
1966                 ret = VM_FAULT_SIGBUS;
1967                 break;
1968         }
1969         return ret;
1970 }
1971
1972 /**
1973  * i915_gem_release_mmap - remove physical page mappings
1974  * @obj: obj in question
1975  *
1976  * Preserve the reservation of the mmapping with the DRM core code, but
1977  * relinquish ownership of the pages back to the system.
1978  *
1979  * It is vital that we remove the page mapping if we have mapped a tiled
1980  * object through the GTT and then lose the fence register due to
1981  * resource pressure. Similarly if the object has been moved out of the
1982  * aperture, than pages mapped into userspace must be revoked. Removing the
1983  * mapping will then trigger a page fault on the next user access, allowing
1984  * fixup by i915_gem_fault().
1985  */
1986 void
1987 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
1988 {
1989         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1990
1991         /* Serialisation between user GTT access and our code depends upon
1992          * revoking the CPU's PTE whilst the mutex is held. The next user
1993          * pagefault then has to wait until we release the mutex.
1994          *
1995          * Note that RPM complicates somewhat by adding an additional
1996          * requirement that operations to the GGTT be made holding the RPM
1997          * wakeref.
1998          */
1999         lockdep_assert_held(&i915->drm.struct_mutex);
2000         intel_runtime_pm_get(i915);
2001
2002         if (list_empty(&obj->userfault_link))
2003                 goto out;
2004
2005         list_del_init(&obj->userfault_link);
2006         drm_vma_node_unmap(&obj->base.vma_node,
2007                            obj->base.dev->anon_inode->i_mapping);
2008
2009         /* Ensure that the CPU's PTE are revoked and there are not outstanding
2010          * memory transactions from userspace before we return. The TLB
2011          * flushing implied above by changing the PTE above *should* be
2012          * sufficient, an extra barrier here just provides us with a bit
2013          * of paranoid documentation about our requirement to serialise
2014          * memory writes before touching registers / GSM.
2015          */
2016         wmb();
2017
2018 out:
2019         intel_runtime_pm_put(i915);
2020 }
2021
2022 void i915_gem_runtime_suspend(struct drm_i915_private *dev_priv)
2023 {
2024         struct drm_i915_gem_object *obj, *on;
2025         int i;
2026
2027         /*
2028          * Only called during RPM suspend. All users of the userfault_list
2029          * must be holding an RPM wakeref to ensure that this can not
2030          * run concurrently with themselves (and use the struct_mutex for
2031          * protection between themselves).
2032          */
2033
2034         list_for_each_entry_safe(obj, on,
2035                                  &dev_priv->mm.userfault_list, userfault_link) {
2036                 list_del_init(&obj->userfault_link);
2037                 drm_vma_node_unmap(&obj->base.vma_node,
2038                                    obj->base.dev->anon_inode->i_mapping);
2039         }
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(!list_empty(&reg->vma->obj->userfault_link));
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, I915_WAIT_INTERRUPTIBLE);
2079                 if (err)
2080                         break;
2081
2082                 i915_gem_drain_freed_objects(dev_priv);
2083                 err = drm_gem_create_mmap_offset(&obj->base);
2084                 if (!err)
2085                         break;
2086
2087         } while (flush_delayed_work(&dev_priv->gt.retire_work));
2088
2089         return err;
2090 }
2091
2092 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
2093 {
2094         drm_gem_free_mmap_offset(&obj->base);
2095 }
2096
2097 int
2098 i915_gem_mmap_gtt(struct drm_file *file,
2099                   struct drm_device *dev,
2100                   uint32_t handle,
2101                   uint64_t *offset)
2102 {
2103         struct drm_i915_gem_object *obj;
2104         int ret;
2105
2106         obj = i915_gem_object_lookup(file, handle);
2107         if (!obj)
2108                 return -ENOENT;
2109
2110         ret = i915_gem_object_create_mmap_offset(obj);
2111         if (ret == 0)
2112                 *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
2113
2114         i915_gem_object_put(obj);
2115         return ret;
2116 }
2117
2118 /**
2119  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
2120  * @dev: DRM device
2121  * @data: GTT mapping ioctl data
2122  * @file: GEM object info
2123  *
2124  * Simply returns the fake offset to userspace so it can mmap it.
2125  * The mmap call will end up in drm_gem_mmap(), which will set things
2126  * up so we can get faults in the handler above.
2127  *
2128  * The fault handler will take care of binding the object into the GTT
2129  * (since it may have been evicted to make room for something), allocating
2130  * a fence register, and mapping the appropriate aperture address into
2131  * userspace.
2132  */
2133 int
2134 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
2135                         struct drm_file *file)
2136 {
2137         struct drm_i915_gem_mmap_gtt *args = data;
2138
2139         return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
2140 }
2141
2142 /* Immediately discard the backing storage */
2143 static void
2144 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
2145 {
2146         i915_gem_object_free_mmap_offset(obj);
2147
2148         if (obj->base.filp == NULL)
2149                 return;
2150
2151         /* Our goal here is to return as much of the memory as
2152          * is possible back to the system as we are called from OOM.
2153          * To do this we must instruct the shmfs to drop all of its
2154          * backing pages, *now*.
2155          */
2156         shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
2157         obj->mm.madv = __I915_MADV_PURGED;
2158         obj->mm.pages = ERR_PTR(-EFAULT);
2159 }
2160
2161 /* Try to discard unwanted pages */
2162 void __i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
2163 {
2164         struct address_space *mapping;
2165
2166         lockdep_assert_held(&obj->mm.lock);
2167         GEM_BUG_ON(obj->mm.pages);
2168
2169         switch (obj->mm.madv) {
2170         case I915_MADV_DONTNEED:
2171                 i915_gem_object_truncate(obj);
2172         case __I915_MADV_PURGED:
2173                 return;
2174         }
2175
2176         if (obj->base.filp == NULL)
2177                 return;
2178
2179         mapping = obj->base.filp->f_mapping,
2180         invalidate_mapping_pages(mapping, 0, (loff_t)-1);
2181 }
2182
2183 static void
2184 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj,
2185                               struct sg_table *pages)
2186 {
2187         struct sgt_iter sgt_iter;
2188         struct page *page;
2189
2190         __i915_gem_object_release_shmem(obj, pages, true);
2191
2192         i915_gem_gtt_finish_pages(obj, pages);
2193
2194         if (i915_gem_object_needs_bit17_swizzle(obj))
2195                 i915_gem_object_save_bit_17_swizzle(obj, pages);
2196
2197         for_each_sgt_page(page, sgt_iter, pages) {
2198                 if (obj->mm.dirty)
2199                         set_page_dirty(page);
2200
2201                 if (obj->mm.madv == I915_MADV_WILLNEED)
2202                         mark_page_accessed(page);
2203
2204                 put_page(page);
2205         }
2206         obj->mm.dirty = false;
2207
2208         sg_free_table(pages);
2209         kfree(pages);
2210 }
2211
2212 static void __i915_gem_object_reset_page_iter(struct drm_i915_gem_object *obj)
2213 {
2214         struct radix_tree_iter iter;
2215         void __rcu **slot;
2216
2217         rcu_read_lock();
2218         radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
2219                 radix_tree_delete(&obj->mm.get_page.radix, iter.index);
2220         rcu_read_unlock();
2221 }
2222
2223 struct reg_and_bit {
2224         i915_reg_t reg;
2225         u32 bit;
2226 };
2227
2228 static struct reg_and_bit
2229 get_reg_and_bit(const struct intel_engine_cs *engine,
2230                 const i915_reg_t *regs, const unsigned int num)
2231 {
2232         const unsigned int class = engine->class;
2233         struct reg_and_bit rb = { .bit = 1 };
2234
2235         if (WARN_ON_ONCE(class >= num || !regs[class].reg))
2236                 return rb;
2237
2238         rb.reg = regs[class];
2239         if (class == VIDEO_DECODE_CLASS)
2240                 rb.reg.reg += 4 * engine->instance; /* GEN8_M2TCR */
2241
2242         return rb;
2243 }
2244
2245 static void invalidate_tlbs(struct drm_i915_private *dev_priv)
2246 {
2247         static const i915_reg_t gen8_regs[] = {
2248                 [RENDER_CLASS]                  = GEN8_RTCR,
2249                 [VIDEO_DECODE_CLASS]            = GEN8_M1TCR, /* , GEN8_M2TCR */
2250                 [VIDEO_ENHANCEMENT_CLASS]       = GEN8_VTCR,
2251                 [COPY_ENGINE_CLASS]             = GEN8_BTCR,
2252         };
2253         const unsigned int num = ARRAY_SIZE(gen8_regs);
2254         const i915_reg_t *regs = gen8_regs;
2255         struct intel_engine_cs *engine;
2256         enum intel_engine_id id;
2257
2258         if (INTEL_GEN(dev_priv) < 8)
2259                 return;
2260
2261         assert_rpm_wakelock_held(dev_priv);
2262
2263         mutex_lock(&dev_priv->tlb_invalidate_lock);
2264         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
2265
2266         for_each_engine(engine, dev_priv, id) {
2267                 /*
2268                  * HW architecture suggest typical invalidation time at 40us,
2269                  * with pessimistic cases up to 100us and a recommendation to
2270                  * cap at 1ms. We go a bit higher just in case.
2271                  */
2272                 const unsigned int timeout_us = 100;
2273                 const unsigned int timeout_ms = 4;
2274                 struct reg_and_bit rb;
2275
2276                 rb = get_reg_and_bit(engine, regs, num);
2277                 if (!i915_mmio_reg_offset(rb.reg))
2278                         continue;
2279
2280                 I915_WRITE_FW(rb.reg, rb.bit);
2281                 if (__intel_wait_for_register_fw(dev_priv,
2282                                                  rb.reg, rb.bit, 0,
2283                                                  timeout_us, timeout_ms,
2284                                                  NULL))
2285                         DRM_ERROR_RATELIMITED("%s TLB invalidation did not complete in %ums!\n",
2286                                               engine->name, timeout_ms);
2287         }
2288
2289         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
2290         mutex_unlock(&dev_priv->tlb_invalidate_lock);
2291 }
2292
2293 void __i915_gem_object_put_pages(struct drm_i915_gem_object *obj,
2294                                  enum i915_mm_subclass subclass)
2295 {
2296         struct sg_table *pages;
2297
2298         if (i915_gem_object_has_pinned_pages(obj))
2299                 return;
2300
2301         GEM_BUG_ON(obj->bind_count);
2302         if (!READ_ONCE(obj->mm.pages))
2303                 return;
2304
2305         /* May be called by shrinker from within get_pages() (on another bo) */
2306         mutex_lock_nested(&obj->mm.lock, subclass);
2307         if (unlikely(atomic_read(&obj->mm.pages_pin_count)))
2308                 goto unlock;
2309
2310         /* ->put_pages might need to allocate memory for the bit17 swizzle
2311          * array, hence protect them from being reaped by removing them from gtt
2312          * lists early. */
2313         pages = fetch_and_zero(&obj->mm.pages);
2314         GEM_BUG_ON(!pages);
2315
2316         if (obj->mm.mapping) {
2317                 void *ptr;
2318
2319                 ptr = page_mask_bits(obj->mm.mapping);
2320                 if (is_vmalloc_addr(ptr))
2321                         vunmap(ptr);
2322                 else
2323                         kunmap(kmap_to_page(ptr));
2324
2325                 obj->mm.mapping = NULL;
2326         }
2327
2328         __i915_gem_object_reset_page_iter(obj);
2329
2330         if (!IS_ERR(pages)) {
2331                 if (test_and_clear_bit(I915_BO_WAS_BOUND_BIT, &obj->flags)) {
2332                         struct drm_i915_private *i915 = to_i915(obj->base.dev);
2333
2334                         if (intel_runtime_pm_get_if_in_use(i915)) {
2335                                 invalidate_tlbs(i915);
2336                                 intel_runtime_pm_put(i915);
2337                         }
2338                 }
2339
2340                 obj->ops->put_pages(obj, pages);
2341         }
2342
2343 unlock:
2344         mutex_unlock(&obj->mm.lock);
2345 }
2346
2347 static bool i915_sg_trim(struct sg_table *orig_st)
2348 {
2349         struct sg_table new_st;
2350         struct scatterlist *sg, *new_sg;
2351         unsigned int i;
2352
2353         if (orig_st->nents == orig_st->orig_nents)
2354                 return false;
2355
2356         if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL | __GFP_NOWARN))
2357                 return false;
2358
2359         new_sg = new_st.sgl;
2360         for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
2361                 sg_set_page(new_sg, sg_page(sg), sg->length, 0);
2362                 /* called before being DMA mapped, no need to copy sg->dma_* */
2363                 new_sg = sg_next(new_sg);
2364         }
2365         GEM_BUG_ON(new_sg); /* Should walk exactly nents and hit the end */
2366
2367         sg_free_table(orig_st);
2368
2369         *orig_st = new_st;
2370         return true;
2371 }
2372
2373 static struct sg_table *
2374 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
2375 {
2376         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
2377         const unsigned long page_count = obj->base.size / PAGE_SIZE;
2378         unsigned long i;
2379         struct address_space *mapping;
2380         struct sg_table *st;
2381         struct scatterlist *sg;
2382         struct sgt_iter sgt_iter;
2383         struct page *page;
2384         unsigned long last_pfn = 0;     /* suppress gcc warning */
2385         unsigned int max_segment;
2386         gfp_t noreclaim;
2387         int ret;
2388
2389         /* Assert that the object is not currently in any GPU domain. As it
2390          * wasn't in the GTT, there shouldn't be any way it could have been in
2391          * a GPU cache
2392          */
2393         GEM_BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2394         GEM_BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2395
2396         max_segment = swiotlb_max_segment();
2397         if (!max_segment)
2398                 max_segment = rounddown(UINT_MAX, PAGE_SIZE);
2399
2400         st = kmalloc(sizeof(*st), GFP_KERNEL);
2401         if (st == NULL)
2402                 return ERR_PTR(-ENOMEM);
2403
2404 rebuild_st:
2405         if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
2406                 kfree(st);
2407                 return ERR_PTR(-ENOMEM);
2408         }
2409
2410         /* Get the list of pages out of our struct file.  They'll be pinned
2411          * at this point until we release them.
2412          *
2413          * Fail silently without starting the shrinker
2414          */
2415         mapping = obj->base.filp->f_mapping;
2416         noreclaim = mapping_gfp_constraint(mapping, ~__GFP_RECLAIM);
2417         noreclaim |= __GFP_NORETRY | __GFP_NOWARN;
2418
2419         sg = st->sgl;
2420         st->nents = 0;
2421         for (i = 0; i < page_count; i++) {
2422                 const unsigned int shrink[] = {
2423                         I915_SHRINK_BOUND | I915_SHRINK_UNBOUND | I915_SHRINK_PURGEABLE,
2424                         0,
2425                 }, *s = shrink;
2426                 gfp_t gfp = noreclaim;
2427
2428                 do {
2429                         page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2430                         if (likely(!IS_ERR(page)))
2431                                 break;
2432
2433                         if (!*s) {
2434                                 ret = PTR_ERR(page);
2435                                 goto err_sg;
2436                         }
2437
2438                         i915_gem_shrink(dev_priv, 2 * page_count, NULL, *s++);
2439                         cond_resched();
2440
2441                         /* We've tried hard to allocate the memory by reaping
2442                          * our own buffer, now let the real VM do its job and
2443                          * go down in flames if truly OOM.
2444                          *
2445                          * However, since graphics tend to be disposable,
2446                          * defer the oom here by reporting the ENOMEM back
2447                          * to userspace.
2448                          */
2449                         if (!*s) {
2450                                 /* reclaim and warn, but no oom */
2451                                 gfp = mapping_gfp_mask(mapping);
2452
2453                                 /* Our bo are always dirty and so we require
2454                                  * kswapd to reclaim our pages (direct reclaim
2455                                  * does not effectively begin pageout of our
2456                                  * buffers on its own). However, direct reclaim
2457                                  * only waits for kswapd when under allocation
2458                                  * congestion. So as a result __GFP_RECLAIM is
2459                                  * unreliable and fails to actually reclaim our
2460                                  * dirty pages -- unless you try over and over
2461                                  * again with !__GFP_NORETRY. However, we still
2462                                  * want to fail this allocation rather than
2463                                  * trigger the out-of-memory killer and for
2464                                  * this we want __GFP_RETRY_MAYFAIL.
2465                                  */
2466                                 gfp |= __GFP_RETRY_MAYFAIL;
2467                         }
2468                 } while (1);
2469
2470                 if (!i ||
2471                     sg->length >= max_segment ||
2472                     page_to_pfn(page) != last_pfn + 1) {
2473                         if (i)
2474                                 sg = sg_next(sg);
2475                         st->nents++;
2476                         sg_set_page(sg, page, PAGE_SIZE, 0);
2477                 } else {
2478                         sg->length += PAGE_SIZE;
2479                 }
2480                 last_pfn = page_to_pfn(page);
2481
2482                 /* Check that the i965g/gm workaround works. */
2483                 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
2484         }
2485         if (sg) /* loop terminated early; short sg table */
2486                 sg_mark_end(sg);
2487
2488         /* Trim unused sg entries to avoid wasting memory. */
2489         i915_sg_trim(st);
2490
2491         ret = i915_gem_gtt_prepare_pages(obj, st);
2492         if (ret) {
2493                 /* DMA remapping failed? One possible cause is that
2494                  * it could not reserve enough large entries, asking
2495                  * for PAGE_SIZE chunks instead may be helpful.
2496                  */
2497                 if (max_segment > PAGE_SIZE) {
2498                         for_each_sgt_page(page, sgt_iter, st)
2499                                 put_page(page);
2500                         sg_free_table(st);
2501
2502                         max_segment = PAGE_SIZE;
2503                         goto rebuild_st;
2504                 } else {
2505                         dev_warn(&dev_priv->drm.pdev->dev,
2506                                  "Failed to DMA remap %lu pages\n",
2507                                  page_count);
2508                         goto err_pages;
2509                 }
2510         }
2511
2512         if (i915_gem_object_needs_bit17_swizzle(obj))
2513                 i915_gem_object_do_bit_17_swizzle(obj, st);
2514
2515         return st;
2516
2517 err_sg:
2518         sg_mark_end(sg);
2519 err_pages:
2520         for_each_sgt_page(page, sgt_iter, st)
2521                 put_page(page);
2522         sg_free_table(st);
2523         kfree(st);
2524
2525         /* shmemfs first checks if there is enough memory to allocate the page
2526          * and reports ENOSPC should there be insufficient, along with the usual
2527          * ENOMEM for a genuine allocation failure.
2528          *
2529          * We use ENOSPC in our driver to mean that we have run out of aperture
2530          * space and so want to translate the error from shmemfs back to our
2531          * usual understanding of ENOMEM.
2532          */
2533         if (ret == -ENOSPC)
2534                 ret = -ENOMEM;
2535
2536         return ERR_PTR(ret);
2537 }
2538
2539 void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
2540                                  struct sg_table *pages)
2541 {
2542         lockdep_assert_held(&obj->mm.lock);
2543
2544         obj->mm.get_page.sg_pos = pages->sgl;
2545         obj->mm.get_page.sg_idx = 0;
2546
2547         obj->mm.pages = pages;
2548
2549         if (i915_gem_object_is_tiled(obj) &&
2550             to_i915(obj->base.dev)->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
2551                 GEM_BUG_ON(obj->mm.quirked);
2552                 __i915_gem_object_pin_pages(obj);
2553                 obj->mm.quirked = true;
2554         }
2555 }
2556
2557 static int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2558 {
2559         struct sg_table *pages;
2560
2561         GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2562
2563         if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
2564                 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2565                 return -EFAULT;
2566         }
2567
2568         pages = obj->ops->get_pages(obj);
2569         if (unlikely(IS_ERR(pages)))
2570                 return PTR_ERR(pages);
2571
2572         __i915_gem_object_set_pages(obj, pages);
2573         return 0;
2574 }
2575
2576 /* Ensure that the associated pages are gathered from the backing storage
2577  * and pinned into our object. i915_gem_object_pin_pages() may be called
2578  * multiple times before they are released by a single call to
2579  * i915_gem_object_unpin_pages() - once the pages are no longer referenced
2580  * either as a result of memory pressure (reaping pages under the shrinker)
2581  * or as the object is itself released.
2582  */
2583 int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2584 {
2585         int err;
2586
2587         err = mutex_lock_interruptible(&obj->mm.lock);
2588         if (err)
2589                 return err;
2590
2591         if (unlikely(IS_ERR_OR_NULL(obj->mm.pages))) {
2592                 err = ____i915_gem_object_get_pages(obj);
2593                 if (err)
2594                         goto unlock;
2595
2596                 smp_mb__before_atomic();
2597         }
2598         atomic_inc(&obj->mm.pages_pin_count);
2599
2600 unlock:
2601         mutex_unlock(&obj->mm.lock);
2602         return err;
2603 }
2604
2605 /* The 'mapping' part of i915_gem_object_pin_map() below */
2606 static void *i915_gem_object_map(const struct drm_i915_gem_object *obj,
2607                                  enum i915_map_type type)
2608 {
2609         unsigned long n_pages = obj->base.size >> PAGE_SHIFT;
2610         struct sg_table *sgt = obj->mm.pages;
2611         struct sgt_iter sgt_iter;
2612         struct page *page;
2613         struct page *stack_pages[32];
2614         struct page **pages = stack_pages;
2615         unsigned long i = 0;
2616         pgprot_t pgprot;
2617         void *addr;
2618
2619         /* A single page can always be kmapped */
2620         if (n_pages == 1 && type == I915_MAP_WB)
2621                 return kmap(sg_page(sgt->sgl));
2622
2623         if (n_pages > ARRAY_SIZE(stack_pages)) {
2624                 /* Too big for stack -- allocate temporary array instead */
2625                 pages = kvmalloc_array(n_pages, sizeof(*pages), GFP_KERNEL);
2626                 if (!pages)
2627                         return NULL;
2628         }
2629
2630         for_each_sgt_page(page, sgt_iter, sgt)
2631                 pages[i++] = page;
2632
2633         /* Check that we have the expected number of pages */
2634         GEM_BUG_ON(i != n_pages);
2635
2636         switch (type) {
2637         default:
2638                 MISSING_CASE(type);
2639                 /* fallthrough to use PAGE_KERNEL anyway */
2640         case I915_MAP_WB:
2641                 pgprot = PAGE_KERNEL;
2642                 break;
2643         case I915_MAP_WC:
2644                 pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
2645                 break;
2646         }
2647         addr = vmap(pages, n_pages, 0, pgprot);
2648
2649         if (pages != stack_pages)
2650                 kvfree(pages);
2651
2652         return addr;
2653 }
2654
2655 /* get, pin, and map the pages of the object into kernel space */
2656 void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
2657                               enum i915_map_type type)
2658 {
2659         enum i915_map_type has_type;
2660         bool pinned;
2661         void *ptr;
2662         int ret;
2663
2664         GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
2665
2666         ret = mutex_lock_interruptible(&obj->mm.lock);
2667         if (ret)
2668                 return ERR_PTR(ret);
2669
2670         pinned = !(type & I915_MAP_OVERRIDE);
2671         type &= ~I915_MAP_OVERRIDE;
2672
2673         if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
2674                 if (unlikely(IS_ERR_OR_NULL(obj->mm.pages))) {
2675                         ret = ____i915_gem_object_get_pages(obj);
2676                         if (ret)
2677                                 goto err_unlock;
2678
2679                         smp_mb__before_atomic();
2680                 }
2681                 atomic_inc(&obj->mm.pages_pin_count);
2682                 pinned = false;
2683         }
2684         GEM_BUG_ON(!obj->mm.pages);
2685
2686         ptr = page_unpack_bits(obj->mm.mapping, &has_type);
2687         if (ptr && has_type != type) {
2688                 if (pinned) {
2689                         ret = -EBUSY;
2690                         goto err_unpin;
2691                 }
2692
2693                 if (is_vmalloc_addr(ptr))
2694                         vunmap(ptr);
2695                 else
2696                         kunmap(kmap_to_page(ptr));
2697
2698                 ptr = obj->mm.mapping = NULL;
2699         }
2700
2701         if (!ptr) {
2702                 ptr = i915_gem_object_map(obj, type);
2703                 if (!ptr) {
2704                         ret = -ENOMEM;
2705                         goto err_unpin;
2706                 }
2707
2708                 obj->mm.mapping = page_pack_bits(ptr, type);
2709         }
2710
2711 out_unlock:
2712         mutex_unlock(&obj->mm.lock);
2713         return ptr;
2714
2715 err_unpin:
2716         atomic_dec(&obj->mm.pages_pin_count);
2717 err_unlock:
2718         ptr = ERR_PTR(ret);
2719         goto out_unlock;
2720 }
2721
2722 static int
2723 i915_gem_object_pwrite_gtt(struct drm_i915_gem_object *obj,
2724                            const struct drm_i915_gem_pwrite *arg)
2725 {
2726         struct address_space *mapping = obj->base.filp->f_mapping;
2727         char __user *user_data = u64_to_user_ptr(arg->data_ptr);
2728         u64 remain, offset;
2729         unsigned int pg;
2730
2731         /* Before we instantiate/pin the backing store for our use, we
2732          * can prepopulate the shmemfs filp efficiently using a write into
2733          * the pagecache. We avoid the penalty of instantiating all the
2734          * pages, important if the user is just writing to a few and never
2735          * uses the object on the GPU, and using a direct write into shmemfs
2736          * allows it to avoid the cost of retrieving a page (either swapin
2737          * or clearing-before-use) before it is overwritten.
2738          */
2739         if (READ_ONCE(obj->mm.pages))
2740                 return -ENODEV;
2741
2742         if (obj->mm.madv != I915_MADV_WILLNEED)
2743                 return -EFAULT;
2744
2745         /* Before the pages are instantiated the object is treated as being
2746          * in the CPU domain. The pages will be clflushed as required before
2747          * use, and we can freely write into the pages directly. If userspace
2748          * races pwrite with any other operation; corruption will ensue -
2749          * that is userspace's prerogative!
2750          */
2751
2752         remain = arg->size;
2753         offset = arg->offset;
2754         pg = offset_in_page(offset);
2755
2756         do {
2757                 unsigned int len, unwritten;
2758                 struct page *page;
2759                 void *data, *vaddr;
2760                 int err;
2761
2762                 len = PAGE_SIZE - pg;
2763                 if (len > remain)
2764                         len = remain;
2765
2766                 err = pagecache_write_begin(obj->base.filp, mapping,
2767                                             offset, len, 0,
2768                                             &page, &data);
2769                 if (err < 0)
2770                         return err;
2771
2772                 vaddr = kmap(page);
2773                 unwritten = copy_from_user(vaddr + pg, user_data, len);
2774                 kunmap(page);
2775
2776                 err = pagecache_write_end(obj->base.filp, mapping,
2777                                           offset, len, len - unwritten,
2778                                           page, data);
2779                 if (err < 0)
2780                         return err;
2781
2782                 if (unwritten)
2783                         return -EFAULT;
2784
2785                 remain -= len;
2786                 user_data += len;
2787                 offset += len;
2788                 pg = 0;
2789         } while (remain);
2790
2791         return 0;
2792 }
2793
2794 static bool ban_context(const struct i915_gem_context *ctx,
2795                         unsigned int score)
2796 {
2797         return (i915_gem_context_is_bannable(ctx) &&
2798                 score >= CONTEXT_SCORE_BAN_THRESHOLD);
2799 }
2800
2801 static void i915_gem_context_mark_guilty(struct i915_gem_context *ctx)
2802 {
2803         unsigned int score;
2804         bool banned;
2805
2806         atomic_inc(&ctx->guilty_count);
2807
2808         score = atomic_add_return(CONTEXT_SCORE_GUILTY, &ctx->ban_score);
2809         banned = ban_context(ctx, score);
2810         DRM_DEBUG_DRIVER("context %s marked guilty (score %d) banned? %s\n",
2811                          ctx->name, score, yesno(banned));
2812         if (!banned)
2813                 return;
2814
2815         i915_gem_context_set_banned(ctx);
2816         if (!IS_ERR_OR_NULL(ctx->file_priv)) {
2817                 atomic_inc(&ctx->file_priv->context_bans);
2818                 DRM_DEBUG_DRIVER("client %s has had %d context banned\n",
2819                                  ctx->name, atomic_read(&ctx->file_priv->context_bans));
2820         }
2821 }
2822
2823 static void i915_gem_context_mark_innocent(struct i915_gem_context *ctx)
2824 {
2825         atomic_inc(&ctx->active_count);
2826 }
2827
2828 struct drm_i915_gem_request *
2829 i915_gem_find_active_request(struct intel_engine_cs *engine)
2830 {
2831         struct drm_i915_gem_request *request, *active = NULL;
2832         unsigned long flags;
2833
2834         /* We are called by the error capture and reset at a random
2835          * point in time. In particular, note that neither is crucially
2836          * ordered with an interrupt. After a hang, the GPU is dead and we
2837          * assume that no more writes can happen (we waited long enough for
2838          * all writes that were in transaction to be flushed) - adding an
2839          * extra delay for a recent interrupt is pointless. Hence, we do
2840          * not need an engine->irq_seqno_barrier() before the seqno reads.
2841          */
2842         spin_lock_irqsave(&engine->timeline->lock, flags);
2843         list_for_each_entry(request, &engine->timeline->requests, link) {
2844                 if (__i915_gem_request_completed(request,
2845                                                  request->global_seqno))
2846                         continue;
2847
2848                 GEM_BUG_ON(request->engine != engine);
2849                 GEM_BUG_ON(test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
2850                                     &request->fence.flags));
2851
2852                 active = request;
2853                 break;
2854         }
2855         spin_unlock_irqrestore(&engine->timeline->lock, flags);
2856
2857         return active;
2858 }
2859
2860 static bool engine_stalled(struct intel_engine_cs *engine)
2861 {
2862         if (!engine->hangcheck.stalled)
2863                 return false;
2864
2865         /* Check for possible seqno movement after hang declaration */
2866         if (engine->hangcheck.seqno != intel_engine_get_seqno(engine)) {
2867                 DRM_DEBUG_DRIVER("%s pardoned\n", engine->name);
2868                 return false;
2869         }
2870
2871         return true;
2872 }
2873
2874 /*
2875  * Ensure irq handler finishes, and not run again.
2876  * Also return the active request so that we only search for it once.
2877  */
2878 struct drm_i915_gem_request *
2879 i915_gem_reset_prepare_engine(struct intel_engine_cs *engine)
2880 {
2881         struct drm_i915_gem_request *request = NULL;
2882
2883         /* Prevent the signaler thread from updating the request
2884          * state (by calling dma_fence_signal) as we are processing
2885          * the reset. The write from the GPU of the seqno is
2886          * asynchronous and the signaler thread may see a different
2887          * value to us and declare the request complete, even though
2888          * the reset routine have picked that request as the active
2889          * (incomplete) request. This conflict is not handled
2890          * gracefully!
2891          */
2892         kthread_park(engine->breadcrumbs.signaler);
2893
2894         /* Prevent request submission to the hardware until we have
2895          * completed the reset in i915_gem_reset_finish(). If a request
2896          * is completed by one engine, it may then queue a request
2897          * to a second via its engine->irq_tasklet *just* as we are
2898          * calling engine->init_hw() and also writing the ELSP.
2899          * Turning off the engine->irq_tasklet until the reset is over
2900          * prevents the race.
2901          */
2902         tasklet_kill(&engine->irq_tasklet);
2903         tasklet_disable(&engine->irq_tasklet);
2904
2905         if (engine->irq_seqno_barrier)
2906                 engine->irq_seqno_barrier(engine);
2907
2908         request = i915_gem_find_active_request(engine);
2909         if (request && request->fence.error == -EIO)
2910                 request = ERR_PTR(-EIO); /* Previous reset failed! */
2911
2912         return request;
2913 }
2914
2915 int i915_gem_reset_prepare(struct drm_i915_private *dev_priv)
2916 {
2917         struct intel_engine_cs *engine;
2918         struct drm_i915_gem_request *request;
2919         enum intel_engine_id id;
2920         int err = 0;
2921
2922         for_each_engine(engine, dev_priv, id) {
2923                 request = i915_gem_reset_prepare_engine(engine);
2924                 if (IS_ERR(request)) {
2925                         err = PTR_ERR(request);
2926                         continue;
2927                 }
2928
2929                 engine->hangcheck.active_request = request;
2930         }
2931
2932         i915_gem_revoke_fences(dev_priv);
2933
2934         return err;
2935 }
2936
2937 static void skip_request(struct drm_i915_gem_request *request)
2938 {
2939         void *vaddr = request->ring->vaddr;
2940         u32 head;
2941
2942         /* As this request likely depends on state from the lost
2943          * context, clear out all the user operations leaving the
2944          * breadcrumb at the end (so we get the fence notifications).
2945          */
2946         head = request->head;
2947         if (request->postfix < head) {
2948                 memset(vaddr + head, 0, request->ring->size - head);
2949                 head = 0;
2950         }
2951         memset(vaddr + head, 0, request->postfix - head);
2952
2953         dma_fence_set_error(&request->fence, -EIO);
2954 }
2955
2956 static void engine_skip_context(struct drm_i915_gem_request *request)
2957 {
2958         struct intel_engine_cs *engine = request->engine;
2959         struct i915_gem_context *hung_ctx = request->ctx;
2960         struct intel_timeline *timeline;
2961         unsigned long flags;
2962
2963         timeline = i915_gem_context_lookup_timeline(hung_ctx, engine);
2964
2965         spin_lock_irqsave(&engine->timeline->lock, flags);
2966         spin_lock(&timeline->lock);
2967
2968         list_for_each_entry_continue(request, &engine->timeline->requests, link)
2969                 if (request->ctx == hung_ctx)
2970                         skip_request(request);
2971
2972         list_for_each_entry(request, &timeline->requests, link)
2973                 skip_request(request);
2974
2975         spin_unlock(&timeline->lock);
2976         spin_unlock_irqrestore(&engine->timeline->lock, flags);
2977 }
2978
2979 /* Returns the request if it was guilty of the hang */
2980 static struct drm_i915_gem_request *
2981 i915_gem_reset_request(struct intel_engine_cs *engine,
2982                        struct drm_i915_gem_request *request)
2983 {
2984         /* The guilty request will get skipped on a hung engine.
2985          *
2986          * Users of client default contexts do not rely on logical
2987          * state preserved between batches so it is safe to execute
2988          * queued requests following the hang. Non default contexts
2989          * rely on preserved state, so skipping a batch loses the
2990          * evolution of the state and it needs to be considered corrupted.
2991          * Executing more queued batches on top of corrupted state is
2992          * risky. But we take the risk by trying to advance through
2993          * the queued requests in order to make the client behaviour
2994          * more predictable around resets, by not throwing away random
2995          * amount of batches it has prepared for execution. Sophisticated
2996          * clients can use gem_reset_stats_ioctl and dma fence status
2997          * (exported via sync_file info ioctl on explicit fences) to observe
2998          * when it loses the context state and should rebuild accordingly.
2999          *
3000          * The context ban, and ultimately the client ban, mechanism are safety
3001          * valves if client submission ends up resulting in nothing more than
3002          * subsequent hangs.
3003          */
3004
3005         if (engine_stalled(engine)) {
3006                 i915_gem_context_mark_guilty(request->ctx);
3007                 skip_request(request);
3008
3009                 /* If this context is now banned, skip all pending requests. */
3010                 if (i915_gem_context_is_banned(request->ctx))
3011                         engine_skip_context(request);
3012         } else {
3013                 /*
3014                  * Since this is not the hung engine, it may have advanced
3015                  * since the hang declaration. Double check by refinding
3016                  * the active request at the time of the reset.
3017                  */
3018                 request = i915_gem_find_active_request(engine);
3019                 if (request) {
3020                         i915_gem_context_mark_innocent(request->ctx);
3021                         dma_fence_set_error(&request->fence, -EAGAIN);
3022
3023                         /* Rewind the engine to replay the incomplete rq */
3024                         spin_lock_irq(&engine->timeline->lock);
3025                         request = list_prev_entry(request, link);
3026                         if (&request->link == &engine->timeline->requests)
3027                                 request = NULL;
3028                         spin_unlock_irq(&engine->timeline->lock);
3029                 }
3030         }
3031
3032         return request;
3033 }
3034
3035 void i915_gem_reset_engine(struct intel_engine_cs *engine,
3036                            struct drm_i915_gem_request *request)
3037 {
3038         engine->irq_posted = 0;
3039
3040         if (request)
3041                 request = i915_gem_reset_request(engine, request);
3042
3043         if (request) {
3044                 DRM_DEBUG_DRIVER("resetting %s to restart from tail of request 0x%x\n",
3045                                  engine->name, request->global_seqno);
3046         }
3047
3048         /* Setup the CS to resume from the breadcrumb of the hung request */
3049         engine->reset_hw(engine, request);
3050 }
3051
3052 void i915_gem_reset(struct drm_i915_private *dev_priv)
3053 {
3054         struct intel_engine_cs *engine;
3055         enum intel_engine_id id;
3056
3057         lockdep_assert_held(&dev_priv->drm.struct_mutex);
3058
3059         i915_gem_retire_requests(dev_priv);
3060
3061         for_each_engine(engine, dev_priv, id) {
3062                 struct i915_gem_context *ctx;
3063
3064                 i915_gem_reset_engine(engine, engine->hangcheck.active_request);
3065                 ctx = fetch_and_zero(&engine->last_retired_context);
3066                 if (ctx)
3067                         engine->context_unpin(engine, ctx);
3068         }
3069
3070         i915_gem_restore_fences(dev_priv);
3071
3072         if (dev_priv->gt.awake) {
3073                 intel_sanitize_gt_powersave(dev_priv);
3074                 intel_enable_gt_powersave(dev_priv);
3075                 if (INTEL_GEN(dev_priv) >= 6)
3076                         gen6_rps_busy(dev_priv);
3077         }
3078 }
3079
3080 void i915_gem_reset_finish_engine(struct intel_engine_cs *engine)
3081 {
3082         tasklet_enable(&engine->irq_tasklet);
3083         kthread_unpark(engine->breadcrumbs.signaler);
3084 }
3085
3086 void i915_gem_reset_finish(struct drm_i915_private *dev_priv)
3087 {
3088         struct intel_engine_cs *engine;
3089         enum intel_engine_id id;
3090
3091         lockdep_assert_held(&dev_priv->drm.struct_mutex);
3092
3093         for_each_engine(engine, dev_priv, id) {
3094                 engine->hangcheck.active_request = NULL;
3095                 i915_gem_reset_finish_engine(engine);
3096         }
3097 }
3098
3099 static void nop_submit_request(struct drm_i915_gem_request *request)
3100 {
3101         unsigned long flags;
3102
3103         GEM_BUG_ON(!i915_terminally_wedged(&request->i915->gpu_error));
3104         dma_fence_set_error(&request->fence, -EIO);
3105
3106         spin_lock_irqsave(&request->engine->timeline->lock, flags);
3107         __i915_gem_request_submit(request);
3108         intel_engine_init_global_seqno(request->engine, request->global_seqno);
3109         spin_unlock_irqrestore(&request->engine->timeline->lock, flags);
3110 }
3111
3112 static void engine_set_wedged(struct intel_engine_cs *engine)
3113 {
3114         struct drm_i915_gem_request *request;
3115         unsigned long flags;
3116
3117         /* We need to be sure that no thread is running the old callback as
3118          * we install the nop handler (otherwise we would submit a request
3119          * to hardware that will never complete). In order to prevent this
3120          * race, we wait until the machine is idle before making the swap
3121          * (using stop_machine()).
3122          */
3123         engine->submit_request = nop_submit_request;
3124
3125         /* Mark all executing requests as skipped */
3126         spin_lock_irqsave(&engine->timeline->lock, flags);
3127         list_for_each_entry(request, &engine->timeline->requests, link)
3128                 if (!i915_gem_request_completed(request))
3129                         dma_fence_set_error(&request->fence, -EIO);
3130         spin_unlock_irqrestore(&engine->timeline->lock, flags);
3131
3132         /*
3133          * Clear the execlists queue up before freeing the requests, as those
3134          * are the ones that keep the context and ringbuffer backing objects
3135          * pinned in place.
3136          */
3137
3138         if (i915.enable_execlists) {
3139                 struct execlist_port *port = engine->execlist_port;
3140                 unsigned long flags;
3141                 unsigned int n;
3142
3143                 spin_lock_irqsave(&engine->timeline->lock, flags);
3144
3145                 for (n = 0; n < ARRAY_SIZE(engine->execlist_port); n++)
3146                         i915_gem_request_put(port_request(&port[n]));
3147                 memset(engine->execlist_port, 0, sizeof(engine->execlist_port));
3148                 engine->execlist_queue = RB_ROOT;
3149                 engine->execlist_first = NULL;
3150
3151                 spin_unlock_irqrestore(&engine->timeline->lock, flags);
3152
3153                 /* The port is checked prior to scheduling a tasklet, but
3154                  * just in case we have suspended the tasklet to do the
3155                  * wedging make sure that when it wakes, it decides there
3156                  * is no work to do by clearing the irq_posted bit.
3157                  */
3158                 clear_bit(ENGINE_IRQ_EXECLIST, &engine->irq_posted);
3159         }
3160
3161         /* Mark all pending requests as complete so that any concurrent
3162          * (lockless) lookup doesn't try and wait upon the request as we
3163          * reset it.
3164          */
3165         intel_engine_init_global_seqno(engine,
3166                                        intel_engine_last_submit(engine));
3167 }
3168
3169 static int __i915_gem_set_wedged_BKL(void *data)
3170 {
3171         struct drm_i915_private *i915 = data;
3172         struct intel_engine_cs *engine;
3173         enum intel_engine_id id;
3174
3175         for_each_engine(engine, i915, id)
3176                 engine_set_wedged(engine);
3177
3178         set_bit(I915_WEDGED, &i915->gpu_error.flags);
3179         wake_up_all(&i915->gpu_error.reset_queue);
3180
3181         return 0;
3182 }
3183
3184 void i915_gem_set_wedged(struct drm_i915_private *dev_priv)
3185 {
3186         stop_machine(__i915_gem_set_wedged_BKL, dev_priv, NULL);
3187 }
3188
3189 bool i915_gem_unset_wedged(struct drm_i915_private *i915)
3190 {
3191         struct i915_gem_timeline *tl;
3192         int i;
3193
3194         lockdep_assert_held(&i915->drm.struct_mutex);
3195         if (!test_bit(I915_WEDGED, &i915->gpu_error.flags))
3196                 return true;
3197
3198         /* Before unwedging, make sure that all pending operations
3199          * are flushed and errored out - we may have requests waiting upon
3200          * third party fences. We marked all inflight requests as EIO, and
3201          * every execbuf since returned EIO, for consistency we want all
3202          * the currently pending requests to also be marked as EIO, which
3203          * is done inside our nop_submit_request - and so we must wait.
3204          *
3205          * No more can be submitted until we reset the wedged bit.
3206          */
3207         list_for_each_entry(tl, &i915->gt.timelines, link) {
3208                 for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
3209                         struct drm_i915_gem_request *rq;
3210
3211                         rq = i915_gem_active_peek(&tl->engine[i].last_request,
3212                                                   &i915->drm.struct_mutex);
3213                         if (!rq)
3214                                 continue;
3215
3216                         /* We can't use our normal waiter as we want to
3217                          * avoid recursively trying to handle the current
3218                          * reset. The basic dma_fence_default_wait() installs
3219                          * a callback for dma_fence_signal(), which is
3220                          * triggered by our nop handler (indirectly, the
3221                          * callback enables the signaler thread which is
3222                          * woken by the nop_submit_request() advancing the seqno
3223                          * and when the seqno passes the fence, the signaler
3224                          * then signals the fence waking us up).
3225                          */
3226                         if (dma_fence_default_wait(&rq->fence, true,
3227                                                    MAX_SCHEDULE_TIMEOUT) < 0)
3228                                 return false;
3229                 }
3230         }
3231
3232         /* Undo nop_submit_request. We prevent all new i915 requests from
3233          * being queued (by disallowing execbuf whilst wedged) so having
3234          * waited for all active requests above, we know the system is idle
3235          * and do not have to worry about a thread being inside
3236          * engine->submit_request() as we swap over. So unlike installing
3237          * the nop_submit_request on reset, we can do this from normal
3238          * context and do not require stop_machine().
3239          */
3240         intel_engines_reset_default_submission(i915);
3241         i915_gem_contexts_lost(i915);
3242
3243         smp_mb__before_atomic(); /* complete takeover before enabling execbuf */
3244         clear_bit(I915_WEDGED, &i915->gpu_error.flags);
3245
3246         return true;
3247 }
3248
3249 static void
3250 i915_gem_retire_work_handler(struct work_struct *work)
3251 {
3252         struct drm_i915_private *dev_priv =
3253                 container_of(work, typeof(*dev_priv), gt.retire_work.work);
3254         struct drm_device *dev = &dev_priv->drm;
3255
3256         /* Come back later if the device is busy... */
3257         if (mutex_trylock(&dev->struct_mutex)) {
3258                 i915_gem_retire_requests(dev_priv);
3259                 mutex_unlock(&dev->struct_mutex);
3260         }
3261
3262         /* Keep the retire handler running until we are finally idle.
3263          * We do not need to do this test under locking as in the worst-case
3264          * we queue the retire worker once too often.
3265          */
3266         if (READ_ONCE(dev_priv->gt.awake)) {
3267                 i915_queue_hangcheck(dev_priv);
3268                 queue_delayed_work(dev_priv->wq,
3269                                    &dev_priv->gt.retire_work,
3270                                    round_jiffies_up_relative(HZ));
3271         }
3272 }
3273
3274 static void
3275 i915_gem_idle_work_handler(struct work_struct *work)
3276 {
3277         struct drm_i915_private *dev_priv =
3278                 container_of(work, typeof(*dev_priv), gt.idle_work.work);
3279         struct drm_device *dev = &dev_priv->drm;
3280         bool rearm_hangcheck;
3281
3282         if (!READ_ONCE(dev_priv->gt.awake))
3283                 return;
3284
3285         /*
3286          * Wait for last execlists context complete, but bail out in case a
3287          * new request is submitted.
3288          */
3289         wait_for(intel_engines_are_idle(dev_priv), 10);
3290         if (READ_ONCE(dev_priv->gt.active_requests))
3291                 return;
3292
3293         rearm_hangcheck =
3294                 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
3295
3296         if (!mutex_trylock(&dev->struct_mutex)) {
3297                 /* Currently busy, come back later */
3298                 mod_delayed_work(dev_priv->wq,
3299                                  &dev_priv->gt.idle_work,
3300                                  msecs_to_jiffies(50));
3301                 goto out_rearm;
3302         }
3303
3304         /*
3305          * New request retired after this work handler started, extend active
3306          * period until next instance of the work.
3307          */
3308         if (work_pending(work))
3309                 goto out_unlock;
3310
3311         if (dev_priv->gt.active_requests)
3312                 goto out_unlock;
3313
3314         if (wait_for(intel_engines_are_idle(dev_priv), 10))
3315                 DRM_ERROR("Timeout waiting for engines to idle\n");
3316
3317         intel_engines_mark_idle(dev_priv);
3318         i915_gem_timelines_mark_idle(dev_priv);
3319
3320         GEM_BUG_ON(!dev_priv->gt.awake);
3321         dev_priv->gt.awake = false;
3322         rearm_hangcheck = false;
3323
3324         if (INTEL_GEN(dev_priv) >= 6)
3325                 gen6_rps_idle(dev_priv);
3326
3327         if (NEEDS_RC6_CTX_CORRUPTION_WA(dev_priv)) {
3328                 i915_rc6_ctx_wa_check(dev_priv);
3329                 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
3330         }
3331
3332         intel_runtime_pm_put(dev_priv);
3333 out_unlock:
3334         mutex_unlock(&dev->struct_mutex);
3335
3336 out_rearm:
3337         if (rearm_hangcheck) {
3338                 GEM_BUG_ON(!dev_priv->gt.awake);
3339                 i915_queue_hangcheck(dev_priv);
3340         }
3341 }
3342
3343 void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
3344 {
3345         struct drm_i915_private *i915 = to_i915(gem->dev);
3346         struct drm_i915_gem_object *obj = to_intel_bo(gem);
3347         struct drm_i915_file_private *fpriv = file->driver_priv;
3348         struct i915_lut_handle *lut, *ln;
3349
3350         mutex_lock(&i915->drm.struct_mutex);
3351
3352         list_for_each_entry_safe(lut, ln, &obj->lut_list, obj_link) {
3353                 struct i915_gem_context *ctx = lut->ctx;
3354                 struct i915_vma *vma;
3355
3356                 if (ctx->file_priv != fpriv)
3357                         continue;
3358
3359                 vma = radix_tree_delete(&ctx->handles_vma, lut->handle);
3360
3361                 GEM_BUG_ON(vma->obj != obj);
3362
3363                 /* We allow the process to have multiple handles to the same
3364                  * vma, in the same fd namespace, by virtue of flink/open.
3365                  */
3366                 GEM_BUG_ON(!vma->open_count);
3367                 if (!--vma->open_count && !i915_vma_is_ggtt(vma))
3368                         i915_vma_close(vma);
3369
3370                 list_del(&lut->obj_link);
3371                 list_del(&lut->ctx_link);
3372
3373                 kmem_cache_free(i915->luts, lut);
3374                 __i915_gem_object_release_unless_active(obj);
3375         }
3376
3377         mutex_unlock(&i915->drm.struct_mutex);
3378 }
3379
3380 static unsigned long to_wait_timeout(s64 timeout_ns)
3381 {
3382         if (timeout_ns < 0)
3383                 return MAX_SCHEDULE_TIMEOUT;
3384
3385         if (timeout_ns == 0)
3386                 return 0;
3387
3388         return nsecs_to_jiffies_timeout(timeout_ns);
3389 }
3390
3391 /**
3392  * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
3393  * @dev: drm device pointer
3394  * @data: ioctl data blob
3395  * @file: drm file pointer
3396  *
3397  * Returns 0 if successful, else an error is returned with the remaining time in
3398  * the timeout parameter.
3399  *  -ETIME: object is still busy after timeout
3400  *  -ERESTARTSYS: signal interrupted the wait
3401  *  -ENONENT: object doesn't exist
3402  * Also possible, but rare:
3403  *  -EAGAIN: incomplete, restart syscall
3404  *  -ENOMEM: damn
3405  *  -ENODEV: Internal IRQ fail
3406  *  -E?: The add request failed
3407  *
3408  * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
3409  * non-zero timeout parameter the wait ioctl will wait for the given number of
3410  * nanoseconds on an object becoming unbusy. Since the wait itself does so
3411  * without holding struct_mutex the object may become re-busied before this
3412  * function completes. A similar but shorter * race condition exists in the busy
3413  * ioctl
3414  */
3415 int
3416 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
3417 {
3418         struct drm_i915_gem_wait *args = data;
3419         struct drm_i915_gem_object *obj;
3420         ktime_t start;
3421         long ret;
3422
3423         if (args->flags != 0)
3424                 return -EINVAL;
3425
3426         obj = i915_gem_object_lookup(file, args->bo_handle);
3427         if (!obj)
3428                 return -ENOENT;
3429
3430         start = ktime_get();
3431
3432         ret = i915_gem_object_wait(obj,
3433                                    I915_WAIT_INTERRUPTIBLE | I915_WAIT_ALL,
3434                                    to_wait_timeout(args->timeout_ns),
3435                                    to_rps_client(file));
3436
3437         if (args->timeout_ns > 0) {
3438                 args->timeout_ns -= ktime_to_ns(ktime_sub(ktime_get(), start));
3439                 if (args->timeout_ns < 0)
3440                         args->timeout_ns = 0;
3441
3442                 /*
3443                  * Apparently ktime isn't accurate enough and occasionally has a
3444                  * bit of mismatch in the jiffies<->nsecs<->ktime loop. So patch
3445                  * things up to make the test happy. We allow up to 1 jiffy.
3446                  *
3447                  * This is a regression from the timespec->ktime conversion.
3448                  */
3449                 if (ret == -ETIME && !nsecs_to_jiffies(args->timeout_ns))
3450                         args->timeout_ns = 0;
3451
3452                 /* Asked to wait beyond the jiffie/scheduler precision? */
3453                 if (ret == -ETIME && args->timeout_ns)
3454                         ret = -EAGAIN;
3455         }
3456
3457         i915_gem_object_put(obj);
3458         return ret;
3459 }
3460
3461 static int wait_for_timeline(struct i915_gem_timeline *tl, unsigned int flags)
3462 {
3463         int ret, i;
3464
3465         for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
3466                 ret = i915_gem_active_wait(&tl->engine[i].last_request, flags);
3467                 if (ret)
3468                         return ret;
3469         }
3470
3471         return 0;
3472 }
3473
3474 static int wait_for_engines(struct drm_i915_private *i915)
3475 {
3476         if (wait_for(intel_engines_are_idle(i915), 50)) {
3477                 DRM_ERROR("Failed to idle engines, declaring wedged!\n");
3478                 i915_gem_set_wedged(i915);
3479                 return -EIO;
3480         }
3481
3482         return 0;
3483 }
3484
3485 int i915_gem_wait_for_idle(struct drm_i915_private *i915, unsigned int flags)
3486 {
3487         int ret;
3488
3489         /* If the device is asleep, we have no requests outstanding */
3490         if (!READ_ONCE(i915->gt.awake))
3491                 return 0;
3492
3493         if (flags & I915_WAIT_LOCKED) {
3494                 struct i915_gem_timeline *tl;
3495
3496                 lockdep_assert_held(&i915->drm.struct_mutex);
3497
3498                 list_for_each_entry(tl, &i915->gt.timelines, link) {
3499                         ret = wait_for_timeline(tl, flags);
3500                         if (ret)
3501                                 return ret;
3502                 }
3503
3504                 i915_gem_retire_requests(i915);
3505                 GEM_BUG_ON(i915->gt.active_requests);
3506
3507                 ret = wait_for_engines(i915);
3508         } else {
3509                 ret = wait_for_timeline(&i915->gt.global_timeline, flags);
3510         }
3511
3512         return ret;
3513 }
3514
3515 static void __i915_gem_object_flush_for_display(struct drm_i915_gem_object *obj)
3516 {
3517         /*
3518          * We manually flush the CPU domain so that we can override and
3519          * force the flush for the display, and perform it asyncrhonously.
3520          */
3521         flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
3522         if (obj->cache_dirty)
3523                 i915_gem_clflush_object(obj, I915_CLFLUSH_FORCE);
3524         obj->base.write_domain = 0;
3525 }
3526
3527 void i915_gem_object_flush_if_display(struct drm_i915_gem_object *obj)
3528 {
3529         if (!READ_ONCE(obj->pin_display))
3530                 return;
3531
3532         mutex_lock(&obj->base.dev->struct_mutex);
3533         __i915_gem_object_flush_for_display(obj);
3534         mutex_unlock(&obj->base.dev->struct_mutex);
3535 }
3536
3537 /**
3538  * Moves a single object to the WC read, and possibly write domain.
3539  * @obj: object to act on
3540  * @write: ask for write access or read only
3541  *
3542  * This function returns when the move is complete, including waiting on
3543  * flushes to occur.
3544  */
3545 int
3546 i915_gem_object_set_to_wc_domain(struct drm_i915_gem_object *obj, bool write)
3547 {
3548         int ret;
3549
3550         lockdep_assert_held(&obj->base.dev->struct_mutex);
3551
3552         ret = i915_gem_object_wait(obj,
3553                                    I915_WAIT_INTERRUPTIBLE |
3554                                    I915_WAIT_LOCKED |
3555                                    (write ? I915_WAIT_ALL : 0),
3556                                    MAX_SCHEDULE_TIMEOUT,
3557                                    NULL);
3558         if (ret)
3559                 return ret;
3560
3561         if (obj->base.write_domain == I915_GEM_DOMAIN_WC)
3562                 return 0;
3563
3564         /* Flush and acquire obj->pages so that we are coherent through
3565          * direct access in memory with previous cached writes through
3566          * shmemfs and that our cache domain tracking remains valid.
3567          * For example, if the obj->filp was moved to swap without us
3568          * being notified and releasing the pages, we would mistakenly
3569          * continue to assume that the obj remained out of the CPU cached
3570          * domain.
3571          */
3572         ret = i915_gem_object_pin_pages(obj);
3573         if (ret)
3574                 return ret;
3575
3576         flush_write_domain(obj, ~I915_GEM_DOMAIN_WC);
3577
3578         /* Serialise direct access to this object with the barriers for
3579          * coherent writes from the GPU, by effectively invalidating the
3580          * WC domain upon first access.
3581          */
3582         if ((obj->base.read_domains & I915_GEM_DOMAIN_WC) == 0)
3583                 mb();
3584
3585         /* It should now be out of any other write domains, and we can update
3586          * the domain values for our changes.
3587          */
3588         GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_WC) != 0);
3589         obj->base.read_domains |= I915_GEM_DOMAIN_WC;
3590         if (write) {
3591                 obj->base.read_domains = I915_GEM_DOMAIN_WC;
3592                 obj->base.write_domain = I915_GEM_DOMAIN_WC;
3593                 obj->mm.dirty = true;
3594         }
3595
3596         i915_gem_object_unpin_pages(obj);
3597         return 0;
3598 }
3599
3600 /**
3601  * Moves a single object to the GTT read, and possibly write domain.
3602  * @obj: object to act on
3603  * @write: ask for write access or read only
3604  *
3605  * This function returns when the move is complete, including waiting on
3606  * flushes to occur.
3607  */
3608 int
3609 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
3610 {
3611         int ret;
3612
3613         lockdep_assert_held(&obj->base.dev->struct_mutex);
3614
3615         ret = i915_gem_object_wait(obj,
3616                                    I915_WAIT_INTERRUPTIBLE |
3617                                    I915_WAIT_LOCKED |
3618                                    (write ? I915_WAIT_ALL : 0),
3619                                    MAX_SCHEDULE_TIMEOUT,
3620                                    NULL);
3621         if (ret)
3622                 return ret;
3623
3624         if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
3625                 return 0;
3626
3627         /* Flush and acquire obj->pages so that we are coherent through
3628          * direct access in memory with previous cached writes through
3629          * shmemfs and that our cache domain tracking remains valid.
3630          * For example, if the obj->filp was moved to swap without us
3631          * being notified and releasing the pages, we would mistakenly
3632          * continue to assume that the obj remained out of the CPU cached
3633          * domain.
3634          */
3635         ret = i915_gem_object_pin_pages(obj);
3636         if (ret)
3637                 return ret;
3638
3639         flush_write_domain(obj, ~I915_GEM_DOMAIN_GTT);
3640
3641         /* Serialise direct access to this object with the barriers for
3642          * coherent writes from the GPU, by effectively invalidating the
3643          * GTT domain upon first access.
3644          */
3645         if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3646                 mb();
3647
3648         /* It should now be out of any other write domains, and we can update
3649          * the domain values for our changes.
3650          */
3651         GEM_BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
3652         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3653         if (write) {
3654                 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
3655                 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
3656                 obj->mm.dirty = true;
3657         }
3658
3659         i915_gem_object_unpin_pages(obj);
3660         return 0;
3661 }
3662
3663 /**
3664  * Changes the cache-level of an object across all VMA.
3665  * @obj: object to act on
3666  * @cache_level: new cache level to set for the object
3667  *
3668  * After this function returns, the object will be in the new cache-level
3669  * across all GTT and the contents of the backing storage will be coherent,
3670  * with respect to the new cache-level. In order to keep the backing storage
3671  * coherent for all users, we only allow a single cache level to be set
3672  * globally on the object and prevent it from being changed whilst the
3673  * hardware is reading from the object. That is if the object is currently
3674  * on the scanout it will be set to uncached (or equivalent display
3675  * cache coherency) and all non-MOCS GPU access will also be uncached so
3676  * that all direct access to the scanout remains coherent.
3677  */
3678 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3679                                     enum i915_cache_level cache_level)
3680 {
3681         struct i915_vma *vma;
3682         int ret;
3683
3684         lockdep_assert_held(&obj->base.dev->struct_mutex);
3685
3686         if (obj->cache_level == cache_level)
3687                 return 0;
3688
3689         /* Inspect the list of currently bound VMA and unbind any that would
3690          * be invalid given the new cache-level. This is principally to
3691          * catch the issue of the CS prefetch crossing page boundaries and
3692          * reading an invalid PTE on older architectures.
3693          */
3694 restart:
3695         list_for_each_entry(vma, &obj->vma_list, obj_link) {
3696                 if (!drm_mm_node_allocated(&vma->node))
3697                         continue;
3698
3699                 if (i915_vma_is_pinned(vma)) {
3700                         DRM_DEBUG("can not change the cache level of pinned objects\n");
3701                         return -EBUSY;
3702                 }
3703
3704                 if (!i915_vma_is_closed(vma) &&
3705                     i915_gem_valid_gtt_space(vma, cache_level))
3706                         continue;
3707
3708                 ret = i915_vma_unbind(vma);
3709                 if (ret)
3710                         return ret;
3711
3712                 /* As unbinding may affect other elements in the
3713                  * obj->vma_list (due to side-effects from retiring
3714                  * an active vma), play safe and restart the iterator.
3715                  */
3716                 goto restart;
3717         }
3718
3719         /* We can reuse the existing drm_mm nodes but need to change the
3720          * cache-level on the PTE. We could simply unbind them all and
3721          * rebind with the correct cache-level on next use. However since
3722          * we already have a valid slot, dma mapping, pages etc, we may as
3723          * rewrite the PTE in the belief that doing so tramples upon less
3724          * state and so involves less work.
3725          */
3726         if (obj->bind_count) {
3727                 /* Before we change the PTE, the GPU must not be accessing it.
3728                  * If we wait upon the object, we know that all the bound
3729                  * VMA are no longer active.
3730                  */
3731                 ret = i915_gem_object_wait(obj,
3732                                            I915_WAIT_INTERRUPTIBLE |
3733                                            I915_WAIT_LOCKED |
3734                                            I915_WAIT_ALL,
3735                                            MAX_SCHEDULE_TIMEOUT,
3736                                            NULL);
3737                 if (ret)
3738                         return ret;
3739
3740                 if (!HAS_LLC(to_i915(obj->base.dev)) &&
3741                     cache_level != I915_CACHE_NONE) {
3742                         /* Access to snoopable pages through the GTT is
3743                          * incoherent and on some machines causes a hard
3744                          * lockup. Relinquish the CPU mmaping to force
3745                          * userspace to refault in the pages and we can
3746                          * then double check if the GTT mapping is still
3747                          * valid for that pointer access.
3748                          */
3749                         i915_gem_release_mmap(obj);
3750
3751                         /* As we no longer need a fence for GTT access,
3752                          * we can relinquish it now (and so prevent having
3753                          * to steal a fence from someone else on the next
3754                          * fence request). Note GPU activity would have
3755                          * dropped the fence as all snoopable access is
3756                          * supposed to be linear.
3757                          */
3758                         list_for_each_entry(vma, &obj->vma_list, obj_link) {
3759                                 ret = i915_vma_put_fence(vma);
3760                                 if (ret)
3761                                         return ret;
3762                         }
3763                 } else {
3764                         /* We either have incoherent backing store and
3765                          * so no GTT access or the architecture is fully
3766                          * coherent. In such cases, existing GTT mmaps
3767                          * ignore the cache bit in the PTE and we can
3768                          * rewrite it without confusing the GPU or having
3769                          * to force userspace to fault back in its mmaps.
3770                          */
3771                 }
3772
3773                 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3774                         if (!drm_mm_node_allocated(&vma->node))
3775                                 continue;
3776
3777                         ret = i915_vma_bind(vma, cache_level, PIN_UPDATE);
3778                         if (ret)
3779                                 return ret;
3780                 }
3781         }
3782
3783         list_for_each_entry(vma, &obj->vma_list, obj_link)
3784                 vma->node.color = cache_level;
3785         i915_gem_object_set_cache_coherency(obj, cache_level);
3786         obj->cache_dirty = true; /* Always invalidate stale cachelines */
3787
3788         return 0;
3789 }
3790
3791 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
3792                                struct drm_file *file)
3793 {
3794         struct drm_i915_gem_caching *args = data;
3795         struct drm_i915_gem_object *obj;
3796         int err = 0;
3797
3798         rcu_read_lock();
3799         obj = i915_gem_object_lookup_rcu(file, args->handle);
3800         if (!obj) {
3801                 err = -ENOENT;
3802                 goto out;
3803         }
3804
3805         switch (obj->cache_level) {
3806         case I915_CACHE_LLC:
3807         case I915_CACHE_L3_LLC:
3808                 args->caching = I915_CACHING_CACHED;
3809                 break;
3810
3811         case I915_CACHE_WT:
3812                 args->caching = I915_CACHING_DISPLAY;
3813                 break;
3814
3815         default:
3816                 args->caching = I915_CACHING_NONE;
3817                 break;
3818         }
3819 out:
3820         rcu_read_unlock();
3821         return err;
3822 }
3823
3824 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
3825                                struct drm_file *file)
3826 {
3827         struct drm_i915_private *i915 = to_i915(dev);
3828         struct drm_i915_gem_caching *args = data;
3829         struct drm_i915_gem_object *obj;
3830         enum i915_cache_level level;
3831         int ret = 0;
3832
3833         switch (args->caching) {
3834         case I915_CACHING_NONE:
3835                 level = I915_CACHE_NONE;
3836                 break;
3837         case I915_CACHING_CACHED:
3838                 /*
3839                  * Due to a HW issue on BXT A stepping, GPU stores via a
3840                  * snooped mapping may leave stale data in a corresponding CPU
3841                  * cacheline, whereas normally such cachelines would get
3842                  * invalidated.
3843                  */
3844                 if (!HAS_LLC(i915) && !HAS_SNOOP(i915))
3845                         return -ENODEV;
3846
3847                 level = I915_CACHE_LLC;
3848                 break;
3849         case I915_CACHING_DISPLAY:
3850                 level = HAS_WT(i915) ? I915_CACHE_WT : I915_CACHE_NONE;
3851                 break;
3852         default:
3853                 return -EINVAL;
3854         }
3855
3856         obj = i915_gem_object_lookup(file, args->handle);
3857         if (!obj)
3858                 return -ENOENT;
3859
3860         if (obj->cache_level == level)
3861                 goto out;
3862
3863         ret = i915_gem_object_wait(obj,
3864                                    I915_WAIT_INTERRUPTIBLE,
3865                                    MAX_SCHEDULE_TIMEOUT,
3866                                    to_rps_client(file));
3867         if (ret)
3868                 goto out;
3869
3870         ret = i915_mutex_lock_interruptible(dev);
3871         if (ret)
3872                 goto out;
3873
3874         ret = i915_gem_object_set_cache_level(obj, level);
3875         mutex_unlock(&dev->struct_mutex);
3876
3877 out:
3878         i915_gem_object_put(obj);
3879         return ret;
3880 }
3881
3882 /*
3883  * Prepare buffer for display plane (scanout, cursors, etc).
3884  * Can be called from an uninterruptible phase (modesetting) and allows
3885  * any flushes to be pipelined (for pageflips).
3886  */
3887 struct i915_vma *
3888 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
3889                                      u32 alignment,
3890                                      const struct i915_ggtt_view *view)
3891 {
3892         struct i915_vma *vma;
3893         int ret;
3894
3895         lockdep_assert_held(&obj->base.dev->struct_mutex);
3896
3897         /* Mark the pin_display early so that we account for the
3898          * display coherency whilst setting up the cache domains.
3899          */
3900         obj->pin_display++;
3901
3902         /* The display engine is not coherent with the LLC cache on gen6.  As
3903          * a result, we make sure that the pinning that is about to occur is
3904          * done with uncached PTEs. This is lowest common denominator for all
3905          * chipsets.
3906          *
3907          * However for gen6+, we could do better by using the GFDT bit instead
3908          * of uncaching, which would allow us to flush all the LLC-cached data
3909          * with that bit in the PTE to main memory with just one PIPE_CONTROL.
3910          */
3911         ret = i915_gem_object_set_cache_level(obj,
3912                                               HAS_WT(to_i915(obj->base.dev)) ?
3913                                               I915_CACHE_WT : I915_CACHE_NONE);
3914         if (ret) {
3915                 vma = ERR_PTR(ret);
3916                 goto err_unpin_display;
3917         }
3918
3919         /* As the user may map the buffer once pinned in the display plane
3920          * (e.g. libkms for the bootup splash), we have to ensure that we
3921          * always use map_and_fenceable for all scanout buffers. However,
3922          * it may simply be too big to fit into mappable, in which case
3923          * put it anyway and hope that userspace can cope (but always first
3924          * try to preserve the existing ABI).
3925          */
3926         vma = ERR_PTR(-ENOSPC);
3927         if (!view || view->type == I915_GGTT_VIEW_NORMAL)
3928                 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment,
3929                                                PIN_MAPPABLE | PIN_NONBLOCK);
3930         if (IS_ERR(vma)) {
3931                 struct drm_i915_private *i915 = to_i915(obj->base.dev);
3932                 unsigned int flags;
3933
3934                 /* Valleyview is definitely limited to scanning out the first
3935                  * 512MiB. Lets presume this behaviour was inherited from the
3936                  * g4x display engine and that all earlier gen are similarly
3937                  * limited. Testing suggests that it is a little more
3938                  * complicated than this. For example, Cherryview appears quite
3939                  * happy to scanout from anywhere within its global aperture.
3940                  */
3941                 flags = 0;
3942                 if (HAS_GMCH_DISPLAY(i915))
3943                         flags = PIN_MAPPABLE;
3944                 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment, flags);
3945         }
3946         if (IS_ERR(vma))
3947                 goto err_unpin_display;
3948
3949         vma->display_alignment = max_t(u64, vma->display_alignment, alignment);
3950
3951         /* Treat this as an end-of-frame, like intel_user_framebuffer_dirty() */
3952         __i915_gem_object_flush_for_display(obj);
3953         intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
3954
3955         /* It should now be out of any other write domains, and we can update
3956          * the domain values for our changes.
3957          */
3958         obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
3959
3960         return vma;
3961
3962 err_unpin_display:
3963         obj->pin_display--;
3964         return vma;
3965 }
3966
3967 void
3968 i915_gem_object_unpin_from_display_plane(struct i915_vma *vma)
3969 {
3970         lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
3971
3972         if (WARN_ON(vma->obj->pin_display == 0))
3973                 return;
3974
3975         if (--vma->obj->pin_display == 0)
3976                 vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
3977
3978         /* Bump the LRU to try and avoid premature eviction whilst flipping  */
3979         i915_gem_object_bump_inactive_ggtt(vma->obj);
3980
3981         i915_vma_unpin(vma);
3982 }
3983
3984 /**
3985  * Moves a single object to the CPU read, and possibly write domain.
3986  * @obj: object to act on
3987  * @write: requesting write or read-only access
3988  *
3989  * This function returns when the move is complete, including waiting on
3990  * flushes to occur.
3991  */
3992 int
3993 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
3994 {
3995         int ret;
3996
3997         lockdep_assert_held(&obj->base.dev->struct_mutex);
3998
3999         ret = i915_gem_object_wait(obj,
4000                                    I915_WAIT_INTERRUPTIBLE |
4001                                    I915_WAIT_LOCKED |
4002                                    (write ? I915_WAIT_ALL : 0),
4003                                    MAX_SCHEDULE_TIMEOUT,
4004                                    NULL);
4005         if (ret)
4006                 return ret;
4007
4008         flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
4009
4010         /* Flush the CPU cache if it's still invalid. */
4011         if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
4012                 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
4013                 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
4014         }
4015
4016         /* It should now be out of any other write domains, and we can update
4017          * the domain values for our changes.
4018          */
4019         GEM_BUG_ON(obj->base.write_domain & ~I915_GEM_DOMAIN_CPU);
4020
4021         /* If we're writing through the CPU, then the GPU read domains will
4022          * need to be invalidated at next use.
4023          */
4024         if (write)
4025                 __start_cpu_write(obj);
4026
4027         return 0;
4028 }
4029
4030 /* Throttle our rendering by waiting until the ring has completed our requests
4031  * emitted over 20 msec ago.
4032  *
4033  * Note that if we were to use the current jiffies each time around the loop,
4034  * we wouldn't escape the function with any frames outstanding if the time to
4035  * render a frame was over 20ms.
4036  *
4037  * This should get us reasonable parallelism between CPU and GPU but also
4038  * relatively low latency when blocking on a particular request to finish.
4039  */
4040 static int
4041 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
4042 {
4043         struct drm_i915_private *dev_priv = to_i915(dev);
4044         struct drm_i915_file_private *file_priv = file->driver_priv;
4045         unsigned long recent_enough = jiffies - DRM_I915_THROTTLE_JIFFIES;
4046         struct drm_i915_gem_request *request, *target = NULL;
4047         long ret;
4048
4049         /* ABI: return -EIO if already wedged */
4050         if (i915_terminally_wedged(&dev_priv->gpu_error))
4051                 return -EIO;
4052
4053         spin_lock(&file_priv->mm.lock);
4054         list_for_each_entry(request, &file_priv->mm.request_list, client_link) {
4055                 if (time_after_eq(request->emitted_jiffies, recent_enough))
4056                         break;
4057
4058                 if (target) {
4059                         list_del(&target->client_link);
4060                         target->file_priv = NULL;
4061                 }
4062
4063                 target = request;
4064         }
4065         if (target)
4066                 i915_gem_request_get(target);
4067         spin_unlock(&file_priv->mm.lock);
4068
4069         if (target == NULL)
4070                 return 0;
4071
4072         ret = i915_wait_request(target,
4073                                 I915_WAIT_INTERRUPTIBLE,
4074                                 MAX_SCHEDULE_TIMEOUT);
4075         i915_gem_request_put(target);
4076
4077         return ret < 0 ? ret : 0;
4078 }
4079
4080 struct i915_vma *
4081 i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
4082                          const struct i915_ggtt_view *view,
4083                          u64 size,
4084                          u64 alignment,
4085                          u64 flags)
4086 {
4087         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
4088         struct i915_address_space *vm = &dev_priv->ggtt.base;
4089
4090         return i915_gem_object_pin(obj, vm, view, size, alignment,
4091                                    flags | PIN_GLOBAL);
4092 }
4093
4094 struct i915_vma *
4095 i915_gem_object_pin(struct drm_i915_gem_object *obj,
4096                     struct i915_address_space *vm,
4097                     const struct i915_ggtt_view *view,
4098                     u64 size,
4099                     u64 alignment,
4100                     u64 flags)
4101 {
4102         struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
4103         struct i915_vma *vma;
4104         int ret;
4105
4106         lockdep_assert_held(&obj->base.dev->struct_mutex);
4107
4108         vma = i915_vma_instance(obj, vm, view);
4109         if (unlikely(IS_ERR(vma)))
4110                 return vma;
4111
4112         if (i915_vma_misplaced(vma, size, alignment, flags)) {
4113                 if (flags & PIN_NONBLOCK &&
4114                     (i915_vma_is_pinned(vma) || i915_vma_is_active(vma)))
4115                         return ERR_PTR(-ENOSPC);
4116
4117                 if (flags & PIN_MAPPABLE) {
4118                         /* If the required space is larger than the available
4119                          * aperture, we will not able to find a slot for the
4120                          * object and unbinding the object now will be in
4121                          * vain. Worse, doing so may cause us to ping-pong
4122                          * the object in and out of the Global GTT and
4123                          * waste a lot of cycles under the mutex.
4124                          */
4125                         if (vma->fence_size > dev_priv->ggtt.mappable_end)
4126                                 return ERR_PTR(-E2BIG);
4127
4128                         /* If NONBLOCK is set the caller is optimistically
4129                          * trying to cache the full object within the mappable
4130                          * aperture, and *must* have a fallback in place for
4131                          * situations where we cannot bind the object. We
4132                          * can be a little more lax here and use the fallback
4133                          * more often to avoid costly migrations of ourselves
4134                          * and other objects within the aperture.
4135                          *
4136                          * Half-the-aperture is used as a simple heuristic.
4137                          * More interesting would to do search for a free
4138                          * block prior to making the commitment to unbind.
4139                          * That caters for the self-harm case, and with a
4140                          * little more heuristics (e.g. NOFAULT, NOEVICT)
4141                          * we could try to minimise harm to others.
4142                          */
4143                         if (flags & PIN_NONBLOCK &&
4144                             vma->fence_size > dev_priv->ggtt.mappable_end / 2)
4145                                 return ERR_PTR(-ENOSPC);
4146                 }
4147
4148                 WARN(i915_vma_is_pinned(vma),
4149                      "bo is already pinned in ggtt with incorrect alignment:"
4150                      " offset=%08x, req.alignment=%llx,"
4151                      " req.map_and_fenceable=%d, vma->map_and_fenceable=%d\n",
4152                      i915_ggtt_offset(vma), alignment,
4153                      !!(flags & PIN_MAPPABLE),
4154                      i915_vma_is_map_and_fenceable(vma));
4155                 ret = i915_vma_unbind(vma);
4156                 if (ret)
4157                         return ERR_PTR(ret);
4158         }
4159
4160         ret = i915_vma_pin(vma, size, alignment, flags);
4161         if (ret)
4162                 return ERR_PTR(ret);
4163
4164         return vma;
4165 }
4166
4167 static __always_inline unsigned int __busy_read_flag(unsigned int id)
4168 {
4169         /* Note that we could alias engines in the execbuf API, but
4170          * that would be very unwise as it prevents userspace from
4171          * fine control over engine selection. Ahem.
4172          *
4173          * This should be something like EXEC_MAX_ENGINE instead of
4174          * I915_NUM_ENGINES.
4175          */
4176         BUILD_BUG_ON(I915_NUM_ENGINES > 16);
4177         return 0x10000 << id;
4178 }
4179
4180 static __always_inline unsigned int __busy_write_id(unsigned int id)
4181 {
4182         /* The uABI guarantees an active writer is also amongst the read
4183          * engines. This would be true if we accessed the activity tracking
4184          * under the lock, but as we perform the lookup of the object and
4185          * its activity locklessly we can not guarantee that the last_write
4186          * being active implies that we have set the same engine flag from
4187          * last_read - hence we always set both read and write busy for
4188          * last_write.
4189          */
4190         return id | __busy_read_flag(id);
4191 }
4192
4193 static __always_inline unsigned int
4194 __busy_set_if_active(const struct dma_fence *fence,
4195                      unsigned int (*flag)(unsigned int id))
4196 {
4197         struct drm_i915_gem_request *rq;
4198
4199         /* We have to check the current hw status of the fence as the uABI
4200          * guarantees forward progress. We could rely on the idle worker
4201          * to eventually flush us, but to minimise latency just ask the
4202          * hardware.
4203          *
4204          * Note we only report on the status of native fences.
4205          */
4206         if (!dma_fence_is_i915(fence))
4207                 return 0;
4208
4209         /* opencode to_request() in order to avoid const warnings */
4210         rq = container_of(fence, struct drm_i915_gem_request, fence);
4211         if (i915_gem_request_completed(rq))
4212                 return 0;
4213
4214         return flag(rq->engine->uabi_id);
4215 }
4216
4217 static __always_inline unsigned int
4218 busy_check_reader(const struct dma_fence *fence)
4219 {
4220         return __busy_set_if_active(fence, __busy_read_flag);
4221 }
4222
4223 static __always_inline unsigned int
4224 busy_check_writer(const struct dma_fence *fence)
4225 {
4226         if (!fence)
4227                 return 0;
4228
4229         return __busy_set_if_active(fence, __busy_write_id);
4230 }
4231
4232 int
4233 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4234                     struct drm_file *file)
4235 {
4236         struct drm_i915_gem_busy *args = data;
4237         struct drm_i915_gem_object *obj;
4238         struct reservation_object_list *list;
4239         unsigned int seq;
4240         int err;
4241
4242         err = -ENOENT;
4243         rcu_read_lock();
4244         obj = i915_gem_object_lookup_rcu(file, args->handle);
4245         if (!obj)
4246                 goto out;
4247
4248         /* A discrepancy here is that we do not report the status of
4249          * non-i915 fences, i.e. even though we may report the object as idle,
4250          * a call to set-domain may still stall waiting for foreign rendering.
4251          * This also means that wait-ioctl may report an object as busy,
4252          * where busy-ioctl considers it idle.
4253          *
4254          * We trade the ability to warn of foreign fences to report on which
4255          * i915 engines are active for the object.
4256          *
4257          * Alternatively, we can trade that extra information on read/write
4258          * activity with
4259          *      args->busy =
4260          *              !reservation_object_test_signaled_rcu(obj->resv, true);
4261          * to report the overall busyness. This is what the wait-ioctl does.
4262          *
4263          */
4264 retry:
4265         seq = raw_read_seqcount(&obj->resv->seq);
4266
4267         /* Translate the exclusive fence to the READ *and* WRITE engine */
4268         args->busy = busy_check_writer(rcu_dereference(obj->resv->fence_excl));
4269
4270         /* Translate shared fences to READ set of engines */
4271         list = rcu_dereference(obj->resv->fence);
4272         if (list) {
4273                 unsigned int shared_count = list->shared_count, i;
4274
4275                 for (i = 0; i < shared_count; ++i) {
4276                         struct dma_fence *fence =
4277                                 rcu_dereference(list->shared[i]);
4278
4279                         args->busy |= busy_check_reader(fence);
4280                 }
4281         }
4282
4283         if (args->busy && read_seqcount_retry(&obj->resv->seq, seq))
4284                 goto retry;
4285
4286         err = 0;
4287 out:
4288         rcu_read_unlock();
4289         return err;
4290 }
4291
4292 int
4293 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
4294                         struct drm_file *file_priv)
4295 {
4296         return i915_gem_ring_throttle(dev, file_priv);
4297 }
4298
4299 int
4300 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
4301                        struct drm_file *file_priv)
4302 {
4303         struct drm_i915_private *dev_priv = to_i915(dev);
4304         struct drm_i915_gem_madvise *args = data;
4305         struct drm_i915_gem_object *obj;
4306         int err;
4307
4308         switch (args->madv) {
4309         case I915_MADV_DONTNEED:
4310         case I915_MADV_WILLNEED:
4311             break;
4312         default:
4313             return -EINVAL;
4314         }
4315
4316         obj = i915_gem_object_lookup(file_priv, args->handle);
4317         if (!obj)
4318                 return -ENOENT;
4319
4320         err = mutex_lock_interruptible(&obj->mm.lock);
4321         if (err)
4322                 goto out;
4323
4324         if (obj->mm.pages &&
4325             i915_gem_object_is_tiled(obj) &&
4326             dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
4327                 if (obj->mm.madv == I915_MADV_WILLNEED) {
4328                         GEM_BUG_ON(!obj->mm.quirked);
4329                         __i915_gem_object_unpin_pages(obj);
4330                         obj->mm.quirked = false;
4331                 }
4332                 if (args->madv == I915_MADV_WILLNEED) {
4333                         GEM_BUG_ON(obj->mm.quirked);
4334                         __i915_gem_object_pin_pages(obj);
4335                         obj->mm.quirked = true;
4336                 }
4337         }
4338
4339         if (obj->mm.madv != __I915_MADV_PURGED)
4340                 obj->mm.madv = args->madv;
4341
4342         /* if the object is no longer attached, discard its backing storage */
4343         if (obj->mm.madv == I915_MADV_DONTNEED && !obj->mm.pages)
4344                 i915_gem_object_truncate(obj);
4345
4346         args->retained = obj->mm.madv != __I915_MADV_PURGED;
4347         mutex_unlock(&obj->mm.lock);
4348
4349 out:
4350         i915_gem_object_put(obj);
4351         return err;
4352 }
4353
4354 static void
4355 frontbuffer_retire(struct i915_gem_active *active,
4356                    struct drm_i915_gem_request *request)
4357 {
4358         struct drm_i915_gem_object *obj =
4359                 container_of(active, typeof(*obj), frontbuffer_write);
4360
4361         intel_fb_obj_flush(obj, ORIGIN_CS);
4362 }
4363
4364 void i915_gem_object_init(struct drm_i915_gem_object *obj,
4365                           const struct drm_i915_gem_object_ops *ops)
4366 {
4367         mutex_init(&obj->mm.lock);
4368
4369         INIT_LIST_HEAD(&obj->global_link);
4370         INIT_LIST_HEAD(&obj->userfault_link);
4371         INIT_LIST_HEAD(&obj->vma_list);
4372         INIT_LIST_HEAD(&obj->lut_list);
4373         INIT_LIST_HEAD(&obj->batch_pool_link);
4374
4375         obj->ops = ops;
4376
4377         reservation_object_init(&obj->__builtin_resv);
4378         obj->resv = &obj->__builtin_resv;
4379
4380         obj->frontbuffer_ggtt_origin = ORIGIN_GTT;
4381         init_request_active(&obj->frontbuffer_write, frontbuffer_retire);
4382
4383         obj->mm.madv = I915_MADV_WILLNEED;
4384         INIT_RADIX_TREE(&obj->mm.get_page.radix, GFP_KERNEL | __GFP_NOWARN);
4385         mutex_init(&obj->mm.get_page.lock);
4386
4387         i915_gem_info_add_obj(to_i915(obj->base.dev), obj->base.size);
4388 }
4389
4390 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
4391         .flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE |
4392                  I915_GEM_OBJECT_IS_SHRINKABLE,
4393
4394         .get_pages = i915_gem_object_get_pages_gtt,
4395         .put_pages = i915_gem_object_put_pages_gtt,
4396
4397         .pwrite = i915_gem_object_pwrite_gtt,
4398 };
4399
4400 struct drm_i915_gem_object *
4401 i915_gem_object_create(struct drm_i915_private *dev_priv, u64 size)
4402 {
4403         struct drm_i915_gem_object *obj;
4404         struct address_space *mapping;
4405         unsigned int cache_level;
4406         gfp_t mask;
4407         int ret;
4408
4409         /* There is a prevalence of the assumption that we fit the object's
4410          * page count inside a 32bit _signed_ variable. Let's document this and
4411          * catch if we ever need to fix it. In the meantime, if you do spot
4412          * such a local variable, please consider fixing!
4413          */
4414         if (size >> PAGE_SHIFT > INT_MAX)
4415                 return ERR_PTR(-E2BIG);
4416
4417         if (overflows_type(size, obj->base.size))
4418                 return ERR_PTR(-E2BIG);
4419
4420         obj = i915_gem_object_alloc(dev_priv);
4421         if (obj == NULL)
4422                 return ERR_PTR(-ENOMEM);
4423
4424         ret = drm_gem_object_init(&dev_priv->drm, &obj->base, size);
4425         if (ret)
4426                 goto fail;
4427
4428         mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
4429         if (IS_I965GM(dev_priv) || IS_I965G(dev_priv)) {
4430                 /* 965gm cannot relocate objects above 4GiB. */
4431                 mask &= ~__GFP_HIGHMEM;
4432                 mask |= __GFP_DMA32;
4433         }
4434
4435         mapping = obj->base.filp->f_mapping;
4436         mapping_set_gfp_mask(mapping, mask);
4437         GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
4438
4439         i915_gem_object_init(obj, &i915_gem_object_ops);
4440
4441         obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4442         obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4443
4444         if (HAS_LLC(dev_priv))
4445                 /* On some devices, we can have the GPU use the LLC (the CPU
4446                  * cache) for about a 10% performance improvement
4447                  * compared to uncached.  Graphics requests other than
4448                  * display scanout are coherent with the CPU in
4449                  * accessing this cache.  This means in this mode we
4450                  * don't need to clflush on the CPU side, and on the
4451                  * GPU side we only need to flush internal caches to
4452                  * get data visible to the CPU.
4453                  *
4454                  * However, we maintain the display planes as UC, and so
4455                  * need to rebind when first used as such.
4456                  */
4457                 cache_level = I915_CACHE_LLC;
4458         else
4459                 cache_level = I915_CACHE_NONE;
4460
4461         i915_gem_object_set_cache_coherency(obj, cache_level);
4462
4463         trace_i915_gem_object_create(obj);
4464
4465         return obj;
4466
4467 fail:
4468         i915_gem_object_free(obj);
4469         return ERR_PTR(ret);
4470 }
4471
4472 static bool discard_backing_storage(struct drm_i915_gem_object *obj)
4473 {
4474         /* If we are the last user of the backing storage (be it shmemfs
4475          * pages or stolen etc), we know that the pages are going to be
4476          * immediately released. In this case, we can then skip copying
4477          * back the contents from the GPU.
4478          */
4479
4480         if (obj->mm.madv != I915_MADV_WILLNEED)
4481                 return false;
4482
4483         if (obj->base.filp == NULL)
4484                 return true;
4485
4486         /* At first glance, this looks racy, but then again so would be
4487          * userspace racing mmap against close. However, the first external
4488          * reference to the filp can only be obtained through the
4489          * i915_gem_mmap_ioctl() which safeguards us against the user
4490          * acquiring such a reference whilst we are in the middle of
4491          * freeing the object.
4492          */
4493         return atomic_long_read(&obj->base.filp->f_count) == 1;
4494 }
4495
4496 static void __i915_gem_free_objects(struct drm_i915_private *i915,
4497                                     struct llist_node *freed)
4498 {
4499         struct drm_i915_gem_object *obj, *on;
4500
4501         mutex_lock(&i915->drm.struct_mutex);
4502         intel_runtime_pm_get(i915);
4503         llist_for_each_entry(obj, freed, freed) {
4504                 struct i915_vma *vma, *vn;
4505
4506                 trace_i915_gem_object_destroy(obj);
4507
4508                 GEM_BUG_ON(i915_gem_object_is_active(obj));
4509                 list_for_each_entry_safe(vma, vn,
4510                                          &obj->vma_list, obj_link) {
4511                         GEM_BUG_ON(i915_vma_is_active(vma));
4512                         vma->flags &= ~I915_VMA_PIN_MASK;
4513                         i915_vma_close(vma);
4514                 }
4515                 GEM_BUG_ON(!list_empty(&obj->vma_list));
4516                 GEM_BUG_ON(!RB_EMPTY_ROOT(&obj->vma_tree));
4517
4518                 list_del(&obj->global_link);
4519         }
4520         intel_runtime_pm_put(i915);
4521         mutex_unlock(&i915->drm.struct_mutex);
4522
4523         cond_resched();
4524
4525         llist_for_each_entry_safe(obj, on, freed, freed) {
4526                 GEM_BUG_ON(obj->bind_count);
4527                 GEM_BUG_ON(atomic_read(&obj->frontbuffer_bits));
4528
4529                 if (obj->ops->release)
4530                         obj->ops->release(obj);
4531
4532                 if (WARN_ON(i915_gem_object_has_pinned_pages(obj)))
4533                         atomic_set(&obj->mm.pages_pin_count, 0);
4534                 __i915_gem_object_put_pages(obj, I915_MM_NORMAL);
4535                 GEM_BUG_ON(obj->mm.pages);
4536
4537                 if (obj->base.import_attach)
4538                         drm_prime_gem_destroy(&obj->base, NULL);
4539
4540                 reservation_object_fini(&obj->__builtin_resv);
4541                 drm_gem_object_release(&obj->base);
4542                 i915_gem_info_remove_obj(i915, obj->base.size);
4543
4544                 kfree(obj->bit_17);
4545                 i915_gem_object_free(obj);
4546         }
4547 }
4548
4549 static void i915_gem_flush_free_objects(struct drm_i915_private *i915)
4550 {
4551         struct llist_node *freed;
4552
4553         freed = llist_del_all(&i915->mm.free_list);
4554         if (unlikely(freed))
4555                 __i915_gem_free_objects(i915, freed);
4556 }
4557
4558 static void __i915_gem_free_work(struct work_struct *work)
4559 {
4560         struct drm_i915_private *i915 =
4561                 container_of(work, struct drm_i915_private, mm.free_work);
4562         struct llist_node *freed;
4563
4564         /* All file-owned VMA should have been released by this point through
4565          * i915_gem_close_object(), or earlier by i915_gem_context_close().
4566          * However, the object may also be bound into the global GTT (e.g.
4567          * older GPUs without per-process support, or for direct access through
4568          * the GTT either for the user or for scanout). Those VMA still need to
4569          * unbound now.
4570          */
4571
4572         while ((freed = llist_del_all(&i915->mm.free_list))) {
4573                 __i915_gem_free_objects(i915, freed);
4574                 if (need_resched())
4575                         break;
4576         }
4577 }
4578
4579 static void __i915_gem_free_object_rcu(struct rcu_head *head)
4580 {
4581         struct drm_i915_gem_object *obj =
4582                 container_of(head, typeof(*obj), rcu);
4583         struct drm_i915_private *i915 = to_i915(obj->base.dev);
4584
4585         /* We can't simply use call_rcu() from i915_gem_free_object()
4586          * as we need to block whilst unbinding, and the call_rcu
4587          * task may be called from softirq context. So we take a
4588          * detour through a worker.
4589          */
4590         if (llist_add(&obj->freed, &i915->mm.free_list))
4591                 schedule_work(&i915->mm.free_work);
4592 }
4593
4594 void i915_gem_free_object(struct drm_gem_object *gem_obj)
4595 {
4596         struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
4597
4598         if (obj->mm.quirked)
4599                 __i915_gem_object_unpin_pages(obj);
4600
4601         if (discard_backing_storage(obj))
4602                 obj->mm.madv = I915_MADV_DONTNEED;
4603
4604         /* Before we free the object, make sure any pure RCU-only
4605          * read-side critical sections are complete, e.g.
4606          * i915_gem_busy_ioctl(). For the corresponding synchronized
4607          * lookup see i915_gem_object_lookup_rcu().
4608          */
4609         call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
4610 }
4611
4612 void __i915_gem_object_release_unless_active(struct drm_i915_gem_object *obj)
4613 {
4614         lockdep_assert_held(&obj->base.dev->struct_mutex);
4615
4616         if (!i915_gem_object_has_active_reference(obj) &&
4617             i915_gem_object_is_active(obj))
4618                 i915_gem_object_set_active_reference(obj);
4619         else
4620                 i915_gem_object_put(obj);
4621 }
4622
4623 static void assert_kernel_context_is_current(struct drm_i915_private *dev_priv)
4624 {
4625         struct intel_engine_cs *engine;
4626         enum intel_engine_id id;
4627
4628         for_each_engine(engine, dev_priv, id)
4629                 GEM_BUG_ON(engine->last_retired_context &&
4630                            !i915_gem_context_is_kernel(engine->last_retired_context));
4631 }
4632
4633 void i915_gem_sanitize(struct drm_i915_private *i915)
4634 {
4635         /*
4636          * If we inherit context state from the BIOS or earlier occupants
4637          * of the GPU, the GPU may be in an inconsistent state when we
4638          * try to take over. The only way to remove the earlier state
4639          * is by resetting. However, resetting on earlier gen is tricky as
4640          * it may impact the display and we are uncertain about the stability
4641          * of the reset, so this could be applied to even earlier gen.
4642          */
4643         if (INTEL_GEN(i915) >= 5) {
4644                 int reset = intel_gpu_reset(i915, ALL_ENGINES);
4645                 WARN_ON(reset && reset != -ENODEV);
4646         }
4647 }
4648
4649 int i915_gem_suspend(struct drm_i915_private *dev_priv)
4650 {
4651         struct drm_device *dev = &dev_priv->drm;
4652         int ret;
4653
4654         intel_runtime_pm_get(dev_priv);
4655         intel_suspend_gt_powersave(dev_priv);
4656
4657         mutex_lock(&dev->struct_mutex);
4658
4659         /* We have to flush all the executing contexts to main memory so
4660          * that they can saved in the hibernation image. To ensure the last
4661          * context image is coherent, we have to switch away from it. That
4662          * leaves the dev_priv->kernel_context still active when
4663          * we actually suspend, and its image in memory may not match the GPU
4664          * state. Fortunately, the kernel_context is disposable and we do
4665          * not rely on its state.
4666          */
4667         ret = i915_gem_switch_to_kernel_context(dev_priv);
4668         if (ret)
4669                 goto err_unlock;
4670
4671         ret = i915_gem_wait_for_idle(dev_priv,
4672                                      I915_WAIT_INTERRUPTIBLE |
4673                                      I915_WAIT_LOCKED);
4674         if (ret && ret != -EIO)
4675                 goto err_unlock;
4676
4677         assert_kernel_context_is_current(dev_priv);
4678         i915_gem_contexts_lost(dev_priv);
4679         mutex_unlock(&dev->struct_mutex);
4680
4681         intel_guc_suspend(dev_priv);
4682
4683         cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
4684         cancel_delayed_work_sync(&dev_priv->gt.retire_work);
4685
4686         /* As the idle_work is rearming if it detects a race, play safe and
4687          * repeat the flush until it is definitely idle.
4688          */
4689         while (flush_delayed_work(&dev_priv->gt.idle_work))
4690                 ;
4691
4692         /* Assert that we sucessfully flushed all the work and
4693          * reset the GPU back to its idle, low power state.
4694          */
4695         WARN_ON(dev_priv->gt.awake);
4696         WARN_ON(!intel_engines_are_idle(dev_priv));
4697
4698         /*
4699          * Neither the BIOS, ourselves or any other kernel
4700          * expects the system to be in execlists mode on startup,
4701          * so we need to reset the GPU back to legacy mode. And the only
4702          * known way to disable logical contexts is through a GPU reset.
4703          *
4704          * So in order to leave the system in a known default configuration,
4705          * always reset the GPU upon unload and suspend. Afterwards we then
4706          * clean up the GEM state tracking, flushing off the requests and
4707          * leaving the system in a known idle state.
4708          *
4709          * Note that is of the upmost importance that the GPU is idle and
4710          * all stray writes are flushed *before* we dismantle the backing
4711          * storage for the pinned objects.
4712          *
4713          * However, since we are uncertain that resetting the GPU on older
4714          * machines is a good idea, we don't - just in case it leaves the
4715          * machine in an unusable condition.
4716          */
4717         i915_gem_sanitize(dev_priv);
4718
4719         intel_runtime_pm_put(dev_priv);
4720         return 0;
4721
4722 err_unlock:
4723         mutex_unlock(&dev->struct_mutex);
4724         intel_runtime_pm_put(dev_priv);
4725         return ret;
4726 }
4727
4728 void i915_gem_resume(struct drm_i915_private *dev_priv)
4729 {
4730         struct drm_device *dev = &dev_priv->drm;
4731
4732         WARN_ON(dev_priv->gt.awake);
4733
4734         mutex_lock(&dev->struct_mutex);
4735         i915_gem_restore_gtt_mappings(dev_priv);
4736
4737         /* As we didn't flush the kernel context before suspend, we cannot
4738          * guarantee that the context image is complete. So let's just reset
4739          * it and start again.
4740          */
4741         dev_priv->gt.resume(dev_priv);
4742
4743         mutex_unlock(&dev->struct_mutex);
4744 }
4745
4746 void i915_gem_init_swizzling(struct drm_i915_private *dev_priv)
4747 {
4748         if (INTEL_GEN(dev_priv) < 5 ||
4749             dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
4750                 return;
4751
4752         I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
4753                                  DISP_TILE_SURFACE_SWIZZLING);
4754
4755         if (IS_GEN5(dev_priv))
4756                 return;
4757
4758         I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
4759         if (IS_GEN6(dev_priv))
4760                 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
4761         else if (IS_GEN7(dev_priv))
4762                 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
4763         else if (IS_GEN8(dev_priv))
4764                 I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
4765         else
4766                 BUG();
4767 }
4768
4769 static void init_unused_ring(struct drm_i915_private *dev_priv, u32 base)
4770 {
4771         I915_WRITE(RING_CTL(base), 0);
4772         I915_WRITE(RING_HEAD(base), 0);
4773         I915_WRITE(RING_TAIL(base), 0);
4774         I915_WRITE(RING_START(base), 0);
4775 }
4776
4777 static void init_unused_rings(struct drm_i915_private *dev_priv)
4778 {
4779         if (IS_I830(dev_priv)) {
4780                 init_unused_ring(dev_priv, PRB1_BASE);
4781                 init_unused_ring(dev_priv, SRB0_BASE);
4782                 init_unused_ring(dev_priv, SRB1_BASE);
4783                 init_unused_ring(dev_priv, SRB2_BASE);
4784                 init_unused_ring(dev_priv, SRB3_BASE);
4785         } else if (IS_GEN2(dev_priv)) {
4786                 init_unused_ring(dev_priv, SRB0_BASE);
4787                 init_unused_ring(dev_priv, SRB1_BASE);
4788         } else if (IS_GEN3(dev_priv)) {
4789                 init_unused_ring(dev_priv, PRB1_BASE);
4790                 init_unused_ring(dev_priv, PRB2_BASE);
4791         }
4792 }
4793
4794 static int __i915_gem_restart_engines(void *data)
4795 {
4796         struct drm_i915_private *i915 = data;
4797         struct intel_engine_cs *engine;
4798         enum intel_engine_id id;
4799         int err;
4800
4801         for_each_engine(engine, i915, id) {
4802                 err = engine->init_hw(engine);
4803                 if (err)
4804                         return err;
4805         }
4806
4807         return 0;
4808 }
4809
4810 int i915_gem_init_hw(struct drm_i915_private *dev_priv)
4811 {
4812         int ret;
4813
4814         dev_priv->gt.last_init_time = ktime_get();
4815
4816         /* Double layer security blanket, see i915_gem_init() */
4817         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4818
4819         if (HAS_EDRAM(dev_priv) && INTEL_GEN(dev_priv) < 9)
4820                 I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
4821
4822         if (IS_HASWELL(dev_priv))
4823                 I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev_priv) ?
4824                            LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
4825
4826         if (HAS_PCH_NOP(dev_priv)) {
4827                 if (IS_IVYBRIDGE(dev_priv)) {
4828                         u32 temp = I915_READ(GEN7_MSG_CTL);
4829                         temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
4830                         I915_WRITE(GEN7_MSG_CTL, temp);
4831                 } else if (INTEL_GEN(dev_priv) >= 7) {
4832                         u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
4833                         temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
4834                         I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
4835                 }
4836         }
4837
4838         i915_gem_init_swizzling(dev_priv);
4839
4840         /*
4841          * At least 830 can leave some of the unused rings
4842          * "active" (ie. head != tail) after resume which
4843          * will prevent c3 entry. Makes sure all unused rings
4844          * are totally idle.
4845          */
4846         init_unused_rings(dev_priv);
4847
4848         BUG_ON(!dev_priv->kernel_context);
4849
4850         ret = i915_ppgtt_init_hw(dev_priv);
4851         if (ret) {
4852                 DRM_ERROR("PPGTT enable HW failed %d\n", ret);
4853                 goto out;
4854         }
4855
4856         /* Need to do basic initialisation of all rings first: */
4857         ret = __i915_gem_restart_engines(dev_priv);
4858         if (ret)
4859                 goto out;
4860
4861         intel_mocs_init_l3cc_table(dev_priv);
4862
4863         /* We can't enable contexts until all firmware is loaded */
4864         ret = intel_uc_init_hw(dev_priv);
4865         if (ret)
4866                 goto out;
4867
4868 out:
4869         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4870         return ret;
4871 }
4872
4873 bool intel_sanitize_semaphores(struct drm_i915_private *dev_priv, int value)
4874 {
4875         if (INTEL_INFO(dev_priv)->gen < 6)
4876                 return false;
4877
4878         /* TODO: make semaphores and Execlists play nicely together */
4879         if (i915.enable_execlists)
4880                 return false;
4881
4882         if (value >= 0)
4883                 return value;
4884
4885         /* Enable semaphores on SNB when IO remapping is off */
4886         if (IS_GEN6(dev_priv) && intel_vtd_active())
4887                 return false;
4888
4889         return true;
4890 }
4891
4892 int i915_gem_init(struct drm_i915_private *dev_priv)
4893 {
4894         int ret;
4895
4896         mutex_lock(&dev_priv->drm.struct_mutex);
4897
4898         dev_priv->mm.unordered_timeline = dma_fence_context_alloc(1);
4899
4900         if (!i915.enable_execlists) {
4901                 dev_priv->gt.resume = intel_legacy_submission_resume;
4902                 dev_priv->gt.cleanup_engine = intel_engine_cleanup;
4903         } else {
4904                 dev_priv->gt.resume = intel_lr_context_resume;
4905                 dev_priv->gt.cleanup_engine = intel_logical_ring_cleanup;
4906         }
4907
4908         /* This is just a security blanket to placate dragons.
4909          * On some systems, we very sporadically observe that the first TLBs
4910          * used by the CS may be stale, despite us poking the TLB reset. If
4911          * we hold the forcewake during initialisation these problems
4912          * just magically go away.
4913          */
4914         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
4915
4916         ret = i915_gem_init_userptr(dev_priv);
4917         if (ret)
4918                 goto out_unlock;
4919
4920         ret = i915_gem_init_ggtt(dev_priv);
4921         if (ret)
4922                 goto out_unlock;
4923
4924         ret = i915_gem_contexts_init(dev_priv);
4925         if (ret)
4926                 goto out_unlock;
4927
4928         ret = intel_engines_init(dev_priv);
4929         if (ret)
4930                 goto out_unlock;
4931
4932         ret = i915_gem_init_hw(dev_priv);
4933         if (ret == -EIO) {
4934                 /* Allow engine initialisation to fail by marking the GPU as
4935                  * wedged. But we only want to do this where the GPU is angry,
4936                  * for all other failure, such as an allocation failure, bail.
4937                  */
4938                 DRM_ERROR("Failed to initialize GPU, declaring it wedged\n");
4939                 i915_gem_set_wedged(dev_priv);
4940                 ret = 0;
4941         }
4942
4943 out_unlock:
4944         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
4945         mutex_unlock(&dev_priv->drm.struct_mutex);
4946
4947         return ret;
4948 }
4949
4950 void i915_gem_init_mmio(struct drm_i915_private *i915)
4951 {
4952         i915_gem_sanitize(i915);
4953 }
4954
4955 void
4956 i915_gem_cleanup_engines(struct drm_i915_private *dev_priv)
4957 {
4958         struct intel_engine_cs *engine;
4959         enum intel_engine_id id;
4960
4961         for_each_engine(engine, dev_priv, id)
4962                 dev_priv->gt.cleanup_engine(engine);
4963 }
4964
4965 void
4966 i915_gem_load_init_fences(struct drm_i915_private *dev_priv)
4967 {
4968         int i;
4969
4970         if (INTEL_INFO(dev_priv)->gen >= 7 && !IS_VALLEYVIEW(dev_priv) &&
4971             !IS_CHERRYVIEW(dev_priv))
4972                 dev_priv->num_fence_regs = 32;
4973         else if (INTEL_INFO(dev_priv)->gen >= 4 ||
4974                  IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
4975                  IS_G33(dev_priv) || IS_PINEVIEW(dev_priv))
4976                 dev_priv->num_fence_regs = 16;
4977         else
4978                 dev_priv->num_fence_regs = 8;
4979
4980         if (intel_vgpu_active(dev_priv))
4981                 dev_priv->num_fence_regs =
4982                                 I915_READ(vgtif_reg(avail_rs.fence_num));
4983
4984         /* Initialize fence registers to zero */
4985         for (i = 0; i < dev_priv->num_fence_regs; i++) {
4986                 struct drm_i915_fence_reg *fence = &dev_priv->fence_regs[i];
4987
4988                 fence->i915 = dev_priv;
4989                 fence->id = i;
4990                 list_add_tail(&fence->link, &dev_priv->mm.fence_list);
4991         }
4992         i915_gem_restore_fences(dev_priv);
4993
4994         i915_gem_detect_bit_6_swizzle(dev_priv);
4995 }
4996
4997 int
4998 i915_gem_load_init(struct drm_i915_private *dev_priv)
4999 {
5000         int err = -ENOMEM;
5001
5002         dev_priv->objects = KMEM_CACHE(drm_i915_gem_object, SLAB_HWCACHE_ALIGN);
5003         if (!dev_priv->objects)
5004                 goto err_out;
5005
5006         dev_priv->vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
5007         if (!dev_priv->vmas)
5008                 goto err_objects;
5009
5010         dev_priv->luts = KMEM_CACHE(i915_lut_handle, 0);
5011         if (!dev_priv->luts)
5012                 goto err_vmas;
5013
5014         dev_priv->requests = KMEM_CACHE(drm_i915_gem_request,
5015                                         SLAB_HWCACHE_ALIGN |
5016                                         SLAB_RECLAIM_ACCOUNT |
5017                                         SLAB_TYPESAFE_BY_RCU);
5018         if (!dev_priv->requests)
5019                 goto err_luts;
5020
5021         dev_priv->dependencies = KMEM_CACHE(i915_dependency,
5022                                             SLAB_HWCACHE_ALIGN |
5023                                             SLAB_RECLAIM_ACCOUNT);
5024         if (!dev_priv->dependencies)
5025                 goto err_requests;
5026
5027         dev_priv->priorities = KMEM_CACHE(i915_priolist, SLAB_HWCACHE_ALIGN);
5028         if (!dev_priv->priorities)
5029                 goto err_dependencies;
5030
5031         mutex_lock(&dev_priv->drm.struct_mutex);
5032         INIT_LIST_HEAD(&dev_priv->gt.timelines);
5033         err = i915_gem_timeline_init__global(dev_priv);
5034         mutex_unlock(&dev_priv->drm.struct_mutex);
5035         if (err)
5036                 goto err_priorities;
5037
5038         INIT_WORK(&dev_priv->mm.free_work, __i915_gem_free_work);
5039         init_llist_head(&dev_priv->mm.free_list);
5040         INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
5041         INIT_LIST_HEAD(&dev_priv->mm.bound_list);
5042         INIT_LIST_HEAD(&dev_priv->mm.fence_list);
5043         INIT_LIST_HEAD(&dev_priv->mm.userfault_list);
5044         INIT_DELAYED_WORK(&dev_priv->gt.retire_work,
5045                           i915_gem_retire_work_handler);
5046         INIT_DELAYED_WORK(&dev_priv->gt.idle_work,
5047                           i915_gem_idle_work_handler);
5048         init_waitqueue_head(&dev_priv->gpu_error.wait_queue);
5049         init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
5050
5051         atomic_set(&dev_priv->mm.bsd_engine_dispatch_index, 0);
5052
5053         spin_lock_init(&dev_priv->fb_tracking.lock);
5054
5055         mutex_init(&dev_priv->tlb_invalidate_lock);
5056
5057         return 0;
5058
5059 err_priorities:
5060         kmem_cache_destroy(dev_priv->priorities);
5061 err_dependencies:
5062         kmem_cache_destroy(dev_priv->dependencies);
5063 err_requests:
5064         kmem_cache_destroy(dev_priv->requests);
5065 err_luts:
5066         kmem_cache_destroy(dev_priv->luts);
5067 err_vmas:
5068         kmem_cache_destroy(dev_priv->vmas);
5069 err_objects:
5070         kmem_cache_destroy(dev_priv->objects);
5071 err_out:
5072         return err;
5073 }
5074
5075 void i915_gem_load_cleanup(struct drm_i915_private *dev_priv)
5076 {
5077         i915_gem_drain_freed_objects(dev_priv);
5078         WARN_ON(!llist_empty(&dev_priv->mm.free_list));
5079         WARN_ON(dev_priv->mm.object_count);
5080
5081         mutex_lock(&dev_priv->drm.struct_mutex);
5082         i915_gem_timeline_fini(&dev_priv->gt.global_timeline);
5083         WARN_ON(!list_empty(&dev_priv->gt.timelines));
5084         mutex_unlock(&dev_priv->drm.struct_mutex);
5085
5086         kmem_cache_destroy(dev_priv->priorities);
5087         kmem_cache_destroy(dev_priv->dependencies);
5088         kmem_cache_destroy(dev_priv->requests);
5089         kmem_cache_destroy(dev_priv->luts);
5090         kmem_cache_destroy(dev_priv->vmas);
5091         kmem_cache_destroy(dev_priv->objects);
5092
5093         /* And ensure that our DESTROY_BY_RCU slabs are truly destroyed */
5094         rcu_barrier();
5095 }
5096
5097 int i915_gem_freeze(struct drm_i915_private *dev_priv)
5098 {
5099         /* Discard all purgeable objects, let userspace recover those as
5100          * required after resuming.
5101          */
5102         i915_gem_shrink_all(dev_priv);
5103
5104         return 0;
5105 }
5106
5107 int i915_gem_freeze_late(struct drm_i915_private *dev_priv)
5108 {
5109         struct drm_i915_gem_object *obj;
5110         struct list_head *phases[] = {
5111                 &dev_priv->mm.unbound_list,
5112                 &dev_priv->mm.bound_list,
5113                 NULL
5114         }, **p;
5115
5116         /* Called just before we write the hibernation image.
5117          *
5118          * We need to update the domain tracking to reflect that the CPU
5119          * will be accessing all the pages to create and restore from the
5120          * hibernation, and so upon restoration those pages will be in the
5121          * CPU domain.
5122          *
5123          * To make sure the hibernation image contains the latest state,
5124          * we update that state just before writing out the image.
5125          *
5126          * To try and reduce the hibernation image, we manually shrink
5127          * the objects as well, see i915_gem_freeze()
5128          */
5129
5130         i915_gem_shrink(dev_priv, -1UL, NULL, I915_SHRINK_UNBOUND);
5131         i915_gem_drain_freed_objects(dev_priv);
5132
5133         mutex_lock(&dev_priv->drm.struct_mutex);
5134         for (p = phases; *p; p++) {
5135                 list_for_each_entry(obj, *p, global_link)
5136                         __start_cpu_write(obj);
5137         }
5138         mutex_unlock(&dev_priv->drm.struct_mutex);
5139
5140         return 0;
5141 }
5142
5143 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
5144 {
5145         struct drm_i915_file_private *file_priv = file->driver_priv;
5146         struct drm_i915_gem_request *request;
5147
5148         /* Clean up our request list when the client is going away, so that
5149          * later retire_requests won't dereference our soon-to-be-gone
5150          * file_priv.
5151          */
5152         spin_lock(&file_priv->mm.lock);
5153         list_for_each_entry(request, &file_priv->mm.request_list, client_link)
5154                 request->file_priv = NULL;
5155         spin_unlock(&file_priv->mm.lock);
5156 }
5157
5158 int i915_gem_open(struct drm_i915_private *i915, struct drm_file *file)
5159 {
5160         struct drm_i915_file_private *file_priv;
5161         int ret;
5162
5163         DRM_DEBUG("\n");
5164
5165         file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
5166         if (!file_priv)
5167                 return -ENOMEM;
5168
5169         file->driver_priv = file_priv;
5170         file_priv->dev_priv = i915;
5171         file_priv->file = file;
5172
5173         spin_lock_init(&file_priv->mm.lock);
5174         INIT_LIST_HEAD(&file_priv->mm.request_list);
5175
5176         file_priv->bsd_engine = -1;
5177
5178         ret = i915_gem_context_open(i915, file);
5179         if (ret)
5180                 kfree(file_priv);
5181
5182         return ret;
5183 }
5184
5185 /**
5186  * i915_gem_track_fb - update frontbuffer tracking
5187  * @old: current GEM buffer for the frontbuffer slots
5188  * @new: new GEM buffer for the frontbuffer slots
5189  * @frontbuffer_bits: bitmask of frontbuffer slots
5190  *
5191  * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
5192  * from @old and setting them in @new. Both @old and @new can be NULL.
5193  */
5194 void i915_gem_track_fb(struct drm_i915_gem_object *old,
5195                        struct drm_i915_gem_object *new,
5196                        unsigned frontbuffer_bits)
5197 {
5198         /* Control of individual bits within the mask are guarded by
5199          * the owning plane->mutex, i.e. we can never see concurrent
5200          * manipulation of individual bits. But since the bitfield as a whole
5201          * is updated using RMW, we need to use atomics in order to update
5202          * the bits.
5203          */
5204         BUILD_BUG_ON(INTEL_FRONTBUFFER_BITS_PER_PIPE * I915_MAX_PIPES >
5205                      sizeof(atomic_t) * BITS_PER_BYTE);
5206
5207         if (old) {
5208                 WARN_ON(!(atomic_read(&old->frontbuffer_bits) & frontbuffer_bits));
5209                 atomic_andnot(frontbuffer_bits, &old->frontbuffer_bits);
5210         }
5211
5212         if (new) {
5213                 WARN_ON(atomic_read(&new->frontbuffer_bits) & frontbuffer_bits);
5214                 atomic_or(frontbuffer_bits, &new->frontbuffer_bits);
5215         }
5216 }
5217
5218 /* Allocate a new GEM object and fill it with the supplied data */
5219 struct drm_i915_gem_object *
5220 i915_gem_object_create_from_data(struct drm_i915_private *dev_priv,
5221                                  const void *data, size_t size)
5222 {
5223         struct drm_i915_gem_object *obj;
5224         struct file *file;
5225         size_t offset;
5226         int err;
5227
5228         obj = i915_gem_object_create(dev_priv, round_up(size, PAGE_SIZE));
5229         if (IS_ERR(obj))
5230                 return obj;
5231
5232         GEM_BUG_ON(obj->base.write_domain != I915_GEM_DOMAIN_CPU);
5233
5234         file = obj->base.filp;
5235         offset = 0;
5236         do {
5237                 unsigned int len = min_t(typeof(size), size, PAGE_SIZE);
5238                 struct page *page;
5239                 void *pgdata, *vaddr;
5240
5241                 err = pagecache_write_begin(file, file->f_mapping,
5242                                             offset, len, 0,
5243                                             &page, &pgdata);
5244                 if (err < 0)
5245                         goto fail;
5246
5247                 vaddr = kmap(page);
5248                 memcpy(vaddr, data, len);
5249                 kunmap(page);
5250
5251                 err = pagecache_write_end(file, file->f_mapping,
5252                                           offset, len, len,
5253                                           page, pgdata);
5254                 if (err < 0)
5255                         goto fail;
5256
5257                 size -= len;
5258                 data += len;
5259                 offset += len;
5260         } while (size);
5261
5262         return obj;
5263
5264 fail:
5265         i915_gem_object_put(obj);
5266         return ERR_PTR(err);
5267 }
5268
5269 struct scatterlist *
5270 i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
5271                        unsigned int n,
5272                        unsigned int *offset)
5273 {
5274         struct i915_gem_object_page_iter *iter = &obj->mm.get_page;
5275         struct scatterlist *sg;
5276         unsigned int idx, count;
5277
5278         might_sleep();
5279         GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
5280         GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
5281
5282         /* As we iterate forward through the sg, we record each entry in a
5283          * radixtree for quick repeated (backwards) lookups. If we have seen
5284          * this index previously, we will have an entry for it.
5285          *
5286          * Initial lookup is O(N), but this is amortized to O(1) for
5287          * sequential page access (where each new request is consecutive
5288          * to the previous one). Repeated lookups are O(lg(obj->base.size)),
5289          * i.e. O(1) with a large constant!
5290          */
5291         if (n < READ_ONCE(iter->sg_idx))
5292                 goto lookup;
5293
5294         mutex_lock(&iter->lock);
5295
5296         /* We prefer to reuse the last sg so that repeated lookup of this
5297          * (or the subsequent) sg are fast - comparing against the last
5298          * sg is faster than going through the radixtree.
5299          */
5300
5301         sg = iter->sg_pos;
5302         idx = iter->sg_idx;
5303         count = __sg_page_count(sg);
5304
5305         while (idx + count <= n) {
5306                 unsigned long exception, i;
5307                 int ret;
5308
5309                 /* If we cannot allocate and insert this entry, or the
5310                  * individual pages from this range, cancel updating the
5311                  * sg_idx so that on this lookup we are forced to linearly
5312                  * scan onwards, but on future lookups we will try the
5313                  * insertion again (in which case we need to be careful of
5314                  * the error return reporting that we have already inserted
5315                  * this index).
5316                  */
5317                 ret = radix_tree_insert(&iter->radix, idx, sg);
5318                 if (ret && ret != -EEXIST)
5319                         goto scan;
5320
5321                 exception =
5322                         RADIX_TREE_EXCEPTIONAL_ENTRY |
5323                         idx << RADIX_TREE_EXCEPTIONAL_SHIFT;
5324                 for (i = 1; i < count; i++) {
5325                         ret = radix_tree_insert(&iter->radix, idx + i,
5326                                                 (void *)exception);
5327                         if (ret && ret != -EEXIST)
5328                                 goto scan;
5329                 }
5330
5331                 idx += count;
5332                 sg = ____sg_next(sg);
5333                 count = __sg_page_count(sg);
5334         }
5335
5336 scan:
5337         iter->sg_pos = sg;
5338         iter->sg_idx = idx;
5339
5340         mutex_unlock(&iter->lock);
5341
5342         if (unlikely(n < idx)) /* insertion completed by another thread */
5343                 goto lookup;
5344
5345         /* In case we failed to insert the entry into the radixtree, we need
5346          * to look beyond the current sg.
5347          */
5348         while (idx + count <= n) {
5349                 idx += count;
5350                 sg = ____sg_next(sg);
5351                 count = __sg_page_count(sg);
5352         }
5353
5354         *offset = n - idx;
5355         return sg;
5356
5357 lookup:
5358         rcu_read_lock();
5359
5360         sg = radix_tree_lookup(&iter->radix, n);
5361         GEM_BUG_ON(!sg);
5362
5363         /* If this index is in the middle of multi-page sg entry,
5364          * the radixtree will contain an exceptional entry that points
5365          * to the start of that range. We will return the pointer to
5366          * the base page and the offset of this page within the
5367          * sg entry's range.
5368          */
5369         *offset = 0;
5370         if (unlikely(radix_tree_exception(sg))) {
5371                 unsigned long base =
5372                         (unsigned long)sg >> RADIX_TREE_EXCEPTIONAL_SHIFT;
5373
5374                 sg = radix_tree_lookup(&iter->radix, base);
5375                 GEM_BUG_ON(!sg);
5376
5377                 *offset = n - base;
5378         }
5379
5380         rcu_read_unlock();
5381
5382         return sg;
5383 }
5384
5385 struct page *
5386 i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
5387 {
5388         struct scatterlist *sg;
5389         unsigned int offset;
5390
5391         GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
5392
5393         sg = i915_gem_object_get_sg(obj, n, &offset);
5394         return nth_page(sg_page(sg), offset);
5395 }
5396
5397 /* Like i915_gem_object_get_page(), but mark the returned page dirty */
5398 struct page *
5399 i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
5400                                unsigned int n)
5401 {
5402         struct page *page;
5403
5404         page = i915_gem_object_get_page(obj, n);
5405         if (!obj->mm.dirty)
5406                 set_page_dirty(page);
5407
5408         return page;
5409 }
5410
5411 dma_addr_t
5412 i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
5413                                 unsigned long n)
5414 {
5415         struct scatterlist *sg;
5416         unsigned int offset;
5417
5418         sg = i915_gem_object_get_sg(obj, n, &offset);
5419         return sg_dma_address(sg) + (offset << PAGE_SHIFT);
5420 }
5421
5422 int i915_gem_object_attach_phys(struct drm_i915_gem_object *obj, int align)
5423 {
5424         struct sg_table *pages;
5425         int err;
5426
5427         if (align > obj->base.size)
5428                 return -EINVAL;
5429
5430         if (obj->ops == &i915_gem_phys_ops)
5431                 return 0;
5432
5433         if (obj->ops != &i915_gem_object_ops)
5434                 return -EINVAL;
5435
5436         err = i915_gem_object_unbind(obj);
5437         if (err)
5438                 return err;
5439
5440         mutex_lock(&obj->mm.lock);
5441
5442         if (obj->mm.madv != I915_MADV_WILLNEED) {
5443                 err = -EFAULT;
5444                 goto err_unlock;
5445         }
5446
5447         if (obj->mm.quirked) {
5448                 err = -EFAULT;
5449                 goto err_unlock;
5450         }
5451
5452         if (obj->mm.mapping) {
5453                 err = -EBUSY;
5454                 goto err_unlock;
5455         }
5456
5457         pages = obj->mm.pages;
5458         obj->ops = &i915_gem_phys_ops;
5459
5460         err = ____i915_gem_object_get_pages(obj);
5461         if (err)
5462                 goto err_xfer;
5463
5464         /* Perma-pin (until release) the physical set of pages */
5465         __i915_gem_object_pin_pages(obj);
5466
5467         if (!IS_ERR_OR_NULL(pages))
5468                 i915_gem_object_ops.put_pages(obj, pages);
5469         mutex_unlock(&obj->mm.lock);
5470         return 0;
5471
5472 err_xfer:
5473         obj->ops = &i915_gem_object_ops;
5474         obj->mm.pages = pages;
5475 err_unlock:
5476         mutex_unlock(&obj->mm.lock);
5477         return err;
5478 }
5479
5480 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
5481 #include "selftests/scatterlist.c"
5482 #include "selftests/mock_gem_device.c"
5483 #include "selftests/huge_gem_object.c"
5484 #include "selftests/i915_gem_object.c"
5485 #include "selftests/i915_gem_coherency.c"
5486 #endif