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