Merge tag 'hwlock-v5.20' of git://git.kernel.org/pub/scm/linux/kernel/git/remoteproc...
[platform/kernel/linux-starfive.git] / drivers / gpu / drm / i915 / i915_vma.c
1 /*
2  * Copyright © 2016 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  */
24
25 #include <linux/sched/mm.h>
26 #include <linux/dma-fence-array.h>
27 #include <drm/drm_gem.h>
28
29 #include "display/intel_frontbuffer.h"
30 #include "gem/i915_gem_lmem.h"
31 #include "gem/i915_gem_tiling.h"
32 #include "gt/intel_engine.h"
33 #include "gt/intel_engine_heartbeat.h"
34 #include "gt/intel_gt.h"
35 #include "gt/intel_gt_requests.h"
36
37 #include "i915_drv.h"
38 #include "i915_gem_evict.h"
39 #include "i915_sw_fence_work.h"
40 #include "i915_trace.h"
41 #include "i915_vma.h"
42 #include "i915_vma_resource.h"
43
44 static inline void assert_vma_held_evict(const struct i915_vma *vma)
45 {
46         /*
47          * We may be forced to unbind when the vm is dead, to clean it up.
48          * This is the only exception to the requirement of the object lock
49          * being held.
50          */
51         if (kref_read(&vma->vm->ref))
52                 assert_object_held_shared(vma->obj);
53 }
54
55 static struct kmem_cache *slab_vmas;
56
57 static struct i915_vma *i915_vma_alloc(void)
58 {
59         return kmem_cache_zalloc(slab_vmas, GFP_KERNEL);
60 }
61
62 static void i915_vma_free(struct i915_vma *vma)
63 {
64         return kmem_cache_free(slab_vmas, vma);
65 }
66
67 #if IS_ENABLED(CONFIG_DRM_I915_ERRLOG_GEM) && IS_ENABLED(CONFIG_DRM_DEBUG_MM)
68
69 #include <linux/stackdepot.h>
70
71 static void vma_print_allocator(struct i915_vma *vma, const char *reason)
72 {
73         char buf[512];
74
75         if (!vma->node.stack) {
76                 DRM_DEBUG_DRIVER("vma.node [%08llx + %08llx] %s: unknown owner\n",
77                                  vma->node.start, vma->node.size, reason);
78                 return;
79         }
80
81         stack_depot_snprint(vma->node.stack, buf, sizeof(buf), 0);
82         DRM_DEBUG_DRIVER("vma.node [%08llx + %08llx] %s: inserted at %s\n",
83                          vma->node.start, vma->node.size, reason, buf);
84 }
85
86 #else
87
88 static void vma_print_allocator(struct i915_vma *vma, const char *reason)
89 {
90 }
91
92 #endif
93
94 static inline struct i915_vma *active_to_vma(struct i915_active *ref)
95 {
96         return container_of(ref, typeof(struct i915_vma), active);
97 }
98
99 static int __i915_vma_active(struct i915_active *ref)
100 {
101         return i915_vma_tryget(active_to_vma(ref)) ? 0 : -ENOENT;
102 }
103
104 static void __i915_vma_retire(struct i915_active *ref)
105 {
106         i915_vma_put(active_to_vma(ref));
107 }
108
109 static struct i915_vma *
110 vma_create(struct drm_i915_gem_object *obj,
111            struct i915_address_space *vm,
112            const struct i915_ggtt_view *view)
113 {
114         struct i915_vma *pos = ERR_PTR(-E2BIG);
115         struct i915_vma *vma;
116         struct rb_node *rb, **p;
117         int err;
118
119         /* The aliasing_ppgtt should never be used directly! */
120         GEM_BUG_ON(vm == &vm->gt->ggtt->alias->vm);
121
122         vma = i915_vma_alloc();
123         if (vma == NULL)
124                 return ERR_PTR(-ENOMEM);
125
126         vma->ops = &vm->vma_ops;
127         vma->obj = obj;
128         vma->size = obj->base.size;
129         vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
130
131         i915_active_init(&vma->active, __i915_vma_active, __i915_vma_retire, 0);
132
133         /* Declare ourselves safe for use inside shrinkers */
134         if (IS_ENABLED(CONFIG_LOCKDEP)) {
135                 fs_reclaim_acquire(GFP_KERNEL);
136                 might_lock(&vma->active.mutex);
137                 fs_reclaim_release(GFP_KERNEL);
138         }
139
140         INIT_LIST_HEAD(&vma->closed_link);
141         INIT_LIST_HEAD(&vma->obj_link);
142         RB_CLEAR_NODE(&vma->obj_node);
143
144         if (view && view->type != I915_GGTT_VIEW_NORMAL) {
145                 vma->ggtt_view = *view;
146                 if (view->type == I915_GGTT_VIEW_PARTIAL) {
147                         GEM_BUG_ON(range_overflows_t(u64,
148                                                      view->partial.offset,
149                                                      view->partial.size,
150                                                      obj->base.size >> PAGE_SHIFT));
151                         vma->size = view->partial.size;
152                         vma->size <<= PAGE_SHIFT;
153                         GEM_BUG_ON(vma->size > obj->base.size);
154                 } else if (view->type == I915_GGTT_VIEW_ROTATED) {
155                         vma->size = intel_rotation_info_size(&view->rotated);
156                         vma->size <<= PAGE_SHIFT;
157                 } else if (view->type == I915_GGTT_VIEW_REMAPPED) {
158                         vma->size = intel_remapped_info_size(&view->remapped);
159                         vma->size <<= PAGE_SHIFT;
160                 }
161         }
162
163         if (unlikely(vma->size > vm->total))
164                 goto err_vma;
165
166         GEM_BUG_ON(!IS_ALIGNED(vma->size, I915_GTT_PAGE_SIZE));
167
168         err = mutex_lock_interruptible(&vm->mutex);
169         if (err) {
170                 pos = ERR_PTR(err);
171                 goto err_vma;
172         }
173
174         vma->vm = vm;
175         list_add_tail(&vma->vm_link, &vm->unbound_list);
176
177         spin_lock(&obj->vma.lock);
178         if (i915_is_ggtt(vm)) {
179                 if (unlikely(overflows_type(vma->size, u32)))
180                         goto err_unlock;
181
182                 vma->fence_size = i915_gem_fence_size(vm->i915, vma->size,
183                                                       i915_gem_object_get_tiling(obj),
184                                                       i915_gem_object_get_stride(obj));
185                 if (unlikely(vma->fence_size < vma->size || /* overflow */
186                              vma->fence_size > vm->total))
187                         goto err_unlock;
188
189                 GEM_BUG_ON(!IS_ALIGNED(vma->fence_size, I915_GTT_MIN_ALIGNMENT));
190
191                 vma->fence_alignment = i915_gem_fence_alignment(vm->i915, vma->size,
192                                                                 i915_gem_object_get_tiling(obj),
193                                                                 i915_gem_object_get_stride(obj));
194                 GEM_BUG_ON(!is_power_of_2(vma->fence_alignment));
195
196                 __set_bit(I915_VMA_GGTT_BIT, __i915_vma_flags(vma));
197         }
198
199         rb = NULL;
200         p = &obj->vma.tree.rb_node;
201         while (*p) {
202                 long cmp;
203
204                 rb = *p;
205                 pos = rb_entry(rb, struct i915_vma, obj_node);
206
207                 /*
208                  * If the view already exists in the tree, another thread
209                  * already created a matching vma, so return the older instance
210                  * and dispose of ours.
211                  */
212                 cmp = i915_vma_compare(pos, vm, view);
213                 if (cmp < 0)
214                         p = &rb->rb_right;
215                 else if (cmp > 0)
216                         p = &rb->rb_left;
217                 else
218                         goto err_unlock;
219         }
220         rb_link_node(&vma->obj_node, rb, p);
221         rb_insert_color(&vma->obj_node, &obj->vma.tree);
222
223         if (i915_vma_is_ggtt(vma))
224                 /*
225                  * We put the GGTT vma at the start of the vma-list, followed
226                  * by the ppGGTT vma. This allows us to break early when
227                  * iterating over only the GGTT vma for an object, see
228                  * for_each_ggtt_vma()
229                  */
230                 list_add(&vma->obj_link, &obj->vma.list);
231         else
232                 list_add_tail(&vma->obj_link, &obj->vma.list);
233
234         spin_unlock(&obj->vma.lock);
235         mutex_unlock(&vm->mutex);
236
237         return vma;
238
239 err_unlock:
240         spin_unlock(&obj->vma.lock);
241         list_del_init(&vma->vm_link);
242         mutex_unlock(&vm->mutex);
243 err_vma:
244         i915_vma_free(vma);
245         return pos;
246 }
247
248 static struct i915_vma *
249 i915_vma_lookup(struct drm_i915_gem_object *obj,
250            struct i915_address_space *vm,
251            const struct i915_ggtt_view *view)
252 {
253         struct rb_node *rb;
254
255         rb = obj->vma.tree.rb_node;
256         while (rb) {
257                 struct i915_vma *vma = rb_entry(rb, struct i915_vma, obj_node);
258                 long cmp;
259
260                 cmp = i915_vma_compare(vma, vm, view);
261                 if (cmp == 0)
262                         return vma;
263
264                 if (cmp < 0)
265                         rb = rb->rb_right;
266                 else
267                         rb = rb->rb_left;
268         }
269
270         return NULL;
271 }
272
273 /**
274  * i915_vma_instance - return the singleton instance of the VMA
275  * @obj: parent &struct drm_i915_gem_object to be mapped
276  * @vm: address space in which the mapping is located
277  * @view: additional mapping requirements
278  *
279  * i915_vma_instance() looks up an existing VMA of the @obj in the @vm with
280  * the same @view characteristics. If a match is not found, one is created.
281  * Once created, the VMA is kept until either the object is freed, or the
282  * address space is closed.
283  *
284  * Returns the vma, or an error pointer.
285  */
286 struct i915_vma *
287 i915_vma_instance(struct drm_i915_gem_object *obj,
288                   struct i915_address_space *vm,
289                   const struct i915_ggtt_view *view)
290 {
291         struct i915_vma *vma;
292
293         GEM_BUG_ON(view && !i915_is_ggtt_or_dpt(vm));
294         GEM_BUG_ON(!kref_read(&vm->ref));
295
296         spin_lock(&obj->vma.lock);
297         vma = i915_vma_lookup(obj, vm, view);
298         spin_unlock(&obj->vma.lock);
299
300         /* vma_create() will resolve the race if another creates the vma */
301         if (unlikely(!vma))
302                 vma = vma_create(obj, vm, view);
303
304         GEM_BUG_ON(!IS_ERR(vma) && i915_vma_compare(vma, vm, view));
305         return vma;
306 }
307
308 struct i915_vma_work {
309         struct dma_fence_work base;
310         struct i915_address_space *vm;
311         struct i915_vm_pt_stash stash;
312         struct i915_vma_resource *vma_res;
313         struct drm_i915_gem_object *obj;
314         struct i915_sw_dma_fence_cb cb;
315         enum i915_cache_level cache_level;
316         unsigned int flags;
317 };
318
319 static void __vma_bind(struct dma_fence_work *work)
320 {
321         struct i915_vma_work *vw = container_of(work, typeof(*vw), base);
322         struct i915_vma_resource *vma_res = vw->vma_res;
323
324         /*
325          * We are about the bind the object, which must mean we have already
326          * signaled the work to potentially clear/move the pages underneath. If
327          * something went wrong at that stage then the object should have
328          * unknown_state set, in which case we need to skip the bind.
329          */
330         if (i915_gem_object_has_unknown_state(vw->obj))
331                 return;
332
333         vma_res->ops->bind_vma(vma_res->vm, &vw->stash,
334                                vma_res, vw->cache_level, vw->flags);
335 }
336
337 static void __vma_release(struct dma_fence_work *work)
338 {
339         struct i915_vma_work *vw = container_of(work, typeof(*vw), base);
340
341         if (vw->obj)
342                 i915_gem_object_put(vw->obj);
343
344         i915_vm_free_pt_stash(vw->vm, &vw->stash);
345         if (vw->vma_res)
346                 i915_vma_resource_put(vw->vma_res);
347 }
348
349 static const struct dma_fence_work_ops bind_ops = {
350         .name = "bind",
351         .work = __vma_bind,
352         .release = __vma_release,
353 };
354
355 struct i915_vma_work *i915_vma_work(void)
356 {
357         struct i915_vma_work *vw;
358
359         vw = kzalloc(sizeof(*vw), GFP_KERNEL);
360         if (!vw)
361                 return NULL;
362
363         dma_fence_work_init(&vw->base, &bind_ops);
364         vw->base.dma.error = -EAGAIN; /* disable the worker by default */
365
366         return vw;
367 }
368
369 int i915_vma_wait_for_bind(struct i915_vma *vma)
370 {
371         int err = 0;
372
373         if (rcu_access_pointer(vma->active.excl.fence)) {
374                 struct dma_fence *fence;
375
376                 rcu_read_lock();
377                 fence = dma_fence_get_rcu_safe(&vma->active.excl.fence);
378                 rcu_read_unlock();
379                 if (fence) {
380                         err = dma_fence_wait(fence, true);
381                         dma_fence_put(fence);
382                 }
383         }
384
385         return err;
386 }
387
388 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)
389 static int i915_vma_verify_bind_complete(struct i915_vma *vma)
390 {
391         struct dma_fence *fence = i915_active_fence_get(&vma->active.excl);
392         int err;
393
394         if (!fence)
395                 return 0;
396
397         if (dma_fence_is_signaled(fence))
398                 err = fence->error;
399         else
400                 err = -EBUSY;
401
402         dma_fence_put(fence);
403
404         return err;
405 }
406 #else
407 #define i915_vma_verify_bind_complete(_vma) 0
408 #endif
409
410 I915_SELFTEST_EXPORT void
411 i915_vma_resource_init_from_vma(struct i915_vma_resource *vma_res,
412                                 struct i915_vma *vma)
413 {
414         struct drm_i915_gem_object *obj = vma->obj;
415
416         i915_vma_resource_init(vma_res, vma->vm, vma->pages, &vma->page_sizes,
417                                obj->mm.rsgt, i915_gem_object_is_readonly(obj),
418                                i915_gem_object_is_lmem(obj), obj->mm.region,
419                                vma->ops, vma->private, vma->node.start,
420                                vma->node.size, vma->size);
421 }
422
423 /**
424  * i915_vma_bind - Sets up PTEs for an VMA in it's corresponding address space.
425  * @vma: VMA to map
426  * @cache_level: mapping cache level
427  * @flags: flags like global or local mapping
428  * @work: preallocated worker for allocating and binding the PTE
429  * @vma_res: pointer to a preallocated vma resource. The resource is either
430  * consumed or freed.
431  *
432  * DMA addresses are taken from the scatter-gather table of this object (or of
433  * this VMA in case of non-default GGTT views) and PTE entries set up.
434  * Note that DMA addresses are also the only part of the SG table we care about.
435  */
436 int i915_vma_bind(struct i915_vma *vma,
437                   enum i915_cache_level cache_level,
438                   u32 flags,
439                   struct i915_vma_work *work,
440                   struct i915_vma_resource *vma_res)
441 {
442         u32 bind_flags;
443         u32 vma_flags;
444         int ret;
445
446         lockdep_assert_held(&vma->vm->mutex);
447         GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
448         GEM_BUG_ON(vma->size > vma->node.size);
449
450         if (GEM_DEBUG_WARN_ON(range_overflows(vma->node.start,
451                                               vma->node.size,
452                                               vma->vm->total))) {
453                 i915_vma_resource_free(vma_res);
454                 return -ENODEV;
455         }
456
457         if (GEM_DEBUG_WARN_ON(!flags)) {
458                 i915_vma_resource_free(vma_res);
459                 return -EINVAL;
460         }
461
462         bind_flags = flags;
463         bind_flags &= I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND;
464
465         vma_flags = atomic_read(&vma->flags);
466         vma_flags &= I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND;
467
468         bind_flags &= ~vma_flags;
469         if (bind_flags == 0) {
470                 i915_vma_resource_free(vma_res);
471                 return 0;
472         }
473
474         GEM_BUG_ON(!atomic_read(&vma->pages_count));
475
476         /* Wait for or await async unbinds touching our range */
477         if (work && bind_flags & vma->vm->bind_async_flags)
478                 ret = i915_vma_resource_bind_dep_await(vma->vm,
479                                                        &work->base.chain,
480                                                        vma->node.start,
481                                                        vma->node.size,
482                                                        true,
483                                                        GFP_NOWAIT |
484                                                        __GFP_RETRY_MAYFAIL |
485                                                        __GFP_NOWARN);
486         else
487                 ret = i915_vma_resource_bind_dep_sync(vma->vm, vma->node.start,
488                                                       vma->node.size, true);
489         if (ret) {
490                 i915_vma_resource_free(vma_res);
491                 return ret;
492         }
493
494         if (vma->resource || !vma_res) {
495                 /* Rebinding with an additional I915_VMA_*_BIND */
496                 GEM_WARN_ON(!vma_flags);
497                 i915_vma_resource_free(vma_res);
498         } else {
499                 i915_vma_resource_init_from_vma(vma_res, vma);
500                 vma->resource = vma_res;
501         }
502         trace_i915_vma_bind(vma, bind_flags);
503         if (work && bind_flags & vma->vm->bind_async_flags) {
504                 struct dma_fence *prev;
505
506                 work->vma_res = i915_vma_resource_get(vma->resource);
507                 work->cache_level = cache_level;
508                 work->flags = bind_flags;
509
510                 /*
511                  * Note we only want to chain up to the migration fence on
512                  * the pages (not the object itself). As we don't track that,
513                  * yet, we have to use the exclusive fence instead.
514                  *
515                  * Also note that we do not want to track the async vma as
516                  * part of the obj->resv->excl_fence as it only affects
517                  * execution and not content or object's backing store lifetime.
518                  */
519                 prev = i915_active_set_exclusive(&vma->active, &work->base.dma);
520                 if (prev) {
521                         __i915_sw_fence_await_dma_fence(&work->base.chain,
522                                                         prev,
523                                                         &work->cb);
524                         dma_fence_put(prev);
525                 }
526
527                 work->base.dma.error = 0; /* enable the queue_work() */
528                 work->obj = i915_gem_object_get(vma->obj);
529         } else {
530                 ret = i915_gem_object_wait_moving_fence(vma->obj, true);
531                 if (ret) {
532                         i915_vma_resource_free(vma->resource);
533                         vma->resource = NULL;
534
535                         return ret;
536                 }
537                 vma->ops->bind_vma(vma->vm, NULL, vma->resource, cache_level,
538                                    bind_flags);
539         }
540
541         set_bit(I915_BO_WAS_BOUND_BIT, &vma->obj->flags);
542
543         atomic_or(bind_flags, &vma->flags);
544         return 0;
545 }
546
547 void __iomem *i915_vma_pin_iomap(struct i915_vma *vma)
548 {
549         void __iomem *ptr;
550         int err;
551
552         if (WARN_ON_ONCE(vma->obj->flags & I915_BO_ALLOC_GPU_ONLY))
553                 return IOMEM_ERR_PTR(-EINVAL);
554
555         GEM_BUG_ON(!i915_vma_is_ggtt(vma));
556         GEM_BUG_ON(!i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND));
557         GEM_BUG_ON(i915_vma_verify_bind_complete(vma));
558
559         ptr = READ_ONCE(vma->iomap);
560         if (ptr == NULL) {
561                 /*
562                  * TODO: consider just using i915_gem_object_pin_map() for lmem
563                  * instead, which already supports mapping non-contiguous chunks
564                  * of pages, that way we can also drop the
565                  * I915_BO_ALLOC_CONTIGUOUS when allocating the object.
566                  */
567                 if (i915_gem_object_is_lmem(vma->obj)) {
568                         ptr = i915_gem_object_lmem_io_map(vma->obj, 0,
569                                                           vma->obj->base.size);
570                 } else if (i915_vma_is_map_and_fenceable(vma)) {
571                         ptr = io_mapping_map_wc(&i915_vm_to_ggtt(vma->vm)->iomap,
572                                                 vma->node.start,
573                                                 vma->node.size);
574                 } else {
575                         ptr = (void __iomem *)
576                                 i915_gem_object_pin_map(vma->obj, I915_MAP_WC);
577                         if (IS_ERR(ptr)) {
578                                 err = PTR_ERR(ptr);
579                                 goto err;
580                         }
581                         ptr = page_pack_bits(ptr, 1);
582                 }
583
584                 if (ptr == NULL) {
585                         err = -ENOMEM;
586                         goto err;
587                 }
588
589                 if (unlikely(cmpxchg(&vma->iomap, NULL, ptr))) {
590                         if (page_unmask_bits(ptr))
591                                 __i915_gem_object_release_map(vma->obj);
592                         else
593                                 io_mapping_unmap(ptr);
594                         ptr = vma->iomap;
595                 }
596         }
597
598         __i915_vma_pin(vma);
599
600         err = i915_vma_pin_fence(vma);
601         if (err)
602                 goto err_unpin;
603
604         i915_vma_set_ggtt_write(vma);
605
606         /* NB Access through the GTT requires the device to be awake. */
607         return page_mask_bits(ptr);
608
609 err_unpin:
610         __i915_vma_unpin(vma);
611 err:
612         return IOMEM_ERR_PTR(err);
613 }
614
615 void i915_vma_flush_writes(struct i915_vma *vma)
616 {
617         if (i915_vma_unset_ggtt_write(vma))
618                 intel_gt_flush_ggtt_writes(vma->vm->gt);
619 }
620
621 void i915_vma_unpin_iomap(struct i915_vma *vma)
622 {
623         GEM_BUG_ON(vma->iomap == NULL);
624
625         /* XXX We keep the mapping until __i915_vma_unbind()/evict() */
626
627         i915_vma_flush_writes(vma);
628
629         i915_vma_unpin_fence(vma);
630         i915_vma_unpin(vma);
631 }
632
633 void i915_vma_unpin_and_release(struct i915_vma **p_vma, unsigned int flags)
634 {
635         struct i915_vma *vma;
636         struct drm_i915_gem_object *obj;
637
638         vma = fetch_and_zero(p_vma);
639         if (!vma)
640                 return;
641
642         obj = vma->obj;
643         GEM_BUG_ON(!obj);
644
645         i915_vma_unpin(vma);
646
647         if (flags & I915_VMA_RELEASE_MAP)
648                 i915_gem_object_unpin_map(obj);
649
650         i915_gem_object_put(obj);
651 }
652
653 bool i915_vma_misplaced(const struct i915_vma *vma,
654                         u64 size, u64 alignment, u64 flags)
655 {
656         if (!drm_mm_node_allocated(&vma->node))
657                 return false;
658
659         if (test_bit(I915_VMA_ERROR_BIT, __i915_vma_flags(vma)))
660                 return true;
661
662         if (vma->node.size < size)
663                 return true;
664
665         GEM_BUG_ON(alignment && !is_power_of_2(alignment));
666         if (alignment && !IS_ALIGNED(vma->node.start, alignment))
667                 return true;
668
669         if (flags & PIN_MAPPABLE && !i915_vma_is_map_and_fenceable(vma))
670                 return true;
671
672         if (flags & PIN_OFFSET_BIAS &&
673             vma->node.start < (flags & PIN_OFFSET_MASK))
674                 return true;
675
676         if (flags & PIN_OFFSET_FIXED &&
677             vma->node.start != (flags & PIN_OFFSET_MASK))
678                 return true;
679
680         return false;
681 }
682
683 void __i915_vma_set_map_and_fenceable(struct i915_vma *vma)
684 {
685         bool mappable, fenceable;
686
687         GEM_BUG_ON(!i915_vma_is_ggtt(vma));
688         GEM_BUG_ON(!vma->fence_size);
689
690         fenceable = (vma->node.size >= vma->fence_size &&
691                      IS_ALIGNED(vma->node.start, vma->fence_alignment));
692
693         mappable = vma->node.start + vma->fence_size <= i915_vm_to_ggtt(vma->vm)->mappable_end;
694
695         if (mappable && fenceable)
696                 set_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
697         else
698                 clear_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
699 }
700
701 bool i915_gem_valid_gtt_space(struct i915_vma *vma, unsigned long color)
702 {
703         struct drm_mm_node *node = &vma->node;
704         struct drm_mm_node *other;
705
706         /*
707          * On some machines we have to be careful when putting differing types
708          * of snoopable memory together to avoid the prefetcher crossing memory
709          * domains and dying. During vm initialisation, we decide whether or not
710          * these constraints apply and set the drm_mm.color_adjust
711          * appropriately.
712          */
713         if (!i915_vm_has_cache_coloring(vma->vm))
714                 return true;
715
716         /* Only valid to be called on an already inserted vma */
717         GEM_BUG_ON(!drm_mm_node_allocated(node));
718         GEM_BUG_ON(list_empty(&node->node_list));
719
720         other = list_prev_entry(node, node_list);
721         if (i915_node_color_differs(other, color) &&
722             !drm_mm_hole_follows(other))
723                 return false;
724
725         other = list_next_entry(node, node_list);
726         if (i915_node_color_differs(other, color) &&
727             !drm_mm_hole_follows(node))
728                 return false;
729
730         return true;
731 }
732
733 /**
734  * i915_vma_insert - finds a slot for the vma in its address space
735  * @vma: the vma
736  * @size: requested size in bytes (can be larger than the VMA)
737  * @alignment: required alignment
738  * @flags: mask of PIN_* flags to use
739  *
740  * First we try to allocate some free space that meets the requirements for
741  * the VMA. Failiing that, if the flags permit, it will evict an old VMA,
742  * preferrably the oldest idle entry to make room for the new VMA.
743  *
744  * Returns:
745  * 0 on success, negative error code otherwise.
746  */
747 static int
748 i915_vma_insert(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
749                 u64 size, u64 alignment, u64 flags)
750 {
751         unsigned long color;
752         u64 start, end;
753         int ret;
754
755         GEM_BUG_ON(i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND));
756         GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
757
758         size = max(size, vma->size);
759         alignment = max(alignment, vma->display_alignment);
760         if (flags & PIN_MAPPABLE) {
761                 size = max_t(typeof(size), size, vma->fence_size);
762                 alignment = max_t(typeof(alignment),
763                                   alignment, vma->fence_alignment);
764         }
765
766         GEM_BUG_ON(!IS_ALIGNED(size, I915_GTT_PAGE_SIZE));
767         GEM_BUG_ON(!IS_ALIGNED(alignment, I915_GTT_MIN_ALIGNMENT));
768         GEM_BUG_ON(!is_power_of_2(alignment));
769
770         start = flags & PIN_OFFSET_BIAS ? flags & PIN_OFFSET_MASK : 0;
771         GEM_BUG_ON(!IS_ALIGNED(start, I915_GTT_PAGE_SIZE));
772
773         end = vma->vm->total;
774         if (flags & PIN_MAPPABLE)
775                 end = min_t(u64, end, i915_vm_to_ggtt(vma->vm)->mappable_end);
776         if (flags & PIN_ZONE_4G)
777                 end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
778         GEM_BUG_ON(!IS_ALIGNED(end, I915_GTT_PAGE_SIZE));
779
780         alignment = max(alignment, i915_vm_obj_min_alignment(vma->vm, vma->obj));
781         /*
782          * for compact-pt we round up the reservation to prevent
783          * any smaller pages being used within the same PDE
784          */
785         if (NEEDS_COMPACT_PT(vma->vm->i915))
786                 size = round_up(size, alignment);
787
788         /* If binding the object/GGTT view requires more space than the entire
789          * aperture has, reject it early before evicting everything in a vain
790          * attempt to find space.
791          */
792         if (size > end) {
793                 DRM_DEBUG("Attempting to bind an object larger than the aperture: request=%llu > %s aperture=%llu\n",
794                           size, flags & PIN_MAPPABLE ? "mappable" : "total",
795                           end);
796                 return -ENOSPC;
797         }
798
799         color = 0;
800
801         if (i915_vm_has_cache_coloring(vma->vm))
802                 color = vma->obj->cache_level;
803
804         if (flags & PIN_OFFSET_FIXED) {
805                 u64 offset = flags & PIN_OFFSET_MASK;
806                 if (!IS_ALIGNED(offset, alignment) ||
807                     range_overflows(offset, size, end))
808                         return -EINVAL;
809
810                 ret = i915_gem_gtt_reserve(vma->vm, ww, &vma->node,
811                                            size, offset, color,
812                                            flags);
813                 if (ret)
814                         return ret;
815         } else {
816                 /*
817                  * We only support huge gtt pages through the 48b PPGTT,
818                  * however we also don't want to force any alignment for
819                  * objects which need to be tightly packed into the low 32bits.
820                  *
821                  * Note that we assume that GGTT are limited to 4GiB for the
822                  * forseeable future. See also i915_ggtt_offset().
823                  */
824                 if (upper_32_bits(end - 1) &&
825                     vma->page_sizes.sg > I915_GTT_PAGE_SIZE) {
826                         /*
827                          * We can't mix 64K and 4K PTEs in the same page-table
828                          * (2M block), and so to avoid the ugliness and
829                          * complexity of coloring we opt for just aligning 64K
830                          * objects to 2M.
831                          */
832                         u64 page_alignment =
833                                 rounddown_pow_of_two(vma->page_sizes.sg |
834                                                      I915_GTT_PAGE_SIZE_2M);
835
836                         /*
837                          * Check we don't expand for the limited Global GTT
838                          * (mappable aperture is even more precious!). This
839                          * also checks that we exclude the aliasing-ppgtt.
840                          */
841                         GEM_BUG_ON(i915_vma_is_ggtt(vma));
842
843                         alignment = max(alignment, page_alignment);
844
845                         if (vma->page_sizes.sg & I915_GTT_PAGE_SIZE_64K)
846                                 size = round_up(size, I915_GTT_PAGE_SIZE_2M);
847                 }
848
849                 ret = i915_gem_gtt_insert(vma->vm, ww, &vma->node,
850                                           size, alignment, color,
851                                           start, end, flags);
852                 if (ret)
853                         return ret;
854
855                 GEM_BUG_ON(vma->node.start < start);
856                 GEM_BUG_ON(vma->node.start + vma->node.size > end);
857         }
858         GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
859         GEM_BUG_ON(!i915_gem_valid_gtt_space(vma, color));
860
861         list_move_tail(&vma->vm_link, &vma->vm->bound_list);
862
863         return 0;
864 }
865
866 static void
867 i915_vma_detach(struct i915_vma *vma)
868 {
869         GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
870         GEM_BUG_ON(i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND));
871
872         /*
873          * And finally now the object is completely decoupled from this
874          * vma, we can drop its hold on the backing storage and allow
875          * it to be reaped by the shrinker.
876          */
877         list_move_tail(&vma->vm_link, &vma->vm->unbound_list);
878 }
879
880 static bool try_qad_pin(struct i915_vma *vma, unsigned int flags)
881 {
882         unsigned int bound;
883
884         bound = atomic_read(&vma->flags);
885
886         if (flags & PIN_VALIDATE) {
887                 flags &= I915_VMA_BIND_MASK;
888
889                 return (flags & bound) == flags;
890         }
891
892         /* with the lock mandatory for unbind, we don't race here */
893         flags &= I915_VMA_BIND_MASK;
894         do {
895                 if (unlikely(flags & ~bound))
896                         return false;
897
898                 if (unlikely(bound & (I915_VMA_OVERFLOW | I915_VMA_ERROR)))
899                         return false;
900
901                 GEM_BUG_ON(((bound + 1) & I915_VMA_PIN_MASK) == 0);
902         } while (!atomic_try_cmpxchg(&vma->flags, &bound, bound + 1));
903
904         return true;
905 }
906
907 static struct scatterlist *
908 rotate_pages(struct drm_i915_gem_object *obj, unsigned int offset,
909              unsigned int width, unsigned int height,
910              unsigned int src_stride, unsigned int dst_stride,
911              struct sg_table *st, struct scatterlist *sg)
912 {
913         unsigned int column, row;
914         unsigned int src_idx;
915
916         for (column = 0; column < width; column++) {
917                 unsigned int left;
918
919                 src_idx = src_stride * (height - 1) + column + offset;
920                 for (row = 0; row < height; row++) {
921                         st->nents++;
922                         /*
923                          * We don't need the pages, but need to initialize
924                          * the entries so the sg list can be happily traversed.
925                          * The only thing we need are DMA addresses.
926                          */
927                         sg_set_page(sg, NULL, I915_GTT_PAGE_SIZE, 0);
928                         sg_dma_address(sg) =
929                                 i915_gem_object_get_dma_address(obj, src_idx);
930                         sg_dma_len(sg) = I915_GTT_PAGE_SIZE;
931                         sg = sg_next(sg);
932                         src_idx -= src_stride;
933                 }
934
935                 left = (dst_stride - height) * I915_GTT_PAGE_SIZE;
936
937                 if (!left)
938                         continue;
939
940                 st->nents++;
941
942                 /*
943                  * The DE ignores the PTEs for the padding tiles, the sg entry
944                  * here is just a conenience to indicate how many padding PTEs
945                  * to insert at this spot.
946                  */
947                 sg_set_page(sg, NULL, left, 0);
948                 sg_dma_address(sg) = 0;
949                 sg_dma_len(sg) = left;
950                 sg = sg_next(sg);
951         }
952
953         return sg;
954 }
955
956 static noinline struct sg_table *
957 intel_rotate_pages(struct intel_rotation_info *rot_info,
958                    struct drm_i915_gem_object *obj)
959 {
960         unsigned int size = intel_rotation_info_size(rot_info);
961         struct drm_i915_private *i915 = to_i915(obj->base.dev);
962         struct sg_table *st;
963         struct scatterlist *sg;
964         int ret = -ENOMEM;
965         int i;
966
967         /* Allocate target SG list. */
968         st = kmalloc(sizeof(*st), GFP_KERNEL);
969         if (!st)
970                 goto err_st_alloc;
971
972         ret = sg_alloc_table(st, size, GFP_KERNEL);
973         if (ret)
974                 goto err_sg_alloc;
975
976         st->nents = 0;
977         sg = st->sgl;
978
979         for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
980                 sg = rotate_pages(obj, rot_info->plane[i].offset,
981                                   rot_info->plane[i].width, rot_info->plane[i].height,
982                                   rot_info->plane[i].src_stride,
983                                   rot_info->plane[i].dst_stride,
984                                   st, sg);
985
986         return st;
987
988 err_sg_alloc:
989         kfree(st);
990 err_st_alloc:
991
992         drm_dbg(&i915->drm, "Failed to create rotated mapping for object size %zu! (%ux%u tiles, %u pages)\n",
993                 obj->base.size, rot_info->plane[0].width,
994                 rot_info->plane[0].height, size);
995
996         return ERR_PTR(ret);
997 }
998
999 static struct scatterlist *
1000 add_padding_pages(unsigned int count,
1001                   struct sg_table *st, struct scatterlist *sg)
1002 {
1003         st->nents++;
1004
1005         /*
1006          * The DE ignores the PTEs for the padding tiles, the sg entry
1007          * here is just a convenience to indicate how many padding PTEs
1008          * to insert at this spot.
1009          */
1010         sg_set_page(sg, NULL, count * I915_GTT_PAGE_SIZE, 0);
1011         sg_dma_address(sg) = 0;
1012         sg_dma_len(sg) = count * I915_GTT_PAGE_SIZE;
1013         sg = sg_next(sg);
1014
1015         return sg;
1016 }
1017
1018 static struct scatterlist *
1019 remap_tiled_color_plane_pages(struct drm_i915_gem_object *obj,
1020                               unsigned int offset, unsigned int alignment_pad,
1021                               unsigned int width, unsigned int height,
1022                               unsigned int src_stride, unsigned int dst_stride,
1023                               struct sg_table *st, struct scatterlist *sg,
1024                               unsigned int *gtt_offset)
1025 {
1026         unsigned int row;
1027
1028         if (!width || !height)
1029                 return sg;
1030
1031         if (alignment_pad)
1032                 sg = add_padding_pages(alignment_pad, st, sg);
1033
1034         for (row = 0; row < height; row++) {
1035                 unsigned int left = width * I915_GTT_PAGE_SIZE;
1036
1037                 while (left) {
1038                         dma_addr_t addr;
1039                         unsigned int length;
1040
1041                         /*
1042                          * We don't need the pages, but need to initialize
1043                          * the entries so the sg list can be happily traversed.
1044                          * The only thing we need are DMA addresses.
1045                          */
1046
1047                         addr = i915_gem_object_get_dma_address_len(obj, offset, &length);
1048
1049                         length = min(left, length);
1050
1051                         st->nents++;
1052
1053                         sg_set_page(sg, NULL, length, 0);
1054                         sg_dma_address(sg) = addr;
1055                         sg_dma_len(sg) = length;
1056                         sg = sg_next(sg);
1057
1058                         offset += length / I915_GTT_PAGE_SIZE;
1059                         left -= length;
1060                 }
1061
1062                 offset += src_stride - width;
1063
1064                 left = (dst_stride - width) * I915_GTT_PAGE_SIZE;
1065
1066                 if (!left)
1067                         continue;
1068
1069                 sg = add_padding_pages(left >> PAGE_SHIFT, st, sg);
1070         }
1071
1072         *gtt_offset += alignment_pad + dst_stride * height;
1073
1074         return sg;
1075 }
1076
1077 static struct scatterlist *
1078 remap_contiguous_pages(struct drm_i915_gem_object *obj,
1079                        unsigned int obj_offset,
1080                        unsigned int count,
1081                        struct sg_table *st, struct scatterlist *sg)
1082 {
1083         struct scatterlist *iter;
1084         unsigned int offset;
1085
1086         iter = i915_gem_object_get_sg_dma(obj, obj_offset, &offset);
1087         GEM_BUG_ON(!iter);
1088
1089         do {
1090                 unsigned int len;
1091
1092                 len = min(sg_dma_len(iter) - (offset << PAGE_SHIFT),
1093                           count << PAGE_SHIFT);
1094                 sg_set_page(sg, NULL, len, 0);
1095                 sg_dma_address(sg) =
1096                         sg_dma_address(iter) + (offset << PAGE_SHIFT);
1097                 sg_dma_len(sg) = len;
1098
1099                 st->nents++;
1100                 count -= len >> PAGE_SHIFT;
1101                 if (count == 0)
1102                         return sg;
1103
1104                 sg = __sg_next(sg);
1105                 iter = __sg_next(iter);
1106                 offset = 0;
1107         } while (1);
1108 }
1109
1110 static struct scatterlist *
1111 remap_linear_color_plane_pages(struct drm_i915_gem_object *obj,
1112                                unsigned int obj_offset, unsigned int alignment_pad,
1113                                unsigned int size,
1114                                struct sg_table *st, struct scatterlist *sg,
1115                                unsigned int *gtt_offset)
1116 {
1117         if (!size)
1118                 return sg;
1119
1120         if (alignment_pad)
1121                 sg = add_padding_pages(alignment_pad, st, sg);
1122
1123         sg = remap_contiguous_pages(obj, obj_offset, size, st, sg);
1124         sg = sg_next(sg);
1125
1126         *gtt_offset += alignment_pad + size;
1127
1128         return sg;
1129 }
1130
1131 static struct scatterlist *
1132 remap_color_plane_pages(const struct intel_remapped_info *rem_info,
1133                         struct drm_i915_gem_object *obj,
1134                         int color_plane,
1135                         struct sg_table *st, struct scatterlist *sg,
1136                         unsigned int *gtt_offset)
1137 {
1138         unsigned int alignment_pad = 0;
1139
1140         if (rem_info->plane_alignment)
1141                 alignment_pad = ALIGN(*gtt_offset, rem_info->plane_alignment) - *gtt_offset;
1142
1143         if (rem_info->plane[color_plane].linear)
1144                 sg = remap_linear_color_plane_pages(obj,
1145                                                     rem_info->plane[color_plane].offset,
1146                                                     alignment_pad,
1147                                                     rem_info->plane[color_plane].size,
1148                                                     st, sg,
1149                                                     gtt_offset);
1150
1151         else
1152                 sg = remap_tiled_color_plane_pages(obj,
1153                                                    rem_info->plane[color_plane].offset,
1154                                                    alignment_pad,
1155                                                    rem_info->plane[color_plane].width,
1156                                                    rem_info->plane[color_plane].height,
1157                                                    rem_info->plane[color_plane].src_stride,
1158                                                    rem_info->plane[color_plane].dst_stride,
1159                                                    st, sg,
1160                                                    gtt_offset);
1161
1162         return sg;
1163 }
1164
1165 static noinline struct sg_table *
1166 intel_remap_pages(struct intel_remapped_info *rem_info,
1167                   struct drm_i915_gem_object *obj)
1168 {
1169         unsigned int size = intel_remapped_info_size(rem_info);
1170         struct drm_i915_private *i915 = to_i915(obj->base.dev);
1171         struct sg_table *st;
1172         struct scatterlist *sg;
1173         unsigned int gtt_offset = 0;
1174         int ret = -ENOMEM;
1175         int i;
1176
1177         /* Allocate target SG list. */
1178         st = kmalloc(sizeof(*st), GFP_KERNEL);
1179         if (!st)
1180                 goto err_st_alloc;
1181
1182         ret = sg_alloc_table(st, size, GFP_KERNEL);
1183         if (ret)
1184                 goto err_sg_alloc;
1185
1186         st->nents = 0;
1187         sg = st->sgl;
1188
1189         for (i = 0 ; i < ARRAY_SIZE(rem_info->plane); i++)
1190                 sg = remap_color_plane_pages(rem_info, obj, i, st, sg, &gtt_offset);
1191
1192         i915_sg_trim(st);
1193
1194         return st;
1195
1196 err_sg_alloc:
1197         kfree(st);
1198 err_st_alloc:
1199
1200         drm_dbg(&i915->drm, "Failed to create remapped mapping for object size %zu! (%ux%u tiles, %u pages)\n",
1201                 obj->base.size, rem_info->plane[0].width,
1202                 rem_info->plane[0].height, size);
1203
1204         return ERR_PTR(ret);
1205 }
1206
1207 static noinline struct sg_table *
1208 intel_partial_pages(const struct i915_ggtt_view *view,
1209                     struct drm_i915_gem_object *obj)
1210 {
1211         struct sg_table *st;
1212         struct scatterlist *sg;
1213         unsigned int count = view->partial.size;
1214         int ret = -ENOMEM;
1215
1216         st = kmalloc(sizeof(*st), GFP_KERNEL);
1217         if (!st)
1218                 goto err_st_alloc;
1219
1220         ret = sg_alloc_table(st, count, GFP_KERNEL);
1221         if (ret)
1222                 goto err_sg_alloc;
1223
1224         st->nents = 0;
1225
1226         sg = remap_contiguous_pages(obj, view->partial.offset, count, st, st->sgl);
1227
1228         sg_mark_end(sg);
1229         i915_sg_trim(st); /* Drop any unused tail entries. */
1230
1231         return st;
1232
1233 err_sg_alloc:
1234         kfree(st);
1235 err_st_alloc:
1236         return ERR_PTR(ret);
1237 }
1238
1239 static int
1240 __i915_vma_get_pages(struct i915_vma *vma)
1241 {
1242         struct sg_table *pages;
1243
1244         /*
1245          * The vma->pages are only valid within the lifespan of the borrowed
1246          * obj->mm.pages. When the obj->mm.pages sg_table is regenerated, so
1247          * must be the vma->pages. A simple rule is that vma->pages must only
1248          * be accessed when the obj->mm.pages are pinned.
1249          */
1250         GEM_BUG_ON(!i915_gem_object_has_pinned_pages(vma->obj));
1251
1252         switch (vma->ggtt_view.type) {
1253         default:
1254                 GEM_BUG_ON(vma->ggtt_view.type);
1255                 fallthrough;
1256         case I915_GGTT_VIEW_NORMAL:
1257                 pages = vma->obj->mm.pages;
1258                 break;
1259
1260         case I915_GGTT_VIEW_ROTATED:
1261                 pages =
1262                         intel_rotate_pages(&vma->ggtt_view.rotated, vma->obj);
1263                 break;
1264
1265         case I915_GGTT_VIEW_REMAPPED:
1266                 pages =
1267                         intel_remap_pages(&vma->ggtt_view.remapped, vma->obj);
1268                 break;
1269
1270         case I915_GGTT_VIEW_PARTIAL:
1271                 pages = intel_partial_pages(&vma->ggtt_view, vma->obj);
1272                 break;
1273         }
1274
1275         if (IS_ERR(pages)) {
1276                 drm_err(&vma->vm->i915->drm,
1277                         "Failed to get pages for VMA view type %u (%ld)!\n",
1278                         vma->ggtt_view.type, PTR_ERR(pages));
1279                 return PTR_ERR(pages);
1280         }
1281
1282         vma->pages = pages;
1283
1284         return 0;
1285 }
1286
1287 I915_SELFTEST_EXPORT int i915_vma_get_pages(struct i915_vma *vma)
1288 {
1289         int err;
1290
1291         if (atomic_add_unless(&vma->pages_count, 1, 0))
1292                 return 0;
1293
1294         err = i915_gem_object_pin_pages(vma->obj);
1295         if (err)
1296                 return err;
1297
1298         err = __i915_vma_get_pages(vma);
1299         if (err)
1300                 goto err_unpin;
1301
1302         vma->page_sizes = vma->obj->mm.page_sizes;
1303         atomic_inc(&vma->pages_count);
1304
1305         return 0;
1306
1307 err_unpin:
1308         __i915_gem_object_unpin_pages(vma->obj);
1309
1310         return err;
1311 }
1312
1313 static void __vma_put_pages(struct i915_vma *vma, unsigned int count)
1314 {
1315         /* We allocate under vma_get_pages, so beware the shrinker */
1316         GEM_BUG_ON(atomic_read(&vma->pages_count) < count);
1317
1318         if (atomic_sub_return(count, &vma->pages_count) == 0) {
1319                 if (vma->pages != vma->obj->mm.pages) {
1320                         sg_free_table(vma->pages);
1321                         kfree(vma->pages);
1322                 }
1323                 vma->pages = NULL;
1324
1325                 i915_gem_object_unpin_pages(vma->obj);
1326         }
1327 }
1328
1329 I915_SELFTEST_EXPORT void i915_vma_put_pages(struct i915_vma *vma)
1330 {
1331         if (atomic_add_unless(&vma->pages_count, -1, 1))
1332                 return;
1333
1334         __vma_put_pages(vma, 1);
1335 }
1336
1337 static void vma_unbind_pages(struct i915_vma *vma)
1338 {
1339         unsigned int count;
1340
1341         lockdep_assert_held(&vma->vm->mutex);
1342
1343         /* The upper portion of pages_count is the number of bindings */
1344         count = atomic_read(&vma->pages_count);
1345         count >>= I915_VMA_PAGES_BIAS;
1346         GEM_BUG_ON(!count);
1347
1348         __vma_put_pages(vma, count | count << I915_VMA_PAGES_BIAS);
1349 }
1350
1351 int i915_vma_pin_ww(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
1352                     u64 size, u64 alignment, u64 flags)
1353 {
1354         struct i915_vma_work *work = NULL;
1355         struct dma_fence *moving = NULL;
1356         struct i915_vma_resource *vma_res = NULL;
1357         intel_wakeref_t wakeref = 0;
1358         unsigned int bound;
1359         int err;
1360
1361         assert_vma_held(vma);
1362         GEM_BUG_ON(!ww);
1363
1364         BUILD_BUG_ON(PIN_GLOBAL != I915_VMA_GLOBAL_BIND);
1365         BUILD_BUG_ON(PIN_USER != I915_VMA_LOCAL_BIND);
1366
1367         GEM_BUG_ON(!(flags & (PIN_USER | PIN_GLOBAL)));
1368
1369         /* First try and grab the pin without rebinding the vma */
1370         if (try_qad_pin(vma, flags))
1371                 return 0;
1372
1373         err = i915_vma_get_pages(vma);
1374         if (err)
1375                 return err;
1376
1377         if (flags & PIN_GLOBAL)
1378                 wakeref = intel_runtime_pm_get(&vma->vm->i915->runtime_pm);
1379
1380         if (flags & vma->vm->bind_async_flags) {
1381                 /* lock VM */
1382                 err = i915_vm_lock_objects(vma->vm, ww);
1383                 if (err)
1384                         goto err_rpm;
1385
1386                 work = i915_vma_work();
1387                 if (!work) {
1388                         err = -ENOMEM;
1389                         goto err_rpm;
1390                 }
1391
1392                 work->vm = vma->vm;
1393
1394                 err = i915_gem_object_get_moving_fence(vma->obj, &moving);
1395                 if (err)
1396                         goto err_rpm;
1397
1398                 dma_fence_work_chain(&work->base, moving);
1399
1400                 /* Allocate enough page directories to used PTE */
1401                 if (vma->vm->allocate_va_range) {
1402                         err = i915_vm_alloc_pt_stash(vma->vm,
1403                                                      &work->stash,
1404                                                      vma->size);
1405                         if (err)
1406                                 goto err_fence;
1407
1408                         err = i915_vm_map_pt_stash(vma->vm, &work->stash);
1409                         if (err)
1410                                 goto err_fence;
1411                 }
1412         }
1413
1414         vma_res = i915_vma_resource_alloc();
1415         if (IS_ERR(vma_res)) {
1416                 err = PTR_ERR(vma_res);
1417                 goto err_fence;
1418         }
1419
1420         /*
1421          * Differentiate between user/kernel vma inside the aliasing-ppgtt.
1422          *
1423          * We conflate the Global GTT with the user's vma when using the
1424          * aliasing-ppgtt, but it is still vitally important to try and
1425          * keep the use cases distinct. For example, userptr objects are
1426          * not allowed inside the Global GTT as that will cause lock
1427          * inversions when we have to evict them the mmu_notifier callbacks -
1428          * but they are allowed to be part of the user ppGTT which can never
1429          * be mapped. As such we try to give the distinct users of the same
1430          * mutex, distinct lockclasses [equivalent to how we keep i915_ggtt
1431          * and i915_ppgtt separate].
1432          *
1433          * NB this may cause us to mask real lock inversions -- while the
1434          * code is safe today, lockdep may not be able to spot future
1435          * transgressions.
1436          */
1437         err = mutex_lock_interruptible_nested(&vma->vm->mutex,
1438                                               !(flags & PIN_GLOBAL));
1439         if (err)
1440                 goto err_vma_res;
1441
1442         /* No more allocations allowed now we hold vm->mutex */
1443
1444         if (unlikely(i915_vma_is_closed(vma))) {
1445                 err = -ENOENT;
1446                 goto err_unlock;
1447         }
1448
1449         bound = atomic_read(&vma->flags);
1450         if (unlikely(bound & I915_VMA_ERROR)) {
1451                 err = -ENOMEM;
1452                 goto err_unlock;
1453         }
1454
1455         if (unlikely(!((bound + 1) & I915_VMA_PIN_MASK))) {
1456                 err = -EAGAIN; /* pins are meant to be fairly temporary */
1457                 goto err_unlock;
1458         }
1459
1460         if (unlikely(!(flags & ~bound & I915_VMA_BIND_MASK))) {
1461                 if (!(flags & PIN_VALIDATE))
1462                         __i915_vma_pin(vma);
1463                 goto err_unlock;
1464         }
1465
1466         err = i915_active_acquire(&vma->active);
1467         if (err)
1468                 goto err_unlock;
1469
1470         if (!(bound & I915_VMA_BIND_MASK)) {
1471                 err = i915_vma_insert(vma, ww, size, alignment, flags);
1472                 if (err)
1473                         goto err_active;
1474
1475                 if (i915_is_ggtt(vma->vm))
1476                         __i915_vma_set_map_and_fenceable(vma);
1477         }
1478
1479         GEM_BUG_ON(!vma->pages);
1480         err = i915_vma_bind(vma,
1481                             vma->obj->cache_level,
1482                             flags, work, vma_res);
1483         vma_res = NULL;
1484         if (err)
1485                 goto err_remove;
1486
1487         /* There should only be at most 2 active bindings (user, global) */
1488         GEM_BUG_ON(bound + I915_VMA_PAGES_ACTIVE < bound);
1489         atomic_add(I915_VMA_PAGES_ACTIVE, &vma->pages_count);
1490         list_move_tail(&vma->vm_link, &vma->vm->bound_list);
1491
1492         if (!(flags & PIN_VALIDATE)) {
1493                 __i915_vma_pin(vma);
1494                 GEM_BUG_ON(!i915_vma_is_pinned(vma));
1495         }
1496         GEM_BUG_ON(!i915_vma_is_bound(vma, flags));
1497         GEM_BUG_ON(i915_vma_misplaced(vma, size, alignment, flags));
1498
1499 err_remove:
1500         if (!i915_vma_is_bound(vma, I915_VMA_BIND_MASK)) {
1501                 i915_vma_detach(vma);
1502                 drm_mm_remove_node(&vma->node);
1503         }
1504 err_active:
1505         i915_active_release(&vma->active);
1506 err_unlock:
1507         mutex_unlock(&vma->vm->mutex);
1508 err_vma_res:
1509         i915_vma_resource_free(vma_res);
1510 err_fence:
1511         if (work)
1512                 dma_fence_work_commit_imm(&work->base);
1513 err_rpm:
1514         if (wakeref)
1515                 intel_runtime_pm_put(&vma->vm->i915->runtime_pm, wakeref);
1516
1517         if (moving)
1518                 dma_fence_put(moving);
1519
1520         i915_vma_put_pages(vma);
1521         return err;
1522 }
1523
1524 static void flush_idle_contexts(struct intel_gt *gt)
1525 {
1526         struct intel_engine_cs *engine;
1527         enum intel_engine_id id;
1528
1529         for_each_engine(engine, gt, id)
1530                 intel_engine_flush_barriers(engine);
1531
1532         intel_gt_wait_for_idle(gt, MAX_SCHEDULE_TIMEOUT);
1533 }
1534
1535 static int __i915_ggtt_pin(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
1536                            u32 align, unsigned int flags)
1537 {
1538         struct i915_address_space *vm = vma->vm;
1539         int err;
1540
1541         do {
1542                 err = i915_vma_pin_ww(vma, ww, 0, align, flags | PIN_GLOBAL);
1543
1544                 if (err != -ENOSPC) {
1545                         if (!err) {
1546                                 err = i915_vma_wait_for_bind(vma);
1547                                 if (err)
1548                                         i915_vma_unpin(vma);
1549                         }
1550                         return err;
1551                 }
1552
1553                 /* Unlike i915_vma_pin, we don't take no for an answer! */
1554                 flush_idle_contexts(vm->gt);
1555                 if (mutex_lock_interruptible(&vm->mutex) == 0) {
1556                         /*
1557                          * We pass NULL ww here, as we don't want to unbind
1558                          * locked objects when called from execbuf when pinning
1559                          * is removed. This would probably regress badly.
1560                          */
1561                         i915_gem_evict_vm(vm, NULL);
1562                         mutex_unlock(&vm->mutex);
1563                 }
1564         } while (1);
1565 }
1566
1567 int i915_ggtt_pin(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
1568                   u32 align, unsigned int flags)
1569 {
1570         struct i915_gem_ww_ctx _ww;
1571         int err;
1572
1573         GEM_BUG_ON(!i915_vma_is_ggtt(vma));
1574
1575         if (ww)
1576                 return __i915_ggtt_pin(vma, ww, align, flags);
1577
1578         lockdep_assert_not_held(&vma->obj->base.resv->lock.base);
1579
1580         for_i915_gem_ww(&_ww, err, true) {
1581                 err = i915_gem_object_lock(vma->obj, &_ww);
1582                 if (!err)
1583                         err = __i915_ggtt_pin(vma, &_ww, align, flags);
1584         }
1585
1586         return err;
1587 }
1588
1589 static void __vma_close(struct i915_vma *vma, struct intel_gt *gt)
1590 {
1591         /*
1592          * We defer actually closing, unbinding and destroying the VMA until
1593          * the next idle point, or if the object is freed in the meantime. By
1594          * postponing the unbind, we allow for it to be resurrected by the
1595          * client, avoiding the work required to rebind the VMA. This is
1596          * advantageous for DRI, where the client/server pass objects
1597          * between themselves, temporarily opening a local VMA to the
1598          * object, and then closing it again. The same object is then reused
1599          * on the next frame (or two, depending on the depth of the swap queue)
1600          * causing us to rebind the VMA once more. This ends up being a lot
1601          * of wasted work for the steady state.
1602          */
1603         GEM_BUG_ON(i915_vma_is_closed(vma));
1604         list_add(&vma->closed_link, &gt->closed_vma);
1605 }
1606
1607 void i915_vma_close(struct i915_vma *vma)
1608 {
1609         struct intel_gt *gt = vma->vm->gt;
1610         unsigned long flags;
1611
1612         if (i915_vma_is_ggtt(vma))
1613                 return;
1614
1615         GEM_BUG_ON(!atomic_read(&vma->open_count));
1616         if (atomic_dec_and_lock_irqsave(&vma->open_count,
1617                                         &gt->closed_lock,
1618                                         flags)) {
1619                 __vma_close(vma, gt);
1620                 spin_unlock_irqrestore(&gt->closed_lock, flags);
1621         }
1622 }
1623
1624 static void __i915_vma_remove_closed(struct i915_vma *vma)
1625 {
1626         list_del_init(&vma->closed_link);
1627 }
1628
1629 void i915_vma_reopen(struct i915_vma *vma)
1630 {
1631         struct intel_gt *gt = vma->vm->gt;
1632
1633         spin_lock_irq(&gt->closed_lock);
1634         if (i915_vma_is_closed(vma))
1635                 __i915_vma_remove_closed(vma);
1636         spin_unlock_irq(&gt->closed_lock);
1637 }
1638
1639 static void force_unbind(struct i915_vma *vma)
1640 {
1641         if (!drm_mm_node_allocated(&vma->node))
1642                 return;
1643
1644         atomic_and(~I915_VMA_PIN_MASK, &vma->flags);
1645         WARN_ON(__i915_vma_unbind(vma));
1646         GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
1647 }
1648
1649 static void release_references(struct i915_vma *vma, struct intel_gt *gt,
1650                                bool vm_ddestroy)
1651 {
1652         struct drm_i915_gem_object *obj = vma->obj;
1653
1654         GEM_BUG_ON(i915_vma_is_active(vma));
1655
1656         spin_lock(&obj->vma.lock);
1657         list_del(&vma->obj_link);
1658         if (!RB_EMPTY_NODE(&vma->obj_node))
1659                 rb_erase(&vma->obj_node, &obj->vma.tree);
1660
1661         spin_unlock(&obj->vma.lock);
1662
1663         spin_lock_irq(&gt->closed_lock);
1664         __i915_vma_remove_closed(vma);
1665         spin_unlock_irq(&gt->closed_lock);
1666
1667         if (vm_ddestroy)
1668                 i915_vm_resv_put(vma->vm);
1669
1670         i915_active_fini(&vma->active);
1671         GEM_WARN_ON(vma->resource);
1672         i915_vma_free(vma);
1673 }
1674
1675 /**
1676  * i915_vma_destroy_locked - Remove all weak reference to the vma and put
1677  * the initial reference.
1678  *
1679  * This function should be called when it's decided the vma isn't needed
1680  * anymore. The caller must assure that it doesn't race with another lookup
1681  * plus destroy, typically by taking an appropriate reference.
1682  *
1683  * Current callsites are
1684  * - __i915_gem_object_pages_fini()
1685  * - __i915_vm_close() - Blocks the above function by taking a reference on
1686  * the object.
1687  * - __i915_vma_parked() - Blocks the above functions by taking a reference
1688  * on the vm and a reference on the object. Also takes the object lock so
1689  * destruction from __i915_vma_parked() can be blocked by holding the
1690  * object lock. Since the object lock is only allowed from within i915 with
1691  * an object refcount, holding the object lock also implicitly blocks the
1692  * vma freeing from __i915_gem_object_pages_fini().
1693  *
1694  * Because of locks taken during destruction, a vma is also guaranteed to
1695  * stay alive while the following locks are held if it was looked up while
1696  * holding one of the locks:
1697  * - vm->mutex
1698  * - obj->vma.lock
1699  * - gt->closed_lock
1700  */
1701 void i915_vma_destroy_locked(struct i915_vma *vma)
1702 {
1703         lockdep_assert_held(&vma->vm->mutex);
1704
1705         force_unbind(vma);
1706         list_del_init(&vma->vm_link);
1707         release_references(vma, vma->vm->gt, false);
1708 }
1709
1710 void i915_vma_destroy(struct i915_vma *vma)
1711 {
1712         struct intel_gt *gt;
1713         bool vm_ddestroy;
1714
1715         mutex_lock(&vma->vm->mutex);
1716         force_unbind(vma);
1717         list_del_init(&vma->vm_link);
1718         vm_ddestroy = vma->vm_ddestroy;
1719         vma->vm_ddestroy = false;
1720
1721         /* vma->vm may be freed when releasing vma->vm->mutex. */
1722         gt = vma->vm->gt;
1723         mutex_unlock(&vma->vm->mutex);
1724         release_references(vma, gt, vm_ddestroy);
1725 }
1726
1727 void i915_vma_parked(struct intel_gt *gt)
1728 {
1729         struct i915_vma *vma, *next;
1730         LIST_HEAD(closed);
1731
1732         spin_lock_irq(&gt->closed_lock);
1733         list_for_each_entry_safe(vma, next, &gt->closed_vma, closed_link) {
1734                 struct drm_i915_gem_object *obj = vma->obj;
1735                 struct i915_address_space *vm = vma->vm;
1736
1737                 /* XXX All to avoid keeping a reference on i915_vma itself */
1738
1739                 if (!kref_get_unless_zero(&obj->base.refcount))
1740                         continue;
1741
1742                 if (!i915_vm_tryget(vm)) {
1743                         i915_gem_object_put(obj);
1744                         continue;
1745                 }
1746
1747                 list_move(&vma->closed_link, &closed);
1748         }
1749         spin_unlock_irq(&gt->closed_lock);
1750
1751         /* As the GT is held idle, no vma can be reopened as we destroy them */
1752         list_for_each_entry_safe(vma, next, &closed, closed_link) {
1753                 struct drm_i915_gem_object *obj = vma->obj;
1754                 struct i915_address_space *vm = vma->vm;
1755
1756                 if (i915_gem_object_trylock(obj, NULL)) {
1757                         INIT_LIST_HEAD(&vma->closed_link);
1758                         i915_vma_destroy(vma);
1759                         i915_gem_object_unlock(obj);
1760                 } else {
1761                         /* back you go.. */
1762                         spin_lock_irq(&gt->closed_lock);
1763                         list_add(&vma->closed_link, &gt->closed_vma);
1764                         spin_unlock_irq(&gt->closed_lock);
1765                 }
1766
1767                 i915_gem_object_put(obj);
1768                 i915_vm_put(vm);
1769         }
1770 }
1771
1772 static void __i915_vma_iounmap(struct i915_vma *vma)
1773 {
1774         GEM_BUG_ON(i915_vma_is_pinned(vma));
1775
1776         if (vma->iomap == NULL)
1777                 return;
1778
1779         if (page_unmask_bits(vma->iomap))
1780                 __i915_gem_object_release_map(vma->obj);
1781         else
1782                 io_mapping_unmap(vma->iomap);
1783         vma->iomap = NULL;
1784 }
1785
1786 void i915_vma_revoke_mmap(struct i915_vma *vma)
1787 {
1788         struct drm_vma_offset_node *node;
1789         u64 vma_offset;
1790
1791         if (!i915_vma_has_userfault(vma))
1792                 return;
1793
1794         GEM_BUG_ON(!i915_vma_is_map_and_fenceable(vma));
1795         GEM_BUG_ON(!vma->obj->userfault_count);
1796
1797         node = &vma->mmo->vma_node;
1798         vma_offset = vma->ggtt_view.partial.offset << PAGE_SHIFT;
1799         unmap_mapping_range(vma->vm->i915->drm.anon_inode->i_mapping,
1800                             drm_vma_node_offset_addr(node) + vma_offset,
1801                             vma->size,
1802                             1);
1803
1804         i915_vma_unset_userfault(vma);
1805         if (!--vma->obj->userfault_count)
1806                 list_del(&vma->obj->userfault_link);
1807 }
1808
1809 static int
1810 __i915_request_await_bind(struct i915_request *rq, struct i915_vma *vma)
1811 {
1812         return __i915_request_await_exclusive(rq, &vma->active);
1813 }
1814
1815 static int __i915_vma_move_to_active(struct i915_vma *vma, struct i915_request *rq)
1816 {
1817         int err;
1818
1819         /* Wait for the vma to be bound before we start! */
1820         err = __i915_request_await_bind(rq, vma);
1821         if (err)
1822                 return err;
1823
1824         return i915_active_add_request(&vma->active, rq);
1825 }
1826
1827 int _i915_vma_move_to_active(struct i915_vma *vma,
1828                              struct i915_request *rq,
1829                              struct dma_fence *fence,
1830                              unsigned int flags)
1831 {
1832         struct drm_i915_gem_object *obj = vma->obj;
1833         int err;
1834
1835         assert_object_held(obj);
1836
1837         GEM_BUG_ON(!vma->pages);
1838
1839         err = __i915_vma_move_to_active(vma, rq);
1840         if (unlikely(err))
1841                 return err;
1842
1843         /*
1844          * Reserve fences slot early to prevent an allocation after preparing
1845          * the workload and associating fences with dma_resv.
1846          */
1847         if (fence && !(flags & __EXEC_OBJECT_NO_RESERVE)) {
1848                 struct dma_fence *curr;
1849                 int idx;
1850
1851                 dma_fence_array_for_each(curr, idx, fence)
1852                         ;
1853                 err = dma_resv_reserve_fences(vma->obj->base.resv, idx);
1854                 if (unlikely(err))
1855                         return err;
1856         }
1857
1858         if (flags & EXEC_OBJECT_WRITE) {
1859                 struct intel_frontbuffer *front;
1860
1861                 front = __intel_frontbuffer_get(obj);
1862                 if (unlikely(front)) {
1863                         if (intel_frontbuffer_invalidate(front, ORIGIN_CS))
1864                                 i915_active_add_request(&front->write, rq);
1865                         intel_frontbuffer_put(front);
1866                 }
1867         }
1868
1869         if (fence) {
1870                 struct dma_fence *curr;
1871                 enum dma_resv_usage usage;
1872                 int idx;
1873
1874                 obj->read_domains = 0;
1875                 if (flags & EXEC_OBJECT_WRITE) {
1876                         usage = DMA_RESV_USAGE_WRITE;
1877                         obj->write_domain = I915_GEM_DOMAIN_RENDER;
1878                 } else {
1879                         usage = DMA_RESV_USAGE_READ;
1880                 }
1881
1882                 dma_fence_array_for_each(curr, idx, fence)
1883                         dma_resv_add_fence(vma->obj->base.resv, curr, usage);
1884         }
1885
1886         if (flags & EXEC_OBJECT_NEEDS_FENCE && vma->fence)
1887                 i915_active_add_request(&vma->fence->active, rq);
1888
1889         obj->read_domains |= I915_GEM_GPU_DOMAINS;
1890         obj->mm.dirty = true;
1891
1892         GEM_BUG_ON(!i915_vma_is_active(vma));
1893         return 0;
1894 }
1895
1896 struct dma_fence *__i915_vma_evict(struct i915_vma *vma, bool async)
1897 {
1898         struct i915_vma_resource *vma_res = vma->resource;
1899         struct dma_fence *unbind_fence;
1900
1901         GEM_BUG_ON(i915_vma_is_pinned(vma));
1902         assert_vma_held_evict(vma);
1903
1904         if (i915_vma_is_map_and_fenceable(vma)) {
1905                 /* Force a pagefault for domain tracking on next user access */
1906                 i915_vma_revoke_mmap(vma);
1907
1908                 /*
1909                  * Check that we have flushed all writes through the GGTT
1910                  * before the unbind, other due to non-strict nature of those
1911                  * indirect writes they may end up referencing the GGTT PTE
1912                  * after the unbind.
1913                  *
1914                  * Note that we may be concurrently poking at the GGTT_WRITE
1915                  * bit from set-domain, as we mark all GGTT vma associated
1916                  * with an object. We know this is for another vma, as we
1917                  * are currently unbinding this one -- so if this vma will be
1918                  * reused, it will be refaulted and have its dirty bit set
1919                  * before the next write.
1920                  */
1921                 i915_vma_flush_writes(vma);
1922
1923                 /* release the fence reg _after_ flushing */
1924                 i915_vma_revoke_fence(vma);
1925
1926                 clear_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
1927         }
1928
1929         __i915_vma_iounmap(vma);
1930
1931         GEM_BUG_ON(vma->fence);
1932         GEM_BUG_ON(i915_vma_has_userfault(vma));
1933
1934         /* Object backend must be async capable. */
1935         GEM_WARN_ON(async && !vma->resource->bi.pages_rsgt);
1936
1937         /* If vm is not open, unbind is a nop. */
1938         vma_res->needs_wakeref = i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND) &&
1939                 kref_read(&vma->vm->ref);
1940         vma_res->skip_pte_rewrite = !kref_read(&vma->vm->ref) ||
1941                 vma->vm->skip_pte_rewrite;
1942         trace_i915_vma_unbind(vma);
1943
1944         unbind_fence = i915_vma_resource_unbind(vma_res);
1945         vma->resource = NULL;
1946
1947         atomic_and(~(I915_VMA_BIND_MASK | I915_VMA_ERROR | I915_VMA_GGTT_WRITE),
1948                    &vma->flags);
1949
1950         i915_vma_detach(vma);
1951
1952         if (!async && unbind_fence) {
1953                 dma_fence_wait(unbind_fence, false);
1954                 dma_fence_put(unbind_fence);
1955                 unbind_fence = NULL;
1956         }
1957
1958         /*
1959          * Binding itself may not have completed until the unbind fence signals,
1960          * so don't drop the pages until that happens, unless the resource is
1961          * async_capable.
1962          */
1963
1964         vma_unbind_pages(vma);
1965         return unbind_fence;
1966 }
1967
1968 int __i915_vma_unbind(struct i915_vma *vma)
1969 {
1970         int ret;
1971
1972         lockdep_assert_held(&vma->vm->mutex);
1973         assert_vma_held_evict(vma);
1974
1975         if (!drm_mm_node_allocated(&vma->node))
1976                 return 0;
1977
1978         if (i915_vma_is_pinned(vma)) {
1979                 vma_print_allocator(vma, "is pinned");
1980                 return -EAGAIN;
1981         }
1982
1983         /*
1984          * After confirming that no one else is pinning this vma, wait for
1985          * any laggards who may have crept in during the wait (through
1986          * a residual pin skipping the vm->mutex) to complete.
1987          */
1988         ret = i915_vma_sync(vma);
1989         if (ret)
1990                 return ret;
1991
1992         GEM_BUG_ON(i915_vma_is_active(vma));
1993         __i915_vma_evict(vma, false);
1994
1995         drm_mm_remove_node(&vma->node); /* pairs with i915_vma_release() */
1996         return 0;
1997 }
1998
1999 static struct dma_fence *__i915_vma_unbind_async(struct i915_vma *vma)
2000 {
2001         struct dma_fence *fence;
2002
2003         lockdep_assert_held(&vma->vm->mutex);
2004
2005         if (!drm_mm_node_allocated(&vma->node))
2006                 return NULL;
2007
2008         if (i915_vma_is_pinned(vma) ||
2009             &vma->obj->mm.rsgt->table != vma->resource->bi.pages)
2010                 return ERR_PTR(-EAGAIN);
2011
2012         /*
2013          * We probably need to replace this with awaiting the fences of the
2014          * object's dma_resv when the vma active goes away. When doing that
2015          * we need to be careful to not add the vma_resource unbind fence
2016          * immediately to the object's dma_resv, because then unbinding
2017          * the next vma from the object, in case there are many, will
2018          * actually await the unbinding of the previous vmas, which is
2019          * undesirable.
2020          */
2021         if (i915_sw_fence_await_active(&vma->resource->chain, &vma->active,
2022                                        I915_ACTIVE_AWAIT_EXCL |
2023                                        I915_ACTIVE_AWAIT_ACTIVE) < 0) {
2024                 return ERR_PTR(-EBUSY);
2025         }
2026
2027         fence = __i915_vma_evict(vma, true);
2028
2029         drm_mm_remove_node(&vma->node); /* pairs with i915_vma_release() */
2030
2031         return fence;
2032 }
2033
2034 int i915_vma_unbind(struct i915_vma *vma)
2035 {
2036         struct i915_address_space *vm = vma->vm;
2037         intel_wakeref_t wakeref = 0;
2038         int err;
2039
2040         assert_object_held_shared(vma->obj);
2041
2042         /* Optimistic wait before taking the mutex */
2043         err = i915_vma_sync(vma);
2044         if (err)
2045                 return err;
2046
2047         if (!drm_mm_node_allocated(&vma->node))
2048                 return 0;
2049
2050         if (i915_vma_is_pinned(vma)) {
2051                 vma_print_allocator(vma, "is pinned");
2052                 return -EAGAIN;
2053         }
2054
2055         if (i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND))
2056                 /* XXX not always required: nop_clear_range */
2057                 wakeref = intel_runtime_pm_get(&vm->i915->runtime_pm);
2058
2059         err = mutex_lock_interruptible_nested(&vma->vm->mutex, !wakeref);
2060         if (err)
2061                 goto out_rpm;
2062
2063         err = __i915_vma_unbind(vma);
2064         mutex_unlock(&vm->mutex);
2065
2066 out_rpm:
2067         if (wakeref)
2068                 intel_runtime_pm_put(&vm->i915->runtime_pm, wakeref);
2069         return err;
2070 }
2071
2072 int i915_vma_unbind_async(struct i915_vma *vma, bool trylock_vm)
2073 {
2074         struct drm_i915_gem_object *obj = vma->obj;
2075         struct i915_address_space *vm = vma->vm;
2076         intel_wakeref_t wakeref = 0;
2077         struct dma_fence *fence;
2078         int err;
2079
2080         /*
2081          * We need the dma-resv lock since we add the
2082          * unbind fence to the dma-resv object.
2083          */
2084         assert_object_held(obj);
2085
2086         if (!drm_mm_node_allocated(&vma->node))
2087                 return 0;
2088
2089         if (i915_vma_is_pinned(vma)) {
2090                 vma_print_allocator(vma, "is pinned");
2091                 return -EAGAIN;
2092         }
2093
2094         if (!obj->mm.rsgt)
2095                 return -EBUSY;
2096
2097         err = dma_resv_reserve_fences(obj->base.resv, 1);
2098         if (err)
2099                 return -EBUSY;
2100
2101         /*
2102          * It would be great if we could grab this wakeref from the
2103          * async unbind work if needed, but we can't because it uses
2104          * kmalloc and it's in the dma-fence signalling critical path.
2105          */
2106         if (i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND))
2107                 wakeref = intel_runtime_pm_get(&vm->i915->runtime_pm);
2108
2109         if (trylock_vm && !mutex_trylock(&vm->mutex)) {
2110                 err = -EBUSY;
2111                 goto out_rpm;
2112         } else if (!trylock_vm) {
2113                 err = mutex_lock_interruptible_nested(&vm->mutex, !wakeref);
2114                 if (err)
2115                         goto out_rpm;
2116         }
2117
2118         fence = __i915_vma_unbind_async(vma);
2119         mutex_unlock(&vm->mutex);
2120         if (IS_ERR_OR_NULL(fence)) {
2121                 err = PTR_ERR_OR_ZERO(fence);
2122                 goto out_rpm;
2123         }
2124
2125         dma_resv_add_fence(obj->base.resv, fence, DMA_RESV_USAGE_READ);
2126         dma_fence_put(fence);
2127
2128 out_rpm:
2129         if (wakeref)
2130                 intel_runtime_pm_put(&vm->i915->runtime_pm, wakeref);
2131         return err;
2132 }
2133
2134 int i915_vma_unbind_unlocked(struct i915_vma *vma)
2135 {
2136         int err;
2137
2138         i915_gem_object_lock(vma->obj, NULL);
2139         err = i915_vma_unbind(vma);
2140         i915_gem_object_unlock(vma->obj);
2141
2142         return err;
2143 }
2144
2145 struct i915_vma *i915_vma_make_unshrinkable(struct i915_vma *vma)
2146 {
2147         i915_gem_object_make_unshrinkable(vma->obj);
2148         return vma;
2149 }
2150
2151 void i915_vma_make_shrinkable(struct i915_vma *vma)
2152 {
2153         i915_gem_object_make_shrinkable(vma->obj);
2154 }
2155
2156 void i915_vma_make_purgeable(struct i915_vma *vma)
2157 {
2158         i915_gem_object_make_purgeable(vma->obj);
2159 }
2160
2161 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2162 #include "selftests/i915_vma.c"
2163 #endif
2164
2165 void i915_vma_module_exit(void)
2166 {
2167         kmem_cache_destroy(slab_vmas);
2168 }
2169
2170 int __init i915_vma_module_init(void)
2171 {
2172         slab_vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
2173         if (!slab_vmas)
2174                 return -ENOMEM;
2175
2176         return 0;
2177 }