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