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