Merge drm/drm-next into drm-intel-gt-next
[platform/kernel/linux-rpi.git] / drivers / gpu / drm / i915 / gem / i915_gem_ttm.c
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2021 Intel Corporation
4  */
5
6 #include <linux/shmem_fs.h>
7
8 #include <drm/ttm/ttm_bo_driver.h>
9 #include <drm/ttm/ttm_placement.h>
10 #include <drm/drm_buddy.h>
11
12 #include "i915_drv.h"
13 #include "i915_ttm_buddy_manager.h"
14 #include "intel_memory_region.h"
15 #include "intel_region_ttm.h"
16
17 #include "gem/i915_gem_mman.h"
18 #include "gem/i915_gem_object.h"
19 #include "gem/i915_gem_region.h"
20 #include "gem/i915_gem_ttm.h"
21 #include "gem/i915_gem_ttm_move.h"
22 #include "gem/i915_gem_ttm_pm.h"
23
24 #define I915_TTM_PRIO_PURGE     0
25 #define I915_TTM_PRIO_NO_PAGES  1
26 #define I915_TTM_PRIO_HAS_PAGES 2
27 #define I915_TTM_PRIO_NEEDS_CPU_ACCESS 3
28
29 /*
30  * Size of struct ttm_place vector in on-stack struct ttm_placement allocs
31  */
32 #define I915_TTM_MAX_PLACEMENTS INTEL_REGION_UNKNOWN
33
34 /**
35  * struct i915_ttm_tt - TTM page vector with additional private information
36  * @ttm: The base TTM page vector.
37  * @dev: The struct device used for dma mapping and unmapping.
38  * @cached_rsgt: The cached scatter-gather table.
39  * @is_shmem: Set if using shmem.
40  * @filp: The shmem file, if using shmem backend.
41  *
42  * Note that DMA may be going on right up to the point where the page-
43  * vector is unpopulated in delayed destroy. Hence keep the
44  * scatter-gather table mapped and cached up to that point. This is
45  * different from the cached gem object io scatter-gather table which
46  * doesn't have an associated dma mapping.
47  */
48 struct i915_ttm_tt {
49         struct ttm_tt ttm;
50         struct device *dev;
51         struct i915_refct_sgt cached_rsgt;
52
53         bool is_shmem;
54         struct file *filp;
55 };
56
57 static const struct ttm_place sys_placement_flags = {
58         .fpfn = 0,
59         .lpfn = 0,
60         .mem_type = I915_PL_SYSTEM,
61         .flags = 0,
62 };
63
64 static struct ttm_placement i915_sys_placement = {
65         .num_placement = 1,
66         .placement = &sys_placement_flags,
67         .num_busy_placement = 1,
68         .busy_placement = &sys_placement_flags,
69 };
70
71 /**
72  * i915_ttm_sys_placement - Return the struct ttm_placement to be
73  * used for an object in system memory.
74  *
75  * Rather than making the struct extern, use this
76  * function.
77  *
78  * Return: A pointer to a static variable for sys placement.
79  */
80 struct ttm_placement *i915_ttm_sys_placement(void)
81 {
82         return &i915_sys_placement;
83 }
84
85 static int i915_ttm_err_to_gem(int err)
86 {
87         /* Fastpath */
88         if (likely(!err))
89                 return 0;
90
91         switch (err) {
92         case -EBUSY:
93                 /*
94                  * TTM likes to convert -EDEADLK to -EBUSY, and wants us to
95                  * restart the operation, since we don't record the contending
96                  * lock. We use -EAGAIN to restart.
97                  */
98                 return -EAGAIN;
99         case -ENOSPC:
100                 /*
101                  * Memory type / region is full, and we can't evict.
102                  * Except possibly system, that returns -ENOMEM;
103                  */
104                 return -ENXIO;
105         default:
106                 break;
107         }
108
109         return err;
110 }
111
112 static enum ttm_caching
113 i915_ttm_select_tt_caching(const struct drm_i915_gem_object *obj)
114 {
115         /*
116          * Objects only allowed in system get cached cpu-mappings, or when
117          * evicting lmem-only buffers to system for swapping. Other objects get
118          * WC mapping for now. Even if in system.
119          */
120         if (obj->mm.n_placements <= 1)
121                 return ttm_cached;
122
123         return ttm_write_combined;
124 }
125
126 static void
127 i915_ttm_place_from_region(const struct intel_memory_region *mr,
128                            struct ttm_place *place,
129                            resource_size_t offset,
130                            resource_size_t size,
131                            unsigned int flags)
132 {
133         memset(place, 0, sizeof(*place));
134         place->mem_type = intel_region_to_ttm_type(mr);
135
136         if (mr->type == INTEL_MEMORY_SYSTEM)
137                 return;
138
139         if (flags & I915_BO_ALLOC_CONTIGUOUS)
140                 place->flags |= TTM_PL_FLAG_CONTIGUOUS;
141         if (offset != I915_BO_INVALID_OFFSET) {
142                 place->fpfn = offset >> PAGE_SHIFT;
143                 place->lpfn = place->fpfn + (size >> PAGE_SHIFT);
144         } else if (mr->io_size && mr->io_size < mr->total) {
145                 if (flags & I915_BO_ALLOC_GPU_ONLY) {
146                         place->flags |= TTM_PL_FLAG_TOPDOWN;
147                 } else {
148                         place->fpfn = 0;
149                         place->lpfn = mr->io_size >> PAGE_SHIFT;
150                 }
151         }
152 }
153
154 static void
155 i915_ttm_placement_from_obj(const struct drm_i915_gem_object *obj,
156                             struct ttm_place *requested,
157                             struct ttm_place *busy,
158                             struct ttm_placement *placement)
159 {
160         unsigned int num_allowed = obj->mm.n_placements;
161         unsigned int flags = obj->flags;
162         unsigned int i;
163
164         placement->num_placement = 1;
165         i915_ttm_place_from_region(num_allowed ? obj->mm.placements[0] :
166                                    obj->mm.region, requested, obj->bo_offset,
167                                    obj->base.size, flags);
168
169         /* Cache this on object? */
170         placement->num_busy_placement = num_allowed;
171         for (i = 0; i < placement->num_busy_placement; ++i)
172                 i915_ttm_place_from_region(obj->mm.placements[i], busy + i,
173                                            obj->bo_offset, obj->base.size, flags);
174
175         if (num_allowed == 0) {
176                 *busy = *requested;
177                 placement->num_busy_placement = 1;
178         }
179
180         placement->placement = requested;
181         placement->busy_placement = busy;
182 }
183
184 static int i915_ttm_tt_shmem_populate(struct ttm_device *bdev,
185                                       struct ttm_tt *ttm,
186                                       struct ttm_operation_ctx *ctx)
187 {
188         struct drm_i915_private *i915 = container_of(bdev, typeof(*i915), bdev);
189         struct intel_memory_region *mr = i915->mm.regions[INTEL_MEMORY_SYSTEM];
190         struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
191         const unsigned int max_segment = i915_sg_segment_size();
192         const size_t size = (size_t)ttm->num_pages << PAGE_SHIFT;
193         struct file *filp = i915_tt->filp;
194         struct sgt_iter sgt_iter;
195         struct sg_table *st;
196         struct page *page;
197         unsigned long i;
198         int err;
199
200         if (!filp) {
201                 struct address_space *mapping;
202                 gfp_t mask;
203
204                 filp = shmem_file_setup("i915-shmem-tt", size, VM_NORESERVE);
205                 if (IS_ERR(filp))
206                         return PTR_ERR(filp);
207
208                 mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
209
210                 mapping = filp->f_mapping;
211                 mapping_set_gfp_mask(mapping, mask);
212                 GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
213
214                 i915_tt->filp = filp;
215         }
216
217         st = &i915_tt->cached_rsgt.table;
218         err = shmem_sg_alloc_table(i915, st, size, mr, filp->f_mapping,
219                                    max_segment);
220         if (err)
221                 return err;
222
223         err = dma_map_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL,
224                               DMA_ATTR_SKIP_CPU_SYNC);
225         if (err)
226                 goto err_free_st;
227
228         i = 0;
229         for_each_sgt_page(page, sgt_iter, st)
230                 ttm->pages[i++] = page;
231
232         if (ttm->page_flags & TTM_TT_FLAG_SWAPPED)
233                 ttm->page_flags &= ~TTM_TT_FLAG_SWAPPED;
234
235         return 0;
236
237 err_free_st:
238         shmem_sg_free_table(st, filp->f_mapping, false, false);
239
240         return err;
241 }
242
243 static void i915_ttm_tt_shmem_unpopulate(struct ttm_tt *ttm)
244 {
245         struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
246         bool backup = ttm->page_flags & TTM_TT_FLAG_SWAPPED;
247         struct sg_table *st = &i915_tt->cached_rsgt.table;
248
249         shmem_sg_free_table(st, file_inode(i915_tt->filp)->i_mapping,
250                             backup, backup);
251 }
252
253 static void i915_ttm_tt_release(struct kref *ref)
254 {
255         struct i915_ttm_tt *i915_tt =
256                 container_of(ref, typeof(*i915_tt), cached_rsgt.kref);
257         struct sg_table *st = &i915_tt->cached_rsgt.table;
258
259         GEM_WARN_ON(st->sgl);
260
261         kfree(i915_tt);
262 }
263
264 static const struct i915_refct_sgt_ops tt_rsgt_ops = {
265         .release = i915_ttm_tt_release
266 };
267
268 static struct ttm_tt *i915_ttm_tt_create(struct ttm_buffer_object *bo,
269                                          uint32_t page_flags)
270 {
271         struct ttm_resource_manager *man =
272                 ttm_manager_type(bo->bdev, bo->resource->mem_type);
273         struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
274         enum ttm_caching caching;
275         struct i915_ttm_tt *i915_tt;
276         int ret;
277
278         if (!obj)
279                 return NULL;
280
281         i915_tt = kzalloc(sizeof(*i915_tt), GFP_KERNEL);
282         if (!i915_tt)
283                 return NULL;
284
285         if (obj->flags & I915_BO_ALLOC_CPU_CLEAR &&
286             man->use_tt)
287                 page_flags |= TTM_TT_FLAG_ZERO_ALLOC;
288
289         caching = i915_ttm_select_tt_caching(obj);
290         if (i915_gem_object_is_shrinkable(obj) && caching == ttm_cached) {
291                 page_flags |= TTM_TT_FLAG_EXTERNAL |
292                               TTM_TT_FLAG_EXTERNAL_MAPPABLE;
293                 i915_tt->is_shmem = true;
294         }
295
296         ret = ttm_tt_init(&i915_tt->ttm, bo, page_flags, caching, 0);
297         if (ret)
298                 goto err_free;
299
300         __i915_refct_sgt_init(&i915_tt->cached_rsgt, bo->base.size,
301                               &tt_rsgt_ops);
302
303         i915_tt->dev = obj->base.dev->dev;
304
305         return &i915_tt->ttm;
306
307 err_free:
308         kfree(i915_tt);
309         return NULL;
310 }
311
312 static int i915_ttm_tt_populate(struct ttm_device *bdev,
313                                 struct ttm_tt *ttm,
314                                 struct ttm_operation_ctx *ctx)
315 {
316         struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
317
318         if (i915_tt->is_shmem)
319                 return i915_ttm_tt_shmem_populate(bdev, ttm, ctx);
320
321         return ttm_pool_alloc(&bdev->pool, ttm, ctx);
322 }
323
324 static void i915_ttm_tt_unpopulate(struct ttm_device *bdev, struct ttm_tt *ttm)
325 {
326         struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
327         struct sg_table *st = &i915_tt->cached_rsgt.table;
328
329         if (st->sgl)
330                 dma_unmap_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL, 0);
331
332         if (i915_tt->is_shmem) {
333                 i915_ttm_tt_shmem_unpopulate(ttm);
334         } else {
335                 sg_free_table(st);
336                 ttm_pool_free(&bdev->pool, ttm);
337         }
338 }
339
340 static void i915_ttm_tt_destroy(struct ttm_device *bdev, struct ttm_tt *ttm)
341 {
342         struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
343
344         if (i915_tt->filp)
345                 fput(i915_tt->filp);
346
347         ttm_tt_fini(ttm);
348         i915_refct_sgt_put(&i915_tt->cached_rsgt);
349 }
350
351 static bool i915_ttm_eviction_valuable(struct ttm_buffer_object *bo,
352                                        const struct ttm_place *place)
353 {
354         struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
355         struct ttm_resource *res = bo->resource;
356
357         if (!obj)
358                 return false;
359
360         /*
361          * EXTERNAL objects should never be swapped out by TTM, instead we need
362          * to handle that ourselves. TTM will already skip such objects for us,
363          * but we would like to avoid grabbing locks for no good reason.
364          */
365         if (bo->ttm && bo->ttm->page_flags & TTM_TT_FLAG_EXTERNAL)
366                 return false;
367
368         /* Will do for now. Our pinned objects are still on TTM's LRU lists */
369         if (!i915_gem_object_evictable(obj))
370                 return false;
371
372         switch (res->mem_type) {
373         case I915_PL_LMEM0: {
374                 struct ttm_resource_manager *man =
375                         ttm_manager_type(bo->bdev, res->mem_type);
376                 struct i915_ttm_buddy_resource *bman_res =
377                         to_ttm_buddy_resource(res);
378                 struct drm_buddy *mm = bman_res->mm;
379                 struct drm_buddy_block *block;
380
381                 if (!place->fpfn && !place->lpfn)
382                         return true;
383
384                 GEM_BUG_ON(!place->lpfn);
385
386                 /*
387                  * If we just want something mappable then we can quickly check
388                  * if the current victim resource is using any of the CPU
389                  * visible portion.
390                  */
391                 if (!place->fpfn &&
392                     place->lpfn == i915_ttm_buddy_man_visible_size(man))
393                         return bman_res->used_visible_size > 0;
394
395                 /* Real range allocation */
396                 list_for_each_entry(block, &bman_res->blocks, link) {
397                         unsigned long fpfn =
398                                 drm_buddy_block_offset(block) >> PAGE_SHIFT;
399                         unsigned long lpfn = fpfn +
400                                 (drm_buddy_block_size(mm, block) >> PAGE_SHIFT);
401
402                         if (place->fpfn < lpfn && place->lpfn > fpfn)
403                                 return true;
404                 }
405                 return false;
406         } default:
407                 break;
408         }
409
410         return true;
411 }
412
413 static void i915_ttm_evict_flags(struct ttm_buffer_object *bo,
414                                  struct ttm_placement *placement)
415 {
416         *placement = i915_sys_placement;
417 }
418
419 /**
420  * i915_ttm_free_cached_io_rsgt - Free object cached LMEM information
421  * @obj: The GEM object
422  * This function frees any LMEM-related information that is cached on
423  * the object. For example the radix tree for fast page lookup and the
424  * cached refcounted sg-table
425  */
426 void i915_ttm_free_cached_io_rsgt(struct drm_i915_gem_object *obj)
427 {
428         struct radix_tree_iter iter;
429         void __rcu **slot;
430
431         if (!obj->ttm.cached_io_rsgt)
432                 return;
433
434         rcu_read_lock();
435         radix_tree_for_each_slot(slot, &obj->ttm.get_io_page.radix, &iter, 0)
436                 radix_tree_delete(&obj->ttm.get_io_page.radix, iter.index);
437         rcu_read_unlock();
438
439         i915_refct_sgt_put(obj->ttm.cached_io_rsgt);
440         obj->ttm.cached_io_rsgt = NULL;
441 }
442
443 /**
444  * i915_ttm_purge - Clear an object of its memory
445  * @obj: The object
446  *
447  * This function is called to clear an object of it's memory when it is
448  * marked as not needed anymore.
449  *
450  * Return: 0 on success, negative error code on failure.
451  */
452 int i915_ttm_purge(struct drm_i915_gem_object *obj)
453 {
454         struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
455         struct i915_ttm_tt *i915_tt =
456                 container_of(bo->ttm, typeof(*i915_tt), ttm);
457         struct ttm_operation_ctx ctx = {
458                 .interruptible = true,
459                 .no_wait_gpu = false,
460         };
461         struct ttm_placement place = {};
462         int ret;
463
464         if (obj->mm.madv == __I915_MADV_PURGED)
465                 return 0;
466
467         ret = ttm_bo_validate(bo, &place, &ctx);
468         if (ret)
469                 return ret;
470
471         if (bo->ttm && i915_tt->filp) {
472                 /*
473                  * The below fput(which eventually calls shmem_truncate) might
474                  * be delayed by worker, so when directly called to purge the
475                  * pages(like by the shrinker) we should try to be more
476                  * aggressive and release the pages immediately.
477                  */
478                 shmem_truncate_range(file_inode(i915_tt->filp),
479                                      0, (loff_t)-1);
480                 fput(fetch_and_zero(&i915_tt->filp));
481         }
482
483         obj->write_domain = 0;
484         obj->read_domains = 0;
485         i915_ttm_adjust_gem_after_move(obj);
486         i915_ttm_free_cached_io_rsgt(obj);
487         obj->mm.madv = __I915_MADV_PURGED;
488
489         return 0;
490 }
491
492 static int i915_ttm_shrink(struct drm_i915_gem_object *obj, unsigned int flags)
493 {
494         struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
495         struct i915_ttm_tt *i915_tt =
496                 container_of(bo->ttm, typeof(*i915_tt), ttm);
497         struct ttm_operation_ctx ctx = {
498                 .interruptible = true,
499                 .no_wait_gpu = flags & I915_GEM_OBJECT_SHRINK_NO_GPU_WAIT,
500         };
501         struct ttm_placement place = {};
502         int ret;
503
504         if (!bo->ttm || bo->resource->mem_type != TTM_PL_SYSTEM)
505                 return 0;
506
507         GEM_BUG_ON(!i915_tt->is_shmem);
508
509         if (!i915_tt->filp)
510                 return 0;
511
512         ret = ttm_bo_wait_ctx(bo, &ctx);
513         if (ret)
514                 return ret;
515
516         switch (obj->mm.madv) {
517         case I915_MADV_DONTNEED:
518                 return i915_ttm_purge(obj);
519         case __I915_MADV_PURGED:
520                 return 0;
521         }
522
523         if (bo->ttm->page_flags & TTM_TT_FLAG_SWAPPED)
524                 return 0;
525
526         bo->ttm->page_flags |= TTM_TT_FLAG_SWAPPED;
527         ret = ttm_bo_validate(bo, &place, &ctx);
528         if (ret) {
529                 bo->ttm->page_flags &= ~TTM_TT_FLAG_SWAPPED;
530                 return ret;
531         }
532
533         if (flags & I915_GEM_OBJECT_SHRINK_WRITEBACK)
534                 __shmem_writeback(obj->base.size, i915_tt->filp->f_mapping);
535
536         return 0;
537 }
538
539 static void i915_ttm_delete_mem_notify(struct ttm_buffer_object *bo)
540 {
541         struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
542
543         if (likely(obj)) {
544                 __i915_gem_object_pages_fini(obj);
545                 i915_ttm_free_cached_io_rsgt(obj);
546         }
547 }
548
549 static struct i915_refct_sgt *i915_ttm_tt_get_st(struct ttm_tt *ttm)
550 {
551         struct i915_ttm_tt *i915_tt = container_of(ttm, typeof(*i915_tt), ttm);
552         struct sg_table *st;
553         int ret;
554
555         if (i915_tt->cached_rsgt.table.sgl)
556                 return i915_refct_sgt_get(&i915_tt->cached_rsgt);
557
558         st = &i915_tt->cached_rsgt.table;
559         ret = sg_alloc_table_from_pages_segment(st,
560                         ttm->pages, ttm->num_pages,
561                         0, (unsigned long)ttm->num_pages << PAGE_SHIFT,
562                         i915_sg_segment_size(), GFP_KERNEL);
563         if (ret) {
564                 st->sgl = NULL;
565                 return ERR_PTR(ret);
566         }
567
568         ret = dma_map_sgtable(i915_tt->dev, st, DMA_BIDIRECTIONAL, 0);
569         if (ret) {
570                 sg_free_table(st);
571                 return ERR_PTR(ret);
572         }
573
574         return i915_refct_sgt_get(&i915_tt->cached_rsgt);
575 }
576
577 /**
578  * i915_ttm_resource_get_st - Get a refcounted sg-table pointing to the
579  * resource memory
580  * @obj: The GEM object used for sg-table caching
581  * @res: The struct ttm_resource for which an sg-table is requested.
582  *
583  * This function returns a refcounted sg-table representing the memory
584  * pointed to by @res. If @res is the object's current resource it may also
585  * cache the sg_table on the object or attempt to access an already cached
586  * sg-table. The refcounted sg-table needs to be put when no-longer in use.
587  *
588  * Return: A valid pointer to a struct i915_refct_sgt or error pointer on
589  * failure.
590  */
591 struct i915_refct_sgt *
592 i915_ttm_resource_get_st(struct drm_i915_gem_object *obj,
593                          struct ttm_resource *res)
594 {
595         struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
596
597         if (!i915_ttm_gtt_binds_lmem(res))
598                 return i915_ttm_tt_get_st(bo->ttm);
599
600         /*
601          * If CPU mapping differs, we need to add the ttm_tt pages to
602          * the resulting st. Might make sense for GGTT.
603          */
604         GEM_WARN_ON(!i915_ttm_cpu_maps_iomem(res));
605         if (bo->resource == res) {
606                 if (!obj->ttm.cached_io_rsgt) {
607                         struct i915_refct_sgt *rsgt;
608
609                         rsgt = intel_region_ttm_resource_to_rsgt(obj->mm.region,
610                                                                  res);
611                         if (IS_ERR(rsgt))
612                                 return rsgt;
613
614                         obj->ttm.cached_io_rsgt = rsgt;
615                 }
616                 return i915_refct_sgt_get(obj->ttm.cached_io_rsgt);
617         }
618
619         return intel_region_ttm_resource_to_rsgt(obj->mm.region, res);
620 }
621
622 static int i915_ttm_truncate(struct drm_i915_gem_object *obj)
623 {
624         struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
625         int err;
626
627         WARN_ON_ONCE(obj->mm.madv == I915_MADV_WILLNEED);
628
629         err = i915_ttm_move_notify(bo);
630         if (err)
631                 return err;
632
633         return i915_ttm_purge(obj);
634 }
635
636 static void i915_ttm_swap_notify(struct ttm_buffer_object *bo)
637 {
638         struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
639         int ret;
640
641         if (!obj)
642                 return;
643
644         ret = i915_ttm_move_notify(bo);
645         GEM_WARN_ON(ret);
646         GEM_WARN_ON(obj->ttm.cached_io_rsgt);
647         if (!ret && obj->mm.madv != I915_MADV_WILLNEED)
648                 i915_ttm_purge(obj);
649 }
650
651 static bool i915_ttm_resource_mappable(struct ttm_resource *res)
652 {
653         struct i915_ttm_buddy_resource *bman_res = to_ttm_buddy_resource(res);
654
655         if (!i915_ttm_cpu_maps_iomem(res))
656                 return true;
657
658         return bman_res->used_visible_size == bman_res->base.num_pages;
659 }
660
661 static int i915_ttm_io_mem_reserve(struct ttm_device *bdev, struct ttm_resource *mem)
662 {
663         if (!i915_ttm_cpu_maps_iomem(mem))
664                 return 0;
665
666         if (!i915_ttm_resource_mappable(mem))
667                 return -EINVAL;
668
669         mem->bus.caching = ttm_write_combined;
670         mem->bus.is_iomem = true;
671
672         return 0;
673 }
674
675 static unsigned long i915_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
676                                          unsigned long page_offset)
677 {
678         struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
679         struct scatterlist *sg;
680         unsigned long base;
681         unsigned int ofs;
682
683         GEM_BUG_ON(!obj);
684         GEM_WARN_ON(bo->ttm);
685
686         base = obj->mm.region->iomap.base - obj->mm.region->region.start;
687         sg = __i915_gem_object_get_sg(obj, &obj->ttm.get_io_page, page_offset, &ofs, true);
688
689         return ((base + sg_dma_address(sg)) >> PAGE_SHIFT) + ofs;
690 }
691
692 /*
693  * All callbacks need to take care not to downcast a struct ttm_buffer_object
694  * without checking its subclass, since it might be a TTM ghost object.
695  */
696 static struct ttm_device_funcs i915_ttm_bo_driver = {
697         .ttm_tt_create = i915_ttm_tt_create,
698         .ttm_tt_populate = i915_ttm_tt_populate,
699         .ttm_tt_unpopulate = i915_ttm_tt_unpopulate,
700         .ttm_tt_destroy = i915_ttm_tt_destroy,
701         .eviction_valuable = i915_ttm_eviction_valuable,
702         .evict_flags = i915_ttm_evict_flags,
703         .move = i915_ttm_move,
704         .swap_notify = i915_ttm_swap_notify,
705         .delete_mem_notify = i915_ttm_delete_mem_notify,
706         .io_mem_reserve = i915_ttm_io_mem_reserve,
707         .io_mem_pfn = i915_ttm_io_mem_pfn,
708 };
709
710 /**
711  * i915_ttm_driver - Return a pointer to the TTM device funcs
712  *
713  * Return: Pointer to statically allocated TTM device funcs.
714  */
715 struct ttm_device_funcs *i915_ttm_driver(void)
716 {
717         return &i915_ttm_bo_driver;
718 }
719
720 static int __i915_ttm_get_pages(struct drm_i915_gem_object *obj,
721                                 struct ttm_placement *placement)
722 {
723         struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
724         struct ttm_operation_ctx ctx = {
725                 .interruptible = true,
726                 .no_wait_gpu = false,
727         };
728         int real_num_busy;
729         int ret;
730
731         /* First try only the requested placement. No eviction. */
732         real_num_busy = fetch_and_zero(&placement->num_busy_placement);
733         ret = ttm_bo_validate(bo, placement, &ctx);
734         if (ret) {
735                 ret = i915_ttm_err_to_gem(ret);
736                 /*
737                  * Anything that wants to restart the operation gets to
738                  * do that.
739                  */
740                 if (ret == -EDEADLK || ret == -EINTR || ret == -ERESTARTSYS ||
741                     ret == -EAGAIN)
742                         return ret;
743
744                 /*
745                  * If the initial attempt fails, allow all accepted placements,
746                  * evicting if necessary.
747                  */
748                 placement->num_busy_placement = real_num_busy;
749                 ret = ttm_bo_validate(bo, placement, &ctx);
750                 if (ret)
751                         return i915_ttm_err_to_gem(ret);
752         }
753
754         if (bo->ttm && !ttm_tt_is_populated(bo->ttm)) {
755                 ret = ttm_tt_populate(bo->bdev, bo->ttm, &ctx);
756                 if (ret)
757                         return ret;
758
759                 i915_ttm_adjust_domains_after_move(obj);
760                 i915_ttm_adjust_gem_after_move(obj);
761         }
762
763         if (!i915_gem_object_has_pages(obj)) {
764                 struct i915_refct_sgt *rsgt =
765                         i915_ttm_resource_get_st(obj, bo->resource);
766
767                 if (IS_ERR(rsgt))
768                         return PTR_ERR(rsgt);
769
770                 GEM_BUG_ON(obj->mm.rsgt);
771                 obj->mm.rsgt = rsgt;
772                 __i915_gem_object_set_pages(obj, &rsgt->table,
773                                             i915_sg_dma_sizes(rsgt->table.sgl));
774         }
775
776         i915_ttm_adjust_lru(obj);
777         return ret;
778 }
779
780 static int i915_ttm_get_pages(struct drm_i915_gem_object *obj)
781 {
782         struct ttm_place requested, busy[I915_TTM_MAX_PLACEMENTS];
783         struct ttm_placement placement;
784
785         GEM_BUG_ON(obj->mm.n_placements > I915_TTM_MAX_PLACEMENTS);
786
787         /* Move to the requested placement. */
788         i915_ttm_placement_from_obj(obj, &requested, busy, &placement);
789
790         return __i915_ttm_get_pages(obj, &placement);
791 }
792
793 /**
794  * DOC: Migration vs eviction
795  *
796  * GEM migration may not be the same as TTM migration / eviction. If
797  * the TTM core decides to evict an object it may be evicted to a
798  * TTM memory type that is not in the object's allowable GEM regions, or
799  * in fact theoretically to a TTM memory type that doesn't correspond to
800  * a GEM memory region. In that case the object's GEM region is not
801  * updated, and the data is migrated back to the GEM region at
802  * get_pages time. TTM may however set up CPU ptes to the object even
803  * when it is evicted.
804  * Gem forced migration using the i915_ttm_migrate() op, is allowed even
805  * to regions that are not in the object's list of allowable placements.
806  */
807 static int __i915_ttm_migrate(struct drm_i915_gem_object *obj,
808                               struct intel_memory_region *mr,
809                               unsigned int flags)
810 {
811         struct ttm_place requested;
812         struct ttm_placement placement;
813         int ret;
814
815         i915_ttm_place_from_region(mr, &requested, obj->bo_offset,
816                                    obj->base.size, flags);
817         placement.num_placement = 1;
818         placement.num_busy_placement = 1;
819         placement.placement = &requested;
820         placement.busy_placement = &requested;
821
822         ret = __i915_ttm_get_pages(obj, &placement);
823         if (ret)
824                 return ret;
825
826         /*
827          * Reinitialize the region bindings. This is primarily
828          * required for objects where the new region is not in
829          * its allowable placements.
830          */
831         if (obj->mm.region != mr) {
832                 i915_gem_object_release_memory_region(obj);
833                 i915_gem_object_init_memory_region(obj, mr);
834         }
835
836         return 0;
837 }
838
839 static int i915_ttm_migrate(struct drm_i915_gem_object *obj,
840                             struct intel_memory_region *mr)
841 {
842         return __i915_ttm_migrate(obj, mr, obj->flags);
843 }
844
845 static void i915_ttm_put_pages(struct drm_i915_gem_object *obj,
846                                struct sg_table *st)
847 {
848         /*
849          * We're currently not called from a shrinker, so put_pages()
850          * typically means the object is about to destroyed, or called
851          * from move_notify(). So just avoid doing much for now.
852          * If the object is not destroyed next, The TTM eviction logic
853          * and shrinkers will move it out if needed.
854          */
855
856         if (obj->mm.rsgt)
857                 i915_refct_sgt_put(fetch_and_zero(&obj->mm.rsgt));
858 }
859
860 /**
861  * i915_ttm_adjust_lru - Adjust an object's position on relevant LRU lists.
862  * @obj: The object
863  */
864 void i915_ttm_adjust_lru(struct drm_i915_gem_object *obj)
865 {
866         struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
867         struct i915_ttm_tt *i915_tt =
868                 container_of(bo->ttm, typeof(*i915_tt), ttm);
869         bool shrinkable =
870                 bo->ttm && i915_tt->filp && ttm_tt_is_populated(bo->ttm);
871
872         /*
873          * Don't manipulate the TTM LRUs while in TTM bo destruction.
874          * We're called through i915_ttm_delete_mem_notify().
875          */
876         if (!kref_read(&bo->kref))
877                 return;
878
879         /*
880          * We skip managing the shrinker LRU in set_pages() and just manage
881          * everything here. This does at least solve the issue with having
882          * temporary shmem mappings(like with evicted lmem) not being visible to
883          * the shrinker. Only our shmem objects are shrinkable, everything else
884          * we keep as unshrinkable.
885          *
886          * To make sure everything plays nice we keep an extra shrink pin in TTM
887          * if the underlying pages are not currently shrinkable. Once we release
888          * our pin, like when the pages are moved to shmem, the pages will then
889          * be added to the shrinker LRU, assuming the caller isn't also holding
890          * a pin.
891          *
892          * TODO: consider maybe also bumping the shrinker list here when we have
893          * already unpinned it, which should give us something more like an LRU.
894          *
895          * TODO: There is a small window of opportunity for this function to
896          * get called from eviction after we've dropped the last GEM refcount,
897          * but before the TTM deleted flag is set on the object. Avoid
898          * adjusting the shrinker list in such cases, since the object is
899          * not available to the shrinker anyway due to its zero refcount.
900          * To fix this properly we should move to a TTM shrinker LRU list for
901          * these objects.
902          */
903         if (kref_get_unless_zero(&obj->base.refcount)) {
904                 if (shrinkable != obj->mm.ttm_shrinkable) {
905                         if (shrinkable) {
906                                 if (obj->mm.madv == I915_MADV_WILLNEED)
907                                         __i915_gem_object_make_shrinkable(obj);
908                                 else
909                                         __i915_gem_object_make_purgeable(obj);
910                         } else {
911                                 i915_gem_object_make_unshrinkable(obj);
912                         }
913
914                         obj->mm.ttm_shrinkable = shrinkable;
915                 }
916                 i915_gem_object_put(obj);
917         }
918
919         /*
920          * Put on the correct LRU list depending on the MADV status
921          */
922         spin_lock(&bo->bdev->lru_lock);
923         if (shrinkable) {
924                 /* Try to keep shmem_tt from being considered for shrinking. */
925                 bo->priority = TTM_MAX_BO_PRIORITY - 1;
926         } else if (obj->mm.madv != I915_MADV_WILLNEED) {
927                 bo->priority = I915_TTM_PRIO_PURGE;
928         } else if (!i915_gem_object_has_pages(obj)) {
929                 bo->priority = I915_TTM_PRIO_NO_PAGES;
930         } else {
931                 struct ttm_resource_manager *man =
932                         ttm_manager_type(bo->bdev, bo->resource->mem_type);
933
934                 /*
935                  * If we need to place an LMEM resource which doesn't need CPU
936                  * access then we should try not to victimize mappable objects
937                  * first, since we likely end up stealing more of the mappable
938                  * portion. And likewise when we try to find space for a mappble
939                  * object, we know not to ever victimize objects that don't
940                  * occupy any mappable pages.
941                  */
942                 if (i915_ttm_cpu_maps_iomem(bo->resource) &&
943                     i915_ttm_buddy_man_visible_size(man) < man->size &&
944                     !(obj->flags & I915_BO_ALLOC_GPU_ONLY))
945                         bo->priority = I915_TTM_PRIO_NEEDS_CPU_ACCESS;
946                 else
947                         bo->priority = I915_TTM_PRIO_HAS_PAGES;
948         }
949
950         ttm_bo_move_to_lru_tail(bo);
951         spin_unlock(&bo->bdev->lru_lock);
952 }
953
954 /*
955  * TTM-backed gem object destruction requires some clarification.
956  * Basically we have two possibilities here. We can either rely on the
957  * i915 delayed destruction and put the TTM object when the object
958  * is idle. This would be detected by TTM which would bypass the
959  * TTM delayed destroy handling. The other approach is to put the TTM
960  * object early and rely on the TTM destroyed handling, and then free
961  * the leftover parts of the GEM object once TTM's destroyed list handling is
962  * complete. For now, we rely on the latter for two reasons:
963  * a) TTM can evict an object even when it's on the delayed destroy list,
964  * which in theory allows for complete eviction.
965  * b) There is work going on in TTM to allow freeing an object even when
966  * it's not idle, and using the TTM destroyed list handling could help us
967  * benefit from that.
968  */
969 static void i915_ttm_delayed_free(struct drm_i915_gem_object *obj)
970 {
971         GEM_BUG_ON(!obj->ttm.created);
972
973         ttm_bo_put(i915_gem_to_ttm(obj));
974 }
975
976 static vm_fault_t vm_fault_ttm(struct vm_fault *vmf)
977 {
978         struct vm_area_struct *area = vmf->vma;
979         struct ttm_buffer_object *bo = area->vm_private_data;
980         struct drm_device *dev = bo->base.dev;
981         struct drm_i915_gem_object *obj;
982         vm_fault_t ret;
983         int idx;
984
985         obj = i915_ttm_to_gem(bo);
986         if (!obj)
987                 return VM_FAULT_SIGBUS;
988
989         /* Sanity check that we allow writing into this object */
990         if (unlikely(i915_gem_object_is_readonly(obj) &&
991                      area->vm_flags & VM_WRITE))
992                 return VM_FAULT_SIGBUS;
993
994         ret = ttm_bo_vm_reserve(bo, vmf);
995         if (ret)
996                 return ret;
997
998         if (obj->mm.madv != I915_MADV_WILLNEED) {
999                 dma_resv_unlock(bo->base.resv);
1000                 return VM_FAULT_SIGBUS;
1001         }
1002
1003         if (!i915_ttm_resource_mappable(bo->resource)) {
1004                 int err = -ENODEV;
1005                 int i;
1006
1007                 for (i = 0; i < obj->mm.n_placements; i++) {
1008                         struct intel_memory_region *mr = obj->mm.placements[i];
1009                         unsigned int flags;
1010
1011                         if (!mr->io_size && mr->type != INTEL_MEMORY_SYSTEM)
1012                                 continue;
1013
1014                         flags = obj->flags;
1015                         flags &= ~I915_BO_ALLOC_GPU_ONLY;
1016                         err = __i915_ttm_migrate(obj, mr, flags);
1017                         if (!err)
1018                                 break;
1019                 }
1020
1021                 if (err) {
1022                         drm_dbg(dev, "Unable to make resource CPU accessible\n");
1023                         dma_resv_unlock(bo->base.resv);
1024                         return VM_FAULT_SIGBUS;
1025                 }
1026         }
1027
1028         if (drm_dev_enter(dev, &idx)) {
1029                 ret = ttm_bo_vm_fault_reserved(vmf, vmf->vma->vm_page_prot,
1030                                                TTM_BO_VM_NUM_PREFAULT);
1031                 drm_dev_exit(idx);
1032         } else {
1033                 ret = ttm_bo_vm_dummy_page(vmf, vmf->vma->vm_page_prot);
1034         }
1035         if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
1036                 return ret;
1037
1038         i915_ttm_adjust_lru(obj);
1039
1040         dma_resv_unlock(bo->base.resv);
1041         return ret;
1042 }
1043
1044 static int
1045 vm_access_ttm(struct vm_area_struct *area, unsigned long addr,
1046               void *buf, int len, int write)
1047 {
1048         struct drm_i915_gem_object *obj =
1049                 i915_ttm_to_gem(area->vm_private_data);
1050
1051         if (i915_gem_object_is_readonly(obj) && write)
1052                 return -EACCES;
1053
1054         return ttm_bo_vm_access(area, addr, buf, len, write);
1055 }
1056
1057 static void ttm_vm_open(struct vm_area_struct *vma)
1058 {
1059         struct drm_i915_gem_object *obj =
1060                 i915_ttm_to_gem(vma->vm_private_data);
1061
1062         GEM_BUG_ON(!obj);
1063         i915_gem_object_get(obj);
1064 }
1065
1066 static void ttm_vm_close(struct vm_area_struct *vma)
1067 {
1068         struct drm_i915_gem_object *obj =
1069                 i915_ttm_to_gem(vma->vm_private_data);
1070
1071         GEM_BUG_ON(!obj);
1072         i915_gem_object_put(obj);
1073 }
1074
1075 static const struct vm_operations_struct vm_ops_ttm = {
1076         .fault = vm_fault_ttm,
1077         .access = vm_access_ttm,
1078         .open = ttm_vm_open,
1079         .close = ttm_vm_close,
1080 };
1081
1082 static u64 i915_ttm_mmap_offset(struct drm_i915_gem_object *obj)
1083 {
1084         /* The ttm_bo must be allocated with I915_BO_ALLOC_USER */
1085         GEM_BUG_ON(!drm_mm_node_allocated(&obj->base.vma_node.vm_node));
1086
1087         return drm_vma_node_offset_addr(&obj->base.vma_node);
1088 }
1089
1090 static void i915_ttm_unmap_virtual(struct drm_i915_gem_object *obj)
1091 {
1092         ttm_bo_unmap_virtual(i915_gem_to_ttm(obj));
1093 }
1094
1095 static const struct drm_i915_gem_object_ops i915_gem_ttm_obj_ops = {
1096         .name = "i915_gem_object_ttm",
1097         .flags = I915_GEM_OBJECT_IS_SHRINKABLE |
1098                  I915_GEM_OBJECT_SELF_MANAGED_SHRINK_LIST,
1099
1100         .get_pages = i915_ttm_get_pages,
1101         .put_pages = i915_ttm_put_pages,
1102         .truncate = i915_ttm_truncate,
1103         .shrink = i915_ttm_shrink,
1104
1105         .adjust_lru = i915_ttm_adjust_lru,
1106         .delayed_free = i915_ttm_delayed_free,
1107         .migrate = i915_ttm_migrate,
1108
1109         .mmap_offset = i915_ttm_mmap_offset,
1110         .unmap_virtual = i915_ttm_unmap_virtual,
1111         .mmap_ops = &vm_ops_ttm,
1112 };
1113
1114 void i915_ttm_bo_destroy(struct ttm_buffer_object *bo)
1115 {
1116         struct drm_i915_gem_object *obj = i915_ttm_to_gem(bo);
1117
1118         i915_gem_object_release_memory_region(obj);
1119         mutex_destroy(&obj->ttm.get_io_page.lock);
1120
1121         if (obj->ttm.created) {
1122                 /*
1123                  * We freely manage the shrinker LRU outide of the mm.pages life
1124                  * cycle. As a result when destroying the object we should be
1125                  * extra paranoid and ensure we remove it from the LRU, before
1126                  * we free the object.
1127                  *
1128                  * Touching the ttm_shrinkable outside of the object lock here
1129                  * should be safe now that the last GEM object ref was dropped.
1130                  */
1131                 if (obj->mm.ttm_shrinkable)
1132                         i915_gem_object_make_unshrinkable(obj);
1133
1134                 i915_ttm_backup_free(obj);
1135
1136                 /* This releases all gem object bindings to the backend. */
1137                 __i915_gem_free_object(obj);
1138
1139                 call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
1140         } else {
1141                 __i915_gem_object_fini(obj);
1142         }
1143 }
1144
1145 /**
1146  * __i915_gem_ttm_object_init - Initialize a ttm-backed i915 gem object
1147  * @mem: The initial memory region for the object.
1148  * @obj: The gem object.
1149  * @size: Object size in bytes.
1150  * @flags: gem object flags.
1151  *
1152  * Return: 0 on success, negative error code on failure.
1153  */
1154 int __i915_gem_ttm_object_init(struct intel_memory_region *mem,
1155                                struct drm_i915_gem_object *obj,
1156                                resource_size_t offset,
1157                                resource_size_t size,
1158                                resource_size_t page_size,
1159                                unsigned int flags)
1160 {
1161         static struct lock_class_key lock_class;
1162         struct drm_i915_private *i915 = mem->i915;
1163         struct ttm_operation_ctx ctx = {
1164                 .interruptible = true,
1165                 .no_wait_gpu = false,
1166         };
1167         enum ttm_bo_type bo_type;
1168         int ret;
1169
1170         drm_gem_private_object_init(&i915->drm, &obj->base, size);
1171         i915_gem_object_init(obj, &i915_gem_ttm_obj_ops, &lock_class, flags);
1172
1173         obj->bo_offset = offset;
1174
1175         /* Don't put on a region list until we're either locked or fully initialized. */
1176         obj->mm.region = mem;
1177         INIT_LIST_HEAD(&obj->mm.region_link);
1178
1179         INIT_RADIX_TREE(&obj->ttm.get_io_page.radix, GFP_KERNEL | __GFP_NOWARN);
1180         mutex_init(&obj->ttm.get_io_page.lock);
1181         bo_type = (obj->flags & I915_BO_ALLOC_USER) ? ttm_bo_type_device :
1182                 ttm_bo_type_kernel;
1183
1184         obj->base.vma_node.driver_private = i915_gem_to_ttm(obj);
1185
1186         /* Forcing the page size is kernel internal only */
1187         GEM_BUG_ON(page_size && obj->mm.n_placements);
1188
1189         /*
1190          * Keep an extra shrink pin to prevent the object from being made
1191          * shrinkable too early. If the ttm_tt is ever allocated in shmem, we
1192          * drop the pin. The TTM backend manages the shrinker LRU itself,
1193          * outside of the normal mm.pages life cycle.
1194          */
1195         i915_gem_object_make_unshrinkable(obj);
1196
1197         /*
1198          * If this function fails, it will call the destructor, but
1199          * our caller still owns the object. So no freeing in the
1200          * destructor until obj->ttm.created is true.
1201          * Similarly, in delayed_destroy, we can't call ttm_bo_put()
1202          * until successful initialization.
1203          */
1204         ret = ttm_bo_init_reserved(&i915->bdev, i915_gem_to_ttm(obj), size,
1205                                    bo_type, &i915_sys_placement,
1206                                    page_size >> PAGE_SHIFT,
1207                                    &ctx, NULL, NULL, i915_ttm_bo_destroy);
1208         if (ret)
1209                 return i915_ttm_err_to_gem(ret);
1210
1211         obj->ttm.created = true;
1212         i915_gem_object_release_memory_region(obj);
1213         i915_gem_object_init_memory_region(obj, mem);
1214         i915_ttm_adjust_domains_after_move(obj);
1215         i915_ttm_adjust_gem_after_move(obj);
1216         i915_gem_object_unlock(obj);
1217
1218         return 0;
1219 }
1220
1221 static const struct intel_memory_region_ops ttm_system_region_ops = {
1222         .init_object = __i915_gem_ttm_object_init,
1223         .release = intel_region_ttm_fini,
1224 };
1225
1226 struct intel_memory_region *
1227 i915_gem_ttm_system_setup(struct drm_i915_private *i915,
1228                           u16 type, u16 instance)
1229 {
1230         struct intel_memory_region *mr;
1231
1232         mr = intel_memory_region_create(i915, 0,
1233                                         totalram_pages() << PAGE_SHIFT,
1234                                         PAGE_SIZE, 0, 0,
1235                                         type, instance,
1236                                         &ttm_system_region_ops);
1237         if (IS_ERR(mr))
1238                 return mr;
1239
1240         intel_memory_region_set_name(mr, "system-ttm");
1241         return mr;
1242 }