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