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