]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/ttm/ttm_bo.c
125798a2f1462793ec34cd7ced66cc83f43b4285
[linux.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_module.h>
35 #include <drm/ttm/ttm_bo_driver.h>
36 #include <drm/ttm/ttm_placement.h>
37 #include <linux/jiffies.h>
38 #include <linux/slab.h>
39 #include <linux/sched.h>
40 #include <linux/mm.h>
41 #include <linux/file.h>
42 #include <linux/module.h>
43 #include <linux/atomic.h>
44 #include <linux/dma-resv.h>
45
46 static void ttm_bo_global_kobj_release(struct kobject *kobj);
47
48 /**
49  * ttm_global_mutex - protecting the global BO state
50  */
51 DEFINE_MUTEX(ttm_global_mutex);
52 unsigned ttm_bo_glob_use_count;
53 struct ttm_bo_global ttm_bo_glob;
54
55 static struct attribute ttm_bo_count = {
56         .name = "bo_count",
57         .mode = S_IRUGO
58 };
59
60 /* default destructor */
61 static void ttm_bo_default_destroy(struct ttm_buffer_object *bo)
62 {
63         kfree(bo);
64 }
65
66 static inline int ttm_mem_type_from_place(const struct ttm_place *place,
67                                           uint32_t *mem_type)
68 {
69         int pos;
70
71         pos = ffs(place->flags & TTM_PL_MASK_MEM);
72         if (unlikely(!pos))
73                 return -EINVAL;
74
75         *mem_type = pos - 1;
76         return 0;
77 }
78
79 static void ttm_mem_type_debug(struct ttm_bo_device *bdev, struct drm_printer *p,
80                                int mem_type)
81 {
82         struct ttm_mem_type_manager *man = &bdev->man[mem_type];
83
84         drm_printf(p, "    has_type: %d\n", man->has_type);
85         drm_printf(p, "    use_type: %d\n", man->use_type);
86         drm_printf(p, "    flags: 0x%08X\n", man->flags);
87         drm_printf(p, "    gpu_offset: 0x%08llX\n", man->gpu_offset);
88         drm_printf(p, "    size: %llu\n", man->size);
89         drm_printf(p, "    available_caching: 0x%08X\n", man->available_caching);
90         drm_printf(p, "    default_caching: 0x%08X\n", man->default_caching);
91         if (mem_type != TTM_PL_SYSTEM)
92                 (*man->func->debug)(man, p);
93 }
94
95 static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
96                                         struct ttm_placement *placement)
97 {
98         struct drm_printer p = drm_debug_printer(TTM_PFX);
99         int i, ret, mem_type;
100
101         drm_printf(&p, "No space for %p (%lu pages, %luK, %luM)\n",
102                    bo, bo->mem.num_pages, bo->mem.size >> 10,
103                    bo->mem.size >> 20);
104         for (i = 0; i < placement->num_placement; i++) {
105                 ret = ttm_mem_type_from_place(&placement->placement[i],
106                                                 &mem_type);
107                 if (ret)
108                         return;
109                 drm_printf(&p, "  placement[%d]=0x%08X (%d)\n",
110                            i, placement->placement[i].flags, mem_type);
111                 ttm_mem_type_debug(bo->bdev, &p, mem_type);
112         }
113 }
114
115 static ssize_t ttm_bo_global_show(struct kobject *kobj,
116                                   struct attribute *attr,
117                                   char *buffer)
118 {
119         struct ttm_bo_global *glob =
120                 container_of(kobj, struct ttm_bo_global, kobj);
121
122         return snprintf(buffer, PAGE_SIZE, "%d\n",
123                                 atomic_read(&glob->bo_count));
124 }
125
126 static struct attribute *ttm_bo_global_attrs[] = {
127         &ttm_bo_count,
128         NULL
129 };
130
131 static const struct sysfs_ops ttm_bo_global_ops = {
132         .show = &ttm_bo_global_show
133 };
134
135 static struct kobj_type ttm_bo_glob_kobj_type  = {
136         .release = &ttm_bo_global_kobj_release,
137         .sysfs_ops = &ttm_bo_global_ops,
138         .default_attrs = ttm_bo_global_attrs
139 };
140
141
142 static inline uint32_t ttm_bo_type_flags(unsigned type)
143 {
144         return 1 << (type);
145 }
146
147 static void ttm_bo_release_list(struct kref *list_kref)
148 {
149         struct ttm_buffer_object *bo =
150             container_of(list_kref, struct ttm_buffer_object, list_kref);
151         struct ttm_bo_device *bdev = bo->bdev;
152         size_t acc_size = bo->acc_size;
153
154         BUG_ON(kref_read(&bo->list_kref));
155         BUG_ON(kref_read(&bo->kref));
156         BUG_ON(bo->mem.mm_node != NULL);
157         BUG_ON(!list_empty(&bo->lru));
158         BUG_ON(!list_empty(&bo->ddestroy));
159         ttm_tt_destroy(bo->ttm);
160         atomic_dec(&bo->bdev->glob->bo_count);
161         dma_fence_put(bo->moving);
162         if (!ttm_bo_uses_embedded_gem_object(bo))
163                 dma_resv_fini(&bo->base._resv);
164         mutex_destroy(&bo->wu_mutex);
165         bo->destroy(bo);
166         ttm_mem_global_free(bdev->glob->mem_glob, acc_size);
167 }
168
169 static void ttm_bo_add_mem_to_lru(struct ttm_buffer_object *bo,
170                                   struct ttm_mem_reg *mem)
171 {
172         struct ttm_bo_device *bdev = bo->bdev;
173         struct ttm_mem_type_manager *man;
174
175         dma_resv_assert_held(bo->base.resv);
176
177         if (!list_empty(&bo->lru))
178                 return;
179
180         if (mem->placement & TTM_PL_FLAG_NO_EVICT)
181                 return;
182
183         man = &bdev->man[mem->mem_type];
184         list_add_tail(&bo->lru, &man->lru[bo->priority]);
185         kref_get(&bo->list_kref);
186
187         if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED) && bo->ttm &&
188             !(bo->ttm->page_flags & (TTM_PAGE_FLAG_SG |
189                                      TTM_PAGE_FLAG_SWAPPED))) {
190                 list_add_tail(&bo->swap, &bdev->glob->swap_lru[bo->priority]);
191                 kref_get(&bo->list_kref);
192         }
193 }
194
195 void ttm_bo_add_to_lru(struct ttm_buffer_object *bo)
196 {
197         ttm_bo_add_mem_to_lru(bo, &bo->mem);
198 }
199 EXPORT_SYMBOL(ttm_bo_add_to_lru);
200
201 static void ttm_bo_ref_bug(struct kref *list_kref)
202 {
203         BUG();
204 }
205
206 void ttm_bo_del_from_lru(struct ttm_buffer_object *bo)
207 {
208         struct ttm_bo_device *bdev = bo->bdev;
209         bool notify = false;
210
211         if (!list_empty(&bo->swap)) {
212                 list_del_init(&bo->swap);
213                 kref_put(&bo->list_kref, ttm_bo_ref_bug);
214                 notify = true;
215         }
216         if (!list_empty(&bo->lru)) {
217                 list_del_init(&bo->lru);
218                 kref_put(&bo->list_kref, ttm_bo_ref_bug);
219                 notify = true;
220         }
221
222         if (notify && bdev->driver->del_from_lru_notify)
223                 bdev->driver->del_from_lru_notify(bo);
224 }
225
226 void ttm_bo_del_sub_from_lru(struct ttm_buffer_object *bo)
227 {
228         struct ttm_bo_global *glob = bo->bdev->glob;
229
230         spin_lock(&glob->lru_lock);
231         ttm_bo_del_from_lru(bo);
232         spin_unlock(&glob->lru_lock);
233 }
234 EXPORT_SYMBOL(ttm_bo_del_sub_from_lru);
235
236 static void ttm_bo_bulk_move_set_pos(struct ttm_lru_bulk_move_pos *pos,
237                                      struct ttm_buffer_object *bo)
238 {
239         if (!pos->first)
240                 pos->first = bo;
241         pos->last = bo;
242 }
243
244 void ttm_bo_move_to_lru_tail(struct ttm_buffer_object *bo,
245                              struct ttm_lru_bulk_move *bulk)
246 {
247         dma_resv_assert_held(bo->base.resv);
248
249         ttm_bo_del_from_lru(bo);
250         ttm_bo_add_to_lru(bo);
251
252         if (bulk && !(bo->mem.placement & TTM_PL_FLAG_NO_EVICT)) {
253                 switch (bo->mem.mem_type) {
254                 case TTM_PL_TT:
255                         ttm_bo_bulk_move_set_pos(&bulk->tt[bo->priority], bo);
256                         break;
257
258                 case TTM_PL_VRAM:
259                         ttm_bo_bulk_move_set_pos(&bulk->vram[bo->priority], bo);
260                         break;
261                 }
262                 if (bo->ttm && !(bo->ttm->page_flags &
263                                  (TTM_PAGE_FLAG_SG | TTM_PAGE_FLAG_SWAPPED)))
264                         ttm_bo_bulk_move_set_pos(&bulk->swap[bo->priority], bo);
265         }
266 }
267 EXPORT_SYMBOL(ttm_bo_move_to_lru_tail);
268
269 void ttm_bo_bulk_move_lru_tail(struct ttm_lru_bulk_move *bulk)
270 {
271         unsigned i;
272
273         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
274                 struct ttm_lru_bulk_move_pos *pos = &bulk->tt[i];
275                 struct ttm_mem_type_manager *man;
276
277                 if (!pos->first)
278                         continue;
279
280                 dma_resv_assert_held(pos->first->base.resv);
281                 dma_resv_assert_held(pos->last->base.resv);
282
283                 man = &pos->first->bdev->man[TTM_PL_TT];
284                 list_bulk_move_tail(&man->lru[i], &pos->first->lru,
285                                     &pos->last->lru);
286         }
287
288         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
289                 struct ttm_lru_bulk_move_pos *pos = &bulk->vram[i];
290                 struct ttm_mem_type_manager *man;
291
292                 if (!pos->first)
293                         continue;
294
295                 dma_resv_assert_held(pos->first->base.resv);
296                 dma_resv_assert_held(pos->last->base.resv);
297
298                 man = &pos->first->bdev->man[TTM_PL_VRAM];
299                 list_bulk_move_tail(&man->lru[i], &pos->first->lru,
300                                     &pos->last->lru);
301         }
302
303         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
304                 struct ttm_lru_bulk_move_pos *pos = &bulk->swap[i];
305                 struct list_head *lru;
306
307                 if (!pos->first)
308                         continue;
309
310                 dma_resv_assert_held(pos->first->base.resv);
311                 dma_resv_assert_held(pos->last->base.resv);
312
313                 lru = &pos->first->bdev->glob->swap_lru[i];
314                 list_bulk_move_tail(lru, &pos->first->swap, &pos->last->swap);
315         }
316 }
317 EXPORT_SYMBOL(ttm_bo_bulk_move_lru_tail);
318
319 static int ttm_bo_handle_move_mem(struct ttm_buffer_object *bo,
320                                   struct ttm_mem_reg *mem, bool evict,
321                                   struct ttm_operation_ctx *ctx)
322 {
323         struct ttm_bo_device *bdev = bo->bdev;
324         bool old_is_pci = ttm_mem_reg_is_pci(bdev, &bo->mem);
325         bool new_is_pci = ttm_mem_reg_is_pci(bdev, mem);
326         struct ttm_mem_type_manager *old_man = &bdev->man[bo->mem.mem_type];
327         struct ttm_mem_type_manager *new_man = &bdev->man[mem->mem_type];
328         int ret = 0;
329
330         if (old_is_pci || new_is_pci ||
331             ((mem->placement & bo->mem.placement & TTM_PL_MASK_CACHING) == 0)) {
332                 ret = ttm_mem_io_lock(old_man, true);
333                 if (unlikely(ret != 0))
334                         goto out_err;
335                 ttm_bo_unmap_virtual_locked(bo);
336                 ttm_mem_io_unlock(old_man);
337         }
338
339         /*
340          * Create and bind a ttm if required.
341          */
342
343         if (!(new_man->flags & TTM_MEMTYPE_FLAG_FIXED)) {
344                 if (bo->ttm == NULL) {
345                         bool zero = !(old_man->flags & TTM_MEMTYPE_FLAG_FIXED);
346                         ret = ttm_tt_create(bo, zero);
347                         if (ret)
348                                 goto out_err;
349                 }
350
351                 ret = ttm_tt_set_placement_caching(bo->ttm, mem->placement);
352                 if (ret)
353                         goto out_err;
354
355                 if (mem->mem_type != TTM_PL_SYSTEM) {
356                         ret = ttm_tt_bind(bo->ttm, mem, ctx);
357                         if (ret)
358                                 goto out_err;
359                 }
360
361                 if (bo->mem.mem_type == TTM_PL_SYSTEM) {
362                         if (bdev->driver->move_notify)
363                                 bdev->driver->move_notify(bo, evict, mem);
364                         bo->mem = *mem;
365                         mem->mm_node = NULL;
366                         goto moved;
367                 }
368         }
369
370         if (bdev->driver->move_notify)
371                 bdev->driver->move_notify(bo, evict, mem);
372
373         if (!(old_man->flags & TTM_MEMTYPE_FLAG_FIXED) &&
374             !(new_man->flags & TTM_MEMTYPE_FLAG_FIXED))
375                 ret = ttm_bo_move_ttm(bo, ctx, mem);
376         else if (bdev->driver->move)
377                 ret = bdev->driver->move(bo, evict, ctx, mem);
378         else
379                 ret = ttm_bo_move_memcpy(bo, ctx, mem);
380
381         if (ret) {
382                 if (bdev->driver->move_notify) {
383                         swap(*mem, bo->mem);
384                         bdev->driver->move_notify(bo, false, mem);
385                         swap(*mem, bo->mem);
386                 }
387
388                 goto out_err;
389         }
390
391 moved:
392         if (bo->evicted) {
393                 if (bdev->driver->invalidate_caches) {
394                         ret = bdev->driver->invalidate_caches(bdev, bo->mem.placement);
395                         if (ret)
396                                 pr_err("Can not flush read caches\n");
397                 }
398                 bo->evicted = false;
399         }
400
401         if (bo->mem.mm_node)
402                 bo->offset = (bo->mem.start << PAGE_SHIFT) +
403                     bdev->man[bo->mem.mem_type].gpu_offset;
404         else
405                 bo->offset = 0;
406
407         ctx->bytes_moved += bo->num_pages << PAGE_SHIFT;
408         return 0;
409
410 out_err:
411         new_man = &bdev->man[bo->mem.mem_type];
412         if (new_man->flags & TTM_MEMTYPE_FLAG_FIXED) {
413                 ttm_tt_destroy(bo->ttm);
414                 bo->ttm = NULL;
415         }
416
417         return ret;
418 }
419
420 /**
421  * Call bo::reserved.
422  * Will release GPU memory type usage on destruction.
423  * This is the place to put in driver specific hooks to release
424  * driver private resources.
425  * Will release the bo::reserved lock.
426  */
427
428 static void ttm_bo_cleanup_memtype_use(struct ttm_buffer_object *bo)
429 {
430         if (bo->bdev->driver->move_notify)
431                 bo->bdev->driver->move_notify(bo, false, NULL);
432
433         ttm_tt_destroy(bo->ttm);
434         bo->ttm = NULL;
435         ttm_bo_mem_put(bo, &bo->mem);
436 }
437
438 static int ttm_bo_individualize_resv(struct ttm_buffer_object *bo)
439 {
440         int r;
441
442         if (bo->base.resv == &bo->base._resv)
443                 return 0;
444
445         BUG_ON(!dma_resv_trylock(&bo->base._resv));
446
447         r = dma_resv_copy_fences(&bo->base._resv, bo->base.resv);
448         if (r)
449                 dma_resv_unlock(&bo->base._resv);
450
451         return r;
452 }
453
454 static void ttm_bo_flush_all_fences(struct ttm_buffer_object *bo)
455 {
456         struct dma_resv_list *fobj;
457         struct dma_fence *fence;
458         int i;
459
460         fobj = dma_resv_get_list(&bo->base._resv);
461         fence = dma_resv_get_excl(&bo->base._resv);
462         if (fence && !fence->ops->signaled)
463                 dma_fence_enable_sw_signaling(fence);
464
465         for (i = 0; fobj && i < fobj->shared_count; ++i) {
466                 fence = rcu_dereference_protected(fobj->shared[i],
467                                         dma_resv_held(bo->base.resv));
468
469                 if (!fence->ops->signaled)
470                         dma_fence_enable_sw_signaling(fence);
471         }
472 }
473
474 static void ttm_bo_cleanup_refs_or_queue(struct ttm_buffer_object *bo)
475 {
476         struct ttm_bo_device *bdev = bo->bdev;
477         struct ttm_bo_global *glob = bdev->glob;
478         int ret;
479
480         ret = ttm_bo_individualize_resv(bo);
481         if (ret) {
482                 /* Last resort, if we fail to allocate memory for the
483                  * fences block for the BO to become idle
484                  */
485                 dma_resv_wait_timeout_rcu(bo->base.resv, true, false,
486                                                     30 * HZ);
487                 spin_lock(&glob->lru_lock);
488                 goto error;
489         }
490
491         spin_lock(&glob->lru_lock);
492         ret = dma_resv_trylock(bo->base.resv) ? 0 : -EBUSY;
493         if (!ret) {
494                 if (dma_resv_test_signaled_rcu(&bo->base._resv, true)) {
495                         ttm_bo_del_from_lru(bo);
496                         spin_unlock(&glob->lru_lock);
497                         if (bo->base.resv != &bo->base._resv)
498                                 dma_resv_unlock(&bo->base._resv);
499
500                         ttm_bo_cleanup_memtype_use(bo);
501                         dma_resv_unlock(bo->base.resv);
502                         return;
503                 }
504
505                 ttm_bo_flush_all_fences(bo);
506
507                 /*
508                  * Make NO_EVICT bos immediately available to
509                  * shrinkers, now that they are queued for
510                  * destruction.
511                  */
512                 if (bo->mem.placement & TTM_PL_FLAG_NO_EVICT) {
513                         bo->mem.placement &= ~TTM_PL_FLAG_NO_EVICT;
514                         ttm_bo_add_to_lru(bo);
515                 }
516
517                 dma_resv_unlock(bo->base.resv);
518         }
519         if (bo->base.resv != &bo->base._resv)
520                 dma_resv_unlock(&bo->base._resv);
521
522 error:
523         kref_get(&bo->list_kref);
524         list_add_tail(&bo->ddestroy, &bdev->ddestroy);
525         spin_unlock(&glob->lru_lock);
526
527         schedule_delayed_work(&bdev->wq,
528                               ((HZ / 100) < 1) ? 1 : HZ / 100);
529 }
530
531 /**
532  * function ttm_bo_cleanup_refs
533  * If bo idle, remove from delayed- and lru lists, and unref.
534  * If not idle, do nothing.
535  *
536  * Must be called with lru_lock and reservation held, this function
537  * will drop the lru lock and optionally the reservation lock before returning.
538  *
539  * @interruptible         Any sleeps should occur interruptibly.
540  * @no_wait_gpu           Never wait for gpu. Return -EBUSY instead.
541  * @unlock_resv           Unlock the reservation lock as well.
542  */
543
544 static int ttm_bo_cleanup_refs(struct ttm_buffer_object *bo,
545                                bool interruptible, bool no_wait_gpu,
546                                bool unlock_resv)
547 {
548         struct ttm_bo_global *glob = bo->bdev->glob;
549         struct dma_resv *resv;
550         int ret;
551
552         if (unlikely(list_empty(&bo->ddestroy)))
553                 resv = bo->base.resv;
554         else
555                 resv = &bo->base._resv;
556
557         if (dma_resv_test_signaled_rcu(resv, true))
558                 ret = 0;
559         else
560                 ret = -EBUSY;
561
562         if (ret && !no_wait_gpu) {
563                 long lret;
564
565                 if (unlock_resv)
566                         dma_resv_unlock(bo->base.resv);
567                 spin_unlock(&glob->lru_lock);
568
569                 lret = dma_resv_wait_timeout_rcu(resv, true,
570                                                            interruptible,
571                                                            30 * HZ);
572
573                 if (lret < 0)
574                         return lret;
575                 else if (lret == 0)
576                         return -EBUSY;
577
578                 spin_lock(&glob->lru_lock);
579                 if (unlock_resv && !dma_resv_trylock(bo->base.resv)) {
580                         /*
581                          * We raced, and lost, someone else holds the reservation now,
582                          * and is probably busy in ttm_bo_cleanup_memtype_use.
583                          *
584                          * Even if it's not the case, because we finished waiting any
585                          * delayed destruction would succeed, so just return success
586                          * here.
587                          */
588                         spin_unlock(&glob->lru_lock);
589                         return 0;
590                 }
591                 ret = 0;
592         }
593
594         if (ret || unlikely(list_empty(&bo->ddestroy))) {
595                 if (unlock_resv)
596                         dma_resv_unlock(bo->base.resv);
597                 spin_unlock(&glob->lru_lock);
598                 return ret;
599         }
600
601         ttm_bo_del_from_lru(bo);
602         list_del_init(&bo->ddestroy);
603         kref_put(&bo->list_kref, ttm_bo_ref_bug);
604
605         spin_unlock(&glob->lru_lock);
606         ttm_bo_cleanup_memtype_use(bo);
607
608         if (unlock_resv)
609                 dma_resv_unlock(bo->base.resv);
610
611         return 0;
612 }
613
614 /**
615  * Traverse the delayed list, and call ttm_bo_cleanup_refs on all
616  * encountered buffers.
617  */
618 static bool ttm_bo_delayed_delete(struct ttm_bo_device *bdev, bool remove_all)
619 {
620         struct ttm_bo_global *glob = bdev->glob;
621         struct list_head removed;
622         bool empty;
623
624         INIT_LIST_HEAD(&removed);
625
626         spin_lock(&glob->lru_lock);
627         while (!list_empty(&bdev->ddestroy)) {
628                 struct ttm_buffer_object *bo;
629
630                 bo = list_first_entry(&bdev->ddestroy, struct ttm_buffer_object,
631                                       ddestroy);
632                 kref_get(&bo->list_kref);
633                 list_move_tail(&bo->ddestroy, &removed);
634
635                 if (remove_all || bo->base.resv != &bo->base._resv) {
636                         spin_unlock(&glob->lru_lock);
637                         dma_resv_lock(bo->base.resv, NULL);
638
639                         spin_lock(&glob->lru_lock);
640                         ttm_bo_cleanup_refs(bo, false, !remove_all, true);
641
642                 } else if (dma_resv_trylock(bo->base.resv)) {
643                         ttm_bo_cleanup_refs(bo, false, !remove_all, true);
644                 } else {
645                         spin_unlock(&glob->lru_lock);
646                 }
647
648                 kref_put(&bo->list_kref, ttm_bo_release_list);
649                 spin_lock(&glob->lru_lock);
650         }
651         list_splice_tail(&removed, &bdev->ddestroy);
652         empty = list_empty(&bdev->ddestroy);
653         spin_unlock(&glob->lru_lock);
654
655         return empty;
656 }
657
658 static void ttm_bo_delayed_workqueue(struct work_struct *work)
659 {
660         struct ttm_bo_device *bdev =
661             container_of(work, struct ttm_bo_device, wq.work);
662
663         if (!ttm_bo_delayed_delete(bdev, false))
664                 schedule_delayed_work(&bdev->wq,
665                                       ((HZ / 100) < 1) ? 1 : HZ / 100);
666 }
667
668 static void ttm_bo_release(struct kref *kref)
669 {
670         struct ttm_buffer_object *bo =
671             container_of(kref, struct ttm_buffer_object, kref);
672         struct ttm_bo_device *bdev = bo->bdev;
673         struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
674
675         if (bo->bdev->driver->release_notify)
676                 bo->bdev->driver->release_notify(bo);
677
678         drm_vma_offset_remove(bdev->vma_manager, &bo->base.vma_node);
679         ttm_mem_io_lock(man, false);
680         ttm_mem_io_free_vm(bo);
681         ttm_mem_io_unlock(man);
682         ttm_bo_cleanup_refs_or_queue(bo);
683         kref_put(&bo->list_kref, ttm_bo_release_list);
684 }
685
686 void ttm_bo_put(struct ttm_buffer_object *bo)
687 {
688         kref_put(&bo->kref, ttm_bo_release);
689 }
690 EXPORT_SYMBOL(ttm_bo_put);
691
692 int ttm_bo_lock_delayed_workqueue(struct ttm_bo_device *bdev)
693 {
694         return cancel_delayed_work_sync(&bdev->wq);
695 }
696 EXPORT_SYMBOL(ttm_bo_lock_delayed_workqueue);
697
698 void ttm_bo_unlock_delayed_workqueue(struct ttm_bo_device *bdev, int resched)
699 {
700         if (resched)
701                 schedule_delayed_work(&bdev->wq,
702                                       ((HZ / 100) < 1) ? 1 : HZ / 100);
703 }
704 EXPORT_SYMBOL(ttm_bo_unlock_delayed_workqueue);
705
706 static int ttm_bo_evict(struct ttm_buffer_object *bo,
707                         struct ttm_operation_ctx *ctx)
708 {
709         struct ttm_bo_device *bdev = bo->bdev;
710         struct ttm_mem_reg evict_mem;
711         struct ttm_placement placement;
712         int ret = 0;
713
714         dma_resv_assert_held(bo->base.resv);
715
716         placement.num_placement = 0;
717         placement.num_busy_placement = 0;
718         bdev->driver->evict_flags(bo, &placement);
719
720         if (!placement.num_placement && !placement.num_busy_placement) {
721                 ret = ttm_bo_pipeline_gutting(bo);
722                 if (ret)
723                         return ret;
724
725                 return ttm_tt_create(bo, false);
726         }
727
728         evict_mem = bo->mem;
729         evict_mem.mm_node = NULL;
730         evict_mem.bus.io_reserved_vm = false;
731         evict_mem.bus.io_reserved_count = 0;
732
733         ret = ttm_bo_mem_space(bo, &placement, &evict_mem, ctx);
734         if (ret) {
735                 if (ret != -ERESTARTSYS) {
736                         pr_err("Failed to find memory space for buffer 0x%p eviction\n",
737                                bo);
738                         ttm_bo_mem_space_debug(bo, &placement);
739                 }
740                 goto out;
741         }
742
743         ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, ctx);
744         if (unlikely(ret)) {
745                 if (ret != -ERESTARTSYS)
746                         pr_err("Buffer eviction failed\n");
747                 ttm_bo_mem_put(bo, &evict_mem);
748                 goto out;
749         }
750         bo->evicted = true;
751 out:
752         return ret;
753 }
754
755 bool ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
756                               const struct ttm_place *place)
757 {
758         /* Don't evict this BO if it's outside of the
759          * requested placement range
760          */
761         if (place->fpfn >= (bo->mem.start + bo->mem.size) ||
762             (place->lpfn && place->lpfn <= bo->mem.start))
763                 return false;
764
765         return true;
766 }
767 EXPORT_SYMBOL(ttm_bo_eviction_valuable);
768
769 /**
770  * Check the target bo is allowable to be evicted or swapout, including cases:
771  *
772  * a. if share same reservation object with ctx->resv, have assumption
773  * reservation objects should already be locked, so not lock again and
774  * return true directly when either the opreation allow_reserved_eviction
775  * or the target bo already is in delayed free list;
776  *
777  * b. Otherwise, trylock it.
778  */
779 static bool ttm_bo_evict_swapout_allowable(struct ttm_buffer_object *bo,
780                         struct ttm_operation_ctx *ctx, bool *locked, bool *busy)
781 {
782         bool ret = false;
783
784         if (bo->base.resv == ctx->resv) {
785                 dma_resv_assert_held(bo->base.resv);
786                 if (ctx->flags & TTM_OPT_FLAG_ALLOW_RES_EVICT
787                     || !list_empty(&bo->ddestroy))
788                         ret = true;
789                 *locked = false;
790                 if (busy)
791                         *busy = false;
792         } else {
793                 ret = dma_resv_trylock(bo->base.resv);
794                 *locked = ret;
795                 if (busy)
796                         *busy = !ret;
797         }
798
799         return ret;
800 }
801
802 /**
803  * ttm_mem_evict_wait_busy - wait for a busy BO to become available
804  *
805  * @busy_bo: BO which couldn't be locked with trylock
806  * @ctx: operation context
807  * @ticket: acquire ticket
808  *
809  * Try to lock a busy buffer object to avoid failing eviction.
810  */
811 static int ttm_mem_evict_wait_busy(struct ttm_buffer_object *busy_bo,
812                                    struct ttm_operation_ctx *ctx,
813                                    struct ww_acquire_ctx *ticket)
814 {
815         int r;
816
817         if (!busy_bo || !ticket)
818                 return -EBUSY;
819
820         if (ctx->interruptible)
821                 r = dma_resv_lock_interruptible(busy_bo->base.resv,
822                                                           ticket);
823         else
824                 r = dma_resv_lock(busy_bo->base.resv, ticket);
825
826         /*
827          * TODO: It would be better to keep the BO locked until allocation is at
828          * least tried one more time, but that would mean a much larger rework
829          * of TTM.
830          */
831         if (!r)
832                 dma_resv_unlock(busy_bo->base.resv);
833
834         return r == -EDEADLK ? -EBUSY : r;
835 }
836
837 static int ttm_mem_evict_first(struct ttm_bo_device *bdev,
838                                uint32_t mem_type,
839                                const struct ttm_place *place,
840                                struct ttm_operation_ctx *ctx,
841                                struct ww_acquire_ctx *ticket)
842 {
843         struct ttm_buffer_object *bo = NULL, *busy_bo = NULL;
844         struct ttm_bo_global *glob = bdev->glob;
845         struct ttm_mem_type_manager *man = &bdev->man[mem_type];
846         bool locked = false;
847         unsigned i;
848         int ret;
849
850         spin_lock(&glob->lru_lock);
851         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
852                 list_for_each_entry(bo, &man->lru[i], lru) {
853                         bool busy;
854
855                         if (!ttm_bo_evict_swapout_allowable(bo, ctx, &locked,
856                                                             &busy)) {
857                                 if (busy && !busy_bo && ticket !=
858                                     dma_resv_locking_ctx(bo->base.resv))
859                                         busy_bo = bo;
860                                 continue;
861                         }
862
863                         if (place && !bdev->driver->eviction_valuable(bo,
864                                                                       place)) {
865                                 if (locked)
866                                         dma_resv_unlock(bo->base.resv);
867                                 continue;
868                         }
869                         break;
870                 }
871
872                 /* If the inner loop terminated early, we have our candidate */
873                 if (&bo->lru != &man->lru[i])
874                         break;
875
876                 bo = NULL;
877         }
878
879         if (!bo) {
880                 if (busy_bo)
881                         kref_get(&busy_bo->list_kref);
882                 spin_unlock(&glob->lru_lock);
883                 ret = ttm_mem_evict_wait_busy(busy_bo, ctx, ticket);
884                 if (busy_bo)
885                         kref_put(&busy_bo->list_kref, ttm_bo_release_list);
886                 return ret;
887         }
888
889         kref_get(&bo->list_kref);
890
891         if (!list_empty(&bo->ddestroy)) {
892                 ret = ttm_bo_cleanup_refs(bo, ctx->interruptible,
893                                           ctx->no_wait_gpu, locked);
894                 kref_put(&bo->list_kref, ttm_bo_release_list);
895                 return ret;
896         }
897
898         ttm_bo_del_from_lru(bo);
899         spin_unlock(&glob->lru_lock);
900
901         ret = ttm_bo_evict(bo, ctx);
902         if (locked) {
903                 ttm_bo_unreserve(bo);
904         } else {
905                 spin_lock(&glob->lru_lock);
906                 ttm_bo_add_to_lru(bo);
907                 spin_unlock(&glob->lru_lock);
908         }
909
910         kref_put(&bo->list_kref, ttm_bo_release_list);
911         return ret;
912 }
913
914 void ttm_bo_mem_put(struct ttm_buffer_object *bo, struct ttm_mem_reg *mem)
915 {
916         struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type];
917
918         if (mem->mm_node)
919                 (*man->func->put_node)(man, mem);
920 }
921 EXPORT_SYMBOL(ttm_bo_mem_put);
922
923 /**
924  * Add the last move fence to the BO and reserve a new shared slot.
925  */
926 static int ttm_bo_add_move_fence(struct ttm_buffer_object *bo,
927                                  struct ttm_mem_type_manager *man,
928                                  struct ttm_mem_reg *mem)
929 {
930         struct dma_fence *fence;
931         int ret;
932
933         spin_lock(&man->move_lock);
934         fence = dma_fence_get(man->move);
935         spin_unlock(&man->move_lock);
936
937         if (fence) {
938                 dma_resv_add_shared_fence(bo->base.resv, fence);
939
940                 ret = dma_resv_reserve_shared(bo->base.resv, 1);
941                 if (unlikely(ret)) {
942                         dma_fence_put(fence);
943                         return ret;
944                 }
945
946                 dma_fence_put(bo->moving);
947                 bo->moving = fence;
948         }
949
950         return 0;
951 }
952
953 /**
954  * Repeatedly evict memory from the LRU for @mem_type until we create enough
955  * space, or we've evicted everything and there isn't enough space.
956  */
957 static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
958                                   const struct ttm_place *place,
959                                   struct ttm_mem_reg *mem,
960                                   struct ttm_operation_ctx *ctx)
961 {
962         struct ttm_bo_device *bdev = bo->bdev;
963         struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
964         struct ww_acquire_ctx *ticket;
965         int ret;
966
967         ticket = dma_resv_locking_ctx(bo->base.resv);
968         do {
969                 ret = (*man->func->get_node)(man, bo, place, mem);
970                 if (unlikely(ret != 0))
971                         return ret;
972                 if (mem->mm_node)
973                         break;
974                 ret = ttm_mem_evict_first(bdev, mem->mem_type, place, ctx,
975                                           ticket);
976                 if (unlikely(ret != 0))
977                         return ret;
978         } while (1);
979
980         return ttm_bo_add_move_fence(bo, man, mem);
981 }
982
983 static uint32_t ttm_bo_select_caching(struct ttm_mem_type_manager *man,
984                                       uint32_t cur_placement,
985                                       uint32_t proposed_placement)
986 {
987         uint32_t caching = proposed_placement & TTM_PL_MASK_CACHING;
988         uint32_t result = proposed_placement & ~TTM_PL_MASK_CACHING;
989
990         /**
991          * Keep current caching if possible.
992          */
993
994         if ((cur_placement & caching) != 0)
995                 result |= (cur_placement & caching);
996         else if ((man->default_caching & caching) != 0)
997                 result |= man->default_caching;
998         else if ((TTM_PL_FLAG_CACHED & caching) != 0)
999                 result |= TTM_PL_FLAG_CACHED;
1000         else if ((TTM_PL_FLAG_WC & caching) != 0)
1001                 result |= TTM_PL_FLAG_WC;
1002         else if ((TTM_PL_FLAG_UNCACHED & caching) != 0)
1003                 result |= TTM_PL_FLAG_UNCACHED;
1004
1005         return result;
1006 }
1007
1008 static bool ttm_bo_mt_compatible(struct ttm_mem_type_manager *man,
1009                                  uint32_t mem_type,
1010                                  const struct ttm_place *place,
1011                                  uint32_t *masked_placement)
1012 {
1013         uint32_t cur_flags = ttm_bo_type_flags(mem_type);
1014
1015         if ((cur_flags & place->flags & TTM_PL_MASK_MEM) == 0)
1016                 return false;
1017
1018         if ((place->flags & man->available_caching) == 0)
1019                 return false;
1020
1021         cur_flags |= (place->flags & man->available_caching);
1022
1023         *masked_placement = cur_flags;
1024         return true;
1025 }
1026
1027 /**
1028  * ttm_bo_mem_placement - check if placement is compatible
1029  * @bo: BO to find memory for
1030  * @place: where to search
1031  * @mem: the memory object to fill in
1032  * @ctx: operation context
1033  *
1034  * Check if placement is compatible and fill in mem structure.
1035  * Returns -EBUSY if placement won't work or negative error code.
1036  * 0 when placement can be used.
1037  */
1038 static int ttm_bo_mem_placement(struct ttm_buffer_object *bo,
1039                                 const struct ttm_place *place,
1040                                 struct ttm_mem_reg *mem,
1041                                 struct ttm_operation_ctx *ctx)
1042 {
1043         struct ttm_bo_device *bdev = bo->bdev;
1044         uint32_t mem_type = TTM_PL_SYSTEM;
1045         struct ttm_mem_type_manager *man;
1046         uint32_t cur_flags = 0;
1047         int ret;
1048
1049         ret = ttm_mem_type_from_place(place, &mem_type);
1050         if (ret)
1051                 return ret;
1052
1053         man = &bdev->man[mem_type];
1054         if (!man->has_type || !man->use_type)
1055                 return -EBUSY;
1056
1057         if (!ttm_bo_mt_compatible(man, mem_type, place, &cur_flags))
1058                 return -EBUSY;
1059
1060         cur_flags = ttm_bo_select_caching(man, bo->mem.placement, cur_flags);
1061         /*
1062          * Use the access and other non-mapping-related flag bits from
1063          * the memory placement flags to the current flags
1064          */
1065         ttm_flag_masked(&cur_flags, place->flags, ~TTM_PL_MASK_MEMTYPE);
1066
1067         mem->mem_type = mem_type;
1068         mem->placement = cur_flags;
1069
1070         if (bo->mem.mem_type < mem_type && !list_empty(&bo->lru)) {
1071                 spin_lock(&bo->bdev->glob->lru_lock);
1072                 ttm_bo_del_from_lru(bo);
1073                 ttm_bo_add_mem_to_lru(bo, mem);
1074                 spin_unlock(&bo->bdev->glob->lru_lock);
1075         }
1076
1077         return 0;
1078 }
1079
1080 /**
1081  * Creates space for memory region @mem according to its type.
1082  *
1083  * This function first searches for free space in compatible memory types in
1084  * the priority order defined by the driver.  If free space isn't found, then
1085  * ttm_bo_mem_force_space is attempted in priority order to evict and find
1086  * space.
1087  */
1088 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
1089                         struct ttm_placement *placement,
1090                         struct ttm_mem_reg *mem,
1091                         struct ttm_operation_ctx *ctx)
1092 {
1093         struct ttm_bo_device *bdev = bo->bdev;
1094         bool type_found = false;
1095         int i, ret;
1096
1097         ret = dma_resv_reserve_shared(bo->base.resv, 1);
1098         if (unlikely(ret))
1099                 return ret;
1100
1101         mem->mm_node = NULL;
1102         for (i = 0; i < placement->num_placement; ++i) {
1103                 const struct ttm_place *place = &placement->placement[i];
1104                 struct ttm_mem_type_manager *man;
1105
1106                 ret = ttm_bo_mem_placement(bo, place, mem, ctx);
1107                 if (ret == -EBUSY)
1108                         continue;
1109                 if (ret)
1110                         goto error;
1111
1112                 type_found = true;
1113                 mem->mm_node = NULL;
1114                 if (mem->mem_type == TTM_PL_SYSTEM)
1115                         return 0;
1116
1117                 man = &bdev->man[mem->mem_type];
1118                 ret = (*man->func->get_node)(man, bo, place, mem);
1119                 if (unlikely(ret))
1120                         goto error;
1121
1122                 if (mem->mm_node) {
1123                         ret = ttm_bo_add_move_fence(bo, man, mem);
1124                         if (unlikely(ret)) {
1125                                 (*man->func->put_node)(man, mem);
1126                                 goto error;
1127                         }
1128                         return 0;
1129                 }
1130         }
1131
1132         for (i = 0; i < placement->num_busy_placement; ++i) {
1133                 const struct ttm_place *place = &placement->busy_placement[i];
1134
1135                 ret = ttm_bo_mem_placement(bo, place, mem, ctx);
1136                 if (ret == -EBUSY)
1137                         continue;
1138                 if (ret)
1139                         goto error;
1140
1141                 type_found = true;
1142                 mem->mm_node = NULL;
1143                 if (mem->mem_type == TTM_PL_SYSTEM)
1144                         return 0;
1145
1146                 ret = ttm_bo_mem_force_space(bo, place, mem, ctx);
1147                 if (ret == 0 && mem->mm_node)
1148                         return 0;
1149
1150                 if (ret && ret != -EBUSY)
1151                         goto error;
1152         }
1153
1154         ret = -ENOMEM;
1155         if (!type_found) {
1156                 pr_err(TTM_PFX "No compatible memory type found\n");
1157                 ret = -EINVAL;
1158         }
1159
1160 error:
1161         if (bo->mem.mem_type == TTM_PL_SYSTEM && !list_empty(&bo->lru)) {
1162                 spin_lock(&bo->bdev->glob->lru_lock);
1163                 ttm_bo_move_to_lru_tail(bo, NULL);
1164                 spin_unlock(&bo->bdev->glob->lru_lock);
1165         }
1166
1167         return ret;
1168 }
1169 EXPORT_SYMBOL(ttm_bo_mem_space);
1170
1171 static int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
1172                               struct ttm_placement *placement,
1173                               struct ttm_operation_ctx *ctx)
1174 {
1175         int ret = 0;
1176         struct ttm_mem_reg mem;
1177
1178         dma_resv_assert_held(bo->base.resv);
1179
1180         mem.num_pages = bo->num_pages;
1181         mem.size = mem.num_pages << PAGE_SHIFT;
1182         mem.page_alignment = bo->mem.page_alignment;
1183         mem.bus.io_reserved_vm = false;
1184         mem.bus.io_reserved_count = 0;
1185         /*
1186          * Determine where to move the buffer.
1187          */
1188         ret = ttm_bo_mem_space(bo, placement, &mem, ctx);
1189         if (ret)
1190                 goto out_unlock;
1191         ret = ttm_bo_handle_move_mem(bo, &mem, false, ctx);
1192 out_unlock:
1193         if (ret && mem.mm_node)
1194                 ttm_bo_mem_put(bo, &mem);
1195         return ret;
1196 }
1197
1198 static bool ttm_bo_places_compat(const struct ttm_place *places,
1199                                  unsigned num_placement,
1200                                  struct ttm_mem_reg *mem,
1201                                  uint32_t *new_flags)
1202 {
1203         unsigned i;
1204
1205         for (i = 0; i < num_placement; i++) {
1206                 const struct ttm_place *heap = &places[i];
1207
1208                 if (mem->mm_node && (mem->start < heap->fpfn ||
1209                      (heap->lpfn != 0 && (mem->start + mem->num_pages) > heap->lpfn)))
1210                         continue;
1211
1212                 *new_flags = heap->flags;
1213                 if ((*new_flags & mem->placement & TTM_PL_MASK_CACHING) &&
1214                     (*new_flags & mem->placement & TTM_PL_MASK_MEM) &&
1215                     (!(*new_flags & TTM_PL_FLAG_CONTIGUOUS) ||
1216                      (mem->placement & TTM_PL_FLAG_CONTIGUOUS)))
1217                         return true;
1218         }
1219         return false;
1220 }
1221
1222 bool ttm_bo_mem_compat(struct ttm_placement *placement,
1223                        struct ttm_mem_reg *mem,
1224                        uint32_t *new_flags)
1225 {
1226         if (ttm_bo_places_compat(placement->placement, placement->num_placement,
1227                                  mem, new_flags))
1228                 return true;
1229
1230         if ((placement->busy_placement != placement->placement ||
1231              placement->num_busy_placement > placement->num_placement) &&
1232             ttm_bo_places_compat(placement->busy_placement,
1233                                  placement->num_busy_placement,
1234                                  mem, new_flags))
1235                 return true;
1236
1237         return false;
1238 }
1239 EXPORT_SYMBOL(ttm_bo_mem_compat);
1240
1241 int ttm_bo_validate(struct ttm_buffer_object *bo,
1242                     struct ttm_placement *placement,
1243                     struct ttm_operation_ctx *ctx)
1244 {
1245         int ret;
1246         uint32_t new_flags;
1247
1248         dma_resv_assert_held(bo->base.resv);
1249         /*
1250          * Check whether we need to move buffer.
1251          */
1252         if (!ttm_bo_mem_compat(placement, &bo->mem, &new_flags)) {
1253                 ret = ttm_bo_move_buffer(bo, placement, ctx);
1254                 if (ret)
1255                         return ret;
1256         } else {
1257                 /*
1258                  * Use the access and other non-mapping-related flag bits from
1259                  * the compatible memory placement flags to the active flags
1260                  */
1261                 ttm_flag_masked(&bo->mem.placement, new_flags,
1262                                 ~TTM_PL_MASK_MEMTYPE);
1263         }
1264         /*
1265          * We might need to add a TTM.
1266          */
1267         if (bo->mem.mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
1268                 ret = ttm_tt_create(bo, true);
1269                 if (ret)
1270                         return ret;
1271         }
1272         return 0;
1273 }
1274 EXPORT_SYMBOL(ttm_bo_validate);
1275
1276 int ttm_bo_init_reserved(struct ttm_bo_device *bdev,
1277                          struct ttm_buffer_object *bo,
1278                          unsigned long size,
1279                          enum ttm_bo_type type,
1280                          struct ttm_placement *placement,
1281                          uint32_t page_alignment,
1282                          struct ttm_operation_ctx *ctx,
1283                          size_t acc_size,
1284                          struct sg_table *sg,
1285                          struct dma_resv *resv,
1286                          void (*destroy) (struct ttm_buffer_object *))
1287 {
1288         int ret = 0;
1289         unsigned long num_pages;
1290         struct ttm_mem_global *mem_glob = bdev->glob->mem_glob;
1291         bool locked;
1292
1293         ret = ttm_mem_global_alloc(mem_glob, acc_size, ctx);
1294         if (ret) {
1295                 pr_err("Out of kernel memory\n");
1296                 if (destroy)
1297                         (*destroy)(bo);
1298                 else
1299                         kfree(bo);
1300                 return -ENOMEM;
1301         }
1302
1303         num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1304         if (num_pages == 0) {
1305                 pr_err("Illegal buffer object size\n");
1306                 if (destroy)
1307                         (*destroy)(bo);
1308                 else
1309                         kfree(bo);
1310                 ttm_mem_global_free(mem_glob, acc_size);
1311                 return -EINVAL;
1312         }
1313         bo->destroy = destroy ? destroy : ttm_bo_default_destroy;
1314
1315         kref_init(&bo->kref);
1316         kref_init(&bo->list_kref);
1317         INIT_LIST_HEAD(&bo->lru);
1318         INIT_LIST_HEAD(&bo->ddestroy);
1319         INIT_LIST_HEAD(&bo->swap);
1320         INIT_LIST_HEAD(&bo->io_reserve_lru);
1321         mutex_init(&bo->wu_mutex);
1322         bo->bdev = bdev;
1323         bo->type = type;
1324         bo->num_pages = num_pages;
1325         bo->mem.size = num_pages << PAGE_SHIFT;
1326         bo->mem.mem_type = TTM_PL_SYSTEM;
1327         bo->mem.num_pages = bo->num_pages;
1328         bo->mem.mm_node = NULL;
1329         bo->mem.page_alignment = page_alignment;
1330         bo->mem.bus.io_reserved_vm = false;
1331         bo->mem.bus.io_reserved_count = 0;
1332         bo->moving = NULL;
1333         bo->mem.placement = (TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED);
1334         bo->acc_size = acc_size;
1335         bo->sg = sg;
1336         if (resv) {
1337                 bo->base.resv = resv;
1338                 dma_resv_assert_held(bo->base.resv);
1339         } else {
1340                 bo->base.resv = &bo->base._resv;
1341         }
1342         if (!ttm_bo_uses_embedded_gem_object(bo)) {
1343                 /*
1344                  * bo.gem is not initialized, so we have to setup the
1345                  * struct elements we want use regardless.
1346                  */
1347                 dma_resv_init(&bo->base._resv);
1348                 drm_vma_node_reset(&bo->base.vma_node);
1349         }
1350         atomic_inc(&bo->bdev->glob->bo_count);
1351
1352         /*
1353          * For ttm_bo_type_device buffers, allocate
1354          * address space from the device.
1355          */
1356         if (bo->type == ttm_bo_type_device ||
1357             bo->type == ttm_bo_type_sg)
1358                 ret = drm_vma_offset_add(bdev->vma_manager, &bo->base.vma_node,
1359                                          bo->mem.num_pages);
1360
1361         /* passed reservation objects should already be locked,
1362          * since otherwise lockdep will be angered in radeon.
1363          */
1364         if (!resv) {
1365                 locked = dma_resv_trylock(bo->base.resv);
1366                 WARN_ON(!locked);
1367         }
1368
1369         if (likely(!ret))
1370                 ret = ttm_bo_validate(bo, placement, ctx);
1371
1372         if (unlikely(ret)) {
1373                 if (!resv)
1374                         ttm_bo_unreserve(bo);
1375
1376                 ttm_bo_put(bo);
1377                 return ret;
1378         }
1379
1380         if (resv && !(bo->mem.placement & TTM_PL_FLAG_NO_EVICT)) {
1381                 spin_lock(&bdev->glob->lru_lock);
1382                 ttm_bo_add_to_lru(bo);
1383                 spin_unlock(&bdev->glob->lru_lock);
1384         }
1385
1386         return ret;
1387 }
1388 EXPORT_SYMBOL(ttm_bo_init_reserved);
1389
1390 int ttm_bo_init(struct ttm_bo_device *bdev,
1391                 struct ttm_buffer_object *bo,
1392                 unsigned long size,
1393                 enum ttm_bo_type type,
1394                 struct ttm_placement *placement,
1395                 uint32_t page_alignment,
1396                 bool interruptible,
1397                 size_t acc_size,
1398                 struct sg_table *sg,
1399                 struct dma_resv *resv,
1400                 void (*destroy) (struct ttm_buffer_object *))
1401 {
1402         struct ttm_operation_ctx ctx = { interruptible, false };
1403         int ret;
1404
1405         ret = ttm_bo_init_reserved(bdev, bo, size, type, placement,
1406                                    page_alignment, &ctx, acc_size,
1407                                    sg, resv, destroy);
1408         if (ret)
1409                 return ret;
1410
1411         if (!resv)
1412                 ttm_bo_unreserve(bo);
1413
1414         return 0;
1415 }
1416 EXPORT_SYMBOL(ttm_bo_init);
1417
1418 size_t ttm_bo_acc_size(struct ttm_bo_device *bdev,
1419                        unsigned long bo_size,
1420                        unsigned struct_size)
1421 {
1422         unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1423         size_t size = 0;
1424
1425         size += ttm_round_pot(struct_size);
1426         size += ttm_round_pot(npages * sizeof(void *));
1427         size += ttm_round_pot(sizeof(struct ttm_tt));
1428         return size;
1429 }
1430 EXPORT_SYMBOL(ttm_bo_acc_size);
1431
1432 size_t ttm_bo_dma_acc_size(struct ttm_bo_device *bdev,
1433                            unsigned long bo_size,
1434                            unsigned struct_size)
1435 {
1436         unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1437         size_t size = 0;
1438
1439         size += ttm_round_pot(struct_size);
1440         size += ttm_round_pot(npages * (2*sizeof(void *) + sizeof(dma_addr_t)));
1441         size += ttm_round_pot(sizeof(struct ttm_dma_tt));
1442         return size;
1443 }
1444 EXPORT_SYMBOL(ttm_bo_dma_acc_size);
1445
1446 int ttm_bo_create(struct ttm_bo_device *bdev,
1447                         unsigned long size,
1448                         enum ttm_bo_type type,
1449                         struct ttm_placement *placement,
1450                         uint32_t page_alignment,
1451                         bool interruptible,
1452                         struct ttm_buffer_object **p_bo)
1453 {
1454         struct ttm_buffer_object *bo;
1455         size_t acc_size;
1456         int ret;
1457
1458         bo = kzalloc(sizeof(*bo), GFP_KERNEL);
1459         if (unlikely(bo == NULL))
1460                 return -ENOMEM;
1461
1462         acc_size = ttm_bo_acc_size(bdev, size, sizeof(struct ttm_buffer_object));
1463         ret = ttm_bo_init(bdev, bo, size, type, placement, page_alignment,
1464                           interruptible, acc_size,
1465                           NULL, NULL, NULL);
1466         if (likely(ret == 0))
1467                 *p_bo = bo;
1468
1469         return ret;
1470 }
1471 EXPORT_SYMBOL(ttm_bo_create);
1472
1473 static int ttm_bo_force_list_clean(struct ttm_bo_device *bdev,
1474                                    unsigned mem_type)
1475 {
1476         struct ttm_operation_ctx ctx = {
1477                 .interruptible = false,
1478                 .no_wait_gpu = false,
1479                 .flags = TTM_OPT_FLAG_FORCE_ALLOC
1480         };
1481         struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1482         struct ttm_bo_global *glob = bdev->glob;
1483         struct dma_fence *fence;
1484         int ret;
1485         unsigned i;
1486
1487         /*
1488          * Can't use standard list traversal since we're unlocking.
1489          */
1490
1491         spin_lock(&glob->lru_lock);
1492         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
1493                 while (!list_empty(&man->lru[i])) {
1494                         spin_unlock(&glob->lru_lock);
1495                         ret = ttm_mem_evict_first(bdev, mem_type, NULL, &ctx,
1496                                                   NULL);
1497                         if (ret)
1498                                 return ret;
1499                         spin_lock(&glob->lru_lock);
1500                 }
1501         }
1502         spin_unlock(&glob->lru_lock);
1503
1504         spin_lock(&man->move_lock);
1505         fence = dma_fence_get(man->move);
1506         spin_unlock(&man->move_lock);
1507
1508         if (fence) {
1509                 ret = dma_fence_wait(fence, false);
1510                 dma_fence_put(fence);
1511                 if (ret)
1512                         return ret;
1513         }
1514
1515         return 0;
1516 }
1517
1518 int ttm_bo_clean_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1519 {
1520         struct ttm_mem_type_manager *man;
1521         int ret = -EINVAL;
1522
1523         if (mem_type >= TTM_NUM_MEM_TYPES) {
1524                 pr_err("Illegal memory type %d\n", mem_type);
1525                 return ret;
1526         }
1527         man = &bdev->man[mem_type];
1528
1529         if (!man->has_type) {
1530                 pr_err("Trying to take down uninitialized memory manager type %u\n",
1531                        mem_type);
1532                 return ret;
1533         }
1534
1535         man->use_type = false;
1536         man->has_type = false;
1537
1538         ret = 0;
1539         if (mem_type > 0) {
1540                 ret = ttm_bo_force_list_clean(bdev, mem_type);
1541                 if (ret) {
1542                         pr_err("Cleanup eviction failed\n");
1543                         return ret;
1544                 }
1545
1546                 ret = (*man->func->takedown)(man);
1547         }
1548
1549         dma_fence_put(man->move);
1550         man->move = NULL;
1551
1552         return ret;
1553 }
1554 EXPORT_SYMBOL(ttm_bo_clean_mm);
1555
1556 int ttm_bo_evict_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1557 {
1558         struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1559
1560         if (mem_type == 0 || mem_type >= TTM_NUM_MEM_TYPES) {
1561                 pr_err("Illegal memory manager memory type %u\n", mem_type);
1562                 return -EINVAL;
1563         }
1564
1565         if (!man->has_type) {
1566                 pr_err("Memory type %u has not been initialized\n", mem_type);
1567                 return 0;
1568         }
1569
1570         return ttm_bo_force_list_clean(bdev, mem_type);
1571 }
1572 EXPORT_SYMBOL(ttm_bo_evict_mm);
1573
1574 int ttm_bo_init_mm(struct ttm_bo_device *bdev, unsigned type,
1575                         unsigned long p_size)
1576 {
1577         int ret;
1578         struct ttm_mem_type_manager *man;
1579         unsigned i;
1580
1581         BUG_ON(type >= TTM_NUM_MEM_TYPES);
1582         man = &bdev->man[type];
1583         BUG_ON(man->has_type);
1584         man->io_reserve_fastpath = true;
1585         man->use_io_reserve_lru = false;
1586         mutex_init(&man->io_reserve_mutex);
1587         spin_lock_init(&man->move_lock);
1588         INIT_LIST_HEAD(&man->io_reserve_lru);
1589
1590         ret = bdev->driver->init_mem_type(bdev, type, man);
1591         if (ret)
1592                 return ret;
1593         man->bdev = bdev;
1594
1595         if (type != TTM_PL_SYSTEM) {
1596                 ret = (*man->func->init)(man, p_size);
1597                 if (ret)
1598                         return ret;
1599         }
1600         man->has_type = true;
1601         man->use_type = true;
1602         man->size = p_size;
1603
1604         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1605                 INIT_LIST_HEAD(&man->lru[i]);
1606         man->move = NULL;
1607
1608         return 0;
1609 }
1610 EXPORT_SYMBOL(ttm_bo_init_mm);
1611
1612 static void ttm_bo_global_kobj_release(struct kobject *kobj)
1613 {
1614         struct ttm_bo_global *glob =
1615                 container_of(kobj, struct ttm_bo_global, kobj);
1616
1617         __free_page(glob->dummy_read_page);
1618 }
1619
1620 static void ttm_bo_global_release(void)
1621 {
1622         struct ttm_bo_global *glob = &ttm_bo_glob;
1623
1624         mutex_lock(&ttm_global_mutex);
1625         if (--ttm_bo_glob_use_count > 0)
1626                 goto out;
1627
1628         kobject_del(&glob->kobj);
1629         kobject_put(&glob->kobj);
1630         ttm_mem_global_release(&ttm_mem_glob);
1631         memset(glob, 0, sizeof(*glob));
1632 out:
1633         mutex_unlock(&ttm_global_mutex);
1634 }
1635
1636 static int ttm_bo_global_init(void)
1637 {
1638         struct ttm_bo_global *glob = &ttm_bo_glob;
1639         int ret = 0;
1640         unsigned i;
1641
1642         mutex_lock(&ttm_global_mutex);
1643         if (++ttm_bo_glob_use_count > 1)
1644                 goto out;
1645
1646         ret = ttm_mem_global_init(&ttm_mem_glob);
1647         if (ret)
1648                 goto out;
1649
1650         spin_lock_init(&glob->lru_lock);
1651         glob->mem_glob = &ttm_mem_glob;
1652         glob->mem_glob->bo_glob = glob;
1653         glob->dummy_read_page = alloc_page(__GFP_ZERO | GFP_DMA32);
1654
1655         if (unlikely(glob->dummy_read_page == NULL)) {
1656                 ret = -ENOMEM;
1657                 goto out;
1658         }
1659
1660         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1661                 INIT_LIST_HEAD(&glob->swap_lru[i]);
1662         INIT_LIST_HEAD(&glob->device_list);
1663         atomic_set(&glob->bo_count, 0);
1664
1665         ret = kobject_init_and_add(
1666                 &glob->kobj, &ttm_bo_glob_kobj_type, ttm_get_kobj(), "buffer_objects");
1667         if (unlikely(ret != 0))
1668                 kobject_put(&glob->kobj);
1669 out:
1670         mutex_unlock(&ttm_global_mutex);
1671         return ret;
1672 }
1673
1674 int ttm_bo_device_release(struct ttm_bo_device *bdev)
1675 {
1676         int ret = 0;
1677         unsigned i = TTM_NUM_MEM_TYPES;
1678         struct ttm_mem_type_manager *man;
1679         struct ttm_bo_global *glob = bdev->glob;
1680
1681         while (i--) {
1682                 man = &bdev->man[i];
1683                 if (man->has_type) {
1684                         man->use_type = false;
1685                         if ((i != TTM_PL_SYSTEM) && ttm_bo_clean_mm(bdev, i)) {
1686                                 ret = -EBUSY;
1687                                 pr_err("DRM memory manager type %d is not clean\n",
1688                                        i);
1689                         }
1690                         man->has_type = false;
1691                 }
1692         }
1693
1694         mutex_lock(&ttm_global_mutex);
1695         list_del(&bdev->device_list);
1696         mutex_unlock(&ttm_global_mutex);
1697
1698         cancel_delayed_work_sync(&bdev->wq);
1699
1700         if (ttm_bo_delayed_delete(bdev, true))
1701                 pr_debug("Delayed destroy list was clean\n");
1702
1703         spin_lock(&glob->lru_lock);
1704         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i)
1705                 if (list_empty(&bdev->man[0].lru[0]))
1706                         pr_debug("Swap list %d was clean\n", i);
1707         spin_unlock(&glob->lru_lock);
1708
1709         if (!ret)
1710                 ttm_bo_global_release();
1711
1712         return ret;
1713 }
1714 EXPORT_SYMBOL(ttm_bo_device_release);
1715
1716 int ttm_bo_device_init(struct ttm_bo_device *bdev,
1717                        struct ttm_bo_driver *driver,
1718                        struct address_space *mapping,
1719                        struct drm_vma_offset_manager *vma_manager,
1720                        bool need_dma32)
1721 {
1722         struct ttm_bo_global *glob = &ttm_bo_glob;
1723         int ret;
1724
1725         if (WARN_ON(vma_manager == NULL))
1726                 return -EINVAL;
1727
1728         ret = ttm_bo_global_init();
1729         if (ret)
1730                 return ret;
1731
1732         bdev->driver = driver;
1733
1734         memset(bdev->man, 0, sizeof(bdev->man));
1735
1736         /*
1737          * Initialize the system memory buffer type.
1738          * Other types need to be driver / IOCTL initialized.
1739          */
1740         ret = ttm_bo_init_mm(bdev, TTM_PL_SYSTEM, 0);
1741         if (unlikely(ret != 0))
1742                 goto out_no_sys;
1743
1744         bdev->vma_manager = vma_manager;
1745         INIT_DELAYED_WORK(&bdev->wq, ttm_bo_delayed_workqueue);
1746         INIT_LIST_HEAD(&bdev->ddestroy);
1747         bdev->dev_mapping = mapping;
1748         bdev->glob = glob;
1749         bdev->need_dma32 = need_dma32;
1750         mutex_lock(&ttm_global_mutex);
1751         list_add_tail(&bdev->device_list, &glob->device_list);
1752         mutex_unlock(&ttm_global_mutex);
1753
1754         return 0;
1755 out_no_sys:
1756         ttm_bo_global_release();
1757         return ret;
1758 }
1759 EXPORT_SYMBOL(ttm_bo_device_init);
1760
1761 /*
1762  * buffer object vm functions.
1763  */
1764
1765 bool ttm_mem_reg_is_pci(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
1766 {
1767         struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
1768
1769         if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED)) {
1770                 if (mem->mem_type == TTM_PL_SYSTEM)
1771                         return false;
1772
1773                 if (man->flags & TTM_MEMTYPE_FLAG_CMA)
1774                         return false;
1775
1776                 if (mem->placement & TTM_PL_FLAG_CACHED)
1777                         return false;
1778         }
1779         return true;
1780 }
1781
1782 void ttm_bo_unmap_virtual_locked(struct ttm_buffer_object *bo)
1783 {
1784         struct ttm_bo_device *bdev = bo->bdev;
1785
1786         drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
1787         ttm_mem_io_free_vm(bo);
1788 }
1789
1790 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1791 {
1792         struct ttm_bo_device *bdev = bo->bdev;
1793         struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
1794
1795         ttm_mem_io_lock(man, false);
1796         ttm_bo_unmap_virtual_locked(bo);
1797         ttm_mem_io_unlock(man);
1798 }
1799
1800
1801 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1802
1803 int ttm_bo_wait(struct ttm_buffer_object *bo,
1804                 bool interruptible, bool no_wait)
1805 {
1806         long timeout = 15 * HZ;
1807
1808         if (no_wait) {
1809                 if (dma_resv_test_signaled_rcu(bo->base.resv, true))
1810                         return 0;
1811                 else
1812                         return -EBUSY;
1813         }
1814
1815         timeout = dma_resv_wait_timeout_rcu(bo->base.resv, true,
1816                                                       interruptible, timeout);
1817         if (timeout < 0)
1818                 return timeout;
1819
1820         if (timeout == 0)
1821                 return -EBUSY;
1822
1823         dma_resv_add_excl_fence(bo->base.resv, NULL);
1824         return 0;
1825 }
1826 EXPORT_SYMBOL(ttm_bo_wait);
1827
1828 /**
1829  * A buffer object shrink method that tries to swap out the first
1830  * buffer object on the bo_global::swap_lru list.
1831  */
1832 int ttm_bo_swapout(struct ttm_bo_global *glob, struct ttm_operation_ctx *ctx)
1833 {
1834         struct ttm_buffer_object *bo;
1835         int ret = -EBUSY;
1836         bool locked;
1837         unsigned i;
1838
1839         spin_lock(&glob->lru_lock);
1840         for (i = 0; i < TTM_MAX_BO_PRIORITY; ++i) {
1841                 list_for_each_entry(bo, &glob->swap_lru[i], swap) {
1842                         if (ttm_bo_evict_swapout_allowable(bo, ctx, &locked,
1843                                                            NULL)) {
1844                                 ret = 0;
1845                                 break;
1846                         }
1847                 }
1848                 if (!ret)
1849                         break;
1850         }
1851
1852         if (ret) {
1853                 spin_unlock(&glob->lru_lock);
1854                 return ret;
1855         }
1856
1857         kref_get(&bo->list_kref);
1858
1859         if (!list_empty(&bo->ddestroy)) {
1860                 ret = ttm_bo_cleanup_refs(bo, false, false, locked);
1861                 kref_put(&bo->list_kref, ttm_bo_release_list);
1862                 return ret;
1863         }
1864
1865         ttm_bo_del_from_lru(bo);
1866         spin_unlock(&glob->lru_lock);
1867
1868         /**
1869          * Move to system cached
1870          */
1871
1872         if (bo->mem.mem_type != TTM_PL_SYSTEM ||
1873             bo->ttm->caching_state != tt_cached) {
1874                 struct ttm_operation_ctx ctx = { false, false };
1875                 struct ttm_mem_reg evict_mem;
1876
1877                 evict_mem = bo->mem;
1878                 evict_mem.mm_node = NULL;
1879                 evict_mem.placement = TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED;
1880                 evict_mem.mem_type = TTM_PL_SYSTEM;
1881
1882                 ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, &ctx);
1883                 if (unlikely(ret != 0))
1884                         goto out;
1885         }
1886
1887         /**
1888          * Make sure BO is idle.
1889          */
1890
1891         ret = ttm_bo_wait(bo, false, false);
1892         if (unlikely(ret != 0))
1893                 goto out;
1894
1895         ttm_bo_unmap_virtual(bo);
1896
1897         /**
1898          * Swap out. Buffer will be swapped in again as soon as
1899          * anyone tries to access a ttm page.
1900          */
1901
1902         if (bo->bdev->driver->swap_notify)
1903                 bo->bdev->driver->swap_notify(bo);
1904
1905         ret = ttm_tt_swapout(bo->ttm, bo->persistent_swap_storage);
1906 out:
1907
1908         /**
1909          *
1910          * Unreserve without putting on LRU to avoid swapping out an
1911          * already swapped buffer.
1912          */
1913         if (locked)
1914                 dma_resv_unlock(bo->base.resv);
1915         kref_put(&bo->list_kref, ttm_bo_release_list);
1916         return ret;
1917 }
1918 EXPORT_SYMBOL(ttm_bo_swapout);
1919
1920 void ttm_bo_swapout_all(struct ttm_bo_device *bdev)
1921 {
1922         struct ttm_operation_ctx ctx = {
1923                 .interruptible = false,
1924                 .no_wait_gpu = false
1925         };
1926
1927         while (ttm_bo_swapout(bdev->glob, &ctx) == 0)
1928                 ;
1929 }
1930 EXPORT_SYMBOL(ttm_bo_swapout_all);
1931
1932 /**
1933  * ttm_bo_wait_unreserved - interruptible wait for a buffer object to become
1934  * unreserved
1935  *
1936  * @bo: Pointer to buffer
1937  */
1938 int ttm_bo_wait_unreserved(struct ttm_buffer_object *bo)
1939 {
1940         int ret;
1941
1942         /*
1943          * In the absense of a wait_unlocked API,
1944          * Use the bo::wu_mutex to avoid triggering livelocks due to
1945          * concurrent use of this function. Note that this use of
1946          * bo::wu_mutex can go away if we change locking order to
1947          * mmap_sem -> bo::reserve.
1948          */
1949         ret = mutex_lock_interruptible(&bo->wu_mutex);
1950         if (unlikely(ret != 0))
1951                 return -ERESTARTSYS;
1952         if (!dma_resv_is_locked(bo->base.resv))
1953                 goto out_unlock;
1954         ret = dma_resv_lock_interruptible(bo->base.resv, NULL);
1955         if (ret == -EINTR)
1956                 ret = -ERESTARTSYS;
1957         if (unlikely(ret != 0))
1958                 goto out_unlock;
1959         dma_resv_unlock(bo->base.resv);
1960
1961 out_unlock:
1962         mutex_unlock(&bo->wu_mutex);
1963         return ret;
1964 }