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