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