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