drm/ttm: Do not add non-system domain BO into swap list
[linux-2.6-microblaze.git] / drivers / gpu / drm / ttm / ttm_bo.c
1 /* SPDX-License-Identifier: GPL-2.0 OR MIT */
2 /**************************************************************************
3  *
4  * Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the
9  * "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sub license, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  *
15  * The above copyright notice and this permission notice (including the
16  * next paragraph) shall be included in all copies or substantial portions
17  * of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
22  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
23  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
25  * USE OR OTHER DEALINGS IN THE SOFTWARE.
26  *
27  **************************************************************************/
28 /*
29  * Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
30  */
31
32 #define pr_fmt(fmt) "[TTM] " fmt
33
34 #include <drm/ttm/ttm_bo_driver.h>
35 #include <drm/ttm/ttm_placement.h>
36 #include <linux/jiffies.h>
37 #include <linux/slab.h>
38 #include <linux/sched.h>
39 #include <linux/mm.h>
40 #include <linux/file.h>
41 #include <linux/module.h>
42 #include <linux/atomic.h>
43 #include <linux/dma-resv.h>
44
45 #include "ttm_module.h"
46
47 /* default destructor */
48 static void ttm_bo_default_destroy(struct ttm_buffer_object *bo)
49 {
50         kfree(bo);
51 }
52
53 static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
54                                         struct ttm_placement *placement)
55 {
56         struct drm_printer p = drm_debug_printer(TTM_PFX);
57         struct ttm_resource_manager *man;
58         int i, mem_type;
59
60         drm_printf(&p, "No space for %p (%lu pages, %zuK, %zuM)\n",
61                    bo, bo->mem.num_pages, bo->base.size >> 10,
62                    bo->base.size >> 20);
63         for (i = 0; i < placement->num_placement; i++) {
64                 mem_type = placement->placement[i].mem_type;
65                 drm_printf(&p, "  placement[%d]=0x%08X (%d)\n",
66                            i, placement->placement[i].flags, mem_type);
67                 man = ttm_manager_type(bo->bdev, mem_type);
68                 ttm_resource_manager_debug(man, &p);
69         }
70 }
71
72 static void ttm_bo_del_from_lru(struct ttm_buffer_object *bo)
73 {
74         struct ttm_device *bdev = bo->bdev;
75
76         list_del_init(&bo->swap);
77         list_del_init(&bo->lru);
78
79         if (bdev->funcs->del_from_lru_notify)
80                 bdev->funcs->del_from_lru_notify(bo);
81 }
82
83 static void ttm_bo_bulk_move_set_pos(struct ttm_lru_bulk_move_pos *pos,
84                                      struct ttm_buffer_object *bo)
85 {
86         if (!pos->first)
87                 pos->first = bo;
88         pos->last = bo;
89 }
90
91 void ttm_bo_move_to_lru_tail(struct ttm_buffer_object *bo,
92                              struct ttm_resource *mem,
93                              struct ttm_lru_bulk_move *bulk)
94 {
95         struct ttm_device *bdev = bo->bdev;
96         struct ttm_resource_manager *man;
97
98         dma_resv_assert_held(bo->base.resv);
99
100         if (bo->pin_count) {
101                 ttm_bo_del_from_lru(bo);
102                 return;
103         }
104
105         man = ttm_manager_type(bdev, mem->mem_type);
106         list_move_tail(&bo->lru, &man->lru[bo->priority]);
107         if (man->use_tt && bo->ttm &&
108             !(bo->ttm->page_flags & (TTM_PAGE_FLAG_SG |
109                                      TTM_PAGE_FLAG_SWAPPED))) {
110                 struct list_head *swap;
111
112                 swap = &ttm_glob.swap_lru[bo->priority];
113                 list_move_tail(&bo->swap, swap);
114         } else {
115                 list_del_init(&bo->swap);
116         }
117
118         if (bdev->funcs->del_from_lru_notify)
119                 bdev->funcs->del_from_lru_notify(bo);
120
121         if (bulk && !bo->pin_count) {
122                 switch (bo->mem.mem_type) {
123                 case TTM_PL_TT:
124                         ttm_bo_bulk_move_set_pos(&bulk->tt[bo->priority], bo);
125                         break;
126
127                 case TTM_PL_VRAM:
128                         ttm_bo_bulk_move_set_pos(&bulk->vram[bo->priority], bo);
129                         break;
130                 }
131                 if (bo->ttm && !(bo->ttm->page_flags &
132                                  (TTM_PAGE_FLAG_SG | TTM_PAGE_FLAG_SWAPPED)))
133                         ttm_bo_bulk_move_set_pos(&bulk->swap[bo->priority], bo);
134         }
135 }
136 EXPORT_SYMBOL(ttm_bo_move_to_lru_tail);
137
138 void ttm_bo_bulk_move_lru_tail(struct ttm_lru_bulk_move *bulk)
139 {
140         unsigned i;
141
142         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
143                 struct ttm_lru_bulk_move_pos *pos = &bulk->tt[i];
144                 struct ttm_resource_manager *man;
145
146                 if (!pos->first)
147                         continue;
148
149                 dma_resv_assert_held(pos->first->base.resv);
150                 dma_resv_assert_held(pos->last->base.resv);
151
152                 man = ttm_manager_type(pos->first->bdev, TTM_PL_TT);
153                 list_bulk_move_tail(&man->lru[i], &pos->first->lru,
154                                     &pos->last->lru);
155         }
156
157         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
158                 struct ttm_lru_bulk_move_pos *pos = &bulk->vram[i];
159                 struct ttm_resource_manager *man;
160
161                 if (!pos->first)
162                         continue;
163
164                 dma_resv_assert_held(pos->first->base.resv);
165                 dma_resv_assert_held(pos->last->base.resv);
166
167                 man = ttm_manager_type(pos->first->bdev, TTM_PL_VRAM);
168                 list_bulk_move_tail(&man->lru[i], &pos->first->lru,
169                                     &pos->last->lru);
170         }
171
172         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
173                 struct ttm_lru_bulk_move_pos *pos = &bulk->swap[i];
174                 struct list_head *lru;
175
176                 if (!pos->first)
177                         continue;
178
179                 dma_resv_assert_held(pos->first->base.resv);
180                 dma_resv_assert_held(pos->last->base.resv);
181
182                 lru = &ttm_glob.swap_lru[i];
183                 list_bulk_move_tail(lru, &pos->first->swap, &pos->last->swap);
184         }
185 }
186 EXPORT_SYMBOL(ttm_bo_bulk_move_lru_tail);
187
188 static int ttm_bo_handle_move_mem(struct ttm_buffer_object *bo,
189                                   struct ttm_resource *mem, bool evict,
190                                   struct ttm_operation_ctx *ctx,
191                                   struct ttm_place *hop)
192 {
193         struct ttm_device *bdev = bo->bdev;
194         struct ttm_resource_manager *old_man = ttm_manager_type(bdev, bo->mem.mem_type);
195         struct ttm_resource_manager *new_man = ttm_manager_type(bdev, mem->mem_type);
196         int ret;
197
198         ttm_bo_unmap_virtual(bo);
199
200         /*
201          * Create and bind a ttm if required.
202          */
203
204         if (new_man->use_tt) {
205                 /* Zero init the new TTM structure if the old location should
206                  * have used one as well.
207                  */
208                 ret = ttm_tt_create(bo, old_man->use_tt);
209                 if (ret)
210                         goto out_err;
211
212                 if (mem->mem_type != TTM_PL_SYSTEM) {
213                         ret = ttm_tt_populate(bo->bdev, bo->ttm, ctx);
214                         if (ret)
215                                 goto out_err;
216                 }
217         }
218
219         ret = bdev->funcs->move(bo, evict, ctx, mem, hop);
220         if (ret) {
221                 if (ret == -EMULTIHOP)
222                         return ret;
223                 goto out_err;
224         }
225
226         ctx->bytes_moved += bo->base.size;
227         return 0;
228
229 out_err:
230         new_man = ttm_manager_type(bdev, bo->mem.mem_type);
231         if (!new_man->use_tt)
232                 ttm_bo_tt_destroy(bo);
233
234         return ret;
235 }
236
237 /*
238  * Call bo::reserved.
239  * Will release GPU memory type usage on destruction.
240  * This is the place to put in driver specific hooks to release
241  * driver private resources.
242  * Will release the bo::reserved lock.
243  */
244
245 static void ttm_bo_cleanup_memtype_use(struct ttm_buffer_object *bo)
246 {
247         if (bo->bdev->funcs->delete_mem_notify)
248                 bo->bdev->funcs->delete_mem_notify(bo);
249
250         ttm_bo_tt_destroy(bo);
251         ttm_resource_free(bo, &bo->mem);
252 }
253
254 static int ttm_bo_individualize_resv(struct ttm_buffer_object *bo)
255 {
256         int r;
257
258         if (bo->base.resv == &bo->base._resv)
259                 return 0;
260
261         BUG_ON(!dma_resv_trylock(&bo->base._resv));
262
263         r = dma_resv_copy_fences(&bo->base._resv, bo->base.resv);
264         dma_resv_unlock(&bo->base._resv);
265         if (r)
266                 return r;
267
268         if (bo->type != ttm_bo_type_sg) {
269                 /* This works because the BO is about to be destroyed and nobody
270                  * reference it any more. The only tricky case is the trylock on
271                  * the resv object while holding the lru_lock.
272                  */
273                 spin_lock(&ttm_glob.lru_lock);
274                 bo->base.resv = &bo->base._resv;
275                 spin_unlock(&ttm_glob.lru_lock);
276         }
277
278         return r;
279 }
280
281 static void ttm_bo_flush_all_fences(struct ttm_buffer_object *bo)
282 {
283         struct dma_resv *resv = &bo->base._resv;
284         struct dma_resv_list *fobj;
285         struct dma_fence *fence;
286         int i;
287
288         rcu_read_lock();
289         fobj = rcu_dereference(resv->fence);
290         fence = rcu_dereference(resv->fence_excl);
291         if (fence && !fence->ops->signaled)
292                 dma_fence_enable_sw_signaling(fence);
293
294         for (i = 0; fobj && i < fobj->shared_count; ++i) {
295                 fence = rcu_dereference(fobj->shared[i]);
296
297                 if (!fence->ops->signaled)
298                         dma_fence_enable_sw_signaling(fence);
299         }
300         rcu_read_unlock();
301 }
302
303 /**
304  * function ttm_bo_cleanup_refs
305  * If bo idle, remove from lru lists, and unref.
306  * If not idle, block if possible.
307  *
308  * Must be called with lru_lock and reservation held, this function
309  * will drop the lru lock and optionally the reservation lock before returning.
310  *
311  * @bo:                    The buffer object to clean-up
312  * @interruptible:         Any sleeps should occur interruptibly.
313  * @no_wait_gpu:           Never wait for gpu. Return -EBUSY instead.
314  * @unlock_resv:           Unlock the reservation lock as well.
315  */
316
317 static int ttm_bo_cleanup_refs(struct ttm_buffer_object *bo,
318                                bool interruptible, bool no_wait_gpu,
319                                bool unlock_resv)
320 {
321         struct dma_resv *resv = &bo->base._resv;
322         int ret;
323
324         if (dma_resv_test_signaled_rcu(resv, true))
325                 ret = 0;
326         else
327                 ret = -EBUSY;
328
329         if (ret && !no_wait_gpu) {
330                 long lret;
331
332                 if (unlock_resv)
333                         dma_resv_unlock(bo->base.resv);
334                 spin_unlock(&ttm_glob.lru_lock);
335
336                 lret = dma_resv_wait_timeout_rcu(resv, true, interruptible,
337                                                  30 * HZ);
338
339                 if (lret < 0)
340                         return lret;
341                 else if (lret == 0)
342                         return -EBUSY;
343
344                 spin_lock(&ttm_glob.lru_lock);
345                 if (unlock_resv && !dma_resv_trylock(bo->base.resv)) {
346                         /*
347                          * We raced, and lost, someone else holds the reservation now,
348                          * and is probably busy in ttm_bo_cleanup_memtype_use.
349                          *
350                          * Even if it's not the case, because we finished waiting any
351                          * delayed destruction would succeed, so just return success
352                          * here.
353                          */
354                         spin_unlock(&ttm_glob.lru_lock);
355                         return 0;
356                 }
357                 ret = 0;
358         }
359
360         if (ret || unlikely(list_empty(&bo->ddestroy))) {
361                 if (unlock_resv)
362                         dma_resv_unlock(bo->base.resv);
363                 spin_unlock(&ttm_glob.lru_lock);
364                 return ret;
365         }
366
367         ttm_bo_del_from_lru(bo);
368         list_del_init(&bo->ddestroy);
369         spin_unlock(&ttm_glob.lru_lock);
370         ttm_bo_cleanup_memtype_use(bo);
371
372         if (unlock_resv)
373                 dma_resv_unlock(bo->base.resv);
374
375         ttm_bo_put(bo);
376
377         return 0;
378 }
379
380 /*
381  * Traverse the delayed list, and call ttm_bo_cleanup_refs on all
382  * encountered buffers.
383  */
384 bool ttm_bo_delayed_delete(struct ttm_device *bdev, bool remove_all)
385 {
386         struct ttm_global *glob = &ttm_glob;
387         struct list_head removed;
388         bool empty;
389
390         INIT_LIST_HEAD(&removed);
391
392         spin_lock(&glob->lru_lock);
393         while (!list_empty(&bdev->ddestroy)) {
394                 struct ttm_buffer_object *bo;
395
396                 bo = list_first_entry(&bdev->ddestroy, struct ttm_buffer_object,
397                                       ddestroy);
398                 list_move_tail(&bo->ddestroy, &removed);
399                 if (!ttm_bo_get_unless_zero(bo))
400                         continue;
401
402                 if (remove_all || bo->base.resv != &bo->base._resv) {
403                         spin_unlock(&glob->lru_lock);
404                         dma_resv_lock(bo->base.resv, NULL);
405
406                         spin_lock(&glob->lru_lock);
407                         ttm_bo_cleanup_refs(bo, false, !remove_all, true);
408
409                 } else if (dma_resv_trylock(bo->base.resv)) {
410                         ttm_bo_cleanup_refs(bo, false, !remove_all, true);
411                 } else {
412                         spin_unlock(&glob->lru_lock);
413                 }
414
415                 ttm_bo_put(bo);
416                 spin_lock(&glob->lru_lock);
417         }
418         list_splice_tail(&removed, &bdev->ddestroy);
419         empty = list_empty(&bdev->ddestroy);
420         spin_unlock(&glob->lru_lock);
421
422         return empty;
423 }
424
425 static void ttm_bo_release(struct kref *kref)
426 {
427         struct ttm_buffer_object *bo =
428             container_of(kref, struct ttm_buffer_object, kref);
429         struct ttm_device *bdev = bo->bdev;
430         int ret;
431
432         if (!bo->deleted) {
433                 ret = ttm_bo_individualize_resv(bo);
434                 if (ret) {
435                         /* Last resort, if we fail to allocate memory for the
436                          * fences block for the BO to become idle
437                          */
438                         dma_resv_wait_timeout_rcu(bo->base.resv, true, false,
439                                                   30 * HZ);
440                 }
441
442                 if (bo->bdev->funcs->release_notify)
443                         bo->bdev->funcs->release_notify(bo);
444
445                 drm_vma_offset_remove(bdev->vma_manager, &bo->base.vma_node);
446                 ttm_mem_io_free(bdev, &bo->mem);
447         }
448
449         if (!dma_resv_test_signaled_rcu(bo->base.resv, true) ||
450             !dma_resv_trylock(bo->base.resv)) {
451                 /* The BO is not idle, resurrect it for delayed destroy */
452                 ttm_bo_flush_all_fences(bo);
453                 bo->deleted = true;
454
455                 spin_lock(&ttm_glob.lru_lock);
456
457                 /*
458                  * Make pinned bos immediately available to
459                  * shrinkers, now that they are queued for
460                  * destruction.
461                  */
462                 if (WARN_ON(bo->pin_count)) {
463                         bo->pin_count = 0;
464                         ttm_bo_move_to_lru_tail(bo, &bo->mem, NULL);
465                 }
466
467                 kref_init(&bo->kref);
468                 list_add_tail(&bo->ddestroy, &bdev->ddestroy);
469                 spin_unlock(&ttm_glob.lru_lock);
470
471                 schedule_delayed_work(&bdev->wq,
472                                       ((HZ / 100) < 1) ? 1 : HZ / 100);
473                 return;
474         }
475
476         spin_lock(&ttm_glob.lru_lock);
477         ttm_bo_del_from_lru(bo);
478         list_del(&bo->ddestroy);
479         spin_unlock(&ttm_glob.lru_lock);
480
481         ttm_bo_cleanup_memtype_use(bo);
482         dma_resv_unlock(bo->base.resv);
483
484         atomic_dec(&ttm_glob.bo_count);
485         dma_fence_put(bo->moving);
486         if (!ttm_bo_uses_embedded_gem_object(bo))
487                 dma_resv_fini(&bo->base._resv);
488         bo->destroy(bo);
489 }
490
491 void ttm_bo_put(struct ttm_buffer_object *bo)
492 {
493         kref_put(&bo->kref, ttm_bo_release);
494 }
495 EXPORT_SYMBOL(ttm_bo_put);
496
497 int ttm_bo_lock_delayed_workqueue(struct ttm_device *bdev)
498 {
499         return cancel_delayed_work_sync(&bdev->wq);
500 }
501 EXPORT_SYMBOL(ttm_bo_lock_delayed_workqueue);
502
503 void ttm_bo_unlock_delayed_workqueue(struct ttm_device *bdev, int resched)
504 {
505         if (resched)
506                 schedule_delayed_work(&bdev->wq,
507                                       ((HZ / 100) < 1) ? 1 : HZ / 100);
508 }
509 EXPORT_SYMBOL(ttm_bo_unlock_delayed_workqueue);
510
511 static int ttm_bo_evict(struct ttm_buffer_object *bo,
512                         struct ttm_operation_ctx *ctx)
513 {
514         struct ttm_device *bdev = bo->bdev;
515         struct ttm_resource evict_mem;
516         struct ttm_placement placement;
517         struct ttm_place hop;
518         int ret = 0;
519
520         memset(&hop, 0, sizeof(hop));
521
522         dma_resv_assert_held(bo->base.resv);
523
524         placement.num_placement = 0;
525         placement.num_busy_placement = 0;
526         bdev->funcs->evict_flags(bo, &placement);
527
528         if (!placement.num_placement && !placement.num_busy_placement) {
529                 ttm_bo_wait(bo, false, false);
530
531                 ttm_bo_cleanup_memtype_use(bo);
532                 return ttm_tt_create(bo, false);
533         }
534
535         evict_mem = bo->mem;
536         evict_mem.mm_node = NULL;
537         evict_mem.bus.offset = 0;
538         evict_mem.bus.addr = NULL;
539
540         ret = ttm_bo_mem_space(bo, &placement, &evict_mem, ctx);
541         if (ret) {
542                 if (ret != -ERESTARTSYS) {
543                         pr_err("Failed to find memory space for buffer 0x%p eviction\n",
544                                bo);
545                         ttm_bo_mem_space_debug(bo, &placement);
546                 }
547                 goto out;
548         }
549
550         ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, ctx, &hop);
551         if (unlikely(ret)) {
552                 WARN(ret == -EMULTIHOP, "Unexpected multihop in eviction - likely driver bug\n");
553                 if (ret != -ERESTARTSYS)
554                         pr_err("Buffer eviction failed\n");
555                 ttm_resource_free(bo, &evict_mem);
556         }
557 out:
558         return ret;
559 }
560
561 bool ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
562                               const struct ttm_place *place)
563 {
564         /* Don't evict this BO if it's outside of the
565          * requested placement range
566          */
567         if (place->fpfn >= (bo->mem.start + bo->mem.num_pages) ||
568             (place->lpfn && place->lpfn <= bo->mem.start))
569                 return false;
570
571         return true;
572 }
573 EXPORT_SYMBOL(ttm_bo_eviction_valuable);
574
575 /*
576  * Check the target bo is allowable to be evicted or swapout, including cases:
577  *
578  * a. if share same reservation object with ctx->resv, have assumption
579  * reservation objects should already be locked, so not lock again and
580  * return true directly when either the opreation allow_reserved_eviction
581  * or the target bo already is in delayed free list;
582  *
583  * b. Otherwise, trylock it.
584  */
585 static bool ttm_bo_evict_swapout_allowable(struct ttm_buffer_object *bo,
586                         struct ttm_operation_ctx *ctx, bool *locked, bool *busy)
587 {
588         bool ret = false;
589
590         if (bo->base.resv == ctx->resv) {
591                 dma_resv_assert_held(bo->base.resv);
592                 if (ctx->allow_res_evict)
593                         ret = true;
594                 *locked = false;
595                 if (busy)
596                         *busy = false;
597         } else {
598                 ret = dma_resv_trylock(bo->base.resv);
599                 *locked = ret;
600                 if (busy)
601                         *busy = !ret;
602         }
603
604         return ret;
605 }
606
607 /**
608  * ttm_mem_evict_wait_busy - wait for a busy BO to become available
609  *
610  * @busy_bo: BO which couldn't be locked with trylock
611  * @ctx: operation context
612  * @ticket: acquire ticket
613  *
614  * Try to lock a busy buffer object to avoid failing eviction.
615  */
616 static int ttm_mem_evict_wait_busy(struct ttm_buffer_object *busy_bo,
617                                    struct ttm_operation_ctx *ctx,
618                                    struct ww_acquire_ctx *ticket)
619 {
620         int r;
621
622         if (!busy_bo || !ticket)
623                 return -EBUSY;
624
625         if (ctx->interruptible)
626                 r = dma_resv_lock_interruptible(busy_bo->base.resv,
627                                                           ticket);
628         else
629                 r = dma_resv_lock(busy_bo->base.resv, ticket);
630
631         /*
632          * TODO: It would be better to keep the BO locked until allocation is at
633          * least tried one more time, but that would mean a much larger rework
634          * of TTM.
635          */
636         if (!r)
637                 dma_resv_unlock(busy_bo->base.resv);
638
639         return r == -EDEADLK ? -EBUSY : r;
640 }
641
642 int ttm_mem_evict_first(struct ttm_device *bdev,
643                         struct ttm_resource_manager *man,
644                         const struct ttm_place *place,
645                         struct ttm_operation_ctx *ctx,
646                         struct ww_acquire_ctx *ticket)
647 {
648         struct ttm_buffer_object *bo = NULL, *busy_bo = NULL;
649         bool locked = false;
650         unsigned i;
651         int ret;
652
653         spin_lock(&ttm_glob.lru_lock);
654         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
655                 list_for_each_entry(bo, &man->lru[i], lru) {
656                         bool busy;
657
658                         if (!ttm_bo_evict_swapout_allowable(bo, ctx, &locked,
659                                                             &busy)) {
660                                 if (busy && !busy_bo && ticket !=
661                                     dma_resv_locking_ctx(bo->base.resv))
662                                         busy_bo = bo;
663                                 continue;
664                         }
665
666                         if (place && !bdev->funcs->eviction_valuable(bo,
667                                                                       place)) {
668                                 if (locked)
669                                         dma_resv_unlock(bo->base.resv);
670                                 continue;
671                         }
672                         if (!ttm_bo_get_unless_zero(bo)) {
673                                 if (locked)
674                                         dma_resv_unlock(bo->base.resv);
675                                 continue;
676                         }
677                         break;
678                 }
679
680                 /* If the inner loop terminated early, we have our candidate */
681                 if (&bo->lru != &man->lru[i])
682                         break;
683
684                 bo = NULL;
685         }
686
687         if (!bo) {
688                 if (busy_bo && !ttm_bo_get_unless_zero(busy_bo))
689                         busy_bo = NULL;
690                 spin_unlock(&ttm_glob.lru_lock);
691                 ret = ttm_mem_evict_wait_busy(busy_bo, ctx, ticket);
692                 if (busy_bo)
693                         ttm_bo_put(busy_bo);
694                 return ret;
695         }
696
697         if (bo->deleted) {
698                 ret = ttm_bo_cleanup_refs(bo, ctx->interruptible,
699                                           ctx->no_wait_gpu, locked);
700                 ttm_bo_put(bo);
701                 return ret;
702         }
703
704         spin_unlock(&ttm_glob.lru_lock);
705
706         ret = ttm_bo_evict(bo, ctx);
707         if (locked)
708                 ttm_bo_unreserve(bo);
709
710         ttm_bo_put(bo);
711         return ret;
712 }
713
714 /*
715  * Add the last move fence to the BO and reserve a new shared slot.
716  */
717 static int ttm_bo_add_move_fence(struct ttm_buffer_object *bo,
718                                  struct ttm_resource_manager *man,
719                                  struct ttm_resource *mem,
720                                  bool no_wait_gpu)
721 {
722         struct dma_fence *fence;
723         int ret;
724
725         spin_lock(&man->move_lock);
726         fence = dma_fence_get(man->move);
727         spin_unlock(&man->move_lock);
728
729         if (!fence)
730                 return 0;
731
732         if (no_wait_gpu) {
733                 dma_fence_put(fence);
734                 return -EBUSY;
735         }
736
737         dma_resv_add_shared_fence(bo->base.resv, fence);
738
739         ret = dma_resv_reserve_shared(bo->base.resv, 1);
740         if (unlikely(ret)) {
741                 dma_fence_put(fence);
742                 return ret;
743         }
744
745         dma_fence_put(bo->moving);
746         bo->moving = fence;
747         return 0;
748 }
749
750 /*
751  * Repeatedly evict memory from the LRU for @mem_type until we create enough
752  * space, or we've evicted everything and there isn't enough space.
753  */
754 static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
755                                   const struct ttm_place *place,
756                                   struct ttm_resource *mem,
757                                   struct ttm_operation_ctx *ctx)
758 {
759         struct ttm_device *bdev = bo->bdev;
760         struct ttm_resource_manager *man = ttm_manager_type(bdev, mem->mem_type);
761         struct ww_acquire_ctx *ticket;
762         int ret;
763
764         ticket = dma_resv_locking_ctx(bo->base.resv);
765         do {
766                 ret = ttm_resource_alloc(bo, place, mem);
767                 if (likely(!ret))
768                         break;
769                 if (unlikely(ret != -ENOSPC))
770                         return ret;
771                 ret = ttm_mem_evict_first(bdev, man, place, ctx,
772                                           ticket);
773                 if (unlikely(ret != 0))
774                         return ret;
775         } while (1);
776
777         return ttm_bo_add_move_fence(bo, man, mem, ctx->no_wait_gpu);
778 }
779
780 /**
781  * ttm_bo_mem_placement - check if placement is compatible
782  * @bo: BO to find memory for
783  * @place: where to search
784  * @mem: the memory object to fill in
785  *
786  * Check if placement is compatible and fill in mem structure.
787  * Returns -EBUSY if placement won't work or negative error code.
788  * 0 when placement can be used.
789  */
790 static int ttm_bo_mem_placement(struct ttm_buffer_object *bo,
791                                 const struct ttm_place *place,
792                                 struct ttm_resource *mem)
793 {
794         struct ttm_device *bdev = bo->bdev;
795         struct ttm_resource_manager *man;
796
797         man = ttm_manager_type(bdev, place->mem_type);
798         if (!man || !ttm_resource_manager_used(man))
799                 return -EBUSY;
800
801         mem->mem_type = place->mem_type;
802         mem->placement = place->flags;
803
804         spin_lock(&ttm_glob.lru_lock);
805         ttm_bo_move_to_lru_tail(bo, mem, NULL);
806         spin_unlock(&ttm_glob.lru_lock);
807
808         return 0;
809 }
810
811 /*
812  * Creates space for memory region @mem according to its type.
813  *
814  * This function first searches for free space in compatible memory types in
815  * the priority order defined by the driver.  If free space isn't found, then
816  * ttm_bo_mem_force_space is attempted in priority order to evict and find
817  * space.
818  */
819 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
820                         struct ttm_placement *placement,
821                         struct ttm_resource *mem,
822                         struct ttm_operation_ctx *ctx)
823 {
824         struct ttm_device *bdev = bo->bdev;
825         bool type_found = false;
826         int i, ret;
827
828         ret = dma_resv_reserve_shared(bo->base.resv, 1);
829         if (unlikely(ret))
830                 return ret;
831
832         for (i = 0; i < placement->num_placement; ++i) {
833                 const struct ttm_place *place = &placement->placement[i];
834                 struct ttm_resource_manager *man;
835
836                 ret = ttm_bo_mem_placement(bo, place, mem);
837                 if (ret)
838                         continue;
839
840                 type_found = true;
841                 ret = ttm_resource_alloc(bo, place, mem);
842                 if (ret == -ENOSPC)
843                         continue;
844                 if (unlikely(ret))
845                         goto error;
846
847                 man = ttm_manager_type(bdev, mem->mem_type);
848                 ret = ttm_bo_add_move_fence(bo, man, mem, ctx->no_wait_gpu);
849                 if (unlikely(ret)) {
850                         ttm_resource_free(bo, mem);
851                         if (ret == -EBUSY)
852                                 continue;
853
854                         goto error;
855                 }
856                 return 0;
857         }
858
859         for (i = 0; i < placement->num_busy_placement; ++i) {
860                 const struct ttm_place *place = &placement->busy_placement[i];
861
862                 ret = ttm_bo_mem_placement(bo, place, mem);
863                 if (ret)
864                         continue;
865
866                 type_found = true;
867                 ret = ttm_bo_mem_force_space(bo, place, mem, ctx);
868                 if (likely(!ret))
869                         return 0;
870
871                 if (ret && ret != -EBUSY)
872                         goto error;
873         }
874
875         ret = -ENOMEM;
876         if (!type_found) {
877                 pr_err(TTM_PFX "No compatible memory type found\n");
878                 ret = -EINVAL;
879         }
880
881 error:
882         if (bo->mem.mem_type == TTM_PL_SYSTEM && !bo->pin_count)
883                 ttm_bo_move_to_lru_tail_unlocked(bo);
884
885         return ret;
886 }
887 EXPORT_SYMBOL(ttm_bo_mem_space);
888
889 static int ttm_bo_bounce_temp_buffer(struct ttm_buffer_object *bo,
890                                      struct ttm_resource *mem,
891                                      struct ttm_operation_ctx *ctx,
892                                      struct ttm_place *hop)
893 {
894         struct ttm_placement hop_placement;
895         int ret;
896         struct ttm_resource hop_mem = *mem;
897
898         hop_mem.mm_node = NULL;
899         hop_mem.mem_type = TTM_PL_SYSTEM;
900         hop_mem.placement = 0;
901
902         hop_placement.num_placement = hop_placement.num_busy_placement = 1;
903         hop_placement.placement = hop_placement.busy_placement = hop;
904
905         /* find space in the bounce domain */
906         ret = ttm_bo_mem_space(bo, &hop_placement, &hop_mem, ctx);
907         if (ret)
908                 return ret;
909         /* move to the bounce domain */
910         ret = ttm_bo_handle_move_mem(bo, &hop_mem, false, ctx, NULL);
911         if (ret)
912                 return ret;
913         return 0;
914 }
915
916 static int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
917                               struct ttm_placement *placement,
918                               struct ttm_operation_ctx *ctx)
919 {
920         int ret = 0;
921         struct ttm_place hop;
922         struct ttm_resource mem;
923
924         dma_resv_assert_held(bo->base.resv);
925
926         memset(&hop, 0, sizeof(hop));
927
928         mem.num_pages = PAGE_ALIGN(bo->base.size) >> PAGE_SHIFT;
929         mem.page_alignment = bo->mem.page_alignment;
930         mem.bus.offset = 0;
931         mem.bus.addr = NULL;
932         mem.mm_node = NULL;
933
934         /*
935          * Determine where to move the buffer.
936          *
937          * If driver determines move is going to need
938          * an extra step then it will return -EMULTIHOP
939          * and the buffer will be moved to the temporary
940          * stop and the driver will be called to make
941          * the second hop.
942          */
943 bounce:
944         ret = ttm_bo_mem_space(bo, placement, &mem, ctx);
945         if (ret)
946                 return ret;
947         ret = ttm_bo_handle_move_mem(bo, &mem, false, ctx, &hop);
948         if (ret == -EMULTIHOP) {
949                 ret = ttm_bo_bounce_temp_buffer(bo, &mem, ctx, &hop);
950                 if (ret)
951                         return ret;
952                 /* try and move to final place now. */
953                 goto bounce;
954         }
955         if (ret)
956                 ttm_resource_free(bo, &mem);
957         return ret;
958 }
959
960 static bool ttm_bo_places_compat(const struct ttm_place *places,
961                                  unsigned num_placement,
962                                  struct ttm_resource *mem,
963                                  uint32_t *new_flags)
964 {
965         unsigned i;
966
967         for (i = 0; i < num_placement; i++) {
968                 const struct ttm_place *heap = &places[i];
969
970                 if ((mem->start < heap->fpfn ||
971                      (heap->lpfn != 0 && (mem->start + mem->num_pages) > heap->lpfn)))
972                         continue;
973
974                 *new_flags = heap->flags;
975                 if ((mem->mem_type == heap->mem_type) &&
976                     (!(*new_flags & TTM_PL_FLAG_CONTIGUOUS) ||
977                      (mem->placement & TTM_PL_FLAG_CONTIGUOUS)))
978                         return true;
979         }
980         return false;
981 }
982
983 bool ttm_bo_mem_compat(struct ttm_placement *placement,
984                        struct ttm_resource *mem,
985                        uint32_t *new_flags)
986 {
987         if (ttm_bo_places_compat(placement->placement, placement->num_placement,
988                                  mem, new_flags))
989                 return true;
990
991         if ((placement->busy_placement != placement->placement ||
992              placement->num_busy_placement > placement->num_placement) &&
993             ttm_bo_places_compat(placement->busy_placement,
994                                  placement->num_busy_placement,
995                                  mem, new_flags))
996                 return true;
997
998         return false;
999 }
1000 EXPORT_SYMBOL(ttm_bo_mem_compat);
1001
1002 int ttm_bo_validate(struct ttm_buffer_object *bo,
1003                     struct ttm_placement *placement,
1004                     struct ttm_operation_ctx *ctx)
1005 {
1006         int ret;
1007         uint32_t new_flags;
1008
1009         dma_resv_assert_held(bo->base.resv);
1010
1011         /*
1012          * Remove the backing store if no placement is given.
1013          */
1014         if (!placement->num_placement && !placement->num_busy_placement) {
1015                 ret = ttm_bo_pipeline_gutting(bo);
1016                 if (ret)
1017                         return ret;
1018
1019                 return ttm_tt_create(bo, false);
1020         }
1021
1022         /*
1023          * Check whether we need to move buffer.
1024          */
1025         if (!ttm_bo_mem_compat(placement, &bo->mem, &new_flags)) {
1026                 ret = ttm_bo_move_buffer(bo, placement, ctx);
1027                 if (ret)
1028                         return ret;
1029         }
1030         /*
1031          * We might need to add a TTM.
1032          */
1033         if (bo->mem.mem_type == TTM_PL_SYSTEM) {
1034                 ret = ttm_tt_create(bo, true);
1035                 if (ret)
1036                         return ret;
1037         }
1038         return 0;
1039 }
1040 EXPORT_SYMBOL(ttm_bo_validate);
1041
1042 int ttm_bo_init_reserved(struct ttm_device *bdev,
1043                          struct ttm_buffer_object *bo,
1044                          size_t size,
1045                          enum ttm_bo_type type,
1046                          struct ttm_placement *placement,
1047                          uint32_t page_alignment,
1048                          struct ttm_operation_ctx *ctx,
1049                          struct sg_table *sg,
1050                          struct dma_resv *resv,
1051                          void (*destroy) (struct ttm_buffer_object *))
1052 {
1053         bool locked;
1054         int ret = 0;
1055
1056         bo->destroy = destroy ? destroy : ttm_bo_default_destroy;
1057
1058         kref_init(&bo->kref);
1059         INIT_LIST_HEAD(&bo->lru);
1060         INIT_LIST_HEAD(&bo->ddestroy);
1061         INIT_LIST_HEAD(&bo->swap);
1062         bo->bdev = bdev;
1063         bo->type = type;
1064         bo->mem.mem_type = TTM_PL_SYSTEM;
1065         bo->mem.num_pages = PAGE_ALIGN(size) >> PAGE_SHIFT;
1066         bo->mem.mm_node = NULL;
1067         bo->mem.page_alignment = page_alignment;
1068         bo->mem.bus.offset = 0;
1069         bo->mem.bus.addr = NULL;
1070         bo->moving = NULL;
1071         bo->mem.placement = 0;
1072         bo->pin_count = 0;
1073         bo->sg = sg;
1074         if (resv) {
1075                 bo->base.resv = resv;
1076                 dma_resv_assert_held(bo->base.resv);
1077         } else {
1078                 bo->base.resv = &bo->base._resv;
1079         }
1080         if (!ttm_bo_uses_embedded_gem_object(bo)) {
1081                 /*
1082                  * bo.base is not initialized, so we have to setup the
1083                  * struct elements we want use regardless.
1084                  */
1085                 bo->base.size = size;
1086                 dma_resv_init(&bo->base._resv);
1087                 drm_vma_node_reset(&bo->base.vma_node);
1088         }
1089         atomic_inc(&ttm_glob.bo_count);
1090
1091         /*
1092          * For ttm_bo_type_device buffers, allocate
1093          * address space from the device.
1094          */
1095         if (bo->type == ttm_bo_type_device ||
1096             bo->type == ttm_bo_type_sg)
1097                 ret = drm_vma_offset_add(bdev->vma_manager, &bo->base.vma_node,
1098                                          bo->mem.num_pages);
1099
1100         /* passed reservation objects should already be locked,
1101          * since otherwise lockdep will be angered in radeon.
1102          */
1103         if (!resv) {
1104                 locked = dma_resv_trylock(bo->base.resv);
1105                 WARN_ON(!locked);
1106         }
1107
1108         if (likely(!ret))
1109                 ret = ttm_bo_validate(bo, placement, ctx);
1110
1111         if (unlikely(ret)) {
1112                 if (!resv)
1113                         ttm_bo_unreserve(bo);
1114
1115                 ttm_bo_put(bo);
1116                 return ret;
1117         }
1118
1119         ttm_bo_move_to_lru_tail_unlocked(bo);
1120
1121         return ret;
1122 }
1123 EXPORT_SYMBOL(ttm_bo_init_reserved);
1124
1125 int ttm_bo_init(struct ttm_device *bdev,
1126                 struct ttm_buffer_object *bo,
1127                 size_t size,
1128                 enum ttm_bo_type type,
1129                 struct ttm_placement *placement,
1130                 uint32_t page_alignment,
1131                 bool interruptible,
1132                 struct sg_table *sg,
1133                 struct dma_resv *resv,
1134                 void (*destroy) (struct ttm_buffer_object *))
1135 {
1136         struct ttm_operation_ctx ctx = { interruptible, false };
1137         int ret;
1138
1139         ret = ttm_bo_init_reserved(bdev, bo, size, type, placement,
1140                                    page_alignment, &ctx, sg, resv, destroy);
1141         if (ret)
1142                 return ret;
1143
1144         if (!resv)
1145                 ttm_bo_unreserve(bo);
1146
1147         return 0;
1148 }
1149 EXPORT_SYMBOL(ttm_bo_init);
1150
1151 /*
1152  * buffer object vm functions.
1153  */
1154
1155 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1156 {
1157         struct ttm_device *bdev = bo->bdev;
1158
1159         drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
1160         ttm_mem_io_free(bdev, &bo->mem);
1161 }
1162 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1163
1164 int ttm_bo_wait(struct ttm_buffer_object *bo,
1165                 bool interruptible, bool no_wait)
1166 {
1167         long timeout = 15 * HZ;
1168
1169         if (no_wait) {
1170                 if (dma_resv_test_signaled_rcu(bo->base.resv, true))
1171                         return 0;
1172                 else
1173                         return -EBUSY;
1174         }
1175
1176         timeout = dma_resv_wait_timeout_rcu(bo->base.resv, true,
1177                                                       interruptible, timeout);
1178         if (timeout < 0)
1179                 return timeout;
1180
1181         if (timeout == 0)
1182                 return -EBUSY;
1183
1184         dma_resv_add_excl_fence(bo->base.resv, NULL);
1185         return 0;
1186 }
1187 EXPORT_SYMBOL(ttm_bo_wait);
1188
1189 /*
1190  * A buffer object shrink method that tries to swap out the first
1191  * buffer object on the bo_global::swap_lru list.
1192  */
1193 int ttm_bo_swapout(struct ttm_operation_ctx *ctx, gfp_t gfp_flags)
1194 {
1195         struct ttm_global *glob = &ttm_glob;
1196         struct ttm_buffer_object *bo;
1197         int ret = -EBUSY;
1198         bool locked;
1199         unsigned i;
1200
1201         spin_lock(&glob->lru_lock);
1202         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
1203                 list_for_each_entry(bo, &glob->swap_lru[i], swap) {
1204                         if (!ttm_bo_evict_swapout_allowable(bo, ctx, &locked,
1205                                                             NULL))
1206                                 continue;
1207
1208                         if (!ttm_bo_get_unless_zero(bo)) {
1209                                 if (locked)
1210                                         dma_resv_unlock(bo->base.resv);
1211                                 continue;
1212                         }
1213
1214                         ret = 0;
1215                         break;
1216                 }
1217                 if (!ret)
1218                         break;
1219         }
1220
1221         if (ret) {
1222                 spin_unlock(&glob->lru_lock);
1223                 return ret;
1224         }
1225
1226         if (bo->deleted) {
1227                 ret = ttm_bo_cleanup_refs(bo, false, false, locked);
1228                 ttm_bo_put(bo);
1229                 return ret;
1230         }
1231
1232         ttm_bo_del_from_lru(bo);
1233         spin_unlock(&glob->lru_lock);
1234
1235         /**
1236          * Move to system cached
1237          */
1238
1239         if (bo->mem.mem_type != TTM_PL_SYSTEM) {
1240                 struct ttm_operation_ctx ctx = { false, false };
1241                 struct ttm_resource evict_mem;
1242                 struct ttm_place hop;
1243
1244                 memset(&hop, 0, sizeof(hop));
1245
1246                 evict_mem = bo->mem;
1247                 evict_mem.mm_node = NULL;
1248                 evict_mem.placement = 0;
1249                 evict_mem.mem_type = TTM_PL_SYSTEM;
1250
1251                 ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, &ctx, &hop);
1252                 if (unlikely(ret != 0)) {
1253                         WARN(ret == -EMULTIHOP, "Unexpected multihop in swaput - likely driver bug.\n");
1254                         goto out;
1255                 }
1256         }
1257
1258         /**
1259          * Make sure BO is idle.
1260          */
1261
1262         ret = ttm_bo_wait(bo, false, false);
1263         if (unlikely(ret != 0))
1264                 goto out;
1265
1266         ttm_bo_unmap_virtual(bo);
1267
1268         /**
1269          * Swap out. Buffer will be swapped in again as soon as
1270          * anyone tries to access a ttm page.
1271          */
1272
1273         if (bo->bdev->funcs->swap_notify)
1274                 bo->bdev->funcs->swap_notify(bo);
1275
1276         ret = ttm_tt_swapout(bo->bdev, bo->ttm, gfp_flags);
1277 out:
1278
1279         /**
1280          *
1281          * Unreserve without putting on LRU to avoid swapping out an
1282          * already swapped buffer.
1283          */
1284         if (locked)
1285                 dma_resv_unlock(bo->base.resv);
1286         ttm_bo_put(bo);
1287         return ret;
1288 }
1289 EXPORT_SYMBOL(ttm_bo_swapout);
1290
1291 void ttm_bo_tt_destroy(struct ttm_buffer_object *bo)
1292 {
1293         if (bo->ttm == NULL)
1294                 return;
1295
1296         ttm_tt_destroy(bo->bdev, bo->ttm);
1297         bo->ttm = NULL;
1298 }