OSDN Git Service

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