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