ion drivers: add 'query client infomation' interface for vpu
[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                 if(!(region.offset & 0xf0000000))
934                         region.offset = buffer->vm_start;
935
936                 dmac_flush_range((void *)region.offset, (void *)(region.offset + region.len));
937
938                 break;
939         }
940         default:
941                 return -ENOTTY;
942         }
943         return 0;
944 }
945
946 static const struct file_operations ion_share_fops = {
947         .owner          = THIS_MODULE,
948         .release        = ion_share_release,
949         .mmap           = ion_share_mmap,
950         .unlocked_ioctl = ion_share_ioctl,
951 };
952
953 static int ion_ioctl_share(struct file *parent, struct ion_client *client,
954                            struct ion_handle *handle)
955 {
956         int fd = get_unused_fd();
957         struct file *file;
958
959         if (fd < 0)
960                 return -ENFILE;
961
962         file = anon_inode_getfile("ion_share_fd", &ion_share_fops,
963                                   handle->buffer, O_RDWR);
964         if (IS_ERR_OR_NULL(file))
965                 goto err;
966
967         if (parent->f_flags & O_DSYNC)
968                 file->f_flags |= O_DSYNC;
969         
970         ion_buffer_get(handle->buffer);
971         fd_install(fd, file);
972
973         return fd;
974
975 err:
976         put_unused_fd(fd);
977         return -ENFILE;
978 }
979
980 static long ion_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
981 {
982         struct ion_client *client = filp->private_data;
983
984         switch (cmd) {
985         case ION_IOC_ALLOC:
986         {
987                 struct ion_allocation_data data;
988                 if (copy_from_user(&data, (void __user *)arg, sizeof(data)))
989                         return -EFAULT;
990
991                 data.handle = ion_alloc(client, data.len, data.align,
992                                              data.flags);
993                 if (IS_ERR_OR_NULL(data.handle)) {
994                         printk("%s: alloc 0x%x bytes failed\n", __func__, data.len);
995             return -ENOMEM;
996                 } 
997                 if (copy_to_user((void __user *)arg, &data, sizeof(data)))
998                         return -EFAULT;
999                 break;
1000         }
1001         case ION_IOC_FREE:
1002         {
1003                 struct ion_handle_data data;
1004                 bool valid;
1005
1006                 if (copy_from_user(&data, (void __user *)arg,
1007                                    sizeof(struct ion_handle_data)))
1008                         return -EFAULT;
1009                 mutex_lock(&client->lock);
1010                 valid = ion_handle_validate(client, data.handle);
1011                 mutex_unlock(&client->lock);
1012                 if (!valid)
1013                         return -EINVAL;
1014                 ion_free(client, data.handle);
1015                 break;
1016         }
1017         case ION_IOC_MAP:
1018         case ION_IOC_SHARE:
1019         {
1020                 struct ion_fd_data data;
1021                 if (copy_from_user(&data, (void __user *)arg, sizeof(data)))
1022                         return -EFAULT;
1023                 mutex_lock(&client->lock);
1024                 if (!ion_handle_validate(client, data.handle)) {
1025                         pr_err("%s: invalid handle passed to share ioctl.\n",
1026                                __func__);
1027                         mutex_unlock(&client->lock);
1028                         return -EINVAL;
1029                 }
1030                 data.fd = ion_ioctl_share(filp, client, data.handle);
1031                 mutex_unlock(&client->lock);
1032                 if (copy_to_user((void __user *)arg, &data, sizeof(data)))
1033                         return -EFAULT;
1034                 break;
1035         }
1036         case ION_IOC_IMPORT:
1037         {
1038                 struct ion_fd_data data;
1039                 if (copy_from_user(&data, (void __user *)arg,
1040                                    sizeof(struct ion_fd_data)))
1041                         return -EFAULT;
1042
1043                 data.handle = ion_import_fd(client, data.fd);
1044                 if (IS_ERR(data.handle)){
1045                         data.handle = NULL;
1046                         return -EFAULT;
1047                 }
1048                 if (copy_to_user((void __user *)arg, &data,
1049                                  sizeof(struct ion_fd_data)))
1050                         return -EFAULT;
1051                 break;
1052         }
1053         case ION_IOC_CUSTOM:
1054         {
1055                 struct ion_device *dev = client->dev;
1056                 struct ion_custom_data data;
1057
1058                 if (!dev->custom_ioctl)
1059                         return -ENOTTY;
1060                 if (copy_from_user(&data, (void __user *)arg,
1061                                 sizeof(struct ion_custom_data)))
1062                         return -EFAULT;
1063                 return dev->custom_ioctl(client, data.cmd, data.arg);
1064         }
1065         case ION_GET_PHYS:
1066         {
1067                 int err = 0;
1068                 struct ion_phys_data data;
1069                 if (copy_from_user(&data, (void __user *)arg,
1070                                    sizeof(struct ion_phys_data)))
1071                         return -EFAULT;
1072                 err = ion_phys(client, data.handle, &data.phys, &data.size);
1073                 if(err < 0){
1074                         return err;
1075                 }
1076                 if (copy_to_user((void __user *)arg, &data,
1077                                  sizeof(struct ion_phys_data)))
1078                         return -EFAULT;
1079                 break;
1080         }
1081         case ION_CACHE_FLUSH:
1082         case ION_CACHE_CLEAN:
1083         case ION_CACHE_INVALID:
1084         {
1085                 int err = 0;
1086                 bool valid;
1087                 struct ion_buffer *buffer;
1088                 struct ion_flush_data data;
1089                 if (copy_from_user(&data, (void __user *)arg,
1090                                    sizeof(struct ion_flush_data)))
1091                         return -EFAULT;
1092                 mutex_lock(&client->lock);
1093                 valid = ion_handle_validate(client, data.handle);
1094                 if (!valid){
1095                     mutex_unlock(&client->lock);
1096                         return -EINVAL;
1097         }
1098                 buffer = data.handle->buffer;
1099                 if (!buffer->heap->ops->cache_op) {
1100                         pr_err("%s: cache_op is not implemented by this heap.\n",
1101                        __func__);
1102                         err = -ENODEV;
1103                         mutex_unlock(&client->lock);
1104                         return err;
1105                 }
1106
1107                 err = data.handle->buffer->heap->ops->cache_op(buffer->heap, buffer, 
1108                         data.virt, data.size, cmd);
1109                 mutex_unlock(&client->lock);
1110                 if(err < 0)
1111                         return err;
1112                 break;
1113         }
1114         case ION_GET_CLIENT: 
1115         {
1116                 struct ion_handle *handle;
1117                 struct ion_client_data data;
1118                 struct rb_node *n;
1119
1120                 if (copy_from_user(&data, (void __user *)arg,
1121                                    sizeof(struct ion_client_data)))
1122                         return -EFAULT;
1123
1124                 mutex_lock(&client->lock);
1125                 switch (data.type) {
1126                         case ION_TYPE_GET_TOTAL_SIZE:
1127                                 data.total_size = 0;
1128                                 for (n = rb_first(&client->handles); n; n = rb_next(n)) {
1129                                         handle = rb_entry(n, struct ion_handle, node);
1130                                         data.total_size += handle->buffer->size;
1131                                 }
1132                                 break;
1133                         case ION_TYPE_SIZE_GET_COUNT:
1134                                 data.count = 0;
1135                                 for (n = rb_first(&client->handles); n; n = rb_next(n)) {
1136                                         handle = rb_entry(n, struct ion_handle, node);
1137                                         if(handle->buffer->size == data.size)
1138                                                 data.count++;
1139                                 }
1140                                 break;
1141                 }
1142                 mutex_unlock(&client->lock);
1143                 if (copy_to_user((void __user *)arg, &data,
1144                                  sizeof(struct ion_client_data)))
1145                         return -EFAULT;
1146                 break;
1147         }
1148         default:
1149                 return -ENOTTY;
1150         }
1151         return 0;
1152 }
1153
1154 static int ion_release(struct inode *inode, struct file *file)
1155 {
1156         struct ion_client *client = file->private_data;
1157
1158         pr_debug("%s: %d\n", __func__, __LINE__);
1159         ion_client_put(client);
1160         return 0;
1161 }
1162
1163 static int ion_open(struct inode *inode, struct file *file)
1164 {
1165         struct miscdevice *miscdev = file->private_data;
1166         struct ion_device *dev = container_of(miscdev, struct ion_device, dev);
1167         struct ion_client *client;
1168
1169         pr_debug("%s: %d\n", __func__, __LINE__);
1170         client = ion_client_create(dev, -1, "user");
1171         if (IS_ERR_OR_NULL(client))
1172                 return PTR_ERR(client);
1173         file->private_data = client;
1174
1175         return 0;
1176 }
1177
1178 static const struct file_operations ion_fops = {
1179         .owner          = THIS_MODULE,
1180         .open           = ion_open,
1181         .release        = ion_release,
1182         .unlocked_ioctl = ion_ioctl,
1183 };
1184
1185 static size_t ion_debug_heap_total(struct ion_client *client,
1186                                    enum ion_heap_ids id)
1187 {
1188         size_t size = 0;
1189         struct rb_node *n;
1190
1191         mutex_lock(&client->lock);
1192         for (n = rb_first(&client->handles); n; n = rb_next(n)) {
1193                 struct ion_handle *handle = rb_entry(n,
1194                                                      struct ion_handle,
1195                                                      node);
1196                 if (handle->buffer->heap->id == id)
1197                         size += handle->buffer->size;
1198         }
1199         mutex_unlock(&client->lock);
1200         return size;
1201 }
1202
1203 static int ion_debug_heap_show(struct seq_file *s, void *unused)
1204 {
1205         struct ion_heap *heap = s->private;
1206         struct ion_device *dev = heap->dev;
1207         struct rb_node *n;
1208         
1209         if (heap->ops->print_debug)
1210                 heap->ops->print_debug(heap, s);
1211         seq_printf(s, "-------------------------------------------------\n");
1212         seq_printf(s, "%16.s %16.s %16.s\n", "client", "pid", "size(K)");
1213         for (n = rb_first(&dev->user_clients); n; n = rb_next(n)) {
1214                 struct ion_client *client = rb_entry(n, struct ion_client,
1215                                                      node);
1216                 char task_comm[TASK_COMM_LEN];
1217                 size_t size = ion_debug_heap_total(client, heap->id);
1218                 if (!size)
1219                         continue;
1220
1221                 get_task_comm(task_comm, client->task);
1222                 seq_printf(s, "%16.s %16u %16u\n", task_comm, client->pid,
1223                            size/SZ_1K);
1224         }
1225
1226         for (n = rb_first(&dev->kernel_clients); n; n = rb_next(n)) {
1227                 struct ion_client *client = rb_entry(n, struct ion_client,
1228                                                      node);
1229                 size_t size = ion_debug_heap_total(client, heap->id);
1230                 if (!size)
1231                         continue;
1232                 seq_printf(s, "%16.s %16u %16u\n", client->name, client->pid,
1233                            size/SZ_1K);
1234         }
1235         return 0;
1236 }
1237
1238 static int ion_debug_heap_open(struct inode *inode, struct file *file)
1239 {
1240         return single_open(file, ion_debug_heap_show, inode->i_private);
1241 }
1242
1243 static const struct file_operations debug_heap_fops = {
1244         .open = ion_debug_heap_open,
1245         .read = seq_read,
1246         .llseek = seq_lseek,
1247         .release = single_release,
1248 };
1249
1250 void ion_device_add_heap(struct ion_device *dev, struct ion_heap *heap)
1251 {
1252         struct rb_node **p = &dev->heaps.rb_node;
1253         struct rb_node *parent = NULL;
1254         struct ion_heap *entry;
1255
1256         heap->dev = dev;
1257         mutex_lock(&dev->lock);
1258         while (*p) {
1259                 parent = *p;
1260                 entry = rb_entry(parent, struct ion_heap, node);
1261
1262                 if (heap->id < entry->id) {
1263                         p = &(*p)->rb_left;
1264                 } else if (heap->id > entry->id ) {
1265                         p = &(*p)->rb_right;
1266                 } else {
1267                         pr_err("%s: can not insert multiple heaps with "
1268                                 "id %d\n", __func__, heap->id);
1269                         goto end;
1270                 }
1271         }
1272
1273         rb_link_node(&heap->node, parent, p);
1274         rb_insert_color(&heap->node, &dev->heaps);
1275         debugfs_create_file(heap->name, 0664, dev->debug_root, heap,
1276                             &debug_heap_fops);
1277 end:
1278         mutex_unlock(&dev->lock);
1279 }
1280
1281 static int ion_debug_leak_show(struct seq_file *s, void *unused)
1282 {
1283         struct ion_device *dev = s->private;
1284         struct rb_node *n;
1285         struct rb_node *n2;
1286
1287         /* mark all buffers as 1 */
1288         seq_printf(s, "%16.s %16.s %16.s %16.s\n", "buffer", "heap", "size(K)",
1289                 "ref_count");
1290         mutex_lock(&dev->lock);
1291         for (n = rb_first(&dev->buffers); n; n = rb_next(n)) {
1292                 struct ion_buffer *buf = rb_entry(n, struct ion_buffer,
1293                                                      node);
1294
1295                 buf->marked = 1;
1296         }
1297
1298         /* now see which buffers we can access */
1299         for (n = rb_first(&dev->kernel_clients); n; n = rb_next(n)) {
1300                 struct ion_client *client = rb_entry(n, struct ion_client,
1301                                                      node);
1302
1303                 mutex_lock(&client->lock);
1304                 for (n2 = rb_first(&client->handles); n2; n2 = rb_next(n2)) {
1305                         struct ion_handle *handle = rb_entry(n2,
1306                                                 struct ion_handle, node);
1307
1308                         handle->buffer->marked = 0;
1309
1310                 }
1311                 mutex_unlock(&client->lock);
1312
1313         }
1314
1315         for (n = rb_first(&dev->user_clients); n; n = rb_next(n)) {
1316                 struct ion_client *client = rb_entry(n, struct ion_client,
1317                                                      node);
1318
1319                 mutex_lock(&client->lock);
1320                 for (n2 = rb_first(&client->handles); n2; n2 = rb_next(n2)) {
1321                         struct ion_handle *handle = rb_entry(n2,
1322                                                 struct ion_handle, node);
1323
1324                         handle->buffer->marked = 0;
1325
1326                 }
1327                 mutex_unlock(&client->lock);
1328
1329         }
1330         /* And anyone still marked as a 1 means a leaked handle somewhere */
1331         for (n = rb_first(&dev->buffers); n; n = rb_next(n)) {
1332                 struct ion_buffer *buf = rb_entry(n, struct ion_buffer,
1333                                                      node);
1334
1335                 if (buf->marked == 1)
1336                         seq_printf(s, "%16.x %16.s %16.d %16.d\n",
1337                                 (int)buf, buf->heap->name, buf->size/SZ_1K,
1338                                 atomic_read(&buf->ref.refcount));
1339         }
1340         mutex_unlock(&dev->lock);
1341         return 0;
1342 }
1343
1344 static int ion_debug_leak_open(struct inode *inode, struct file *file)
1345 {
1346         return single_open(file, ion_debug_leak_show, inode->i_private);
1347 }
1348
1349 static const struct file_operations debug_leak_fops = {
1350         .open = ion_debug_leak_open,
1351         .read = seq_read,
1352         .llseek = seq_lseek,
1353         .release = single_release,
1354 };
1355 struct ion_device *ion_device_create(long (*custom_ioctl)
1356                                      (struct ion_client *client,
1357                                       unsigned int cmd,
1358                                       unsigned long arg))
1359 {
1360         struct ion_device *idev;
1361         int ret;
1362
1363         idev = kzalloc(sizeof(struct ion_device), GFP_KERNEL);
1364         if (!idev)
1365                 return ERR_PTR(-ENOMEM);
1366
1367         idev->dev.minor = MISC_DYNAMIC_MINOR;
1368         idev->dev.name = "ion";
1369         idev->dev.fops = &ion_fops;
1370         idev->dev.parent = NULL;
1371         ret = misc_register(&idev->dev);
1372         if (ret) {
1373                 pr_err("ion: failed to register misc device.\n");
1374                 return ERR_PTR(ret);
1375         }
1376
1377         idev->debug_root = debugfs_create_dir("ion", NULL);
1378         if (IS_ERR_OR_NULL(idev->debug_root))
1379                 pr_err("ion: failed to create debug files.\n");
1380
1381         idev->custom_ioctl = custom_ioctl;
1382         idev->buffers = RB_ROOT;
1383         mutex_init(&idev->lock);
1384         idev->heaps = RB_ROOT;
1385         idev->user_clients = RB_ROOT;
1386         idev->kernel_clients = RB_ROOT;
1387         debugfs_create_file("leak", 0664, idev->debug_root, idev,
1388                             &debug_leak_fops);
1389         return idev;
1390 }
1391
1392 void ion_device_destroy(struct ion_device *dev)
1393 {
1394         misc_deregister(&dev->dev);
1395         /* XXX need to free the heaps and clients ? */
1396         kfree(dev);
1397 }