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