GNU Linux-libre 4.4.284-gnu1
[releases.git] / drivers / staging / android / ion / ion.c
1 /*
2  *
3  * drivers/staging/android/ion/ion.c
4  *
5  * Copyright (C) 2011 Google, Inc.
6  *
7  * This software is licensed under the terms of the GNU General Public
8  * License version 2, as published by the Free Software Foundation, and
9  * may be copied, distributed, and modified under those terms.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  */
17
18 #include <linux/atomic.h>
19 #include <linux/device.h>
20 #include <linux/err.h>
21 #include <linux/file.h>
22 #include <linux/freezer.h>
23 #include <linux/fs.h>
24 #include <linux/anon_inodes.h>
25 #include <linux/kthread.h>
26 #include <linux/list.h>
27 #include <linux/memblock.h>
28 #include <linux/miscdevice.h>
29 #include <linux/export.h>
30 #include <linux/mm.h>
31 #include <linux/mm_types.h>
32 #include <linux/rbtree.h>
33 #include <linux/slab.h>
34 #include <linux/seq_file.h>
35 #include <linux/uaccess.h>
36 #include <linux/vmalloc.h>
37 #include <linux/debugfs.h>
38 #include <linux/dma-buf.h>
39 #include <linux/idr.h>
40
41 #include "ion.h"
42 #include "ion_priv.h"
43 #include "compat_ion.h"
44
45 /**
46  * struct ion_device - the metadata of the ion device node
47  * @dev:                the actual misc device
48  * @buffers:            an rb tree of all the existing buffers
49  * @buffer_lock:        lock protecting the tree of buffers
50  * @lock:               rwsem protecting the tree of heaps and clients
51  * @heaps:              list of all the heaps in the system
52  * @user_clients:       list of all the clients created from userspace
53  */
54 struct ion_device {
55         struct miscdevice dev;
56         struct rb_root buffers;
57         struct mutex buffer_lock;
58         struct rw_semaphore lock;
59         struct plist_head heaps;
60         long (*custom_ioctl)(struct ion_client *client, unsigned int cmd,
61                              unsigned long arg);
62         struct rb_root clients;
63         struct dentry *debug_root;
64         struct dentry *heaps_debug_root;
65         struct dentry *clients_debug_root;
66 };
67
68 /**
69  * struct ion_client - a process/hw block local address space
70  * @node:               node in the tree of all clients
71  * @dev:                backpointer to ion device
72  * @handles:            an rb tree of all the handles in this client
73  * @idr:                an idr space for allocating handle ids
74  * @lock:               lock protecting the tree of handles
75  * @name:               used for debugging
76  * @display_name:       used for debugging (unique version of @name)
77  * @display_serial:     used for debugging (to make display_name unique)
78  * @task:               used for debugging
79  *
80  * A client represents a list of buffers this client may access.
81  * The mutex stored here is used to protect both handles tree
82  * as well as the handles themselves, and should be held while modifying either.
83  */
84 struct ion_client {
85         struct rb_node node;
86         struct ion_device *dev;
87         struct rb_root handles;
88         struct idr idr;
89         struct mutex lock;
90         const char *name;
91         char *display_name;
92         int display_serial;
93         struct task_struct *task;
94         pid_t pid;
95         struct dentry *debug_root;
96 };
97
98 /**
99  * ion_handle - a client local reference to a buffer
100  * @ref:                reference count
101  * @client:             back pointer to the client the buffer resides in
102  * @buffer:             pointer to the buffer
103  * @node:               node in the client's handle rbtree
104  * @kmap_cnt:           count of times this client has mapped to kernel
105  * @id:                 client-unique id allocated by client->idr
106  *
107  * Modifications to node, map_cnt or mapping should be protected by the
108  * lock in the client.  Other fields are never changed after initialization.
109  */
110 struct ion_handle {
111         struct kref ref;
112         struct ion_client *client;
113         struct ion_buffer *buffer;
114         struct rb_node node;
115         unsigned int kmap_cnt;
116         int id;
117 };
118
119 bool ion_buffer_fault_user_mappings(struct ion_buffer *buffer)
120 {
121         return (buffer->flags & ION_FLAG_CACHED) &&
122                 !(buffer->flags & ION_FLAG_CACHED_NEEDS_SYNC);
123 }
124
125 bool ion_buffer_cached(struct ion_buffer *buffer)
126 {
127         return !!(buffer->flags & ION_FLAG_CACHED);
128 }
129
130 static inline struct page *ion_buffer_page(struct page *page)
131 {
132         return (struct page *)((unsigned long)page & ~(1UL));
133 }
134
135 static inline bool ion_buffer_page_is_dirty(struct page *page)
136 {
137         return !!((unsigned long)page & 1UL);
138 }
139
140 static inline void ion_buffer_page_dirty(struct page **page)
141 {
142         *page = (struct page *)((unsigned long)(*page) | 1UL);
143 }
144
145 static inline void ion_buffer_page_clean(struct page **page)
146 {
147         *page = (struct page *)((unsigned long)(*page) & ~(1UL));
148 }
149
150 /* this function should only be called while dev->lock is held */
151 static void ion_buffer_add(struct ion_device *dev,
152                            struct ion_buffer *buffer)
153 {
154         struct rb_node **p = &dev->buffers.rb_node;
155         struct rb_node *parent = NULL;
156         struct ion_buffer *entry;
157
158         while (*p) {
159                 parent = *p;
160                 entry = rb_entry(parent, struct ion_buffer, node);
161
162                 if (buffer < entry) {
163                         p = &(*p)->rb_left;
164                 } else if (buffer > entry) {
165                         p = &(*p)->rb_right;
166                 } else {
167                         pr_err("%s: buffer already found.", __func__);
168                         BUG();
169                 }
170         }
171
172         rb_link_node(&buffer->node, parent, p);
173         rb_insert_color(&buffer->node, &dev->buffers);
174 }
175
176 /* this function should only be called while dev->lock is held */
177 static struct ion_buffer *ion_buffer_create(struct ion_heap *heap,
178                                      struct ion_device *dev,
179                                      unsigned long len,
180                                      unsigned long align,
181                                      unsigned long flags)
182 {
183         struct ion_buffer *buffer;
184         struct sg_table *table;
185         struct scatterlist *sg;
186         int i, ret;
187
188         buffer = kzalloc(sizeof(struct ion_buffer), GFP_KERNEL);
189         if (!buffer)
190                 return ERR_PTR(-ENOMEM);
191
192         buffer->heap = heap;
193         buffer->flags = flags;
194         kref_init(&buffer->ref);
195
196         ret = heap->ops->allocate(heap, buffer, len, align, flags);
197
198         if (ret) {
199                 if (!(heap->flags & ION_HEAP_FLAG_DEFER_FREE))
200                         goto err2;
201
202                 ion_heap_freelist_drain(heap, 0);
203                 ret = heap->ops->allocate(heap, buffer, len, align,
204                                           flags);
205                 if (ret)
206                         goto err2;
207         }
208
209         buffer->dev = dev;
210         buffer->size = len;
211
212         table = heap->ops->map_dma(heap, buffer);
213         if (WARN_ONCE(table == NULL,
214                         "heap->ops->map_dma should return ERR_PTR on error"))
215                 table = ERR_PTR(-EINVAL);
216         if (IS_ERR(table)) {
217                 ret = -EINVAL;
218                 goto err1;
219         }
220
221         buffer->sg_table = table;
222         if (ion_buffer_fault_user_mappings(buffer)) {
223                 int num_pages = PAGE_ALIGN(buffer->size) / PAGE_SIZE;
224                 struct scatterlist *sg;
225                 int i, j, k = 0;
226
227                 buffer->pages = vmalloc(sizeof(struct page *) * num_pages);
228                 if (!buffer->pages) {
229                         ret = -ENOMEM;
230                         goto err;
231                 }
232
233                 for_each_sg(table->sgl, sg, table->nents, i) {
234                         struct page *page = sg_page(sg);
235
236                         for (j = 0; j < sg->length / PAGE_SIZE; j++)
237                                 buffer->pages[k++] = page++;
238                 }
239         }
240
241         buffer->dev = dev;
242         buffer->size = len;
243         INIT_LIST_HEAD(&buffer->vmas);
244         mutex_init(&buffer->lock);
245         /*
246          * this will set up dma addresses for the sglist -- it is not
247          * technically correct as per the dma api -- a specific
248          * device isn't really taking ownership here.  However, in practice on
249          * our systems the only dma_address space is physical addresses.
250          * Additionally, we can't afford the overhead of invalidating every
251          * allocation via dma_map_sg. The implicit contract here is that
252          * memory coming from the heaps is ready for dma, ie if it has a
253          * cached mapping that mapping has been invalidated
254          */
255         for_each_sg(buffer->sg_table->sgl, sg, buffer->sg_table->nents, i) {
256                 sg_dma_address(sg) = sg_phys(sg);
257                 sg_dma_len(sg) = sg->length;
258         }
259         mutex_lock(&dev->buffer_lock);
260         ion_buffer_add(dev, buffer);
261         mutex_unlock(&dev->buffer_lock);
262         return buffer;
263
264 err:
265         heap->ops->unmap_dma(heap, buffer);
266 err1:
267         heap->ops->free(buffer);
268 err2:
269         kfree(buffer);
270         return ERR_PTR(ret);
271 }
272
273 void ion_buffer_destroy(struct ion_buffer *buffer)
274 {
275         if (WARN_ON(buffer->kmap_cnt > 0))
276                 buffer->heap->ops->unmap_kernel(buffer->heap, buffer);
277         buffer->heap->ops->unmap_dma(buffer->heap, buffer);
278         buffer->heap->ops->free(buffer);
279         vfree(buffer->pages);
280         kfree(buffer);
281 }
282
283 static void _ion_buffer_destroy(struct kref *kref)
284 {
285         struct ion_buffer *buffer = container_of(kref, struct ion_buffer, ref);
286         struct ion_heap *heap = buffer->heap;
287         struct ion_device *dev = buffer->dev;
288
289         mutex_lock(&dev->buffer_lock);
290         rb_erase(&buffer->node, &dev->buffers);
291         mutex_unlock(&dev->buffer_lock);
292
293         if (heap->flags & ION_HEAP_FLAG_DEFER_FREE)
294                 ion_heap_freelist_add(heap, buffer);
295         else
296                 ion_buffer_destroy(buffer);
297 }
298
299 static void ion_buffer_get(struct ion_buffer *buffer)
300 {
301         kref_get(&buffer->ref);
302 }
303
304 static int ion_buffer_put(struct ion_buffer *buffer)
305 {
306         return kref_put(&buffer->ref, _ion_buffer_destroy);
307 }
308
309 static void ion_buffer_add_to_handle(struct ion_buffer *buffer)
310 {
311         mutex_lock(&buffer->lock);
312         buffer->handle_count++;
313         mutex_unlock(&buffer->lock);
314 }
315
316 static void ion_buffer_remove_from_handle(struct ion_buffer *buffer)
317 {
318         /*
319          * when a buffer is removed from a handle, if it is not in
320          * any other handles, copy the taskcomm and the pid of the
321          * process it's being removed from into the buffer.  At this
322          * point there will be no way to track what processes this buffer is
323          * being used by, it only exists as a dma_buf file descriptor.
324          * The taskcomm and pid can provide a debug hint as to where this fd
325          * is in the system
326          */
327         mutex_lock(&buffer->lock);
328         buffer->handle_count--;
329         BUG_ON(buffer->handle_count < 0);
330         if (!buffer->handle_count) {
331                 struct task_struct *task;
332
333                 task = current->group_leader;
334                 get_task_comm(buffer->task_comm, task);
335                 buffer->pid = task_pid_nr(task);
336         }
337         mutex_unlock(&buffer->lock);
338 }
339
340 static struct ion_handle *ion_handle_create(struct ion_client *client,
341                                      struct ion_buffer *buffer)
342 {
343         struct ion_handle *handle;
344
345         handle = kzalloc(sizeof(struct ion_handle), GFP_KERNEL);
346         if (!handle)
347                 return ERR_PTR(-ENOMEM);
348         kref_init(&handle->ref);
349         RB_CLEAR_NODE(&handle->node);
350         handle->client = client;
351         ion_buffer_get(buffer);
352         ion_buffer_add_to_handle(buffer);
353         handle->buffer = buffer;
354
355         return handle;
356 }
357
358 static void ion_handle_kmap_put(struct ion_handle *);
359
360 static void ion_handle_destroy(struct kref *kref)
361 {
362         struct ion_handle *handle = container_of(kref, struct ion_handle, ref);
363         struct ion_client *client = handle->client;
364         struct ion_buffer *buffer = handle->buffer;
365
366         mutex_lock(&buffer->lock);
367         while (handle->kmap_cnt)
368                 ion_handle_kmap_put(handle);
369         mutex_unlock(&buffer->lock);
370
371         idr_remove(&client->idr, handle->id);
372         if (!RB_EMPTY_NODE(&handle->node))
373                 rb_erase(&handle->node, &client->handles);
374
375         ion_buffer_remove_from_handle(buffer);
376         ion_buffer_put(buffer);
377
378         kfree(handle);
379 }
380
381 struct ion_buffer *ion_handle_buffer(struct ion_handle *handle)
382 {
383         return handle->buffer;
384 }
385
386 static void ion_handle_get(struct ion_handle *handle)
387 {
388         kref_get(&handle->ref);
389 }
390
391 /* Must hold the client lock */
392 static struct ion_handle *ion_handle_get_check_overflow(
393                                         struct ion_handle *handle)
394 {
395         if (atomic_read(&handle->ref.refcount) + 1 == 0)
396                 return ERR_PTR(-EOVERFLOW);
397         ion_handle_get(handle);
398         return handle;
399 }
400
401 static int ion_handle_put_nolock(struct ion_handle *handle)
402 {
403         int ret;
404
405         ret = kref_put(&handle->ref, ion_handle_destroy);
406
407         return ret;
408 }
409
410 int ion_handle_put(struct ion_handle *handle)
411 {
412         struct ion_client *client = handle->client;
413         int ret;
414
415         mutex_lock(&client->lock);
416         ret = ion_handle_put_nolock(handle);
417         mutex_unlock(&client->lock);
418
419         return ret;
420 }
421
422 static struct ion_handle *ion_handle_lookup(struct ion_client *client,
423                                             struct ion_buffer *buffer)
424 {
425         struct rb_node *n = client->handles.rb_node;
426
427         while (n) {
428                 struct ion_handle *entry = rb_entry(n, struct ion_handle, node);
429
430                 if (buffer < entry->buffer)
431                         n = n->rb_left;
432                 else if (buffer > entry->buffer)
433                         n = n->rb_right;
434                 else
435                         return entry;
436         }
437         return ERR_PTR(-EINVAL);
438 }
439
440 static struct ion_handle *ion_handle_get_by_id_nolock(struct ion_client *client,
441                                                 int id)
442 {
443         struct ion_handle *handle;
444
445         handle = idr_find(&client->idr, id);
446         if (handle)
447                 return ion_handle_get_check_overflow(handle);
448
449         return ERR_PTR(-EINVAL);
450 }
451
452 static bool ion_handle_validate(struct ion_client *client,
453                                 struct ion_handle *handle)
454 {
455         WARN_ON(!mutex_is_locked(&client->lock));
456         return idr_find(&client->idr, handle->id) == handle;
457 }
458
459 static int ion_handle_add(struct ion_client *client, struct ion_handle *handle)
460 {
461         int id;
462         struct rb_node **p = &client->handles.rb_node;
463         struct rb_node *parent = NULL;
464         struct ion_handle *entry;
465
466         id = idr_alloc(&client->idr, handle, 1, 0, GFP_KERNEL);
467         if (id < 0)
468                 return id;
469
470         handle->id = id;
471
472         while (*p) {
473                 parent = *p;
474                 entry = rb_entry(parent, struct ion_handle, node);
475
476                 if (handle->buffer < entry->buffer)
477                         p = &(*p)->rb_left;
478                 else if (handle->buffer > entry->buffer)
479                         p = &(*p)->rb_right;
480                 else
481                         WARN(1, "%s: buffer already found.", __func__);
482         }
483
484         rb_link_node(&handle->node, parent, p);
485         rb_insert_color(&handle->node, &client->handles);
486
487         return 0;
488 }
489
490 struct ion_handle *ion_alloc(struct ion_client *client, size_t len,
491                              size_t align, unsigned int heap_id_mask,
492                              unsigned int flags)
493 {
494         struct ion_handle *handle;
495         struct ion_device *dev = client->dev;
496         struct ion_buffer *buffer = NULL;
497         struct ion_heap *heap;
498         int ret;
499
500         pr_debug("%s: len %zu align %zu heap_id_mask %u flags %x\n", __func__,
501                  len, align, heap_id_mask, flags);
502         /*
503          * traverse the list of heaps available in this system in priority
504          * order.  If the heap type is supported by the client, and matches the
505          * request of the caller allocate from it.  Repeat until allocate has
506          * succeeded or all heaps have been tried
507          */
508         len = PAGE_ALIGN(len);
509
510         if (!len)
511                 return ERR_PTR(-EINVAL);
512
513         down_read(&dev->lock);
514         plist_for_each_entry(heap, &dev->heaps, node) {
515                 /* if the caller didn't specify this heap id */
516                 if (!((1 << heap->id) & heap_id_mask))
517                         continue;
518                 buffer = ion_buffer_create(heap, dev, len, align, flags);
519                 if (!IS_ERR(buffer))
520                         break;
521         }
522         up_read(&dev->lock);
523
524         if (buffer == NULL)
525                 return ERR_PTR(-ENODEV);
526
527         if (IS_ERR(buffer))
528                 return ERR_CAST(buffer);
529
530         handle = ion_handle_create(client, buffer);
531
532         /*
533          * ion_buffer_create will create a buffer with a ref_cnt of 1,
534          * and ion_handle_create will take a second reference, drop one here
535          */
536         ion_buffer_put(buffer);
537
538         if (IS_ERR(handle))
539                 return handle;
540
541         mutex_lock(&client->lock);
542         ret = ion_handle_add(client, handle);
543         mutex_unlock(&client->lock);
544         if (ret) {
545                 ion_handle_put(handle);
546                 handle = ERR_PTR(ret);
547         }
548
549         return handle;
550 }
551 EXPORT_SYMBOL(ion_alloc);
552
553 static void ion_free_nolock(struct ion_client *client, struct ion_handle *handle)
554 {
555         bool valid_handle;
556
557         BUG_ON(client != handle->client);
558
559         valid_handle = ion_handle_validate(client, handle);
560
561         if (!valid_handle) {
562                 WARN(1, "%s: invalid handle passed to free.\n", __func__);
563                 return;
564         }
565         ion_handle_put_nolock(handle);
566 }
567
568 void ion_free(struct ion_client *client, struct ion_handle *handle)
569 {
570         BUG_ON(client != handle->client);
571
572         mutex_lock(&client->lock);
573         ion_free_nolock(client, handle);
574         mutex_unlock(&client->lock);
575 }
576 EXPORT_SYMBOL(ion_free);
577
578 int ion_phys(struct ion_client *client, struct ion_handle *handle,
579              ion_phys_addr_t *addr, size_t *len)
580 {
581         struct ion_buffer *buffer;
582         int ret;
583
584         mutex_lock(&client->lock);
585         if (!ion_handle_validate(client, handle)) {
586                 mutex_unlock(&client->lock);
587                 return -EINVAL;
588         }
589
590         buffer = handle->buffer;
591
592         if (!buffer->heap->ops->phys) {
593                 pr_err("%s: ion_phys is not implemented by this heap (name=%s, type=%d).\n",
594                         __func__, buffer->heap->name, buffer->heap->type);
595                 mutex_unlock(&client->lock);
596                 return -ENODEV;
597         }
598         mutex_unlock(&client->lock);
599         ret = buffer->heap->ops->phys(buffer->heap, buffer, addr, len);
600         return ret;
601 }
602 EXPORT_SYMBOL(ion_phys);
603
604 static void *ion_buffer_kmap_get(struct ion_buffer *buffer)
605 {
606         void *vaddr;
607
608         if (buffer->kmap_cnt) {
609                 buffer->kmap_cnt++;
610                 return buffer->vaddr;
611         }
612         vaddr = buffer->heap->ops->map_kernel(buffer->heap, buffer);
613         if (WARN_ONCE(vaddr == NULL,
614                         "heap->ops->map_kernel should return ERR_PTR on error"))
615                 return ERR_PTR(-EINVAL);
616         if (IS_ERR(vaddr))
617                 return vaddr;
618         buffer->vaddr = vaddr;
619         buffer->kmap_cnt++;
620         return vaddr;
621 }
622
623 static void *ion_handle_kmap_get(struct ion_handle *handle)
624 {
625         struct ion_buffer *buffer = handle->buffer;
626         void *vaddr;
627
628         if (handle->kmap_cnt) {
629                 handle->kmap_cnt++;
630                 return buffer->vaddr;
631         }
632         vaddr = ion_buffer_kmap_get(buffer);
633         if (IS_ERR(vaddr))
634                 return vaddr;
635         handle->kmap_cnt++;
636         return vaddr;
637 }
638
639 static void ion_buffer_kmap_put(struct ion_buffer *buffer)
640 {
641         buffer->kmap_cnt--;
642         if (!buffer->kmap_cnt) {
643                 buffer->heap->ops->unmap_kernel(buffer->heap, buffer);
644                 buffer->vaddr = NULL;
645         }
646 }
647
648 static void ion_handle_kmap_put(struct ion_handle *handle)
649 {
650         struct ion_buffer *buffer = handle->buffer;
651
652         if (!handle->kmap_cnt) {
653                 WARN(1, "%s: Double unmap detected! bailing...\n", __func__);
654                 return;
655         }
656         handle->kmap_cnt--;
657         if (!handle->kmap_cnt)
658                 ion_buffer_kmap_put(buffer);
659 }
660
661 void *ion_map_kernel(struct ion_client *client, struct ion_handle *handle)
662 {
663         struct ion_buffer *buffer;
664         void *vaddr;
665
666         mutex_lock(&client->lock);
667         if (!ion_handle_validate(client, handle)) {
668                 pr_err("%s: invalid handle passed to map_kernel.\n",
669                        __func__);
670                 mutex_unlock(&client->lock);
671                 return ERR_PTR(-EINVAL);
672         }
673
674         buffer = handle->buffer;
675
676         if (!handle->buffer->heap->ops->map_kernel) {
677                 pr_err("%s: map_kernel is not implemented by this heap.\n",
678                        __func__);
679                 mutex_unlock(&client->lock);
680                 return ERR_PTR(-ENODEV);
681         }
682
683         mutex_lock(&buffer->lock);
684         vaddr = ion_handle_kmap_get(handle);
685         mutex_unlock(&buffer->lock);
686         mutex_unlock(&client->lock);
687         return vaddr;
688 }
689 EXPORT_SYMBOL(ion_map_kernel);
690
691 void ion_unmap_kernel(struct ion_client *client, struct ion_handle *handle)
692 {
693         struct ion_buffer *buffer;
694
695         mutex_lock(&client->lock);
696         buffer = handle->buffer;
697         mutex_lock(&buffer->lock);
698         ion_handle_kmap_put(handle);
699         mutex_unlock(&buffer->lock);
700         mutex_unlock(&client->lock);
701 }
702 EXPORT_SYMBOL(ion_unmap_kernel);
703
704 static int ion_debug_client_show(struct seq_file *s, void *unused)
705 {
706         struct ion_client *client = s->private;
707         struct rb_node *n;
708         size_t sizes[ION_NUM_HEAP_IDS] = {0};
709         const char *names[ION_NUM_HEAP_IDS] = {NULL};
710         int i;
711
712         mutex_lock(&client->lock);
713         for (n = rb_first(&client->handles); n; n = rb_next(n)) {
714                 struct ion_handle *handle = rb_entry(n, struct ion_handle,
715                                                      node);
716                 unsigned int id = handle->buffer->heap->id;
717
718                 if (!names[id])
719                         names[id] = handle->buffer->heap->name;
720                 sizes[id] += handle->buffer->size;
721         }
722         mutex_unlock(&client->lock);
723
724         seq_printf(s, "%16.16s: %16.16s\n", "heap_name", "size_in_bytes");
725         for (i = 0; i < ION_NUM_HEAP_IDS; i++) {
726                 if (!names[i])
727                         continue;
728                 seq_printf(s, "%16.16s: %16zu\n", names[i], sizes[i]);
729         }
730         return 0;
731 }
732
733 static int ion_debug_client_open(struct inode *inode, struct file *file)
734 {
735         return single_open(file, ion_debug_client_show, inode->i_private);
736 }
737
738 static const struct file_operations debug_client_fops = {
739         .open = ion_debug_client_open,
740         .read = seq_read,
741         .llseek = seq_lseek,
742         .release = single_release,
743 };
744
745 static int ion_get_client_serial(const struct rb_root *root,
746                                         const unsigned char *name)
747 {
748         int serial = -1;
749         struct rb_node *node;
750
751         for (node = rb_first(root); node; node = rb_next(node)) {
752                 struct ion_client *client = rb_entry(node, struct ion_client,
753                                                 node);
754
755                 if (strcmp(client->name, name))
756                         continue;
757                 serial = max(serial, client->display_serial);
758         }
759         return serial + 1;
760 }
761
762 struct ion_client *ion_client_create(struct ion_device *dev,
763                                      const char *name)
764 {
765         struct ion_client *client;
766         struct task_struct *task;
767         struct rb_node **p;
768         struct rb_node *parent = NULL;
769         struct ion_client *entry;
770         pid_t pid;
771
772         if (!name) {
773                 pr_err("%s: Name cannot be null\n", __func__);
774                 return ERR_PTR(-EINVAL);
775         }
776
777         get_task_struct(current->group_leader);
778         task_lock(current->group_leader);
779         pid = task_pid_nr(current->group_leader);
780         /*
781          * don't bother to store task struct for kernel threads,
782          * they can't be killed anyway
783          */
784         if (current->group_leader->flags & PF_KTHREAD) {
785                 put_task_struct(current->group_leader);
786                 task = NULL;
787         } else {
788                 task = current->group_leader;
789         }
790         task_unlock(current->group_leader);
791
792         client = kzalloc(sizeof(struct ion_client), GFP_KERNEL);
793         if (!client)
794                 goto err_put_task_struct;
795
796         client->dev = dev;
797         client->handles = RB_ROOT;
798         idr_init(&client->idr);
799         mutex_init(&client->lock);
800         client->task = task;
801         client->pid = pid;
802         client->name = kstrdup(name, GFP_KERNEL);
803         if (!client->name)
804                 goto err_free_client;
805
806         down_write(&dev->lock);
807         client->display_serial = ion_get_client_serial(&dev->clients, name);
808         client->display_name = kasprintf(
809                 GFP_KERNEL, "%s-%d", name, client->display_serial);
810         if (!client->display_name) {
811                 up_write(&dev->lock);
812                 goto err_free_client_name;
813         }
814         p = &dev->clients.rb_node;
815         while (*p) {
816                 parent = *p;
817                 entry = rb_entry(parent, struct ion_client, node);
818
819                 if (client < entry)
820                         p = &(*p)->rb_left;
821                 else if (client > entry)
822                         p = &(*p)->rb_right;
823         }
824         rb_link_node(&client->node, parent, p);
825         rb_insert_color(&client->node, &dev->clients);
826
827         client->debug_root = debugfs_create_file(client->display_name, 0664,
828                                                 dev->clients_debug_root,
829                                                 client, &debug_client_fops);
830         if (!client->debug_root) {
831                 char buf[256], *path;
832
833                 path = dentry_path(dev->clients_debug_root, buf, 256);
834                 pr_err("Failed to create client debugfs at %s/%s\n",
835                         path, client->display_name);
836         }
837
838         up_write(&dev->lock);
839
840         return client;
841
842 err_free_client_name:
843         kfree(client->name);
844 err_free_client:
845         kfree(client);
846 err_put_task_struct:
847         if (task)
848                 put_task_struct(current->group_leader);
849         return ERR_PTR(-ENOMEM);
850 }
851 EXPORT_SYMBOL(ion_client_create);
852
853 void ion_client_destroy(struct ion_client *client)
854 {
855         struct ion_device *dev = client->dev;
856         struct rb_node *n;
857
858         pr_debug("%s: %d\n", __func__, __LINE__);
859         while ((n = rb_first(&client->handles))) {
860                 struct ion_handle *handle = rb_entry(n, struct ion_handle,
861                                                      node);
862                 ion_handle_destroy(&handle->ref);
863         }
864
865         idr_destroy(&client->idr);
866
867         down_write(&dev->lock);
868         if (client->task)
869                 put_task_struct(client->task);
870         rb_erase(&client->node, &dev->clients);
871         debugfs_remove_recursive(client->debug_root);
872         up_write(&dev->lock);
873
874         kfree(client->display_name);
875         kfree(client->name);
876         kfree(client);
877 }
878 EXPORT_SYMBOL(ion_client_destroy);
879
880 struct sg_table *ion_sg_table(struct ion_client *client,
881                               struct ion_handle *handle)
882 {
883         struct ion_buffer *buffer;
884         struct sg_table *table;
885
886         mutex_lock(&client->lock);
887         if (!ion_handle_validate(client, handle)) {
888                 pr_err("%s: invalid handle passed to map_dma.\n",
889                        __func__);
890                 mutex_unlock(&client->lock);
891                 return ERR_PTR(-EINVAL);
892         }
893         buffer = handle->buffer;
894         table = buffer->sg_table;
895         mutex_unlock(&client->lock);
896         return table;
897 }
898 EXPORT_SYMBOL(ion_sg_table);
899
900 static void ion_buffer_sync_for_device(struct ion_buffer *buffer,
901                                        struct device *dev,
902                                        enum dma_data_direction direction);
903
904 static struct sg_table *ion_map_dma_buf(struct dma_buf_attachment *attachment,
905                                         enum dma_data_direction direction)
906 {
907         struct dma_buf *dmabuf = attachment->dmabuf;
908         struct ion_buffer *buffer = dmabuf->priv;
909
910         ion_buffer_sync_for_device(buffer, attachment->dev, direction);
911         return buffer->sg_table;
912 }
913
914 static void ion_unmap_dma_buf(struct dma_buf_attachment *attachment,
915                               struct sg_table *table,
916                               enum dma_data_direction direction)
917 {
918 }
919
920 void ion_pages_sync_for_device(struct device *dev, struct page *page,
921                 size_t size, enum dma_data_direction dir)
922 {
923         struct scatterlist sg;
924
925         sg_init_table(&sg, 1);
926         sg_set_page(&sg, page, size, 0);
927         /*
928          * This is not correct - sg_dma_address needs a dma_addr_t that is valid
929          * for the targeted device, but this works on the currently targeted
930          * hardware.
931          */
932         sg_dma_address(&sg) = page_to_phys(page);
933         dma_sync_sg_for_device(dev, &sg, 1, dir);
934 }
935
936 struct ion_vma_list {
937         struct list_head list;
938         struct vm_area_struct *vma;
939 };
940
941 static void ion_buffer_sync_for_device(struct ion_buffer *buffer,
942                                        struct device *dev,
943                                        enum dma_data_direction dir)
944 {
945         struct ion_vma_list *vma_list;
946         int pages = PAGE_ALIGN(buffer->size) / PAGE_SIZE;
947         int i;
948
949         pr_debug("%s: syncing for device %s\n", __func__,
950                  dev ? dev_name(dev) : "null");
951
952         if (!ion_buffer_fault_user_mappings(buffer))
953                 return;
954
955         mutex_lock(&buffer->lock);
956         for (i = 0; i < pages; i++) {
957                 struct page *page = buffer->pages[i];
958
959                 if (ion_buffer_page_is_dirty(page))
960                         ion_pages_sync_for_device(dev, ion_buffer_page(page),
961                                                         PAGE_SIZE, dir);
962
963                 ion_buffer_page_clean(buffer->pages + i);
964         }
965         list_for_each_entry(vma_list, &buffer->vmas, list) {
966                 struct vm_area_struct *vma = vma_list->vma;
967
968                 zap_page_range(vma, vma->vm_start, vma->vm_end - vma->vm_start,
969                                NULL);
970         }
971         mutex_unlock(&buffer->lock);
972 }
973
974 static int ion_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
975 {
976         struct ion_buffer *buffer = vma->vm_private_data;
977         unsigned long pfn;
978         int ret;
979
980         mutex_lock(&buffer->lock);
981         ion_buffer_page_dirty(buffer->pages + vmf->pgoff);
982         BUG_ON(!buffer->pages || !buffer->pages[vmf->pgoff]);
983
984         pfn = page_to_pfn(ion_buffer_page(buffer->pages[vmf->pgoff]));
985         ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
986         mutex_unlock(&buffer->lock);
987         if (ret)
988                 return VM_FAULT_ERROR;
989
990         return VM_FAULT_NOPAGE;
991 }
992
993 static void ion_vm_open(struct vm_area_struct *vma)
994 {
995         struct ion_buffer *buffer = vma->vm_private_data;
996         struct ion_vma_list *vma_list;
997
998         vma_list = kmalloc(sizeof(struct ion_vma_list), GFP_KERNEL);
999         if (!vma_list)
1000                 return;
1001         vma_list->vma = vma;
1002         mutex_lock(&buffer->lock);
1003         list_add(&vma_list->list, &buffer->vmas);
1004         mutex_unlock(&buffer->lock);
1005         pr_debug("%s: adding %p\n", __func__, vma);
1006 }
1007
1008 static void ion_vm_close(struct vm_area_struct *vma)
1009 {
1010         struct ion_buffer *buffer = vma->vm_private_data;
1011         struct ion_vma_list *vma_list, *tmp;
1012
1013         pr_debug("%s\n", __func__);
1014         mutex_lock(&buffer->lock);
1015         list_for_each_entry_safe(vma_list, tmp, &buffer->vmas, list) {
1016                 if (vma_list->vma != vma)
1017                         continue;
1018                 list_del(&vma_list->list);
1019                 kfree(vma_list);
1020                 pr_debug("%s: deleting %p\n", __func__, vma);
1021                 break;
1022         }
1023         mutex_unlock(&buffer->lock);
1024 }
1025
1026 static const struct vm_operations_struct ion_vma_ops = {
1027         .open = ion_vm_open,
1028         .close = ion_vm_close,
1029         .fault = ion_vm_fault,
1030 };
1031
1032 static int ion_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma)
1033 {
1034         struct ion_buffer *buffer = dmabuf->priv;
1035         int ret = 0;
1036
1037         if (!buffer->heap->ops->map_user) {
1038                 pr_err("%s: this heap does not define a method for mapping to userspace\n",
1039                         __func__);
1040                 return -EINVAL;
1041         }
1042
1043         if (ion_buffer_fault_user_mappings(buffer)) {
1044                 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND |
1045                                                         VM_DONTDUMP;
1046                 vma->vm_private_data = buffer;
1047                 vma->vm_ops = &ion_vma_ops;
1048                 ion_vm_open(vma);
1049                 return 0;
1050         }
1051
1052         if (!(buffer->flags & ION_FLAG_CACHED))
1053                 vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
1054
1055         mutex_lock(&buffer->lock);
1056         /* now map it to userspace */
1057         ret = buffer->heap->ops->map_user(buffer->heap, buffer, vma);
1058         mutex_unlock(&buffer->lock);
1059
1060         if (ret)
1061                 pr_err("%s: failure mapping buffer to userspace\n",
1062                        __func__);
1063
1064         return ret;
1065 }
1066
1067 static void ion_dma_buf_release(struct dma_buf *dmabuf)
1068 {
1069         struct ion_buffer *buffer = dmabuf->priv;
1070
1071         ion_buffer_put(buffer);
1072 }
1073
1074 static void *ion_dma_buf_kmap(struct dma_buf *dmabuf, unsigned long offset)
1075 {
1076         struct ion_buffer *buffer = dmabuf->priv;
1077
1078         return buffer->vaddr + offset * PAGE_SIZE;
1079 }
1080
1081 static void ion_dma_buf_kunmap(struct dma_buf *dmabuf, unsigned long offset,
1082                                void *ptr)
1083 {
1084 }
1085
1086 static int ion_dma_buf_begin_cpu_access(struct dma_buf *dmabuf, size_t start,
1087                                         size_t len,
1088                                         enum dma_data_direction direction)
1089 {
1090         struct ion_buffer *buffer = dmabuf->priv;
1091         void *vaddr;
1092
1093         if (!buffer->heap->ops->map_kernel) {
1094                 pr_err("%s: map kernel is not implemented by this heap.\n",
1095                        __func__);
1096                 return -ENODEV;
1097         }
1098
1099         mutex_lock(&buffer->lock);
1100         vaddr = ion_buffer_kmap_get(buffer);
1101         mutex_unlock(&buffer->lock);
1102         return PTR_ERR_OR_ZERO(vaddr);
1103 }
1104
1105 static void ion_dma_buf_end_cpu_access(struct dma_buf *dmabuf, size_t start,
1106                                        size_t len,
1107                                        enum dma_data_direction direction)
1108 {
1109         struct ion_buffer *buffer = dmabuf->priv;
1110
1111         mutex_lock(&buffer->lock);
1112         ion_buffer_kmap_put(buffer);
1113         mutex_unlock(&buffer->lock);
1114 }
1115
1116 static struct dma_buf_ops dma_buf_ops = {
1117         .map_dma_buf = ion_map_dma_buf,
1118         .unmap_dma_buf = ion_unmap_dma_buf,
1119         .mmap = ion_mmap,
1120         .release = ion_dma_buf_release,
1121         .begin_cpu_access = ion_dma_buf_begin_cpu_access,
1122         .end_cpu_access = ion_dma_buf_end_cpu_access,
1123         .kmap_atomic = ion_dma_buf_kmap,
1124         .kunmap_atomic = ion_dma_buf_kunmap,
1125         .kmap = ion_dma_buf_kmap,
1126         .kunmap = ion_dma_buf_kunmap,
1127 };
1128
1129 static struct dma_buf *__ion_share_dma_buf(struct ion_client *client,
1130                                            struct ion_handle *handle,
1131                                            bool lock_client)
1132 {
1133         DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
1134         struct ion_buffer *buffer;
1135         struct dma_buf *dmabuf;
1136         bool valid_handle;
1137
1138         if (lock_client)
1139                 mutex_lock(&client->lock);
1140         valid_handle = ion_handle_validate(client, handle);
1141         if (!valid_handle) {
1142                 WARN(1, "%s: invalid handle passed to share.\n", __func__);
1143                 if (lock_client)
1144                         mutex_unlock(&client->lock);
1145                 return ERR_PTR(-EINVAL);
1146         }
1147         buffer = handle->buffer;
1148         ion_buffer_get(buffer);
1149         if (lock_client)
1150                 mutex_unlock(&client->lock);
1151
1152         exp_info.ops = &dma_buf_ops;
1153         exp_info.size = buffer->size;
1154         exp_info.flags = O_RDWR;
1155         exp_info.priv = buffer;
1156
1157         dmabuf = dma_buf_export(&exp_info);
1158         if (IS_ERR(dmabuf)) {
1159                 ion_buffer_put(buffer);
1160                 return dmabuf;
1161         }
1162
1163         return dmabuf;
1164 }
1165
1166 struct dma_buf *ion_share_dma_buf(struct ion_client *client,
1167                                   struct ion_handle *handle)
1168 {
1169         return __ion_share_dma_buf(client, handle, true);
1170 }
1171 EXPORT_SYMBOL(ion_share_dma_buf);
1172
1173 static int __ion_share_dma_buf_fd(struct ion_client *client,
1174                                   struct ion_handle *handle, bool lock_client)
1175 {
1176         struct dma_buf *dmabuf;
1177         int fd;
1178
1179         dmabuf = __ion_share_dma_buf(client, handle, lock_client);
1180         if (IS_ERR(dmabuf))
1181                 return PTR_ERR(dmabuf);
1182
1183         fd = dma_buf_fd(dmabuf, O_CLOEXEC);
1184         if (fd < 0)
1185                 dma_buf_put(dmabuf);
1186
1187         return fd;
1188 }
1189
1190 int ion_share_dma_buf_fd(struct ion_client *client, struct ion_handle *handle)
1191 {
1192         return __ion_share_dma_buf_fd(client, handle, true);
1193 }
1194 EXPORT_SYMBOL(ion_share_dma_buf_fd);
1195
1196 static int ion_share_dma_buf_fd_nolock(struct ion_client *client,
1197                                        struct ion_handle *handle)
1198 {
1199         return __ion_share_dma_buf_fd(client, handle, false);
1200 }
1201
1202 struct ion_handle *ion_import_dma_buf(struct ion_client *client, int fd)
1203 {
1204         struct dma_buf *dmabuf;
1205         struct ion_buffer *buffer;
1206         struct ion_handle *handle;
1207         int ret;
1208
1209         dmabuf = dma_buf_get(fd);
1210         if (IS_ERR(dmabuf))
1211                 return ERR_CAST(dmabuf);
1212         /* if this memory came from ion */
1213
1214         if (dmabuf->ops != &dma_buf_ops) {
1215                 pr_err("%s: can not import dmabuf from another exporter\n",
1216                        __func__);
1217                 dma_buf_put(dmabuf);
1218                 return ERR_PTR(-EINVAL);
1219         }
1220         buffer = dmabuf->priv;
1221
1222         mutex_lock(&client->lock);
1223         /* if a handle exists for this buffer just take a reference to it */
1224         handle = ion_handle_lookup(client, buffer);
1225         if (!IS_ERR(handle)) {
1226                 handle = ion_handle_get_check_overflow(handle);
1227                 mutex_unlock(&client->lock);
1228                 goto end;
1229         }
1230
1231         handle = ion_handle_create(client, buffer);
1232         if (IS_ERR(handle)) {
1233                 mutex_unlock(&client->lock);
1234                 goto end;
1235         }
1236
1237         ret = ion_handle_add(client, handle);
1238         mutex_unlock(&client->lock);
1239         if (ret) {
1240                 ion_handle_put(handle);
1241                 handle = ERR_PTR(ret);
1242         }
1243
1244 end:
1245         dma_buf_put(dmabuf);
1246         return handle;
1247 }
1248 EXPORT_SYMBOL(ion_import_dma_buf);
1249
1250 static int ion_sync_for_device(struct ion_client *client, int fd)
1251 {
1252         struct dma_buf *dmabuf;
1253         struct ion_buffer *buffer;
1254
1255         dmabuf = dma_buf_get(fd);
1256         if (IS_ERR(dmabuf))
1257                 return PTR_ERR(dmabuf);
1258
1259         /* if this memory came from ion */
1260         if (dmabuf->ops != &dma_buf_ops) {
1261                 pr_err("%s: can not sync dmabuf from another exporter\n",
1262                        __func__);
1263                 dma_buf_put(dmabuf);
1264                 return -EINVAL;
1265         }
1266         buffer = dmabuf->priv;
1267
1268         dma_sync_sg_for_device(NULL, buffer->sg_table->sgl,
1269                                buffer->sg_table->nents, DMA_BIDIRECTIONAL);
1270         dma_buf_put(dmabuf);
1271         return 0;
1272 }
1273
1274 /* fix up the cases where the ioctl direction bits are incorrect */
1275 static unsigned int ion_ioctl_dir(unsigned int cmd)
1276 {
1277         switch (cmd) {
1278         case ION_IOC_SYNC:
1279         case ION_IOC_FREE:
1280         case ION_IOC_CUSTOM:
1281                 return _IOC_WRITE;
1282         default:
1283                 return _IOC_DIR(cmd);
1284         }
1285 }
1286
1287 static long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1288 {
1289         struct ion_client *client = filp->private_data;
1290         struct ion_device *dev = client->dev;
1291         struct ion_handle *cleanup_handle = NULL;
1292         int ret = 0;
1293         unsigned int dir;
1294
1295         union {
1296                 struct ion_fd_data fd;
1297                 struct ion_allocation_data allocation;
1298                 struct ion_handle_data handle;
1299                 struct ion_custom_data custom;
1300         } data;
1301
1302         dir = ion_ioctl_dir(cmd);
1303
1304         if (_IOC_SIZE(cmd) > sizeof(data))
1305                 return -EINVAL;
1306
1307         if (dir & _IOC_WRITE)
1308                 if (copy_from_user(&data, (void __user *)arg, _IOC_SIZE(cmd)))
1309                         return -EFAULT;
1310
1311         switch (cmd) {
1312         case ION_IOC_ALLOC:
1313         {
1314                 struct ion_handle *handle;
1315
1316                 handle = ion_alloc(client, data.allocation.len,
1317                                                 data.allocation.align,
1318                                                 data.allocation.heap_id_mask,
1319                                                 data.allocation.flags);
1320                 if (IS_ERR(handle))
1321                         return PTR_ERR(handle);
1322
1323                 data.allocation.handle = handle->id;
1324
1325                 cleanup_handle = handle;
1326                 break;
1327         }
1328         case ION_IOC_FREE:
1329         {
1330                 struct ion_handle *handle;
1331
1332                 mutex_lock(&client->lock);
1333                 handle = ion_handle_get_by_id_nolock(client, data.handle.handle);
1334                 if (IS_ERR(handle)) {
1335                         mutex_unlock(&client->lock);
1336                         return PTR_ERR(handle);
1337                 }
1338                 ion_free_nolock(client, handle);
1339                 ion_handle_put_nolock(handle);
1340                 mutex_unlock(&client->lock);
1341                 break;
1342         }
1343         case ION_IOC_SHARE:
1344         case ION_IOC_MAP:
1345         {
1346                 struct ion_handle *handle;
1347
1348                 mutex_lock(&client->lock);
1349                 handle = ion_handle_get_by_id_nolock(client, data.handle.handle);
1350                 if (IS_ERR(handle)) {
1351                         mutex_unlock(&client->lock);
1352                         return PTR_ERR(handle);
1353                 }
1354                 data.fd.fd = ion_share_dma_buf_fd_nolock(client, handle);
1355                 ion_handle_put_nolock(handle);
1356                 mutex_unlock(&client->lock);
1357                 if (data.fd.fd < 0)
1358                         ret = data.fd.fd;
1359                 break;
1360         }
1361         case ION_IOC_IMPORT:
1362         {
1363                 struct ion_handle *handle;
1364
1365                 handle = ion_import_dma_buf(client, data.fd.fd);
1366                 if (IS_ERR(handle))
1367                         ret = PTR_ERR(handle);
1368                 else
1369                         data.handle.handle = handle->id;
1370                 break;
1371         }
1372         case ION_IOC_SYNC:
1373         {
1374                 ret = ion_sync_for_device(client, data.fd.fd);
1375                 break;
1376         }
1377         case ION_IOC_CUSTOM:
1378         {
1379                 if (!dev->custom_ioctl)
1380                         return -ENOTTY;
1381                 ret = dev->custom_ioctl(client, data.custom.cmd,
1382                                                 data.custom.arg);
1383                 break;
1384         }
1385         default:
1386                 return -ENOTTY;
1387         }
1388
1389         if (dir & _IOC_READ) {
1390                 if (copy_to_user((void __user *)arg, &data, _IOC_SIZE(cmd))) {
1391                         if (cleanup_handle)
1392                                 ion_free(client, cleanup_handle);
1393                         return -EFAULT;
1394                 }
1395         }
1396         return ret;
1397 }
1398
1399 static int ion_release(struct inode *inode, struct file *file)
1400 {
1401         struct ion_client *client = file->private_data;
1402
1403         pr_debug("%s: %d\n", __func__, __LINE__);
1404         ion_client_destroy(client);
1405         return 0;
1406 }
1407
1408 static int ion_open(struct inode *inode, struct file *file)
1409 {
1410         struct miscdevice *miscdev = file->private_data;
1411         struct ion_device *dev = container_of(miscdev, struct ion_device, dev);
1412         struct ion_client *client;
1413         char debug_name[64];
1414
1415         pr_debug("%s: %d\n", __func__, __LINE__);
1416         snprintf(debug_name, 64, "%u", task_pid_nr(current->group_leader));
1417         client = ion_client_create(dev, debug_name);
1418         if (IS_ERR(client))
1419                 return PTR_ERR(client);
1420         file->private_data = client;
1421
1422         return 0;
1423 }
1424
1425 static const struct file_operations ion_fops = {
1426         .owner          = THIS_MODULE,
1427         .open           = ion_open,
1428         .release        = ion_release,
1429         .unlocked_ioctl = ion_ioctl,
1430         .compat_ioctl   = compat_ion_ioctl,
1431 };
1432
1433 static size_t ion_debug_heap_total(struct ion_client *client,
1434                                    unsigned int id)
1435 {
1436         size_t size = 0;
1437         struct rb_node *n;
1438
1439         mutex_lock(&client->lock);
1440         for (n = rb_first(&client->handles); n; n = rb_next(n)) {
1441                 struct ion_handle *handle = rb_entry(n,
1442                                                      struct ion_handle,
1443                                                      node);
1444                 if (handle->buffer->heap->id == id)
1445                         size += handle->buffer->size;
1446         }
1447         mutex_unlock(&client->lock);
1448         return size;
1449 }
1450
1451 static int ion_debug_heap_show(struct seq_file *s, void *unused)
1452 {
1453         struct ion_heap *heap = s->private;
1454         struct ion_device *dev = heap->dev;
1455         struct rb_node *n;
1456         size_t total_size = 0;
1457         size_t total_orphaned_size = 0;
1458
1459         seq_printf(s, "%16s %16s %16s\n", "client", "pid", "size");
1460         seq_puts(s, "----------------------------------------------------\n");
1461
1462         for (n = rb_first(&dev->clients); n; n = rb_next(n)) {
1463                 struct ion_client *client = rb_entry(n, struct ion_client,
1464                                                      node);
1465                 size_t size = ion_debug_heap_total(client, heap->id);
1466
1467                 if (!size)
1468                         continue;
1469                 if (client->task) {
1470                         char task_comm[TASK_COMM_LEN];
1471
1472                         get_task_comm(task_comm, client->task);
1473                         seq_printf(s, "%16s %16u %16zu\n", task_comm,
1474                                    client->pid, size);
1475                 } else {
1476                         seq_printf(s, "%16s %16u %16zu\n", client->name,
1477                                    client->pid, size);
1478                 }
1479         }
1480         seq_puts(s, "----------------------------------------------------\n");
1481         seq_puts(s, "orphaned allocations (info is from last known client):\n");
1482         mutex_lock(&dev->buffer_lock);
1483         for (n = rb_first(&dev->buffers); n; n = rb_next(n)) {
1484                 struct ion_buffer *buffer = rb_entry(n, struct ion_buffer,
1485                                                      node);
1486                 if (buffer->heap->id != heap->id)
1487                         continue;
1488                 total_size += buffer->size;
1489                 if (!buffer->handle_count) {
1490                         seq_printf(s, "%16s %16u %16zu %d %d\n",
1491                                    buffer->task_comm, buffer->pid,
1492                                    buffer->size, buffer->kmap_cnt,
1493                                    atomic_read(&buffer->ref.refcount));
1494                         total_orphaned_size += buffer->size;
1495                 }
1496         }
1497         mutex_unlock(&dev->buffer_lock);
1498         seq_puts(s, "----------------------------------------------------\n");
1499         seq_printf(s, "%16s %16zu\n", "total orphaned",
1500                    total_orphaned_size);
1501         seq_printf(s, "%16s %16zu\n", "total ", total_size);
1502         if (heap->flags & ION_HEAP_FLAG_DEFER_FREE)
1503                 seq_printf(s, "%16s %16zu\n", "deferred free",
1504                                 heap->free_list_size);
1505         seq_puts(s, "----------------------------------------------------\n");
1506
1507         if (heap->debug_show)
1508                 heap->debug_show(heap, s, unused);
1509
1510         return 0;
1511 }
1512
1513 static int ion_debug_heap_open(struct inode *inode, struct file *file)
1514 {
1515         return single_open(file, ion_debug_heap_show, inode->i_private);
1516 }
1517
1518 static const struct file_operations debug_heap_fops = {
1519         .open = ion_debug_heap_open,
1520         .read = seq_read,
1521         .llseek = seq_lseek,
1522         .release = single_release,
1523 };
1524
1525 static int debug_shrink_set(void *data, u64 val)
1526 {
1527         struct ion_heap *heap = data;
1528         struct shrink_control sc;
1529         int objs;
1530
1531         sc.gfp_mask = -1;
1532         sc.nr_to_scan = val;
1533
1534         if (!val) {
1535                 objs = heap->shrinker.count_objects(&heap->shrinker, &sc);
1536                 sc.nr_to_scan = objs;
1537         }
1538
1539         heap->shrinker.scan_objects(&heap->shrinker, &sc);
1540         return 0;
1541 }
1542
1543 static int debug_shrink_get(void *data, u64 *val)
1544 {
1545         struct ion_heap *heap = data;
1546         struct shrink_control sc;
1547         int objs;
1548
1549         sc.gfp_mask = -1;
1550         sc.nr_to_scan = 0;
1551
1552         objs = heap->shrinker.count_objects(&heap->shrinker, &sc);
1553         *val = objs;
1554         return 0;
1555 }
1556
1557 DEFINE_SIMPLE_ATTRIBUTE(debug_shrink_fops, debug_shrink_get,
1558                         debug_shrink_set, "%llu\n");
1559
1560 void ion_device_add_heap(struct ion_device *dev, struct ion_heap *heap)
1561 {
1562         struct dentry *debug_file;
1563
1564         if (!heap->ops->allocate || !heap->ops->free || !heap->ops->map_dma ||
1565             !heap->ops->unmap_dma)
1566                 pr_err("%s: can not add heap with invalid ops struct.\n",
1567                        __func__);
1568
1569         spin_lock_init(&heap->free_lock);
1570         heap->free_list_size = 0;
1571
1572         if (heap->flags & ION_HEAP_FLAG_DEFER_FREE)
1573                 ion_heap_init_deferred_free(heap);
1574
1575         if ((heap->flags & ION_HEAP_FLAG_DEFER_FREE) || heap->ops->shrink)
1576                 ion_heap_init_shrinker(heap);
1577
1578         heap->dev = dev;
1579         down_write(&dev->lock);
1580         /*
1581          * use negative heap->id to reverse the priority -- when traversing
1582          * the list later attempt higher id numbers first
1583          */
1584         plist_node_init(&heap->node, -heap->id);
1585         plist_add(&heap->node, &dev->heaps);
1586         debug_file = debugfs_create_file(heap->name, 0664,
1587                                         dev->heaps_debug_root, heap,
1588                                         &debug_heap_fops);
1589
1590         if (!debug_file) {
1591                 char buf[256], *path;
1592
1593                 path = dentry_path(dev->heaps_debug_root, buf, 256);
1594                 pr_err("Failed to create heap debugfs at %s/%s\n",
1595                         path, heap->name);
1596         }
1597
1598         if (heap->shrinker.count_objects && heap->shrinker.scan_objects) {
1599                 char debug_name[64];
1600
1601                 snprintf(debug_name, 64, "%s_shrink", heap->name);
1602                 debug_file = debugfs_create_file(
1603                         debug_name, 0644, dev->heaps_debug_root, heap,
1604                         &debug_shrink_fops);
1605                 if (!debug_file) {
1606                         char buf[256], *path;
1607
1608                         path = dentry_path(dev->heaps_debug_root, buf, 256);
1609                         pr_err("Failed to create heap shrinker debugfs at %s/%s\n",
1610                                 path, debug_name);
1611                 }
1612         }
1613
1614         up_write(&dev->lock);
1615 }
1616 EXPORT_SYMBOL(ion_device_add_heap);
1617
1618 struct ion_device *ion_device_create(long (*custom_ioctl)
1619                                      (struct ion_client *client,
1620                                       unsigned int cmd,
1621                                       unsigned long arg))
1622 {
1623         struct ion_device *idev;
1624         int ret;
1625
1626         idev = kzalloc(sizeof(struct ion_device), GFP_KERNEL);
1627         if (!idev)
1628                 return ERR_PTR(-ENOMEM);
1629
1630         idev->dev.minor = MISC_DYNAMIC_MINOR;
1631         idev->dev.name = "ion";
1632         idev->dev.fops = &ion_fops;
1633         idev->dev.parent = NULL;
1634         ret = misc_register(&idev->dev);
1635         if (ret) {
1636                 pr_err("ion: failed to register misc device.\n");
1637                 kfree(idev);
1638                 return ERR_PTR(ret);
1639         }
1640
1641         idev->debug_root = debugfs_create_dir("ion", NULL);
1642         if (!idev->debug_root) {
1643                 pr_err("ion: failed to create debugfs root directory.\n");
1644                 goto debugfs_done;
1645         }
1646         idev->heaps_debug_root = debugfs_create_dir("heaps", idev->debug_root);
1647         if (!idev->heaps_debug_root) {
1648                 pr_err("ion: failed to create debugfs heaps directory.\n");
1649                 goto debugfs_done;
1650         }
1651         idev->clients_debug_root = debugfs_create_dir("clients",
1652                                                 idev->debug_root);
1653         if (!idev->clients_debug_root)
1654                 pr_err("ion: failed to create debugfs clients directory.\n");
1655
1656 debugfs_done:
1657
1658         idev->custom_ioctl = custom_ioctl;
1659         idev->buffers = RB_ROOT;
1660         mutex_init(&idev->buffer_lock);
1661         init_rwsem(&idev->lock);
1662         plist_head_init(&idev->heaps);
1663         idev->clients = RB_ROOT;
1664         return idev;
1665 }
1666 EXPORT_SYMBOL(ion_device_create);
1667
1668 void ion_device_destroy(struct ion_device *dev)
1669 {
1670         misc_deregister(&dev->dev);
1671         debugfs_remove_recursive(dev->debug_root);
1672         /* XXX need to free the heaps and clients ? */
1673         kfree(dev);
1674 }
1675 EXPORT_SYMBOL(ion_device_destroy);
1676
1677 void __init ion_reserve(struct ion_platform_data *data)
1678 {
1679         int i;
1680
1681         for (i = 0; i < data->nr; i++) {
1682                 if (data->heaps[i].size == 0)
1683                         continue;
1684
1685                 if (data->heaps[i].base == 0) {
1686                         phys_addr_t paddr;
1687
1688                         paddr = memblock_alloc_base(data->heaps[i].size,
1689                                                     data->heaps[i].align,
1690                                                     MEMBLOCK_ALLOC_ANYWHERE);
1691                         if (!paddr) {
1692                                 pr_err("%s: error allocating memblock for heap %d\n",
1693                                         __func__, i);
1694                                 continue;
1695                         }
1696                         data->heaps[i].base = paddr;
1697                 } else {
1698                         int ret = memblock_reserve(data->heaps[i].base,
1699                                                data->heaps[i].size);
1700                         if (ret)
1701                                 pr_err("memblock reserve of %zx@%lx failed\n",
1702                                        data->heaps[i].size,
1703                                        data->heaps[i].base);
1704                 }
1705                 pr_info("%s: %s reserved base %lx size %zu\n", __func__,
1706                         data->heaps[i].name,
1707                         data->heaps[i].base,
1708                         data->heaps[i].size);
1709         }
1710 }