drm/ttm: Reduce differences with Linux 3.9
[dragonfly.git] / sys / dev / drm / ttm / ttm_bo.c
1 /**************************************************************************
2  *
3  * Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sub license, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial portions
16  * of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
22  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
24  * USE OR OTHER DEALINGS IN THE SOFTWARE.
25  *
26  **************************************************************************/
27 /*
28  * Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
29  *
30  * $FreeBSD: head/sys/dev/drm2/ttm/ttm_bo.c 248060 2013-03-08 18:11:02Z dumbbell $
31  */
32
33 #define pr_fmt(fmt) "[TTM] " fmt
34
35 #include <drm/ttm/ttm_module.h>
36 #include <drm/ttm/ttm_bo_driver.h>
37 #include <drm/ttm/ttm_placement.h>
38 #include <linux/atomic.h>
39 #include <linux/export.h>
40
41 #define TTM_ASSERT_LOCKED(param)
42 #define TTM_DEBUG(fmt, arg...)
43 #define TTM_BO_HASH_ORDER 13
44
45 static int ttm_bo_setup_vm(struct ttm_buffer_object *bo);
46 static int ttm_bo_swapout(struct ttm_mem_shrink *shrink);
47 static void ttm_bo_global_kobj_release(struct ttm_bo_global *glob);
48
49 MALLOC_DEFINE(M_TTM_BO, "ttm_bo", "TTM Buffer Objects");
50
51 static inline int ttm_mem_type_from_flags(uint32_t flags, uint32_t *mem_type)
52 {
53         int i;
54
55         for (i = 0; i <= TTM_PL_PRIV5; i++)
56                 if (flags & (1 << i)) {
57                         *mem_type = i;
58                         return 0;
59                 }
60         return -EINVAL;
61 }
62
63 static void ttm_mem_type_debug(struct ttm_bo_device *bdev, int mem_type)
64 {
65         struct ttm_mem_type_manager *man = &bdev->man[mem_type];
66
67         kprintf("    has_type: %d\n", man->has_type);
68         kprintf("    use_type: %d\n", man->use_type);
69         kprintf("    flags: 0x%08X\n", man->flags);
70         kprintf("    gpu_offset: 0x%08lX\n", man->gpu_offset);
71         kprintf("    size: %ju\n", (uintmax_t)man->size);
72         kprintf("    available_caching: 0x%08X\n", man->available_caching);
73         kprintf("    default_caching: 0x%08X\n", man->default_caching);
74         if (mem_type != TTM_PL_SYSTEM)
75                 (*man->func->debug)(man, TTM_PFX);
76 }
77
78 static void ttm_bo_mem_space_debug(struct ttm_buffer_object *bo,
79                                         struct ttm_placement *placement)
80 {
81         int i, ret, mem_type;
82
83         kprintf("No space for %p (%lu pages, %luK, %luM)\n",
84                bo, bo->mem.num_pages, bo->mem.size >> 10,
85                bo->mem.size >> 20);
86         for (i = 0; i < placement->num_placement; i++) {
87                 ret = ttm_mem_type_from_flags(placement->placement[i],
88                                                 &mem_type);
89                 if (ret)
90                         return;
91                 kprintf("  placement[%d]=0x%08X (%d)\n",
92                        i, placement->placement[i], mem_type);
93                 ttm_mem_type_debug(bo->bdev, mem_type);
94         }
95 }
96
97 #if 0
98 static ssize_t ttm_bo_global_show(struct ttm_bo_global *glob,
99     char *buffer)
100 {
101
102         return snprintf(buffer, PAGE_SIZE, "%lu\n",
103                         (unsigned long) atomic_read(&glob->bo_count));
104 }
105 #endif
106
107 static inline uint32_t ttm_bo_type_flags(unsigned type)
108 {
109         return 1 << (type);
110 }
111
112 static void ttm_bo_release_list(struct kref *list_kref)
113 {
114         struct ttm_buffer_object *bo =
115             container_of(list_kref, struct ttm_buffer_object, list_kref);
116         struct ttm_bo_device *bdev = bo->bdev;
117         size_t acc_size = bo->acc_size;
118
119         BUG_ON(atomic_read(&bo->list_kref.refcount));
120         BUG_ON(atomic_read(&bo->kref.refcount));
121         BUG_ON(atomic_read(&bo->cpu_writers));
122         BUG_ON(bo->sync_obj != NULL);
123         BUG_ON(bo->mem.mm_node != NULL);
124         BUG_ON(!list_empty(&bo->lru));
125         BUG_ON(!list_empty(&bo->ddestroy));
126
127         if (bo->ttm)
128                 ttm_tt_destroy(bo->ttm);
129         atomic_dec(&bo->glob->bo_count);
130         if (bo->destroy)
131                 bo->destroy(bo);
132         else {
133                 kfree(bo, M_TTM_BO);
134         }
135         ttm_mem_global_free(bdev->glob->mem_glob, acc_size);
136 }
137
138 static int ttm_bo_wait_unreserved(struct ttm_buffer_object *bo,
139                                   bool interruptible)
140 {
141         const char *wmsg;
142         int flags, ret;
143
144         ret = 0;
145         if (interruptible) {
146                 flags = PCATCH;
147                 wmsg = "ttbowi";
148         } else {
149                 flags = 0;
150                 wmsg = "ttbowu";
151         }
152         while (ttm_bo_is_reserved(bo)) {
153                 ret = -lksleep(bo, &bo->glob->lru_lock, 0, wmsg, 0);
154                 if (ret != 0)
155                         break;
156         }
157         return (ret);
158 }
159
160 void ttm_bo_add_to_lru(struct ttm_buffer_object *bo)
161 {
162         struct ttm_bo_device *bdev = bo->bdev;
163         struct ttm_mem_type_manager *man;
164
165         BUG_ON(!ttm_bo_is_reserved(bo));
166
167         if (!(bo->mem.placement & TTM_PL_FLAG_NO_EVICT)) {
168
169                 BUG_ON(!list_empty(&bo->lru));
170
171                 man = &bdev->man[bo->mem.mem_type];
172                 list_add_tail(&bo->lru, &man->lru);
173                 kref_get(&bo->list_kref);
174
175                 if (bo->ttm != NULL) {
176                         list_add_tail(&bo->swap, &bo->glob->swap_lru);
177                         kref_get(&bo->list_kref);
178                 }
179         }
180 }
181
182 int ttm_bo_del_from_lru(struct ttm_buffer_object *bo)
183 {
184         int put_count = 0;
185
186         if (!list_empty(&bo->swap)) {
187                 list_del_init(&bo->swap);
188                 ++put_count;
189         }
190         if (!list_empty(&bo->lru)) {
191                 list_del_init(&bo->lru);
192                 ++put_count;
193         }
194
195         /*
196          * TODO: Add a driver hook to delete from
197          * driver-specific LRU's here.
198          */
199
200         return put_count;
201 }
202
203 int ttm_bo_reserve_nolru(struct ttm_buffer_object *bo,
204                           bool interruptible,
205                           bool no_wait, bool use_sequence, uint32_t sequence)
206 {
207         int ret;
208
209         while (unlikely(atomic_xchg(&bo->reserved, 1) != 0)) {
210                 /**
211                  * Deadlock avoidance for multi-bo reserving.
212                  */
213                 if (use_sequence && bo->seq_valid) {
214                         /**
215                          * We've already reserved this one.
216                          */
217                         if (unlikely(sequence == bo->val_seq))
218                                 return -EDEADLK;
219                         /**
220                          * Already reserved by a thread that will not back
221                          * off for us. We need to back off.
222                          */
223                         if (unlikely(sequence - bo->val_seq < (1 << 31)))
224                                 return -EAGAIN;
225                 }
226
227                 if (no_wait)
228                         return -EBUSY;
229
230                 ret = ttm_bo_wait_unreserved(bo, interruptible);
231
232                 if (unlikely(ret))
233                         return ret;
234         }
235
236         if (use_sequence) {
237                 bool wake_up = false;
238                 /**
239                  * Wake up waiters that may need to recheck for deadlock,
240                  * if we decreased the sequence number.
241                  */
242                 if (unlikely((bo->val_seq - sequence < (1 << 31))
243                              || !bo->seq_valid))
244                         wake_up = true;
245
246                 /*
247                  * In the worst case with memory ordering these values can be
248                  * seen in the wrong order. However since we call wake_up_all
249                  * in that case, this will hopefully not pose a problem,
250                  * and the worst case would only cause someone to accidentally
251                  * hit -EAGAIN in ttm_bo_reserve when they see old value of
252                  * val_seq. However this would only happen if seq_valid was
253                  * written before val_seq was, and just means some slightly
254                  * increased cpu usage
255                  */
256                 bo->val_seq = sequence;
257                 bo->seq_valid = true;
258                 if (wake_up)
259                         wakeup(bo);
260         } else {
261                 bo->seq_valid = false;
262         }
263
264         return 0;
265 }
266 EXPORT_SYMBOL(ttm_bo_reserve);
267
268 static void ttm_bo_ref_bug(struct kref *list_kref)
269 {
270         BUG();
271 }
272
273 void ttm_bo_list_ref_sub(struct ttm_buffer_object *bo, int count,
274                          bool never_free)
275 {
276         kref_sub(&bo->list_kref, count,
277                  (never_free) ? ttm_bo_ref_bug : ttm_bo_release_list);
278 }
279
280 int ttm_bo_reserve(struct ttm_buffer_object *bo,
281                    bool interruptible,
282                    bool no_wait, bool use_sequence, uint32_t sequence)
283 {
284         struct ttm_bo_global *glob = bo->glob;
285         int put_count = 0;
286         int ret;
287
288         ret = ttm_bo_reserve_nolru(bo, interruptible, no_wait, use_sequence,
289                                    sequence);
290         if (likely(ret == 0)) {
291                 lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
292                 put_count = ttm_bo_del_from_lru(bo);
293                 lockmgr(&glob->lru_lock, LK_RELEASE);
294                 ttm_bo_list_ref_sub(bo, put_count, true);
295         }
296
297         return ret;
298 }
299
300 int ttm_bo_reserve_slowpath_nolru(struct ttm_buffer_object *bo,
301                                   bool interruptible, uint32_t sequence)
302 {
303         bool wake_up = false;
304         int ret;
305
306         while (unlikely(atomic_xchg(&bo->reserved, 1) != 0)) {
307                 WARN_ON(bo->seq_valid && sequence == bo->val_seq);
308
309                 ret = ttm_bo_wait_unreserved(bo, interruptible);
310
311                 if (unlikely(ret))
312                         return ret;
313         }
314
315         if ((bo->val_seq - sequence < (1 << 31)) || !bo->seq_valid)
316                 wake_up = true;
317
318         /**
319          * Wake up waiters that may need to recheck for deadlock,
320          * if we decreased the sequence number.
321          */
322         bo->val_seq = sequence;
323         bo->seq_valid = true;
324         if (wake_up)
325                 wakeup(bo);
326
327         return 0;
328 }
329
330 int ttm_bo_reserve_slowpath(struct ttm_buffer_object *bo,
331                             bool interruptible, uint32_t sequence)
332 {
333         struct ttm_bo_global *glob = bo->glob;
334         int put_count, ret;
335
336         ret = ttm_bo_reserve_slowpath_nolru(bo, interruptible, sequence);
337         if (likely(!ret)) {
338                 lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
339                 put_count = ttm_bo_del_from_lru(bo);
340                 lockmgr(&glob->lru_lock, LK_RELEASE);
341                 ttm_bo_list_ref_sub(bo, put_count, true);
342         }
343         return ret;
344 }
345 EXPORT_SYMBOL(ttm_bo_reserve_slowpath);
346
347 void ttm_bo_unreserve_locked(struct ttm_buffer_object *bo)
348 {
349         ttm_bo_add_to_lru(bo);
350         atomic_set(&bo->reserved, 0);
351         wakeup(bo);
352 }
353
354 void ttm_bo_unreserve(struct ttm_buffer_object *bo)
355 {
356         struct ttm_bo_global *glob = bo->glob;
357
358         lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
359         ttm_bo_unreserve_locked(bo);
360         lockmgr(&glob->lru_lock, LK_RELEASE);
361 }
362 EXPORT_SYMBOL(ttm_bo_unreserve);
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                 kprintf("[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                         kprintf("[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         cpu_mfence();
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         lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
557         ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
558
559         lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
560         (void) ttm_bo_wait(bo, false, false, true);
561         if (!ret && !bo->sync_obj) {
562                 lockmgr(&bdev->fence_lock, LK_RELEASE);
563                 put_count = ttm_bo_del_from_lru(bo);
564
565                 lockmgr(&glob->lru_lock, LK_RELEASE);
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         lockmgr(&bdev->fence_lock, LK_RELEASE);
575
576         if (!ret) {
577                 atomic_set(&bo->reserved, 0);
578                 wakeup(bo);
579         }
580
581         kref_get(&bo->list_kref);
582         list_add_tail(&bo->ddestroy, &bdev->ddestroy);
583         lockmgr(&glob->lru_lock, LK_RELEASE);
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[mycpuid], &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         lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
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                 lockmgr(&bdev->fence_lock, LK_RELEASE);
628
629                 atomic_set(&bo->reserved, 0);
630                 wakeup(bo);
631                 lockmgr(&glob->lru_lock, LK_RELEASE);
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                 lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
643                 ret = ttm_bo_wait(bo, false, false, true);
644                 WARN_ON(ret);
645                 lockmgr(&bdev->fence_lock, LK_RELEASE);
646                 if (ret)
647                         return ret;
648
649                 lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
650                 ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
651
652                 /*
653                  * We raced, and lost, someone else holds the reservation now,
654                  * and is probably busy in ttm_bo_cleanup_memtype_use.
655                  *
656                  * Even if it's not the case, because we finished waiting any
657                  * delayed destruction would succeed, so just return success
658                  * here.
659                  */
660                 if (ret) {
661                         lockmgr(&glob->lru_lock, LK_RELEASE);
662                         return 0;
663                 }
664         } else
665                 lockmgr(&bdev->fence_lock, LK_RELEASE);
666
667         if (ret || unlikely(list_empty(&bo->ddestroy))) {
668                 atomic_set(&bo->reserved, 0);
669                 wakeup(bo);
670                 lockmgr(&glob->lru_lock, LK_RELEASE);
671                 return ret;
672         }
673
674         put_count = ttm_bo_del_from_lru(bo);
675         list_del_init(&bo->ddestroy);
676         ++put_count;
677
678         lockmgr(&glob->lru_lock, LK_RELEASE);
679         ttm_bo_cleanup_memtype_use(bo);
680
681         ttm_bo_list_ref_sub(bo, put_count, true);
682
683         return 0;
684 }
685
686 /**
687  * Traverse the delayed list, and call ttm_bo_cleanup_refs on all
688  * encountered buffers.
689  */
690
691 static int ttm_bo_delayed_delete(struct ttm_bo_device *bdev, bool remove_all)
692 {
693         struct ttm_bo_global *glob = bdev->glob;
694         struct ttm_buffer_object *entry = NULL;
695         int ret = 0;
696
697         lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
698         if (list_empty(&bdev->ddestroy))
699                 goto out_unlock;
700
701         entry = list_first_entry(&bdev->ddestroy,
702                 struct ttm_buffer_object, ddestroy);
703         kref_get(&entry->list_kref);
704
705         for (;;) {
706                 struct ttm_buffer_object *nentry = NULL;
707
708                 if (entry->ddestroy.next != &bdev->ddestroy) {
709                         nentry = list_first_entry(&entry->ddestroy,
710                                 struct ttm_buffer_object, ddestroy);
711                         kref_get(&nentry->list_kref);
712                 }
713
714                 ret = ttm_bo_reserve_nolru(entry, false, true, false, 0);
715                 if (remove_all && ret) {
716                         lockmgr(&glob->lru_lock, LK_RELEASE);
717                         ret = ttm_bo_reserve_nolru(entry, false, false,
718                                                    false, 0);
719                         lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
720                 }
721
722                 if (!ret)
723                         ret = ttm_bo_cleanup_refs_and_unlock(entry, false,
724                                                              !remove_all);
725                 else
726                         lockmgr(&glob->lru_lock, LK_RELEASE);
727
728                 kref_put(&entry->list_kref, ttm_bo_release_list);
729                 entry = nentry;
730
731                 if (ret || !entry)
732                         goto out;
733
734                 lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
735                 if (list_empty(&entry->ddestroy))
736                         break;
737         }
738
739 out_unlock:
740         lockmgr(&glob->lru_lock, LK_RELEASE);
741 out:
742         if (entry)
743                 kref_put(&entry->list_kref, ttm_bo_release_list);
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[mycpuid], &bdev->wq,
753                     ((hz / 100) < 1) ? 1 : hz / 100);
754         }
755 }
756
757 static void ttm_bo_release(struct kref *kref)
758 {
759         struct ttm_buffer_object *bo =
760             container_of(kref, struct ttm_buffer_object, kref);
761         struct ttm_bo_device *bdev = bo->bdev;
762         struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
763
764         lockmgr(&bdev->vm_lock, LK_EXCLUSIVE);
765         if (likely(bo->vm_node != NULL)) {
766                 RB_REMOVE(ttm_bo_device_buffer_objects,
767                     &bdev->addr_space_rb, bo);
768                 drm_mm_put_block(bo->vm_node);
769                 bo->vm_node = NULL;
770         }
771         lockmgr(&bdev->vm_lock, LK_RELEASE);
772         ttm_mem_io_lock(man, false);
773         ttm_mem_io_free_vm(bo);
774         ttm_mem_io_unlock(man);
775         ttm_bo_cleanup_refs_or_queue(bo);
776         kref_put(&bo->list_kref, ttm_bo_release_list);
777 }
778
779 void ttm_bo_unref(struct ttm_buffer_object **p_bo)
780 {
781         struct ttm_buffer_object *bo = *p_bo;
782
783         *p_bo = NULL;
784         kref_put(&bo->kref, ttm_bo_release);
785 }
786 EXPORT_SYMBOL(ttm_bo_unref);
787
788 int ttm_bo_lock_delayed_workqueue(struct ttm_bo_device *bdev)
789 {
790         int pending;
791
792         taskqueue_cancel_timeout(taskqueue_thread[mycpuid], &bdev->wq, &pending);
793         if (pending)
794                 taskqueue_drain_timeout(taskqueue_thread[mycpuid], &bdev->wq);
795         return (pending);
796 }
797 EXPORT_SYMBOL(ttm_bo_lock_delayed_workqueue);
798
799 void ttm_bo_unlock_delayed_workqueue(struct ttm_bo_device *bdev, int resched)
800 {
801         if (resched) {
802                 taskqueue_enqueue_timeout(taskqueue_thread[mycpuid], &bdev->wq,
803                     ((hz / 100) < 1) ? 1 : hz / 100);
804         }
805 }
806 EXPORT_SYMBOL(ttm_bo_unlock_delayed_workqueue);
807
808 static int ttm_bo_evict(struct ttm_buffer_object *bo, bool interruptible,
809                         bool no_wait_gpu)
810 {
811         struct ttm_bo_device *bdev = bo->bdev;
812         struct ttm_mem_reg evict_mem;
813         struct ttm_placement placement;
814         int ret = 0;
815
816         lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
817         ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
818         lockmgr(&bdev->fence_lock, LK_RELEASE);
819
820         if (unlikely(ret != 0)) {
821                 if (ret != -ERESTART) {
822                         kprintf("[TTM] Failed to expire sync object before buffer eviction\n");
823                 }
824                 goto out;
825         }
826
827         BUG_ON(!ttm_bo_is_reserved(bo));
828
829         evict_mem = bo->mem;
830         evict_mem.mm_node = NULL;
831         evict_mem.bus.io_reserved_vm = false;
832         evict_mem.bus.io_reserved_count = 0;
833
834         placement.fpfn = 0;
835         placement.lpfn = 0;
836         placement.num_placement = 0;
837         placement.num_busy_placement = 0;
838         bdev->driver->evict_flags(bo, &placement);
839         ret = ttm_bo_mem_space(bo, &placement, &evict_mem, interruptible,
840                                 no_wait_gpu);
841         if (ret) {
842                 if (ret != -ERESTART) {
843                         kprintf("[TTM] Failed to find memory space for buffer 0x%p eviction\n",
844                                bo);
845                         ttm_bo_mem_space_debug(bo, &placement);
846                 }
847                 goto out;
848         }
849
850         ret = ttm_bo_handle_move_mem(bo, &evict_mem, true, interruptible,
851                                      no_wait_gpu);
852         if (ret) {
853                 if (ret != -ERESTART)
854                         kprintf("[TTM] Buffer eviction failed\n");
855                 ttm_bo_mem_put(bo, &evict_mem);
856                 goto out;
857         }
858         bo->evicted = true;
859 out:
860         return ret;
861 }
862
863 static int ttm_mem_evict_first(struct ttm_bo_device *bdev,
864                                 uint32_t mem_type,
865                                 bool interruptible,
866                                 bool no_wait_gpu)
867 {
868         struct ttm_bo_global *glob = bdev->glob;
869         struct ttm_mem_type_manager *man = &bdev->man[mem_type];
870         struct ttm_buffer_object *bo;
871         int ret = -EBUSY, put_count;
872
873         lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
874         list_for_each_entry(bo, &man->lru, lru) {
875                 ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
876                 if (!ret)
877                         break;
878         }
879
880         if (ret) {
881                 lockmgr(&glob->lru_lock, LK_RELEASE);
882                 return ret;
883         }
884
885         kref_get(&bo->list_kref);
886
887         if (!list_empty(&bo->ddestroy)) {
888                 ret = ttm_bo_cleanup_refs_and_unlock(bo, interruptible,
889                                                      no_wait_gpu);
890                 kref_put(&bo->list_kref, ttm_bo_release_list);
891                 return ret;
892         }
893
894         put_count = ttm_bo_del_from_lru(bo);
895         lockmgr(&glob->lru_lock, LK_RELEASE);
896
897         BUG_ON(ret != 0);
898
899         ttm_bo_list_ref_sub(bo, put_count, true);
900
901         ret = ttm_bo_evict(bo, interruptible, no_wait_gpu);
902         ttm_bo_unreserve(bo);
903
904         kref_put(&bo->list_kref, ttm_bo_release_list);
905         return ret;
906 }
907
908 void ttm_bo_mem_put(struct ttm_buffer_object *bo, struct ttm_mem_reg *mem)
909 {
910         struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type];
911
912         if (mem->mm_node)
913                 (*man->func->put_node)(man, mem);
914 }
915 EXPORT_SYMBOL(ttm_bo_mem_put);
916
917 /**
918  * Repeatedly evict memory from the LRU for @mem_type until we create enough
919  * space, or we've evicted everything and there isn't enough space.
920  */
921 static int ttm_bo_mem_force_space(struct ttm_buffer_object *bo,
922                                         uint32_t mem_type,
923                                         struct ttm_placement *placement,
924                                         struct ttm_mem_reg *mem,
925                                         bool interruptible,
926                                         bool no_wait_gpu)
927 {
928         struct ttm_bo_device *bdev = bo->bdev;
929         struct ttm_mem_type_manager *man = &bdev->man[mem_type];
930         int ret;
931
932         do {
933                 ret = (*man->func->get_node)(man, bo, placement, mem);
934                 if (unlikely(ret != 0))
935                         return ret;
936                 if (mem->mm_node)
937                         break;
938                 ret = ttm_mem_evict_first(bdev, mem_type,
939                                           interruptible, no_wait_gpu);
940                 if (unlikely(ret != 0))
941                         return ret;
942         } while (1);
943         if (mem->mm_node == NULL)
944                 return -ENOMEM;
945         mem->mem_type = mem_type;
946         return 0;
947 }
948
949 static uint32_t ttm_bo_select_caching(struct ttm_mem_type_manager *man,
950                                       uint32_t cur_placement,
951                                       uint32_t proposed_placement)
952 {
953         uint32_t caching = proposed_placement & TTM_PL_MASK_CACHING;
954         uint32_t result = proposed_placement & ~TTM_PL_MASK_CACHING;
955
956         /**
957          * Keep current caching if possible.
958          */
959
960         if ((cur_placement & caching) != 0)
961                 result |= (cur_placement & caching);
962         else if ((man->default_caching & caching) != 0)
963                 result |= man->default_caching;
964         else if ((TTM_PL_FLAG_CACHED & caching) != 0)
965                 result |= TTM_PL_FLAG_CACHED;
966         else if ((TTM_PL_FLAG_WC & caching) != 0)
967                 result |= TTM_PL_FLAG_WC;
968         else if ((TTM_PL_FLAG_UNCACHED & caching) != 0)
969                 result |= TTM_PL_FLAG_UNCACHED;
970
971         return result;
972 }
973
974 static bool ttm_bo_mt_compatible(struct ttm_mem_type_manager *man,
975                                  uint32_t mem_type,
976                                  uint32_t proposed_placement,
977                                  uint32_t *masked_placement)
978 {
979         uint32_t cur_flags = ttm_bo_type_flags(mem_type);
980
981         if ((cur_flags & proposed_placement & TTM_PL_MASK_MEM) == 0)
982                 return false;
983
984         if ((proposed_placement & man->available_caching) == 0)
985                 return false;
986
987         cur_flags |= (proposed_placement & man->available_caching);
988
989         *masked_placement = cur_flags;
990         return true;
991 }
992
993 /**
994  * Creates space for memory region @mem according to its type.
995  *
996  * This function first searches for free space in compatible memory types in
997  * the priority order defined by the driver.  If free space isn't found, then
998  * ttm_bo_mem_force_space is attempted in priority order to evict and find
999  * space.
1000  */
1001 int ttm_bo_mem_space(struct ttm_buffer_object *bo,
1002                         struct ttm_placement *placement,
1003                         struct ttm_mem_reg *mem,
1004                         bool interruptible,
1005                         bool no_wait_gpu)
1006 {
1007         struct ttm_bo_device *bdev = bo->bdev;
1008         struct ttm_mem_type_manager *man;
1009         uint32_t mem_type = TTM_PL_SYSTEM;
1010         uint32_t cur_flags = 0;
1011         bool type_found = false;
1012         bool type_ok = false;
1013         bool has_erestartsys = false;
1014         int i, ret;
1015
1016         mem->mm_node = NULL;
1017         for (i = 0; i < placement->num_placement; ++i) {
1018                 ret = ttm_mem_type_from_flags(placement->placement[i],
1019                                                 &mem_type);
1020                 if (ret)
1021                         return ret;
1022                 man = &bdev->man[mem_type];
1023
1024                 type_ok = ttm_bo_mt_compatible(man,
1025                                                 mem_type,
1026                                                 placement->placement[i],
1027                                                 &cur_flags);
1028
1029                 if (!type_ok)
1030                         continue;
1031
1032                 cur_flags = ttm_bo_select_caching(man, bo->mem.placement,
1033                                                   cur_flags);
1034                 /*
1035                  * Use the access and other non-mapping-related flag bits from
1036                  * the memory placement flags to the current flags
1037                  */
1038                 ttm_flag_masked(&cur_flags, placement->placement[i],
1039                                 ~TTM_PL_MASK_MEMTYPE);
1040
1041                 if (mem_type == TTM_PL_SYSTEM)
1042                         break;
1043
1044                 if (man->has_type && man->use_type) {
1045                         type_found = true;
1046                         ret = (*man->func->get_node)(man, bo, placement, mem);
1047                         if (unlikely(ret))
1048                                 return ret;
1049                 }
1050                 if (mem->mm_node)
1051                         break;
1052         }
1053
1054         if ((type_ok && (mem_type == TTM_PL_SYSTEM)) || mem->mm_node) {
1055                 mem->mem_type = mem_type;
1056                 mem->placement = cur_flags;
1057                 return 0;
1058         }
1059
1060         if (!type_found)
1061                 return -EINVAL;
1062
1063         for (i = 0; i < placement->num_busy_placement; ++i) {
1064                 ret = ttm_mem_type_from_flags(placement->busy_placement[i],
1065                                                 &mem_type);
1066                 if (ret)
1067                         return ret;
1068                 man = &bdev->man[mem_type];
1069                 if (!man->has_type)
1070                         continue;
1071                 if (!ttm_bo_mt_compatible(man,
1072                                                 mem_type,
1073                                                 placement->busy_placement[i],
1074                                                 &cur_flags))
1075                         continue;
1076
1077                 cur_flags = ttm_bo_select_caching(man, bo->mem.placement,
1078                                                   cur_flags);
1079                 /*
1080                  * Use the access and other non-mapping-related flag bits from
1081                  * the memory placement flags to the current flags
1082                  */
1083                 ttm_flag_masked(&cur_flags, placement->busy_placement[i],
1084                                 ~TTM_PL_MASK_MEMTYPE);
1085
1086
1087                 if (mem_type == TTM_PL_SYSTEM) {
1088                         mem->mem_type = mem_type;
1089                         mem->placement = cur_flags;
1090                         mem->mm_node = NULL;
1091                         return 0;
1092                 }
1093
1094                 ret = ttm_bo_mem_force_space(bo, mem_type, placement, mem,
1095                                                 interruptible, no_wait_gpu);
1096                 if (ret == 0 && mem->mm_node) {
1097                         mem->placement = cur_flags;
1098                         return 0;
1099                 }
1100                 if (ret == -ERESTART)
1101                         has_erestartsys = true;
1102         }
1103         ret = (has_erestartsys) ? -ERESTART : -ENOMEM;
1104         return ret;
1105 }
1106 EXPORT_SYMBOL(ttm_bo_mem_space);
1107
1108 static
1109 int ttm_bo_move_buffer(struct ttm_buffer_object *bo,
1110                         struct ttm_placement *placement,
1111                         bool interruptible,
1112                         bool no_wait_gpu)
1113 {
1114         int ret = 0;
1115         struct ttm_mem_reg mem;
1116         struct ttm_bo_device *bdev = bo->bdev;
1117
1118         BUG_ON(!ttm_bo_is_reserved(bo));
1119
1120         /*
1121          * FIXME: It's possible to pipeline buffer moves.
1122          * Have the driver move function wait for idle when necessary,
1123          * instead of doing it here.
1124          */
1125         lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1126         ret = ttm_bo_wait(bo, false, interruptible, no_wait_gpu);
1127         lockmgr(&bdev->fence_lock, LK_RELEASE);
1128         if (ret)
1129                 return ret;
1130         mem.num_pages = bo->num_pages;
1131         mem.size = mem.num_pages << PAGE_SHIFT;
1132         mem.page_alignment = bo->mem.page_alignment;
1133         mem.bus.io_reserved_vm = false;
1134         mem.bus.io_reserved_count = 0;
1135         /*
1136          * Determine where to move the buffer.
1137          */
1138         ret = ttm_bo_mem_space(bo, placement, &mem,
1139                                interruptible, no_wait_gpu);
1140         if (ret)
1141                 goto out_unlock;
1142         ret = ttm_bo_handle_move_mem(bo, &mem, false,
1143                                      interruptible, no_wait_gpu);
1144 out_unlock:
1145         if (ret && mem.mm_node)
1146                 ttm_bo_mem_put(bo, &mem);
1147         return ret;
1148 }
1149
1150 static int ttm_bo_mem_compat(struct ttm_placement *placement,
1151                              struct ttm_mem_reg *mem)
1152 {
1153         int i;
1154
1155         if (mem->mm_node && placement->lpfn != 0 &&
1156             (mem->start < placement->fpfn ||
1157              mem->start + mem->num_pages > placement->lpfn))
1158                 return -1;
1159
1160         for (i = 0; i < placement->num_placement; i++) {
1161                 if ((placement->placement[i] & mem->placement &
1162                         TTM_PL_MASK_CACHING) &&
1163                         (placement->placement[i] & mem->placement &
1164                         TTM_PL_MASK_MEM))
1165                         return i;
1166         }
1167         return -1;
1168 }
1169
1170 int ttm_bo_validate(struct ttm_buffer_object *bo,
1171                         struct ttm_placement *placement,
1172                         bool interruptible,
1173                         bool no_wait_gpu)
1174 {
1175         int ret;
1176
1177         BUG_ON(!ttm_bo_is_reserved(bo));
1178         /* Check that range is valid */
1179         if (placement->lpfn || placement->fpfn)
1180                 if (placement->fpfn > placement->lpfn ||
1181                         (placement->lpfn - placement->fpfn) < bo->num_pages)
1182                         return -EINVAL;
1183         /*
1184          * Check whether we need to move buffer.
1185          */
1186         ret = ttm_bo_mem_compat(placement, &bo->mem);
1187         if (ret < 0) {
1188                 ret = ttm_bo_move_buffer(bo, placement, interruptible,
1189                                          no_wait_gpu);
1190                 if (ret)
1191                         return ret;
1192         } else {
1193                 /*
1194                  * Use the access and other non-mapping-related flag bits from
1195                  * the compatible memory placement flags to the active flags
1196                  */
1197                 ttm_flag_masked(&bo->mem.placement, placement->placement[ret],
1198                                 ~TTM_PL_MASK_MEMTYPE);
1199         }
1200         /*
1201          * We might need to add a TTM.
1202          */
1203         if (bo->mem.mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
1204                 ret = ttm_bo_add_ttm(bo, true);
1205                 if (ret)
1206                         return ret;
1207         }
1208         return 0;
1209 }
1210 EXPORT_SYMBOL(ttm_bo_validate);
1211
1212 int ttm_bo_check_placement(struct ttm_buffer_object *bo,
1213                                 struct ttm_placement *placement)
1214 {
1215         BUG_ON((placement->fpfn || placement->lpfn) &&
1216                (bo->mem.num_pages > (placement->lpfn - placement->fpfn)));
1217
1218         return 0;
1219 }
1220
1221 int ttm_bo_init(struct ttm_bo_device *bdev,
1222                 struct ttm_buffer_object *bo,
1223                 unsigned long size,
1224                 enum ttm_bo_type type,
1225                 struct ttm_placement *placement,
1226                 uint32_t page_alignment,
1227                 bool interruptible,
1228                 struct vm_object *persistent_swap_storage,
1229                 size_t acc_size,
1230                 struct sg_table *sg,
1231                 void (*destroy) (struct ttm_buffer_object *))
1232 {
1233         int ret = 0;
1234         unsigned long num_pages;
1235         struct ttm_mem_global *mem_glob = bdev->glob->mem_glob;
1236
1237         ret = ttm_mem_global_alloc(mem_glob, acc_size, false, false);
1238         if (ret) {
1239                 kprintf("[TTM] Out of kernel memory\n");
1240                 if (destroy)
1241                         (*destroy)(bo);
1242                 else
1243                         kfree(bo, M_TTM_BO);
1244                 return -ENOMEM;
1245         }
1246
1247         num_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1248         if (num_pages == 0) {
1249                 kprintf("[TTM] Illegal buffer object size\n");
1250                 if (destroy)
1251                         (*destroy)(bo);
1252                 else
1253                         kfree(bo, M_TTM_BO);
1254                 ttm_mem_global_free(mem_glob, acc_size);
1255                 return -EINVAL;
1256         }
1257         bo->destroy = destroy;
1258
1259         kref_init(&bo->kref);
1260         kref_init(&bo->list_kref);
1261         atomic_set(&bo->cpu_writers, 0);
1262         atomic_set(&bo->reserved, 1);
1263         INIT_LIST_HEAD(&bo->lru);
1264         INIT_LIST_HEAD(&bo->ddestroy);
1265         INIT_LIST_HEAD(&bo->swap);
1266         INIT_LIST_HEAD(&bo->io_reserve_lru);
1267         bo->bdev = bdev;
1268         bo->glob = bdev->glob;
1269         bo->type = type;
1270         bo->num_pages = num_pages;
1271         bo->mem.size = num_pages << PAGE_SHIFT;
1272         bo->mem.mem_type = TTM_PL_SYSTEM;
1273         bo->mem.num_pages = bo->num_pages;
1274         bo->mem.mm_node = NULL;
1275         bo->mem.page_alignment = page_alignment;
1276         bo->mem.bus.io_reserved_vm = false;
1277         bo->mem.bus.io_reserved_count = 0;
1278         bo->priv_flags = 0;
1279         bo->mem.placement = (TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED);
1280         bo->seq_valid = false;
1281         bo->persistent_swap_storage = persistent_swap_storage;
1282         bo->acc_size = acc_size;
1283         bo->sg = sg;
1284         atomic_inc(&bo->glob->bo_count);
1285
1286         ret = ttm_bo_check_placement(bo, placement);
1287         if (unlikely(ret != 0))
1288                 goto out_err;
1289
1290         /*
1291          * For ttm_bo_type_device buffers, allocate
1292          * address space from the device.
1293          */
1294         if (bo->type == ttm_bo_type_device ||
1295             bo->type == ttm_bo_type_sg) {
1296                 ret = ttm_bo_setup_vm(bo);
1297                 if (ret)
1298                         goto out_err;
1299         }
1300
1301         ret = ttm_bo_validate(bo, placement, interruptible, false);
1302         if (ret)
1303                 goto out_err;
1304
1305         ttm_bo_unreserve(bo);
1306         return 0;
1307
1308 out_err:
1309         ttm_bo_unreserve(bo);
1310         ttm_bo_unref(&bo);
1311
1312         return ret;
1313 }
1314 EXPORT_SYMBOL(ttm_bo_init);
1315
1316 size_t ttm_bo_acc_size(struct ttm_bo_device *bdev,
1317                        unsigned long bo_size,
1318                        unsigned struct_size)
1319 {
1320         unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1321         size_t size = 0;
1322
1323         size += ttm_round_pot(struct_size);
1324         size += PAGE_ALIGN(npages * sizeof(void *));
1325         size += ttm_round_pot(sizeof(struct ttm_tt));
1326         return size;
1327 }
1328 EXPORT_SYMBOL(ttm_bo_acc_size);
1329
1330 size_t ttm_bo_dma_acc_size(struct ttm_bo_device *bdev,
1331                            unsigned long bo_size,
1332                            unsigned struct_size)
1333 {
1334         unsigned npages = (PAGE_ALIGN(bo_size)) >> PAGE_SHIFT;
1335         size_t size = 0;
1336
1337         size += ttm_round_pot(struct_size);
1338         size += PAGE_ALIGN(npages * sizeof(void *));
1339         size += PAGE_ALIGN(npages * sizeof(dma_addr_t));
1340         size += ttm_round_pot(sizeof(struct ttm_dma_tt));
1341         return size;
1342 }
1343 EXPORT_SYMBOL(ttm_bo_dma_acc_size);
1344
1345 int ttm_bo_create(struct ttm_bo_device *bdev,
1346                         unsigned long size,
1347                         enum ttm_bo_type type,
1348                         struct ttm_placement *placement,
1349                         uint32_t page_alignment,
1350                         bool interruptible,
1351                         struct vm_object *persistent_swap_storage,
1352                         struct ttm_buffer_object **p_bo)
1353 {
1354         struct ttm_buffer_object *bo;
1355         size_t acc_size;
1356         int ret;
1357
1358         bo = kmalloc(sizeof(*bo), M_TTM_BO, M_WAITOK | M_ZERO);
1359         if (unlikely(bo == NULL))
1360                 return -ENOMEM;
1361
1362         acc_size = ttm_bo_acc_size(bdev, size, sizeof(struct ttm_buffer_object));
1363         ret = ttm_bo_init(bdev, bo, size, type, placement, page_alignment,
1364                           interruptible, persistent_swap_storage, acc_size,
1365                           NULL, NULL);
1366         if (likely(ret == 0))
1367                 *p_bo = bo;
1368
1369         return ret;
1370 }
1371 EXPORT_SYMBOL(ttm_bo_create);
1372
1373 static int ttm_bo_force_list_clean(struct ttm_bo_device *bdev,
1374                                         unsigned mem_type, bool allow_errors)
1375 {
1376         struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1377         struct ttm_bo_global *glob = bdev->glob;
1378         int ret;
1379
1380         /*
1381          * Can't use standard list traversal since we're unlocking.
1382          */
1383
1384         lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
1385         while (!list_empty(&man->lru)) {
1386                 lockmgr(&glob->lru_lock, LK_RELEASE);
1387                 ret = ttm_mem_evict_first(bdev, mem_type, false, false);
1388                 if (ret) {
1389                         if (allow_errors) {
1390                                 return ret;
1391                         } else {
1392                                 kprintf("[TTM] Cleanup eviction failed\n");
1393                         }
1394                 }
1395                 lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
1396         }
1397         lockmgr(&glob->lru_lock, LK_RELEASE);
1398         return 0;
1399 }
1400
1401 int ttm_bo_clean_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1402 {
1403         struct ttm_mem_type_manager *man;
1404         int ret = -EINVAL;
1405
1406         if (mem_type >= TTM_NUM_MEM_TYPES) {
1407                 kprintf("[TTM] Illegal memory type %d\n", mem_type);
1408                 return ret;
1409         }
1410         man = &bdev->man[mem_type];
1411
1412         if (!man->has_type) {
1413                 kprintf("[TTM] Trying to take down uninitialized memory manager type %u\n",
1414                        mem_type);
1415                 return ret;
1416         }
1417
1418         man->use_type = false;
1419         man->has_type = false;
1420
1421         ret = 0;
1422         if (mem_type > 0) {
1423                 ttm_bo_force_list_clean(bdev, mem_type, false);
1424
1425                 ret = (*man->func->takedown)(man);
1426         }
1427
1428         return ret;
1429 }
1430 EXPORT_SYMBOL(ttm_bo_clean_mm);
1431
1432 int ttm_bo_evict_mm(struct ttm_bo_device *bdev, unsigned mem_type)
1433 {
1434         struct ttm_mem_type_manager *man = &bdev->man[mem_type];
1435
1436         if (mem_type == 0 || mem_type >= TTM_NUM_MEM_TYPES) {
1437                 kprintf("[TTM] Illegal memory manager memory type %u\n", mem_type);
1438                 return -EINVAL;
1439         }
1440
1441         if (!man->has_type) {
1442                 kprintf("[TTM] Memory type %u has not been initialized\n", mem_type);
1443                 return 0;
1444         }
1445
1446         return ttm_bo_force_list_clean(bdev, mem_type, true);
1447 }
1448 EXPORT_SYMBOL(ttm_bo_evict_mm);
1449
1450 int ttm_bo_init_mm(struct ttm_bo_device *bdev, unsigned type,
1451                         unsigned long p_size)
1452 {
1453         int ret = -EINVAL;
1454         struct ttm_mem_type_manager *man;
1455
1456         BUG_ON(type >= TTM_NUM_MEM_TYPES);
1457         man = &bdev->man[type];
1458         BUG_ON(man->has_type);
1459         man->io_reserve_fastpath = true;
1460         man->use_io_reserve_lru = false;
1461         lockinit(&man->io_reserve_mutex, "ttmman", 0, LK_CANRECURSE);
1462         INIT_LIST_HEAD(&man->io_reserve_lru);
1463
1464         ret = bdev->driver->init_mem_type(bdev, type, man);
1465         if (ret)
1466                 return ret;
1467         man->bdev = bdev;
1468
1469         ret = 0;
1470         if (type != TTM_PL_SYSTEM) {
1471                 ret = (*man->func->init)(man, p_size);
1472                 if (ret)
1473                         return ret;
1474         }
1475         man->has_type = true;
1476         man->use_type = true;
1477         man->size = p_size;
1478
1479         INIT_LIST_HEAD(&man->lru);
1480
1481         return 0;
1482 }
1483 EXPORT_SYMBOL(ttm_bo_init_mm);
1484
1485 static void ttm_bo_global_kobj_release(struct ttm_bo_global *glob)
1486 {
1487
1488         ttm_mem_unregister_shrink(glob->mem_glob, &glob->shrink);
1489         vm_page_free(glob->dummy_read_page);
1490 }
1491
1492 void ttm_bo_global_release(struct drm_global_reference *ref)
1493 {
1494         struct ttm_bo_global *glob = ref->object;
1495
1496         if (refcount_release(&glob->kobj_ref))
1497                 ttm_bo_global_kobj_release(glob);
1498 }
1499 EXPORT_SYMBOL(ttm_bo_global_release);
1500
1501 int ttm_bo_global_init(struct drm_global_reference *ref)
1502 {
1503         struct ttm_bo_global_ref *bo_ref =
1504                 container_of(ref, struct ttm_bo_global_ref, ref);
1505         struct ttm_bo_global *glob = ref->object;
1506         int ret;
1507
1508         lockinit(&glob->device_list_mutex, "ttmdlm", 0, LK_CANRECURSE);
1509         lockinit(&glob->lru_lock, "ttmlru", 0, LK_CANRECURSE);
1510         glob->mem_glob = bo_ref->mem_glob;
1511         glob->dummy_read_page = vm_page_alloc_contig(
1512             0, VM_MAX_ADDRESS, PAGE_SIZE, 0, 1*PAGE_SIZE, VM_MEMATTR_UNCACHEABLE);
1513
1514         if (unlikely(glob->dummy_read_page == NULL)) {
1515                 ret = -ENOMEM;
1516                 goto out_no_drp;
1517         }
1518
1519         INIT_LIST_HEAD(&glob->swap_lru);
1520         INIT_LIST_HEAD(&glob->device_list);
1521
1522         ttm_mem_init_shrink(&glob->shrink, ttm_bo_swapout);
1523         ret = ttm_mem_register_shrink(glob->mem_glob, &glob->shrink);
1524         if (unlikely(ret != 0)) {
1525                 kprintf("[TTM] Could not register buffer object swapout\n");
1526                 goto out_no_shrink;
1527         }
1528
1529         atomic_set(&glob->bo_count, 0);
1530
1531         refcount_init(&glob->kobj_ref, 1);
1532         return (0);
1533
1534 out_no_shrink:
1535         vm_page_free(glob->dummy_read_page);
1536 out_no_drp:
1537         kfree(glob, M_DRM_GLOBAL);
1538         return ret;
1539 }
1540 EXPORT_SYMBOL(ttm_bo_global_init);
1541
1542
1543 int ttm_bo_device_release(struct ttm_bo_device *bdev)
1544 {
1545         int ret = 0;
1546         unsigned i = TTM_NUM_MEM_TYPES;
1547         struct ttm_mem_type_manager *man;
1548         struct ttm_bo_global *glob = bdev->glob;
1549
1550         while (i--) {
1551                 man = &bdev->man[i];
1552                 if (man->has_type) {
1553                         man->use_type = false;
1554                         if ((i != TTM_PL_SYSTEM) && ttm_bo_clean_mm(bdev, i)) {
1555                                 ret = -EBUSY;
1556                                 kprintf("[TTM] DRM memory manager type %d is not clean\n",
1557                                        i);
1558                         }
1559                         man->has_type = false;
1560                 }
1561         }
1562
1563         lockmgr(&glob->device_list_mutex, LK_EXCLUSIVE);
1564         list_del(&bdev->device_list);
1565         lockmgr(&glob->device_list_mutex, LK_RELEASE);
1566
1567         if (taskqueue_cancel_timeout(taskqueue_thread[mycpuid], &bdev->wq, NULL))
1568                 taskqueue_drain_timeout(taskqueue_thread[mycpuid], &bdev->wq);
1569
1570         while (ttm_bo_delayed_delete(bdev, true))
1571                 ;
1572
1573         lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
1574         if (list_empty(&bdev->ddestroy))
1575                 TTM_DEBUG("Delayed destroy list was clean\n");
1576
1577         if (list_empty(&bdev->man[0].lru))
1578                 TTM_DEBUG("Swap list was clean\n");
1579         lockmgr(&glob->lru_lock, LK_RELEASE);
1580
1581         BUG_ON(!drm_mm_clean(&bdev->addr_space_mm));
1582         lockmgr(&bdev->vm_lock, LK_EXCLUSIVE);
1583         drm_mm_takedown(&bdev->addr_space_mm);
1584         lockmgr(&bdev->vm_lock, LK_RELEASE);
1585
1586         return ret;
1587 }
1588 EXPORT_SYMBOL(ttm_bo_device_release);
1589
1590 int ttm_bo_device_init(struct ttm_bo_device *bdev,
1591                        struct ttm_bo_global *glob,
1592                        struct ttm_bo_driver *driver,
1593                        uint64_t file_page_offset,
1594                        bool need_dma32)
1595 {
1596         int ret = -EINVAL;
1597
1598         lockinit(&bdev->vm_lock, "ttmvml", 0, LK_CANRECURSE);
1599         bdev->driver = driver;
1600
1601         memset(bdev->man, 0, sizeof(bdev->man));
1602
1603         /*
1604          * Initialize the system memory buffer type.
1605          * Other types need to be driver / IOCTL initialized.
1606          */
1607         ret = ttm_bo_init_mm(bdev, TTM_PL_SYSTEM, 0);
1608         if (unlikely(ret != 0))
1609                 goto out_no_sys;
1610
1611         RB_INIT(&bdev->addr_space_rb);
1612         ret = drm_mm_init(&bdev->addr_space_mm, file_page_offset, 0x10000000);
1613         if (unlikely(ret != 0))
1614                 goto out_no_addr_mm;
1615
1616         TIMEOUT_TASK_INIT(taskqueue_thread[mycpuid], &bdev->wq, 0,
1617             ttm_bo_delayed_workqueue, bdev);
1618         INIT_LIST_HEAD(&bdev->ddestroy);
1619         bdev->dev_mapping = NULL;
1620         bdev->glob = glob;
1621         bdev->need_dma32 = need_dma32;
1622         bdev->val_seq = 0;
1623         lockinit(&bdev->fence_lock, "ttmfence", 0, LK_CANRECURSE);
1624         lockmgr(&glob->device_list_mutex, LK_EXCLUSIVE);
1625         list_add_tail(&bdev->device_list, &glob->device_list);
1626         lockmgr(&glob->device_list_mutex, LK_RELEASE);
1627
1628         return 0;
1629 out_no_addr_mm:
1630         ttm_bo_clean_mm(bdev, 0);
1631 out_no_sys:
1632         return ret;
1633 }
1634 EXPORT_SYMBOL(ttm_bo_device_init);
1635
1636 /*
1637  * buffer object vm functions.
1638  */
1639
1640 bool ttm_mem_reg_is_pci(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
1641 {
1642         struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
1643
1644         if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED)) {
1645                 if (mem->mem_type == TTM_PL_SYSTEM)
1646                         return false;
1647
1648                 if (man->flags & TTM_MEMTYPE_FLAG_CMA)
1649                         return false;
1650
1651                 if (mem->placement & TTM_PL_FLAG_CACHED)
1652                         return false;
1653         }
1654         return true;
1655 }
1656
1657 void ttm_bo_unmap_virtual_locked(struct ttm_buffer_object *bo)
1658 {
1659
1660         ttm_bo_release_mmap(bo);
1661         ttm_mem_io_free_vm(bo);
1662 }
1663
1664 void ttm_bo_unmap_virtual(struct ttm_buffer_object *bo)
1665 {
1666         struct ttm_bo_device *bdev = bo->bdev;
1667         struct ttm_mem_type_manager *man = &bdev->man[bo->mem.mem_type];
1668
1669         ttm_mem_io_lock(man, false);
1670         ttm_bo_unmap_virtual_locked(bo);
1671         ttm_mem_io_unlock(man);
1672 }
1673
1674
1675 EXPORT_SYMBOL(ttm_bo_unmap_virtual);
1676
1677 static void ttm_bo_vm_insert_rb(struct ttm_buffer_object *bo)
1678 {
1679         struct ttm_bo_device *bdev = bo->bdev;
1680
1681         /* The caller acquired bdev->vm_lock. */
1682         RB_INSERT(ttm_bo_device_buffer_objects, &bdev->addr_space_rb, bo);
1683 }
1684
1685 /**
1686  * ttm_bo_setup_vm:
1687  *
1688  * @bo: the buffer to allocate address space for
1689  *
1690  * Allocate address space in the drm device so that applications
1691  * can mmap the buffer and access the contents. This only
1692  * applies to ttm_bo_type_device objects as others are not
1693  * placed in the drm device address space.
1694  */
1695
1696 static int ttm_bo_setup_vm(struct ttm_buffer_object *bo)
1697 {
1698         struct ttm_bo_device *bdev = bo->bdev;
1699         int ret;
1700
1701 retry_pre_get:
1702         ret = drm_mm_pre_get(&bdev->addr_space_mm);
1703         if (unlikely(ret != 0))
1704                 return ret;
1705
1706         lockmgr(&bdev->vm_lock, LK_EXCLUSIVE);
1707         bo->vm_node = drm_mm_search_free(&bdev->addr_space_mm,
1708                                          bo->mem.num_pages, 0, 0);
1709
1710         if (unlikely(bo->vm_node == NULL)) {
1711                 ret = -ENOMEM;
1712                 goto out_unlock;
1713         }
1714
1715         bo->vm_node = drm_mm_get_block_atomic(bo->vm_node,
1716                                               bo->mem.num_pages, 0);
1717
1718         if (unlikely(bo->vm_node == NULL)) {
1719                 lockmgr(&bdev->vm_lock, LK_RELEASE);
1720                 goto retry_pre_get;
1721         }
1722
1723         ttm_bo_vm_insert_rb(bo);
1724         lockmgr(&bdev->vm_lock, LK_RELEASE);
1725         bo->addr_space_offset = ((uint64_t) bo->vm_node->start) << PAGE_SHIFT;
1726
1727         return 0;
1728 out_unlock:
1729         lockmgr(&bdev->vm_lock, LK_RELEASE);
1730         return ret;
1731 }
1732
1733 int ttm_bo_wait(struct ttm_buffer_object *bo,
1734                 bool lazy, bool interruptible, bool no_wait)
1735 {
1736         struct ttm_bo_driver *driver = bo->bdev->driver;
1737         struct ttm_bo_device *bdev = bo->bdev;
1738         void *sync_obj;
1739         int ret = 0;
1740
1741         if (likely(bo->sync_obj == NULL))
1742                 return 0;
1743
1744         while (bo->sync_obj) {
1745
1746                 if (driver->sync_obj_signaled(bo->sync_obj)) {
1747                         void *tmp_obj = bo->sync_obj;
1748                         bo->sync_obj = NULL;
1749                         clear_bit(TTM_BO_PRIV_FLAG_MOVING, &bo->priv_flags);
1750                         lockmgr(&bdev->fence_lock, LK_RELEASE);
1751                         driver->sync_obj_unref(&tmp_obj);
1752                         lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1753                         continue;
1754                 }
1755
1756                 if (no_wait)
1757                         return -EBUSY;
1758
1759                 sync_obj = driver->sync_obj_ref(bo->sync_obj);
1760                 lockmgr(&bdev->fence_lock, LK_RELEASE);
1761                 ret = driver->sync_obj_wait(sync_obj,
1762                                             lazy, interruptible);
1763                 if (unlikely(ret != 0)) {
1764                         driver->sync_obj_unref(&sync_obj);
1765                         lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1766                         return ret;
1767                 }
1768                 lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1769                 if (likely(bo->sync_obj == sync_obj)) {
1770                         void *tmp_obj = bo->sync_obj;
1771                         bo->sync_obj = NULL;
1772                         clear_bit(TTM_BO_PRIV_FLAG_MOVING,
1773                                   &bo->priv_flags);
1774                         lockmgr(&bdev->fence_lock, LK_RELEASE);
1775                         driver->sync_obj_unref(&sync_obj);
1776                         driver->sync_obj_unref(&tmp_obj);
1777                         lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1778                 } else {
1779                         lockmgr(&bdev->fence_lock, LK_RELEASE);
1780                         driver->sync_obj_unref(&sync_obj);
1781                         lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1782                 }
1783         }
1784         return 0;
1785 }
1786 EXPORT_SYMBOL(ttm_bo_wait);
1787
1788 int ttm_bo_synccpu_write_grab(struct ttm_buffer_object *bo, bool no_wait)
1789 {
1790         struct ttm_bo_device *bdev = bo->bdev;
1791         int ret = 0;
1792
1793         /*
1794          * Using ttm_bo_reserve makes sure the lru lists are updated.
1795          */
1796
1797         ret = ttm_bo_reserve(bo, true, no_wait, false, 0);
1798         if (unlikely(ret != 0))
1799                 return ret;
1800         lockmgr(&bdev->fence_lock, LK_EXCLUSIVE);
1801         ret = ttm_bo_wait(bo, false, true, no_wait);
1802         lockmgr(&bdev->fence_lock, LK_RELEASE);
1803         if (likely(ret == 0))
1804                 atomic_inc(&bo->cpu_writers);
1805         ttm_bo_unreserve(bo);
1806         return ret;
1807 }
1808 EXPORT_SYMBOL(ttm_bo_synccpu_write_grab);
1809
1810 void ttm_bo_synccpu_write_release(struct ttm_buffer_object *bo)
1811 {
1812         atomic_dec(&bo->cpu_writers);
1813 }
1814 EXPORT_SYMBOL(ttm_bo_synccpu_write_release);
1815
1816 /**
1817  * A buffer object shrink method that tries to swap out the first
1818  * buffer object on the bo_global::swap_lru list.
1819  */
1820
1821 static int ttm_bo_swapout(struct ttm_mem_shrink *shrink)
1822 {
1823         struct ttm_bo_global *glob =
1824             container_of(shrink, struct ttm_bo_global, shrink);
1825         struct ttm_buffer_object *bo;
1826         int ret = -EBUSY;
1827         int put_count;
1828         uint32_t swap_placement = (TTM_PL_FLAG_CACHED | TTM_PL_FLAG_SYSTEM);
1829
1830         lockmgr(&glob->lru_lock, LK_EXCLUSIVE);
1831         list_for_each_entry(bo, &glob->swap_lru, swap) {
1832                 ret = ttm_bo_reserve_nolru(bo, false, true, false, 0);
1833                 if (!ret)
1834                         break;
1835         }
1836
1837         if (ret) {
1838                 lockmgr(&glob->lru_lock, LK_RELEASE);
1839                 return ret;
1840         }
1841
1842         kref_get(&bo->list_kref);
1843
1844         if (!list_empty(&bo->ddestroy)) {
1845                 ret = ttm_bo_cleanup_refs_and_unlock(bo, false, false);
1846                 kref_put(&bo->list_kref, ttm_bo_release_list);
1847                 return ret;
1848         }
1849
1850         put_count = ttm_bo_del_from_lru(bo);
1851         lockmgr(&glob->lru_lock, LK_RELEASE);
1852
1853         ttm_bo_list_ref_sub(bo, put_count, true);
1854
1855         /**
1856          * Wait for GPU, then move to system cached.
1857          */
1858
1859         lockmgr(&bo->bdev->fence_lock, LK_EXCLUSIVE);
1860         ret = ttm_bo_wait(bo, false, false, false);
1861         lockmgr(&bo->bdev->fence_lock, LK_RELEASE);
1862
1863         if (unlikely(ret != 0))
1864                 goto out;
1865
1866         if ((bo->mem.placement & swap_placement) != swap_placement) {
1867                 struct ttm_mem_reg evict_mem;
1868
1869                 evict_mem = bo->mem;
1870                 evict_mem.mm_node = NULL;
1871                 evict_mem.placement = TTM_PL_FLAG_SYSTEM | TTM_PL_FLAG_CACHED;
1872                 evict_mem.mem_type = TTM_PL_SYSTEM;
1873
1874                 ret = ttm_bo_handle_move_mem(bo, &evict_mem, true,
1875                                              false, false);
1876                 if (unlikely(ret != 0))
1877                         goto out;
1878         }
1879
1880         ttm_bo_unmap_virtual(bo);
1881
1882         /**
1883          * Swap out. Buffer will be swapped in again as soon as
1884          * anyone tries to access a ttm page.
1885          */
1886
1887         if (bo->bdev->driver->swap_notify)
1888                 bo->bdev->driver->swap_notify(bo);
1889
1890         ret = ttm_tt_swapout(bo->ttm, bo->persistent_swap_storage);
1891 out:
1892
1893         /**
1894          *
1895          * Unreserve without putting on LRU to avoid swapping out an
1896          * already swapped buffer.
1897          */
1898
1899         atomic_set(&bo->reserved, 0);
1900         wakeup(bo);
1901         kref_put(&bo->list_kref, ttm_bo_release_list);
1902         return ret;
1903 }
1904
1905 void ttm_bo_swapout_all(struct ttm_bo_device *bdev)
1906 {
1907         while (ttm_bo_swapout(&bdev->glob->shrink) == 0)
1908                 ;
1909 }
1910 EXPORT_SYMBOL(ttm_bo_swapout_all);