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