mmc; fix the kernel crasht for th he bug in rk29_sdmmc_progress_store()
[firefly-linux-kernel-4.4.55.git] / drivers / gpu / ion / ion.c
1 /*
2  * drivers/gpu/ion/ion.c
3  *
4  * Copyright (C) 2011 Google, Inc.
5  *
6  * This software is licensed under the terms of the GNU General Public
7  * License version 2, as published by the Free Software Foundation, and
8  * may be copied, distributed, and modified under those terms.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  */
16
17 #include <linux/device.h>
18 #include <linux/file.h>
19 #include <linux/fs.h>
20 #include <linux/anon_inodes.h>
21 #include <linux/ion.h>
22 #include <linux/list.h>
23 #include <linux/miscdevice.h>
24 #include <linux/mm.h>
25 #include <linux/mm_types.h>
26 #include <linux/rbtree.h>
27 #include <linux/sched.h>
28 #include <linux/slab.h>
29 #include <linux/seq_file.h>
30 #include <linux/uaccess.h>
31 #include <linux/debugfs.h>
32 #include <linux/android_pmem.h>
33 #include <linux/dma-mapping.h>
34 #include <asm/cacheflush.h>
35 #include "ion_priv.h"
36 #define DEBUG
37
38 /**
39  * struct ion_device - the metadata of the ion device node
40  * @dev:                the actual misc device
41  * @buffers:    an rb tree of all the existing buffers
42  * @lock:               lock protecting the buffers & heaps trees
43  * @heaps:              list of all the heaps in the system
44  * @user_clients:       list of all the clients created from userspace
45  */
46 struct ion_device {
47         struct miscdevice dev;
48         struct rb_root buffers;
49         struct mutex lock;
50         struct rb_root heaps;
51         long (*custom_ioctl) (struct ion_client *client, unsigned int cmd,
52                               unsigned long arg);
53         struct rb_root user_clients;
54         struct rb_root kernel_clients;
55         struct dentry *debug_root;
56 };
57
58 /**
59  * struct ion_client - a process/hw block local address space
60  * @ref:                for reference counting the client
61  * @node:               node in the tree of all clients
62  * @dev:                backpointer to ion device
63  * @handles:            an rb tree of all the handles in this client
64  * @lock:               lock protecting the tree of handles
65  * @heap_mask:          mask of all supported heaps
66  * @name:               used for debugging
67  * @task:               used for debugging
68  *
69  * A client represents a list of buffers this client may access.
70  * The mutex stored here is used to protect both handles tree
71  * as well as the handles themselves, and should be held while modifying either.
72  */
73 struct ion_client {
74         struct kref ref;
75         struct rb_node node;
76         struct ion_device *dev;
77         struct rb_root handles;
78         struct mutex lock;
79         unsigned int heap_mask;
80         const char *name;
81         struct task_struct *task;
82         pid_t pid;
83         struct dentry *debug_root;
84 };
85
86 /**
87  * ion_handle - a client local reference to a buffer
88  * @ref:                reference count
89  * @client:             back pointer to the client the buffer resides in
90  * @buffer:             pointer to the buffer
91  * @node:               node in the client's handle rbtree
92  * @kmap_cnt:           count of times this client has mapped to kernel
93  * @dmap_cnt:           count of times this client has mapped for dma
94  * @usermap_cnt:        count of times this client has mapped for userspace
95  *
96  * Modifications to node, map_cnt or mapping should be protected by the
97  * lock in the client.  Other fields are never changed after initialization.
98  */
99 struct ion_handle {
100         struct kref ref;
101         struct ion_client *client;
102         struct ion_buffer *buffer;
103         struct rb_node node;
104         unsigned int kmap_cnt;
105         unsigned int dmap_cnt;
106         unsigned int usermap_cnt;
107 };
108
109 /* this function should only be called while dev->lock is held */
110 static void ion_buffer_add(struct ion_device *dev,
111                            struct ion_buffer *buffer)
112 {
113         struct rb_node **p = &dev->buffers.rb_node;
114         struct rb_node *parent = NULL;
115         struct ion_buffer *entry;
116
117         while (*p) {
118                 parent = *p;
119                 entry = rb_entry(parent, struct ion_buffer, node);
120
121                 if (buffer < entry) {
122                         p = &(*p)->rb_left;
123                 } else if (buffer > entry) {
124                         p = &(*p)->rb_right;
125                 } else {
126                         pr_err("%s: buffer already found.", __func__);
127                         BUG();
128                 }
129         }
130
131         rb_link_node(&buffer->node, parent, p);
132         rb_insert_color(&buffer->node, &dev->buffers);
133 }
134
135 /* this function should only be called while dev->lock is held */
136 static struct ion_buffer *ion_buffer_create(struct ion_heap *heap,
137                                      struct ion_device *dev,
138                                      unsigned long len,
139                                      unsigned long align,
140                                      unsigned long flags)
141 {
142         struct ion_buffer *buffer;
143         int ret;
144
145         buffer = kzalloc(sizeof(struct ion_buffer), GFP_KERNEL);
146         if (!buffer)
147                 return ERR_PTR(-ENOMEM);
148
149         buffer->heap = heap;
150         kref_init(&buffer->ref);
151
152         ret = heap->ops->allocate(heap, buffer, len, align, flags);
153         if (ret) {
154                 kfree(buffer);
155                 return ERR_PTR(ret);
156         }
157         buffer->dev = dev;
158         buffer->size = len;
159         buffer->flags = flags;
160         mutex_init(&buffer->lock);
161         ion_buffer_add(dev, buffer);
162         return buffer;
163 }
164
165 static void ion_buffer_destroy(struct kref *kref)
166 {
167         struct ion_buffer *buffer = container_of(kref, struct ion_buffer, ref);
168         struct ion_device *dev = buffer->dev;
169
170         buffer->heap->ops->free(buffer);
171         mutex_lock(&dev->lock);
172         rb_erase(&buffer->node, &dev->buffers);
173         mutex_unlock(&dev->lock);
174         kfree(buffer);
175 }
176
177 static void ion_buffer_get(struct ion_buffer *buffer)
178 {
179         kref_get(&buffer->ref);
180 }
181
182 static int ion_buffer_put(struct ion_buffer *buffer)
183 {
184         return kref_put(&buffer->ref, ion_buffer_destroy);
185 }
186
187 static struct ion_handle *ion_handle_create(struct ion_client *client,
188                                      struct ion_buffer *buffer)
189 {
190         struct ion_handle *handle;
191
192         handle = kzalloc(sizeof(struct ion_handle), GFP_KERNEL);
193         if (!handle)
194                 return ERR_PTR(-ENOMEM);
195         kref_init(&handle->ref);
196         rb_init_node(&handle->node);
197         handle->client = client;
198         ion_buffer_get(buffer);
199         handle->buffer = buffer;
200
201         return handle;
202 }
203
204 static void ion_handle_destroy(struct kref *kref)
205 {
206         struct ion_handle *handle = container_of(kref, struct ion_handle, ref);
207         /* XXX Can a handle be destroyed while it's map count is non-zero?:
208            if (handle->map_cnt) unmap
209          */
210         ion_buffer_put(handle->buffer);
211         mutex_lock(&handle->client->lock);
212         if (!RB_EMPTY_NODE(&handle->node))
213                 rb_erase(&handle->node, &handle->client->handles);
214         mutex_unlock(&handle->client->lock);
215         kfree(handle);
216 }
217
218 struct ion_buffer *ion_handle_buffer(struct ion_handle *handle)
219 {
220         return handle->buffer;
221 }
222
223 static void ion_handle_get(struct ion_handle *handle)
224 {
225         kref_get(&handle->ref);
226 }
227
228 static int ion_handle_put(struct ion_handle *handle)
229 {
230         return kref_put(&handle->ref, ion_handle_destroy);
231 }
232
233 static struct ion_handle *ion_handle_lookup(struct ion_client *client,
234                                             struct ion_buffer *buffer)
235 {
236         struct rb_node *n;
237
238         for (n = rb_first(&client->handles); n; n = rb_next(n)) {
239                 struct ion_handle *handle = rb_entry(n, struct ion_handle,
240                                                      node);
241                 if (handle->buffer == buffer)
242                         return handle;
243         }
244         return NULL;
245 }
246
247 static bool ion_handle_validate(struct ion_client *client, struct ion_handle *handle)
248 {
249         struct rb_node *n = client->handles.rb_node;
250
251         while (n) {
252                 struct ion_handle *handle_node = rb_entry(n, struct ion_handle,
253                                                           node);
254                 if (handle < handle_node)
255                         n = n->rb_left;
256                 else if (handle > handle_node)
257                         n = n->rb_right;
258                 else
259                         return true;
260         }
261         return false;
262 }
263
264 static void ion_handle_add(struct ion_client *client, struct ion_handle *handle)
265 {
266         struct rb_node **p = &client->handles.rb_node;
267         struct rb_node *parent = NULL;
268         struct ion_handle *entry;
269
270         while (*p) {
271                 parent = *p;
272                 entry = rb_entry(parent, struct ion_handle, node);
273
274                 if (handle < entry)
275                         p = &(*p)->rb_left;
276                 else if (handle > entry)
277                         p = &(*p)->rb_right;
278                 else
279                         WARN(1, "%s: buffer already found.", __func__);
280         }
281
282         rb_link_node(&handle->node, parent, p);
283         rb_insert_color(&handle->node, &client->handles);
284 }
285
286 struct ion_handle *ion_alloc(struct ion_client *client, size_t len,
287                              size_t align, unsigned int flags)
288 {
289         struct rb_node *n;
290         struct ion_handle *handle;
291         struct ion_device *dev = client->dev;
292         struct ion_buffer *buffer = NULL;
293
294         /*
295          * traverse the list of heaps available in this system in priority
296          * order.  If the heap type is supported by the client, and matches the
297          * request of the caller allocate from it.  Repeat until allocate has
298          * succeeded or all heaps have been tried
299          */
300         mutex_lock(&dev->lock);
301         for (n = rb_first(&dev->heaps); n != NULL; n = rb_next(n)) {
302                 struct ion_heap *heap = rb_entry(n, struct ion_heap, node);
303                 /* if the client doesn't support this heap type */
304                 if (!((1 << heap->type) & client->heap_mask))
305                         continue;
306                 
307                 /* if the caller didn't specify this heap type */
308                 if (!((1 << heap->id) & flags))
309                         continue;
310                 buffer = ion_buffer_create(heap, dev, len, align, flags);
311                 if (!IS_ERR_OR_NULL(buffer))
312                         break;
313         }
314         mutex_unlock(&dev->lock);
315
316         if (IS_ERR_OR_NULL(buffer))
317                 return ERR_PTR(PTR_ERR(buffer));
318
319         handle = ion_handle_create(client, buffer);
320
321         if (IS_ERR_OR_NULL(handle))
322                 goto end;
323
324         /*
325          * ion_buffer_create will create a buffer with a ref_cnt of 1,
326          * and ion_handle_create will take a second reference, drop one here
327          */
328         ion_buffer_put(buffer);
329
330         mutex_lock(&client->lock);
331         ion_handle_add(client, handle);
332         mutex_unlock(&client->lock);
333         return handle;
334
335 end:
336         ion_buffer_put(buffer);
337         return handle;
338 }
339
340 void ion_free(struct ion_client *client, struct ion_handle *handle)
341 {
342         bool valid_handle;
343
344         BUG_ON(client != handle->client);
345
346         mutex_lock(&client->lock);
347         valid_handle = ion_handle_validate(client, handle);
348         mutex_unlock(&client->lock);
349
350         if (!valid_handle) {
351                 WARN("%s: invalid handle passed to free.\n", __func__);
352                 return;
353         }
354         ion_handle_put(handle);
355 }
356
357 static void ion_client_get(struct ion_client *client);
358 static int ion_client_put(struct ion_client *client);
359
360 static bool _ion_map(int *buffer_cnt, int *handle_cnt)
361 {
362         bool map;
363
364         BUG_ON(*handle_cnt != 0 && *buffer_cnt == 0);
365
366         if (*buffer_cnt)
367                 map = false;
368         else
369                 map = true;
370         if (*handle_cnt == 0)
371                 (*buffer_cnt)++;
372         (*handle_cnt)++;
373         return map;
374 }
375
376 static bool _ion_unmap(int *buffer_cnt, int *handle_cnt)
377 {
378         BUG_ON(*handle_cnt == 0);
379         (*handle_cnt)--;
380         if (*handle_cnt != 0)
381                 return false;
382         BUG_ON(*buffer_cnt == 0);
383         (*buffer_cnt)--;
384         if (*buffer_cnt == 0)
385                 return true;
386         return false;
387 }
388
389 int ion_phys(struct ion_client *client, struct ion_handle *handle,
390              ion_phys_addr_t *addr, size_t *len)
391 {
392         struct ion_buffer *buffer;
393         int ret;
394
395         mutex_lock(&client->lock);
396         if (!ion_handle_validate(client, handle)) {
397                 mutex_unlock(&client->lock);
398                 return -EINVAL;
399         }
400
401         buffer = handle->buffer;
402
403         if (!buffer->heap->ops->phys) {
404                 pr_err("%s: ion_phys is not implemented by this heap.\n",
405                        __func__);
406                 mutex_unlock(&client->lock);
407                 return -ENODEV;
408         }
409         mutex_unlock(&client->lock);
410         ret = buffer->heap->ops->phys(buffer->heap, buffer, addr, len);
411         return ret;
412 }
413
414 void *ion_map_kernel(struct ion_client *client, struct ion_handle *handle)
415 {
416         struct ion_buffer *buffer;
417         void *vaddr;
418
419         mutex_lock(&client->lock);
420         if (!ion_handle_validate(client, handle)) {
421                 pr_err("%s: invalid handle passed to map_kernel.\n",
422                        __func__);
423                 mutex_unlock(&client->lock);
424                 return ERR_PTR(-EINVAL);
425         }
426
427         buffer = handle->buffer;
428         mutex_lock(&buffer->lock);
429
430         if (!handle->buffer->heap->ops->map_kernel) {
431                 pr_err("%s: map_kernel is not implemented by this heap.\n",
432                        __func__);
433                 mutex_unlock(&buffer->lock);
434                 mutex_unlock(&client->lock);
435                 return ERR_PTR(-ENODEV);
436         }
437
438         if (_ion_map(&buffer->kmap_cnt, &handle->kmap_cnt)) {
439                 vaddr = buffer->heap->ops->map_kernel(buffer->heap, buffer);
440                 if (IS_ERR_OR_NULL(vaddr))
441                         _ion_unmap(&buffer->kmap_cnt, &handle->kmap_cnt);
442                 buffer->vaddr = vaddr;
443         } else {
444                 vaddr = buffer->vaddr;
445         }
446         mutex_unlock(&buffer->lock);
447         mutex_unlock(&client->lock);
448         return vaddr;
449 }
450
451 struct scatterlist *ion_map_dma(struct ion_client *client,
452                                 struct ion_handle *handle)
453 {
454         struct ion_buffer *buffer;
455         struct scatterlist *sglist;
456
457         mutex_lock(&client->lock);
458         if (!ion_handle_validate(client, handle)) {
459                 pr_err("%s: invalid handle passed to map_dma.\n",
460                        __func__);
461                 mutex_unlock(&client->lock);
462                 return ERR_PTR(-EINVAL);
463         }
464         buffer = handle->buffer;
465         mutex_lock(&buffer->lock);
466
467         if (!handle->buffer->heap->ops->map_dma) {
468                 pr_err("%s: map_kernel is not implemented by this heap.\n",
469                        __func__);
470                 mutex_unlock(&buffer->lock);
471                 mutex_unlock(&client->lock);
472                 return ERR_PTR(-ENODEV);
473         }
474         if (_ion_map(&buffer->dmap_cnt, &handle->dmap_cnt)) {
475                 sglist = buffer->heap->ops->map_dma(buffer->heap, buffer);
476                 if (IS_ERR_OR_NULL(sglist))
477                         _ion_unmap(&buffer->dmap_cnt, &handle->dmap_cnt);
478                 buffer->sglist = sglist;
479         } else {
480                 sglist = buffer->sglist;
481         }
482         mutex_unlock(&buffer->lock);
483         mutex_unlock(&client->lock);
484         return sglist;
485 }
486
487 void ion_unmap_kernel(struct ion_client *client, struct ion_handle *handle)
488 {
489         struct ion_buffer *buffer;
490
491         mutex_lock(&client->lock);
492         buffer = handle->buffer;
493         mutex_lock(&buffer->lock);
494         if (_ion_unmap(&buffer->kmap_cnt, &handle->kmap_cnt)) {
495                 buffer->heap->ops->unmap_kernel(buffer->heap, buffer);
496                 buffer->vaddr = NULL;
497         }
498         mutex_unlock(&buffer->lock);
499         mutex_unlock(&client->lock);
500 }
501
502 void ion_unmap_dma(struct ion_client *client, struct ion_handle *handle)
503 {
504         struct ion_buffer *buffer;
505
506         mutex_lock(&client->lock);
507         buffer = handle->buffer;
508         mutex_lock(&buffer->lock);
509         if (_ion_unmap(&buffer->dmap_cnt, &handle->dmap_cnt)) {
510                 buffer->heap->ops->unmap_dma(buffer->heap, buffer);
511                 buffer->sglist = NULL;
512         }
513         mutex_unlock(&buffer->lock);
514         mutex_unlock(&client->lock);
515 }
516
517
518 struct ion_buffer *ion_share(struct ion_client *client,
519                                  struct ion_handle *handle)
520 {
521         bool valid_handle;
522
523         mutex_lock(&client->lock);
524         valid_handle = ion_handle_validate(client, handle);
525         mutex_unlock(&client->lock);
526         if (!valid_handle) {
527                 WARN("%s: invalid handle passed to share.\n", __func__);
528                 return ERR_PTR(-EINVAL);
529         }
530
531         /* do not take an extra reference here, the burden is on the caller
532          * to make sure the buffer doesn't go away while it's passing it
533          * to another client -- ion_free should not be called on this handle
534          * until the buffer has been imported into the other client
535          */
536         return handle->buffer;
537 }
538
539 struct ion_handle *ion_import(struct ion_client *client,
540                               struct ion_buffer *buffer)
541 {
542         struct ion_handle *handle = NULL;
543
544         mutex_lock(&client->lock);
545         /* if a handle exists for this buffer just take a reference to it */
546         handle = ion_handle_lookup(client, buffer);
547         if (!IS_ERR_OR_NULL(handle)) {
548                 ion_handle_get(handle);
549                 goto end;
550         }
551         handle = ion_handle_create(client, buffer);
552         if (IS_ERR_OR_NULL(handle))
553                 goto end;
554         ion_handle_add(client, handle);
555 end:
556         mutex_unlock(&client->lock);
557         return handle;
558 }
559
560 static const struct file_operations ion_share_fops;
561
562 struct ion_handle *ion_import_fd(struct ion_client *client, int fd)
563 {
564         struct file *file = fget(fd);
565         struct ion_handle *handle;
566
567         if (!file) {
568                 pr_err("%s: imported fd not found in file table.\n", __func__);
569                 return ERR_PTR(-EINVAL);
570         }
571         if (file->f_op != &ion_share_fops) {
572                 pr_err("%s: imported file is not a shared ion file.\n",
573                        __func__);
574                 handle = ERR_PTR(-EINVAL);
575                 goto end;
576         }
577         handle = ion_import(client, file->private_data);
578 end:
579         fput(file);
580         return handle;
581 }
582
583 static int ion_debug_client_show(struct seq_file *s, void *unused)
584 {
585         struct ion_client *client = s->private;
586         struct rb_node *n;
587
588         seq_printf(s, "%16.16s: %16.16s  %16.16s  %16.16s\n", "heap_name",
589                         "size(K)", "handle refcount", "buffer");
590         mutex_lock(&client->lock);
591         for (n = rb_first(&client->handles); n; n = rb_next(n)) {
592                 struct ion_handle *handle = rb_entry(n, struct ion_handle,
593                                                      node);
594
595                 seq_printf(s, "%16.16s: %16u  %16d  %16p\n",
596                                 handle->buffer->heap->name,
597                                 handle->buffer->size/SZ_1K,
598                                 atomic_read(&handle->ref.refcount),
599                                 handle->buffer);
600         }
601
602         seq_printf(s, "%16.16s %d\n", "client refcount:",
603                         atomic_read(&client->ref.refcount));
604         mutex_unlock(&client->lock);
605
606         return 0;
607 }
608
609 static int ion_debug_client_open(struct inode *inode, struct file *file)
610 {
611         return single_open(file, ion_debug_client_show, inode->i_private);
612 }
613
614 static const struct file_operations debug_client_fops = {
615         .open = ion_debug_client_open,
616         .read = seq_read,
617         .llseek = seq_lseek,
618         .release = single_release,
619 };
620
621 static struct ion_client *ion_client_lookup(struct ion_device *dev,
622                                             struct task_struct *task)
623 {
624         struct rb_node *n = dev->user_clients.rb_node;
625         struct ion_client *client;
626
627         mutex_lock(&dev->lock);
628         while (n) {
629                 client = rb_entry(n, struct ion_client, node);
630                 if (task == client->task) {
631                         ion_client_get(client);
632                         mutex_unlock(&dev->lock);
633                         return client;
634                 } else if (task < client->task) {
635                         n = n->rb_left;
636                 } else if (task > client->task) {
637                         n = n->rb_right;
638                 }
639         }
640         mutex_unlock(&dev->lock);
641         return NULL;
642 }
643
644 struct ion_client *ion_client_create(struct ion_device *dev,
645                                      unsigned int heap_mask,
646                                      const char *name)
647 {
648         struct ion_client *client;
649         struct task_struct *task;
650         struct rb_node **p;
651         struct rb_node *parent = NULL;
652         struct ion_client *entry;
653         char debug_name[64];
654         pid_t pid;
655
656         get_task_struct(current->group_leader);
657         task_lock(current->group_leader);
658         pid = task_pid_nr(current->group_leader);
659         /* don't bother to store task struct for kernel threads,
660            they can't be killed anyway */
661         if (current->group_leader->flags & PF_KTHREAD) {
662                 put_task_struct(current->group_leader);
663                 task = NULL;
664         } else {
665                 task = current->group_leader;
666         }
667         task_unlock(current->group_leader);
668
669         /* if this isn't a kernel thread, see if a client already
670            exists */
671         if (task) {
672                 client = ion_client_lookup(dev, task);
673                 if (!IS_ERR_OR_NULL(client)) {
674                         put_task_struct(current->group_leader);
675                         return client;
676                 }
677         }
678
679         client = kzalloc(sizeof(struct ion_client), GFP_KERNEL);
680         if (!client) {
681                 put_task_struct(current->group_leader);
682                 return ERR_PTR(-ENOMEM);
683         }
684
685         client->dev = dev;
686         client->handles = RB_ROOT;
687         mutex_init(&client->lock);
688         client->name = name;
689         client->heap_mask = heap_mask;
690         client->task = task;
691         client->pid = pid;
692         kref_init(&client->ref);
693
694         mutex_lock(&dev->lock);
695         if (task) {
696                 p = &dev->user_clients.rb_node;
697                 while (*p) {
698                         parent = *p;
699                         entry = rb_entry(parent, struct ion_client, node);
700
701                         if (task < entry->task)
702                                 p = &(*p)->rb_left;
703                         else if (task > entry->task)
704                                 p = &(*p)->rb_right;
705                 }
706                 rb_link_node(&client->node, parent, p);
707                 rb_insert_color(&client->node, &dev->user_clients);
708         } else {
709                 p = &dev->kernel_clients.rb_node;
710                 while (*p) {
711                         parent = *p;
712                         entry = rb_entry(parent, struct ion_client, node);
713
714                         if (client < entry)
715                                 p = &(*p)->rb_left;
716                         else if (client > entry)
717                                 p = &(*p)->rb_right;
718                 }
719                 rb_link_node(&client->node, parent, p);
720                 rb_insert_color(&client->node, &dev->kernel_clients);
721         }
722
723         snprintf(debug_name, 64, "%u", client->pid);
724         client->debug_root = debugfs_create_file(debug_name, 0664,
725                                                  dev->debug_root, client,
726                                                  &debug_client_fops);
727         mutex_unlock(&dev->lock);
728
729         return client;
730 }
731
732 static void _ion_client_destroy(struct kref *kref)
733 {
734         struct ion_client *client = container_of(kref, struct ion_client, ref);
735         struct ion_device *dev = client->dev;
736         struct rb_node *n;
737
738         pr_debug("%s: %d\n", __func__, __LINE__);
739         while ((n = rb_first(&client->handles))) {
740                 struct ion_handle *handle = rb_entry(n, struct ion_handle,
741                                                      node);
742                 ion_handle_destroy(&handle->ref);
743         }
744         mutex_lock(&dev->lock);
745         if (client->task) {
746                 rb_erase(&client->node, &dev->user_clients);
747                 put_task_struct(client->task);
748         } else {
749                 rb_erase(&client->node, &dev->kernel_clients);
750         }
751         debugfs_remove_recursive(client->debug_root);
752         mutex_unlock(&dev->lock);
753
754         kfree(client);
755 }
756
757 static void ion_client_get(struct ion_client *client)
758 {
759         kref_get(&client->ref);
760 }
761
762 static int ion_client_put(struct ion_client *client)
763 {
764         return kref_put(&client->ref, _ion_client_destroy);
765 }
766
767 void ion_client_destroy(struct ion_client *client)
768 {
769         ion_client_put(client);
770 }
771
772 static int ion_share_release(struct inode *inode, struct file* file)
773 {
774         struct ion_buffer *buffer = file->private_data;
775
776         pr_debug("%s: %d\n", __func__, __LINE__);
777         /* drop the reference to the buffer -- this prevents the
778            buffer from going away because the client holding it exited
779            while it was being passed */
780         ion_buffer_put(buffer);
781         return 0;
782 }
783
784 static void ion_vma_open(struct vm_area_struct *vma)
785 {
786
787         struct ion_buffer *buffer = vma->vm_file->private_data;
788         struct ion_handle *handle = vma->vm_private_data;
789         struct ion_client *client;
790
791         pr_debug("%s: %d\n", __func__, __LINE__);
792         /* check that the client still exists and take a reference so
793            it can't go away until this vma is closed */
794         client = ion_client_lookup(buffer->dev, current->group_leader);
795         if (IS_ERR_OR_NULL(client)) {
796                 vma->vm_private_data = NULL;
797                 return;
798         }
799         ion_handle_get(handle);
800         pr_debug("%s: %d client_cnt %d handle_cnt %d alloc_cnt %d\n",
801                  __func__, __LINE__,
802                  atomic_read(&client->ref.refcount),
803                  atomic_read(&handle->ref.refcount),
804                  atomic_read(&buffer->ref.refcount));
805 }
806
807 static void ion_vma_close(struct vm_area_struct *vma)
808 {
809         struct ion_handle *handle = vma->vm_private_data;
810         struct ion_buffer *buffer = vma->vm_file->private_data;
811         struct ion_client *client;
812
813         pr_debug("%s: %d\n", __func__, __LINE__);
814         /* this indicates the client is gone, nothing to do here */
815         if (!handle)
816                 return;
817         client = handle->client;
818         pr_debug("%s: %d client_cnt %d handle_cnt %d alloc_cnt %d\n",
819                  __func__, __LINE__,
820                  atomic_read(&client->ref.refcount),
821                  atomic_read(&handle->ref.refcount),
822                  atomic_read(&buffer->ref.refcount));
823         ion_handle_put(handle);
824         ion_client_put(client);
825         pr_debug("%s: %d client_cnt %d handle_cnt %d alloc_cnt %d\n",
826                  __func__, __LINE__,
827                  atomic_read(&client->ref.refcount),
828                  atomic_read(&handle->ref.refcount),
829                  atomic_read(&buffer->ref.refcount));
830 }
831
832 static struct vm_operations_struct ion_vm_ops = {
833         .open = ion_vma_open,
834         .close = ion_vma_close,
835 };
836
837 static int ion_share_mmap(struct file *file, struct vm_area_struct *vma)
838 {
839         struct ion_buffer *buffer = file->private_data;
840         unsigned long size = vma->vm_end - vma->vm_start;
841         struct ion_client *client;
842         struct ion_handle *handle;
843         int ret;
844         unsigned long flags = file->f_flags & O_DSYNC ?
845                                 ION_SET_CACHE(UNCACHED) :
846                                 ION_SET_CACHE(CACHED);
847
848         pr_debug("%s: %d\n", __func__, __LINE__);
849         /* make sure the client still exists, it's possible for the client to
850            have gone away but the map/share fd still to be around, take
851            a reference to it so it can't go away while this mapping exists */
852         client = ion_client_lookup(buffer->dev, current->group_leader);
853         if (IS_ERR_OR_NULL(client)) {
854                 pr_err("%s: trying to mmap an ion handle in a process with no "
855                        "ion client\n", __func__);
856                 return -EINVAL;
857         }
858
859         if ((size > buffer->size) || (size + (vma->vm_pgoff << PAGE_SHIFT) >
860                                      buffer->size)) {
861                 pr_err("%s: trying to map larger area than handle has available"
862                        "\n", __func__);
863                 ret = -EINVAL;
864                 goto err;
865         }
866
867         /* find the handle and take a reference to it */
868         handle = ion_import(client, buffer);
869         if (IS_ERR_OR_NULL(handle)) {
870                 ret = -EINVAL;
871                 goto err;
872         }
873
874         if (!handle->buffer->heap->ops->map_user) {
875                 pr_err("%s: this heap does not define a method for mapping "
876                        "to userspace\n", __func__);
877                 ret = -EINVAL;
878                 goto err1;
879         }
880
881         mutex_lock(&buffer->lock);
882         /* now map it to userspace */
883         ret = buffer->heap->ops->map_user(buffer->heap, buffer, vma, flags);
884         mutex_unlock(&buffer->lock);
885         if (ret) {
886                 pr_err("%s: failure mapping buffer to userspace\n",
887                        __func__);
888                 goto err1;
889         }
890
891         vma->vm_ops = &ion_vm_ops;
892         /* move the handle into the vm_private_data so we can access it from
893            vma_open/close */
894         vma->vm_private_data = handle;
895         pr_debug("%s: %d client_cnt %d handle_cnt %d alloc_cnt %d\n",
896                  __func__, __LINE__,
897                  atomic_read(&client->ref.refcount),
898                  atomic_read(&handle->ref.refcount),
899                  atomic_read(&buffer->ref.refcount));
900         return 0;
901
902 err1:
903         /* drop the reference to the handle */
904         ion_handle_put(handle);
905 err:
906         /* drop the reference to the client */
907         ion_client_put(client);
908         return ret;
909 }
910
911 static long ion_share_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
912 {
913         struct ion_buffer *buffer = filp->private_data;
914         
915         switch (cmd) {
916         case PMEM_GET_PHYS:
917         {
918                 struct pmem_region region;
919                 region.offset = buffer->priv_phys;
920                 region.len = buffer->size;
921
922                 if (copy_to_user((void __user *)arg, &region,
923                                 sizeof(struct pmem_region)))
924                         return -EFAULT;
925                 break;
926         }
927         case PMEM_CACHE_FLUSH:
928         {
929                 struct pmem_region region;
930                 if (copy_from_user(&region, (void __user *)arg,
931                                 sizeof(struct pmem_region)))
932                         return -EFAULT;
933                 dmac_flush_range((void *)region.offset, (void *)(region.offset + region.len));
934
935                 break;
936         }
937         default:
938                 return -ENOTTY;
939         }
940         return 0;
941 }
942
943 static const struct file_operations ion_share_fops = {
944         .owner          = THIS_MODULE,
945         .release        = ion_share_release,
946         .mmap           = ion_share_mmap,
947         .unlocked_ioctl = ion_share_ioctl,
948 };
949
950 static int ion_ioctl_share(struct file *parent, struct ion_client *client,
951                            struct ion_handle *handle)
952 {
953         int fd = get_unused_fd();
954         struct file *file;
955
956         if (fd < 0)
957                 return -ENFILE;
958
959         file = anon_inode_getfile("ion_share_fd", &ion_share_fops,
960                                   handle->buffer, O_RDWR);
961         if (IS_ERR_OR_NULL(file))
962                 goto err;
963
964         if (parent->f_flags & O_DSYNC)
965                 file->f_flags |= O_DSYNC;
966         
967         ion_buffer_get(handle->buffer);
968         fd_install(fd, file);
969
970         return fd;
971
972 err:
973         put_unused_fd(fd);
974         return -ENFILE;
975 }
976
977 static long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
978 {
979         struct ion_client *client = filp->private_data;
980
981         switch (cmd) {
982         case ION_IOC_ALLOC:
983         {
984                 struct ion_allocation_data data;
985                 if (copy_from_user(&data, (void __user *)arg, sizeof(data)))
986                         return -EFAULT;
987
988                 data.handle = ion_alloc(client, data.len, data.align,
989                                              data.flags);
990                 if (IS_ERR_OR_NULL(data.handle)) {
991                         printk("%s: alloc 0x%x bytes failed\n", __func__, data.len);
992             return -ENOMEM;
993                 } 
994                 if (copy_to_user((void __user *)arg, &data, sizeof(data)))
995                         return -EFAULT;
996                 break;
997         }
998         case ION_IOC_FREE:
999         {
1000                 struct ion_handle_data data;
1001                 bool valid;
1002
1003                 if (copy_from_user(&data, (void __user *)arg,
1004                                    sizeof(struct ion_handle_data)))
1005                         return -EFAULT;
1006                 mutex_lock(&client->lock);
1007                 valid = ion_handle_validate(client, data.handle);
1008                 mutex_unlock(&client->lock);
1009                 if (!valid)
1010                         return -EINVAL;
1011                 ion_free(client, data.handle);
1012                 break;
1013         }
1014         case ION_IOC_MAP:
1015         case ION_IOC_SHARE:
1016         {
1017                 struct ion_fd_data data;
1018                 if (copy_from_user(&data, (void __user *)arg, sizeof(data)))
1019                         return -EFAULT;
1020                 mutex_lock(&client->lock);
1021                 if (!ion_handle_validate(client, data.handle)) {
1022                         pr_err("%s: invalid handle passed to share ioctl.\n",
1023                                __func__);
1024                         mutex_unlock(&client->lock);
1025                         return -EINVAL;
1026                 }
1027                 data.fd = ion_ioctl_share(filp, client, data.handle);
1028                 mutex_unlock(&client->lock);
1029                 if (copy_to_user((void __user *)arg, &data, sizeof(data)))
1030                         return -EFAULT;
1031                 break;
1032         }
1033         case ION_IOC_IMPORT:
1034         {
1035                 struct ion_fd_data data;
1036                 if (copy_from_user(&data, (void __user *)arg,
1037                                    sizeof(struct ion_fd_data)))
1038                         return -EFAULT;
1039
1040                 data.handle = ion_import_fd(client, data.fd);
1041                 if (IS_ERR(data.handle)){
1042                         data.handle = NULL;
1043                         return -EFAULT;
1044                 }
1045                 if (copy_to_user((void __user *)arg, &data,
1046                                  sizeof(struct ion_fd_data)))
1047                         return -EFAULT;
1048                 break;
1049         }
1050         case ION_IOC_CUSTOM:
1051         {
1052                 struct ion_device *dev = client->dev;
1053                 struct ion_custom_data data;
1054
1055                 if (!dev->custom_ioctl)
1056                         return -ENOTTY;
1057                 if (copy_from_user(&data, (void __user *)arg,
1058                                 sizeof(struct ion_custom_data)))
1059                         return -EFAULT;
1060                 return dev->custom_ioctl(client, data.cmd, data.arg);
1061         }
1062         case ION_GET_PHYS:
1063         {
1064                 int err = 0;
1065                 struct ion_phys_data data;
1066                 if (copy_from_user(&data, (void __user *)arg,
1067                                    sizeof(struct ion_phys_data)))
1068                         return -EFAULT;
1069                 err = ion_phys(client, data.handle, &data.phys, &data.size);
1070                 if(err < 0){
1071                         return err;
1072                 }
1073                 if (copy_to_user((void __user *)arg, &data,
1074                                  sizeof(struct ion_phys_data)))
1075                         return -EFAULT;
1076                 break;
1077         }
1078         case ION_CACHE_FLUSH:
1079         case ION_CACHE_CLEAN:
1080         case ION_CACHE_INVALID:
1081         {
1082                 int err = 0;
1083                 bool valid;
1084                 struct ion_buffer *buffer;
1085                 struct ion_flush_data data;
1086                 if (copy_from_user(&data, (void __user *)arg,
1087                                    sizeof(struct ion_flush_data)))
1088                         return -EFAULT;
1089                 mutex_lock(&client->lock);
1090                 valid = ion_handle_validate(client, data.handle);
1091                 if (!valid){
1092                     mutex_unlock(&client->lock);
1093                         return -EINVAL;
1094         }
1095                 buffer = data.handle->buffer;
1096                 if (!buffer->heap->ops->cache_op) {
1097                         pr_err("%s: cache_op is not implemented by this heap.\n",
1098                        __func__);
1099                         err = -ENODEV;
1100                         mutex_unlock(&client->lock);
1101                         return err;
1102                 }
1103
1104                 err = data.handle->buffer->heap->ops->cache_op(buffer->heap, buffer, 
1105                         data.virt, data.size, cmd);
1106                 mutex_unlock(&client->lock);
1107                 if(err < 0)
1108                         return err;
1109                 break;
1110         }
1111         default:
1112                 return -ENOTTY;
1113         }
1114         return 0;
1115 }
1116
1117 static int ion_release(struct inode *inode, struct file *file)
1118 {
1119         struct ion_client *client = file->private_data;
1120
1121         pr_debug("%s: %d\n", __func__, __LINE__);
1122         ion_client_put(client);
1123         return 0;
1124 }
1125
1126 static int ion_open(struct inode *inode, struct file *file)
1127 {
1128         struct miscdevice *miscdev = file->private_data;
1129         struct ion_device *dev = container_of(miscdev, struct ion_device, dev);
1130         struct ion_client *client;
1131
1132         pr_debug("%s: %d\n", __func__, __LINE__);
1133         client = ion_client_create(dev, -1, "user");
1134         if (IS_ERR_OR_NULL(client))
1135                 return PTR_ERR(client);
1136         file->private_data = client;
1137
1138         return 0;
1139 }
1140
1141 static const struct file_operations ion_fops = {
1142         .owner          = THIS_MODULE,
1143         .open           = ion_open,
1144         .release        = ion_release,
1145         .unlocked_ioctl = ion_ioctl,
1146 };
1147
1148 static size_t ion_debug_heap_total(struct ion_client *client,
1149                                    enum ion_heap_ids id)
1150 {
1151         size_t size = 0;
1152         struct rb_node *n;
1153
1154         mutex_lock(&client->lock);
1155         for (n = rb_first(&client->handles); n; n = rb_next(n)) {
1156                 struct ion_handle *handle = rb_entry(n,
1157                                                      struct ion_handle,
1158                                                      node);
1159                 if (handle->buffer->heap->id == id)
1160                         size += handle->buffer->size;
1161         }
1162         mutex_unlock(&client->lock);
1163         return size;
1164 }
1165
1166 static int ion_debug_heap_show(struct seq_file *s, void *unused)
1167 {
1168         struct ion_heap *heap = s->private;
1169         struct ion_device *dev = heap->dev;
1170         struct rb_node *n;
1171         
1172         if (heap->ops->print_debug)
1173                 heap->ops->print_debug(heap, s);
1174         seq_printf(s, "-------------------------------------------------\n");
1175         seq_printf(s, "%16.s %16.s %16.s\n", "client", "pid", "size(K)");
1176         for (n = rb_first(&dev->user_clients); n; n = rb_next(n)) {
1177                 struct ion_client *client = rb_entry(n, struct ion_client,
1178                                                      node);
1179                 char task_comm[TASK_COMM_LEN];
1180                 size_t size = ion_debug_heap_total(client, heap->id);
1181                 if (!size)
1182                         continue;
1183
1184                 get_task_comm(task_comm, client->task);
1185                 seq_printf(s, "%16.s %16u %16u\n", task_comm, client->pid,
1186                            size/SZ_1K);
1187         }
1188
1189         for (n = rb_first(&dev->kernel_clients); n; n = rb_next(n)) {
1190                 struct ion_client *client = rb_entry(n, struct ion_client,
1191                                                      node);
1192                 size_t size = ion_debug_heap_total(client, heap->id);
1193                 if (!size)
1194                         continue;
1195                 seq_printf(s, "%16.s %16u %16u\n", client->name, client->pid,
1196                            size/SZ_1K);
1197         }
1198         return 0;
1199 }
1200
1201 static int ion_debug_heap_open(struct inode *inode, struct file *file)
1202 {
1203         return single_open(file, ion_debug_heap_show, inode->i_private);
1204 }
1205
1206 static const struct file_operations debug_heap_fops = {
1207         .open = ion_debug_heap_open,
1208         .read = seq_read,
1209         .llseek = seq_lseek,
1210         .release = single_release,
1211 };
1212
1213 void ion_device_add_heap(struct ion_device *dev, struct ion_heap *heap)
1214 {
1215         struct rb_node **p = &dev->heaps.rb_node;
1216         struct rb_node *parent = NULL;
1217         struct ion_heap *entry;
1218
1219         heap->dev = dev;
1220         mutex_lock(&dev->lock);
1221         while (*p) {
1222                 parent = *p;
1223                 entry = rb_entry(parent, struct ion_heap, node);
1224
1225                 if (heap->id < entry->id) {
1226                         p = &(*p)->rb_left;
1227                 } else if (heap->id > entry->id ) {
1228                         p = &(*p)->rb_right;
1229                 } else {
1230                         pr_err("%s: can not insert multiple heaps with "
1231                                 "id %d\n", __func__, heap->id);
1232                         goto end;
1233                 }
1234         }
1235
1236         rb_link_node(&heap->node, parent, p);
1237         rb_insert_color(&heap->node, &dev->heaps);
1238         debugfs_create_file(heap->name, 0664, dev->debug_root, heap,
1239                             &debug_heap_fops);
1240 end:
1241         mutex_unlock(&dev->lock);
1242 }
1243
1244 static int ion_debug_leak_show(struct seq_file *s, void *unused)
1245 {
1246         struct ion_device *dev = s->private;
1247         struct rb_node *n;
1248         struct rb_node *n2;
1249
1250         /* mark all buffers as 1 */
1251         seq_printf(s, "%16.s %16.s %16.s %16.s\n", "buffer", "heap", "size(K)",
1252                 "ref_count");
1253         mutex_lock(&dev->lock);
1254         for (n = rb_first(&dev->buffers); n; n = rb_next(n)) {
1255                 struct ion_buffer *buf = rb_entry(n, struct ion_buffer,
1256                                                      node);
1257
1258                 buf->marked = 1;
1259         }
1260
1261         /* now see which buffers we can access */
1262         for (n = rb_first(&dev->kernel_clients); n; n = rb_next(n)) {
1263                 struct ion_client *client = rb_entry(n, struct ion_client,
1264                                                      node);
1265
1266                 mutex_lock(&client->lock);
1267                 for (n2 = rb_first(&client->handles); n2; n2 = rb_next(n2)) {
1268                         struct ion_handle *handle = rb_entry(n2,
1269                                                 struct ion_handle, node);
1270
1271                         handle->buffer->marked = 0;
1272
1273                 }
1274                 mutex_unlock(&client->lock);
1275
1276         }
1277
1278         for (n = rb_first(&dev->user_clients); n; n = rb_next(n)) {
1279                 struct ion_client *client = rb_entry(n, struct ion_client,
1280                                                      node);
1281
1282                 mutex_lock(&client->lock);
1283                 for (n2 = rb_first(&client->handles); n2; n2 = rb_next(n2)) {
1284                         struct ion_handle *handle = rb_entry(n2,
1285                                                 struct ion_handle, node);
1286
1287                         handle->buffer->marked = 0;
1288
1289                 }
1290                 mutex_unlock(&client->lock);
1291
1292         }
1293         /* And anyone still marked as a 1 means a leaked handle somewhere */
1294         for (n = rb_first(&dev->buffers); n; n = rb_next(n)) {
1295                 struct ion_buffer *buf = rb_entry(n, struct ion_buffer,
1296                                                      node);
1297
1298                 if (buf->marked == 1)
1299                         seq_printf(s, "%16.x %16.s %16.d %16.d\n",
1300                                 (int)buf, buf->heap->name, buf->size/SZ_1K,
1301                                 atomic_read(&buf->ref.refcount));
1302         }
1303         mutex_unlock(&dev->lock);
1304         return 0;
1305 }
1306
1307 static int ion_debug_leak_open(struct inode *inode, struct file *file)
1308 {
1309         return single_open(file, ion_debug_leak_show, inode->i_private);
1310 }
1311
1312 static const struct file_operations debug_leak_fops = {
1313         .open = ion_debug_leak_open,
1314         .read = seq_read,
1315         .llseek = seq_lseek,
1316         .release = single_release,
1317 };
1318 struct ion_device *ion_device_create(long (*custom_ioctl)
1319                                      (struct ion_client *client,
1320                                       unsigned int cmd,
1321                                       unsigned long arg))
1322 {
1323         struct ion_device *idev;
1324         int ret;
1325
1326         idev = kzalloc(sizeof(struct ion_device), GFP_KERNEL);
1327         if (!idev)
1328                 return ERR_PTR(-ENOMEM);
1329
1330         idev->dev.minor = MISC_DYNAMIC_MINOR;
1331         idev->dev.name = "ion";
1332         idev->dev.fops = &ion_fops;
1333         idev->dev.parent = NULL;
1334         ret = misc_register(&idev->dev);
1335         if (ret) {
1336                 pr_err("ion: failed to register misc device.\n");
1337                 return ERR_PTR(ret);
1338         }
1339
1340         idev->debug_root = debugfs_create_dir("ion", NULL);
1341         if (IS_ERR_OR_NULL(idev->debug_root))
1342                 pr_err("ion: failed to create debug files.\n");
1343
1344         idev->custom_ioctl = custom_ioctl;
1345         idev->buffers = RB_ROOT;
1346         mutex_init(&idev->lock);
1347         idev->heaps = RB_ROOT;
1348         idev->user_clients = RB_ROOT;
1349         idev->kernel_clients = RB_ROOT;
1350         debugfs_create_file("leak", 0664, idev->debug_root, idev,
1351                             &debug_leak_fops);
1352         return idev;
1353 }
1354
1355 void ion_device_destroy(struct ion_device *dev)
1356 {
1357         misc_deregister(&dev->dev);
1358         /* XXX need to free the heaps and clients ? */
1359         kfree(dev);
1360 }