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