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