OSDN Git Service

Revert "Revert "Revert "CHROMIUM: android: binder: Fix potential scheduling-while...
[android-x86/kernel.git] / drivers / android / binder.c
1 /* binder.c
2  *
3  * Android IPC Subsystem
4  *
5  * Copyright (C) 2007-2008 Google, Inc.
6  *
7  * This software is licensed under the terms of the GNU General Public
8  * License version 2, as published by the Free Software Foundation, and
9  * may be copied, distributed, and modified under those terms.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  */
17
18 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19
20 #include <asm/cacheflush.h>
21 #include <linux/atomic.h>
22 #include <linux/fdtable.h>
23 #include <linux/file.h>
24 #include <linux/freezer.h>
25 #include <linux/fs.h>
26 #include <linux/list.h>
27 #include <linux/miscdevice.h>
28 #include <linux/mm.h>
29 #include <linux/module.h>
30 #include <linux/mutex.h>
31 #include <linux/nsproxy.h>
32 #include <linux/poll.h>
33 #include <linux/debugfs.h>
34 #include <linux/rbtree.h>
35 #include <linux/sched.h>
36 #include <linux/seq_file.h>
37 #include <linux/uaccess.h>
38 #include <linux/vmalloc.h>
39 #include <linux/slab.h>
40 #include <linux/pid_namespace.h>
41 #include <linux/security.h>
42
43 #ifdef CONFIG_ANDROID_BINDER_IPC_32BIT
44 #define BINDER_IPC_32BIT 1
45 #endif
46
47 #include <uapi/linux/android/binder.h>
48 #include "binder_trace.h"
49
50 static HLIST_HEAD(binder_devices);
51
52 static struct dentry *binder_debugfs_dir_entry_root;
53 static struct dentry *binder_debugfs_dir_entry_proc;
54 atomic_t binder_last_id;
55
56 #define BINDER_DEBUG_ENTRY(name) \
57 static int binder_##name##_open(struct inode *inode, struct file *file) \
58 { \
59         return single_open(file, binder_##name##_show, inode->i_private); \
60 } \
61 \
62 static const struct file_operations binder_##name##_fops = { \
63         .owner = THIS_MODULE, \
64         .open = binder_##name##_open, \
65         .read = seq_read, \
66         .llseek = seq_lseek, \
67         .release = single_release, \
68 }
69
70 static int binder_proc_show(struct seq_file *m, void *unused);
71 BINDER_DEBUG_ENTRY(proc);
72
73 /* This is only defined in include/asm-arm/sizes.h */
74 #ifndef SZ_1K
75 #define SZ_1K                               0x400
76 #endif
77
78 #ifndef SZ_4M
79 #define SZ_4M                               0x400000
80 #endif
81
82 #define FORBIDDEN_MMAP_FLAGS                (VM_WRITE)
83
84 #define BINDER_SMALL_BUF_SIZE (PAGE_SIZE * 64)
85
86 enum {
87         BINDER_DEBUG_USER_ERROR             = 1U << 0,
88         BINDER_DEBUG_FAILED_TRANSACTION     = 1U << 1,
89         BINDER_DEBUG_DEAD_TRANSACTION       = 1U << 2,
90         BINDER_DEBUG_OPEN_CLOSE             = 1U << 3,
91         BINDER_DEBUG_DEAD_BINDER            = 1U << 4,
92         BINDER_DEBUG_DEATH_NOTIFICATION     = 1U << 5,
93         BINDER_DEBUG_READ_WRITE             = 1U << 6,
94         BINDER_DEBUG_USER_REFS              = 1U << 7,
95         BINDER_DEBUG_THREADS                = 1U << 8,
96         BINDER_DEBUG_TRANSACTION            = 1U << 9,
97         BINDER_DEBUG_TRANSACTION_COMPLETE   = 1U << 10,
98         BINDER_DEBUG_FREE_BUFFER            = 1U << 11,
99         BINDER_DEBUG_INTERNAL_REFS          = 1U << 12,
100         BINDER_DEBUG_BUFFER_ALLOC           = 1U << 13,
101         BINDER_DEBUG_PRIORITY_CAP           = 1U << 14,
102         BINDER_DEBUG_BUFFER_ALLOC_ASYNC     = 1U << 15,
103 };
104 static uint32_t binder_debug_mask = BINDER_DEBUG_USER_ERROR |
105         BINDER_DEBUG_FAILED_TRANSACTION | BINDER_DEBUG_DEAD_TRANSACTION;
106 module_param_named(debug_mask, binder_debug_mask, uint, S_IWUSR | S_IRUGO);
107
108 static bool binder_debug_no_lock;
109 module_param_named(proc_no_lock, binder_debug_no_lock, bool, S_IWUSR | S_IRUGO);
110
111 static char *binder_devices_param = CONFIG_ANDROID_BINDER_DEVICES;
112 module_param_named(devices, binder_devices_param, charp, S_IRUGO);
113
114 static DECLARE_WAIT_QUEUE_HEAD(binder_user_error_wait);
115 static int binder_stop_on_user_error;
116
117 static int binder_set_stop_on_user_error(const char *val,
118                                          struct kernel_param *kp)
119 {
120         int ret;
121
122         ret = param_set_int(val, kp);
123         if (binder_stop_on_user_error < 2)
124                 wake_up(&binder_user_error_wait);
125         return ret;
126 }
127 module_param_call(stop_on_user_error, binder_set_stop_on_user_error,
128         param_get_int, &binder_stop_on_user_error, S_IWUSR | S_IRUGO);
129
130 #define binder_debug(mask, x...) \
131         do { \
132                 if (binder_debug_mask & mask) \
133                         pr_info(x); \
134         } while (0)
135
136 #define binder_user_error(x...) \
137         do { \
138                 if (binder_debug_mask & BINDER_DEBUG_USER_ERROR) \
139                         pr_info(x); \
140                 if (binder_stop_on_user_error) \
141                         binder_stop_on_user_error = 2; \
142         } while (0)
143
144 #define to_flat_binder_object(hdr) \
145         container_of(hdr, struct flat_binder_object, hdr)
146
147 #define to_binder_fd_object(hdr) container_of(hdr, struct binder_fd_object, hdr)
148
149 #define to_binder_buffer_object(hdr) \
150         container_of(hdr, struct binder_buffer_object, hdr)
151
152 #define to_binder_fd_array_object(hdr) \
153         container_of(hdr, struct binder_fd_array_object, hdr)
154
155 enum binder_stat_types {
156         BINDER_STAT_PROC,
157         BINDER_STAT_THREAD,
158         BINDER_STAT_NODE,
159         BINDER_STAT_REF,
160         BINDER_STAT_DEATH,
161         BINDER_STAT_TRANSACTION,
162         BINDER_STAT_TRANSACTION_COMPLETE,
163         BINDER_STAT_COUNT
164 };
165
166 struct binder_stats {
167         int br[_IOC_NR(BR_FAILED_REPLY) + 1];
168         int bc[_IOC_NR(BC_REPLY_SG) + 1];
169 };
170
171 /* These are still global, since it's not always easy to get the context */
172 struct binder_obj_stats {
173         atomic_t obj_created[BINDER_STAT_COUNT];
174         atomic_t obj_deleted[BINDER_STAT_COUNT];
175 };
176
177 static struct binder_obj_stats binder_obj_stats;
178
179 static inline void binder_stats_deleted(enum binder_stat_types type)
180 {
181         atomic_inc(&binder_obj_stats.obj_deleted[type]);
182 }
183
184 static inline void binder_stats_created(enum binder_stat_types type)
185 {
186         atomic_inc(&binder_obj_stats.obj_created[type]);
187 }
188
189 struct binder_transaction_log_entry {
190         int debug_id;
191         int call_type;
192         int from_proc;
193         int from_thread;
194         int target_handle;
195         int to_proc;
196         int to_thread;
197         int to_node;
198         int data_size;
199         int offsets_size;
200         const char *context_name;
201 };
202 struct binder_transaction_log {
203         int next;
204         int full;
205         struct binder_transaction_log_entry entry[32];
206 };
207
208 static struct binder_transaction_log_entry *binder_transaction_log_add(
209         struct binder_transaction_log *log)
210 {
211         struct binder_transaction_log_entry *e;
212
213         e = &log->entry[log->next];
214         memset(e, 0, sizeof(*e));
215         log->next++;
216         if (log->next == ARRAY_SIZE(log->entry)) {
217                 log->next = 0;
218                 log->full = 1;
219         }
220         return e;
221 }
222
223 struct binder_context {
224         struct binder_node *binder_context_mgr_node;
225         kuid_t binder_context_mgr_uid;
226         const char *name;
227
228         struct mutex binder_main_lock;
229         struct mutex binder_deferred_lock;
230         struct mutex binder_mmap_lock;
231
232         struct hlist_head binder_procs;
233         struct hlist_head binder_dead_nodes;
234         struct hlist_head binder_deferred_list;
235
236         struct work_struct deferred_work;
237         struct workqueue_struct *binder_deferred_workqueue;
238         struct binder_transaction_log transaction_log;
239         struct binder_transaction_log transaction_log_failed;
240
241         struct binder_stats binder_stats;
242 };
243
244 struct binder_device {
245         struct hlist_node hlist;
246         struct miscdevice miscdev;
247         struct binder_context context;
248 };
249
250 struct binder_work {
251         struct list_head entry;
252         enum {
253                 BINDER_WORK_TRANSACTION = 1,
254                 BINDER_WORK_TRANSACTION_COMPLETE,
255                 BINDER_WORK_NODE,
256                 BINDER_WORK_DEAD_BINDER,
257                 BINDER_WORK_DEAD_BINDER_AND_CLEAR,
258                 BINDER_WORK_CLEAR_DEATH_NOTIFICATION,
259         } type;
260 };
261
262 struct binder_node {
263         int debug_id;
264         struct binder_work work;
265         union {
266                 struct rb_node rb_node;
267                 struct hlist_node dead_node;
268         };
269         struct binder_proc *proc;
270         struct hlist_head refs;
271         int internal_strong_refs;
272         int local_weak_refs;
273         int local_strong_refs;
274         binder_uintptr_t ptr;
275         binder_uintptr_t cookie;
276         unsigned has_strong_ref:1;
277         unsigned pending_strong_ref:1;
278         unsigned has_weak_ref:1;
279         unsigned pending_weak_ref:1;
280         unsigned has_async_transaction:1;
281         unsigned accept_fds:1;
282         unsigned min_priority:8;
283         struct list_head async_todo;
284 };
285
286 struct binder_ref_death {
287         struct binder_work work;
288         binder_uintptr_t cookie;
289 };
290
291 struct binder_ref {
292         /* Lookups needed: */
293         /*   node + proc => ref (transaction) */
294         /*   desc + proc => ref (transaction, inc/dec ref) */
295         /*   node => refs + procs (proc exit) */
296         int debug_id;
297         struct rb_node rb_node_desc;
298         struct rb_node rb_node_node;
299         struct hlist_node node_entry;
300         struct binder_proc *proc;
301         struct binder_node *node;
302         uint32_t desc;
303         int strong;
304         int weak;
305         struct binder_ref_death *death;
306 };
307
308 struct binder_buffer {
309         struct list_head entry; /* free and allocated entries by address */
310         struct rb_node rb_node; /* free entry by size or allocated entry */
311                                 /* by address */
312         unsigned free:1;
313         unsigned allow_user_free:1;
314         unsigned async_transaction:1;
315         unsigned debug_id:29;
316
317         struct binder_transaction *transaction;
318
319         struct binder_node *target_node;
320         size_t data_size;
321         size_t offsets_size;
322         size_t extra_buffers_size;
323         uint8_t data[0];
324 };
325
326 enum binder_deferred_state {
327         BINDER_DEFERRED_PUT_FILES    = 0x01,
328         BINDER_DEFERRED_FLUSH        = 0x02,
329         BINDER_DEFERRED_RELEASE      = 0x04,
330 };
331
332 struct binder_proc {
333         struct hlist_node proc_node;
334         struct rb_root threads;
335         struct rb_root nodes;
336         struct rb_root refs_by_desc;
337         struct rb_root refs_by_node;
338         int pid;
339         struct vm_area_struct *vma;
340         struct mm_struct *vma_vm_mm;
341         struct task_struct *tsk;
342         struct files_struct *files;
343         struct hlist_node deferred_work_node;
344         int deferred_work;
345         void *buffer;
346         ptrdiff_t user_buffer_offset;
347
348         struct list_head buffers;
349         struct rb_root free_buffers;
350         struct rb_root allocated_buffers;
351         size_t free_async_space;
352
353         struct page **pages;
354         size_t buffer_size;
355         uint32_t buffer_free;
356         struct list_head todo;
357         wait_queue_head_t wait;
358         struct binder_stats stats;
359         struct list_head delivered_death;
360         int max_threads;
361         int requested_threads;
362         int requested_threads_started;
363         int ready_threads;
364         long default_priority;
365         struct dentry *debugfs_entry;
366         struct binder_context *context;
367 };
368
369 enum {
370         BINDER_LOOPER_STATE_REGISTERED  = 0x01,
371         BINDER_LOOPER_STATE_ENTERED     = 0x02,
372         BINDER_LOOPER_STATE_EXITED      = 0x04,
373         BINDER_LOOPER_STATE_INVALID     = 0x08,
374         BINDER_LOOPER_STATE_WAITING     = 0x10,
375         BINDER_LOOPER_STATE_NEED_RETURN = 0x20
376 };
377
378 struct binder_thread {
379         struct binder_proc *proc;
380         struct rb_node rb_node;
381         int pid;
382         int looper;
383         struct binder_transaction *transaction_stack;
384         struct list_head todo;
385         uint32_t return_error; /* Write failed, return error code in read buf */
386         uint32_t return_error2; /* Write failed, return error code in read */
387                 /* buffer. Used when sending a reply to a dead process that */
388                 /* we are also waiting on */
389         wait_queue_head_t wait;
390         struct binder_stats stats;
391 };
392
393 struct binder_transaction {
394         int debug_id;
395         struct binder_work work;
396         struct binder_thread *from;
397         struct binder_transaction *from_parent;
398         struct binder_proc *to_proc;
399         struct binder_thread *to_thread;
400         struct binder_transaction *to_parent;
401         unsigned need_reply:1;
402         /* unsigned is_dead:1; */       /* not used at the moment */
403
404         struct binder_buffer *buffer;
405         unsigned int    code;
406         unsigned int    flags;
407         long    priority;
408         long    saved_priority;
409         kuid_t  sender_euid;
410 };
411
412 static void
413 binder_defer_work(struct binder_proc *proc, enum binder_deferred_state defer);
414
415 static int task_get_unused_fd_flags(struct binder_proc *proc, int flags)
416 {
417         struct files_struct *files = proc->files;
418         unsigned long rlim_cur;
419         unsigned long irqs;
420
421         if (files == NULL)
422                 return -ESRCH;
423
424         if (!lock_task_sighand(proc->tsk, &irqs))
425                 return -EMFILE;
426
427         rlim_cur = task_rlimit(proc->tsk, RLIMIT_NOFILE);
428         unlock_task_sighand(proc->tsk, &irqs);
429
430         return __alloc_fd(files, 0, rlim_cur, flags);
431 }
432
433 /*
434  * copied from fd_install
435  */
436 static void task_fd_install(
437         struct binder_proc *proc, unsigned int fd, struct file *file)
438 {
439         if (proc->files)
440                 __fd_install(proc->files, fd, file);
441 }
442
443 /*
444  * copied from sys_close
445  */
446 static long task_close_fd(struct binder_proc *proc, unsigned int fd)
447 {
448         int retval;
449
450         if (proc->files == NULL)
451                 return -ESRCH;
452
453         retval = __close_fd(proc->files, fd);
454         /* can't restart close syscall because file table entry was cleared */
455         if (unlikely(retval == -ERESTARTSYS ||
456                      retval == -ERESTARTNOINTR ||
457                      retval == -ERESTARTNOHAND ||
458                      retval == -ERESTART_RESTARTBLOCK))
459                 retval = -EINTR;
460
461         return retval;
462 }
463
464 static inline void binder_lock(struct binder_context *context, const char *tag)
465 {
466         trace_binder_lock(tag);
467         mutex_lock(&context->binder_main_lock);
468         trace_binder_locked(tag);
469 }
470
471 static inline void binder_unlock(struct binder_context *context,
472                                  const char *tag)
473 {
474         trace_binder_unlock(tag);
475         mutex_unlock(&context->binder_main_lock);
476 }
477
478 static void binder_set_nice(long nice)
479 {
480         long min_nice;
481
482         if (can_nice(current, nice)) {
483                 set_user_nice(current, nice);
484                 return;
485         }
486         min_nice = rlimit_to_nice(current->signal->rlim[RLIMIT_NICE].rlim_cur);
487         binder_debug(BINDER_DEBUG_PRIORITY_CAP,
488                      "%d: nice value %ld not allowed use %ld instead\n",
489                       current->pid, nice, min_nice);
490         set_user_nice(current, min_nice);
491         if (min_nice <= MAX_NICE)
492                 return;
493         binder_user_error("%d RLIMIT_NICE not set\n", current->pid);
494 }
495
496 static size_t binder_buffer_size(struct binder_proc *proc,
497                                  struct binder_buffer *buffer)
498 {
499         if (list_is_last(&buffer->entry, &proc->buffers))
500                 return proc->buffer + proc->buffer_size - (void *)buffer->data;
501         return (size_t)list_entry(buffer->entry.next,
502                           struct binder_buffer, entry) - (size_t)buffer->data;
503 }
504
505 static void binder_insert_free_buffer(struct binder_proc *proc,
506                                       struct binder_buffer *new_buffer)
507 {
508         struct rb_node **p = &proc->free_buffers.rb_node;
509         struct rb_node *parent = NULL;
510         struct binder_buffer *buffer;
511         size_t buffer_size;
512         size_t new_buffer_size;
513
514         BUG_ON(!new_buffer->free);
515
516         new_buffer_size = binder_buffer_size(proc, new_buffer);
517
518         binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
519                      "%d: add free buffer, size %zd, at %p\n",
520                       proc->pid, new_buffer_size, new_buffer);
521
522         while (*p) {
523                 parent = *p;
524                 buffer = rb_entry(parent, struct binder_buffer, rb_node);
525                 BUG_ON(!buffer->free);
526
527                 buffer_size = binder_buffer_size(proc, buffer);
528
529                 if (new_buffer_size < buffer_size)
530                         p = &parent->rb_left;
531                 else
532                         p = &parent->rb_right;
533         }
534         rb_link_node(&new_buffer->rb_node, parent, p);
535         rb_insert_color(&new_buffer->rb_node, &proc->free_buffers);
536 }
537
538 static void binder_insert_allocated_buffer(struct binder_proc *proc,
539                                            struct binder_buffer *new_buffer)
540 {
541         struct rb_node **p = &proc->allocated_buffers.rb_node;
542         struct rb_node *parent = NULL;
543         struct binder_buffer *buffer;
544
545         BUG_ON(new_buffer->free);
546
547         while (*p) {
548                 parent = *p;
549                 buffer = rb_entry(parent, struct binder_buffer, rb_node);
550                 BUG_ON(buffer->free);
551
552                 if (new_buffer < buffer)
553                         p = &parent->rb_left;
554                 else if (new_buffer > buffer)
555                         p = &parent->rb_right;
556                 else
557                         BUG();
558         }
559         rb_link_node(&new_buffer->rb_node, parent, p);
560         rb_insert_color(&new_buffer->rb_node, &proc->allocated_buffers);
561 }
562
563 static struct binder_buffer *binder_buffer_lookup(struct binder_proc *proc,
564                                                   uintptr_t user_ptr)
565 {
566         struct rb_node *n = proc->allocated_buffers.rb_node;
567         struct binder_buffer *buffer;
568         struct binder_buffer *kern_ptr;
569
570         kern_ptr = (struct binder_buffer *)(user_ptr - proc->user_buffer_offset
571                 - offsetof(struct binder_buffer, data));
572
573         while (n) {
574                 buffer = rb_entry(n, struct binder_buffer, rb_node);
575                 BUG_ON(buffer->free);
576
577                 if (kern_ptr < buffer)
578                         n = n->rb_left;
579                 else if (kern_ptr > buffer)
580                         n = n->rb_right;
581                 else
582                         return buffer;
583         }
584         return NULL;
585 }
586
587 static int binder_update_page_range(struct binder_proc *proc, int allocate,
588                                     void *start, void *end,
589                                     struct vm_area_struct *vma)
590 {
591         void *page_addr;
592         unsigned long user_page_addr;
593         struct page **page;
594         struct mm_struct *mm;
595
596         binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
597                      "%d: %s pages %p-%p\n", proc->pid,
598                      allocate ? "allocate" : "free", start, end);
599
600         if (end <= start)
601                 return 0;
602
603         trace_binder_update_page_range(proc, allocate, start, end);
604
605         if (vma)
606                 mm = NULL;
607         else
608                 mm = get_task_mm(proc->tsk);
609
610         if (mm) {
611                 down_write(&mm->mmap_sem);
612                 vma = proc->vma;
613                 if (vma && mm != proc->vma_vm_mm) {
614                         pr_err("%d: vma mm and task mm mismatch\n",
615                                 proc->pid);
616                         vma = NULL;
617                 }
618         }
619
620         if (allocate == 0)
621                 goto free_range;
622
623         if (vma == NULL) {
624                 pr_err("%d: binder_alloc_buf failed to map pages in userspace, no vma\n",
625                         proc->pid);
626                 goto err_no_vma;
627         }
628
629         for (page_addr = start; page_addr < end; page_addr += PAGE_SIZE) {
630                 int ret;
631
632                 page = &proc->pages[(page_addr - proc->buffer) / PAGE_SIZE];
633
634                 BUG_ON(*page);
635                 *page = alloc_page(GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO);
636                 if (*page == NULL) {
637                         pr_err("%d: binder_alloc_buf failed for page at %p\n",
638                                 proc->pid, page_addr);
639                         goto err_alloc_page_failed;
640                 }
641                 ret = map_kernel_range_noflush((unsigned long)page_addr,
642                                         PAGE_SIZE, PAGE_KERNEL, page);
643                 flush_cache_vmap((unsigned long)page_addr,
644                                 (unsigned long)page_addr + PAGE_SIZE);
645                 if (ret != 1) {
646                         pr_err("%d: binder_alloc_buf failed to map page at %p in kernel\n",
647                                proc->pid, page_addr);
648                         goto err_map_kernel_failed;
649                 }
650                 user_page_addr =
651                         (uintptr_t)page_addr + proc->user_buffer_offset;
652                 ret = vm_insert_page(vma, user_page_addr, page[0]);
653                 if (ret) {
654                         pr_err("%d: binder_alloc_buf failed to map page at %lx in userspace\n",
655                                proc->pid, user_page_addr);
656                         goto err_vm_insert_page_failed;
657                 }
658                 /* vm_insert_page does not seem to increment the refcount */
659         }
660         if (mm) {
661                 up_write(&mm->mmap_sem);
662                 mmput(mm);
663         }
664         return 0;
665
666 free_range:
667         for (page_addr = end - PAGE_SIZE; page_addr >= start;
668              page_addr -= PAGE_SIZE) {
669                 page = &proc->pages[(page_addr - proc->buffer) / PAGE_SIZE];
670                 if (vma)
671                         zap_page_range(vma, (uintptr_t)page_addr +
672                                 proc->user_buffer_offset, PAGE_SIZE, NULL);
673 err_vm_insert_page_failed:
674                 unmap_kernel_range((unsigned long)page_addr, PAGE_SIZE);
675 err_map_kernel_failed:
676                 __free_page(*page);
677                 *page = NULL;
678 err_alloc_page_failed:
679                 ;
680         }
681 err_no_vma:
682         if (mm) {
683                 up_write(&mm->mmap_sem);
684                 mmput(mm);
685         }
686         return -ENOMEM;
687 }
688
689 static struct binder_buffer *binder_alloc_buf(struct binder_proc *proc,
690                                               size_t data_size,
691                                               size_t offsets_size,
692                                               size_t extra_buffers_size,
693                                               int is_async)
694 {
695         struct rb_node *n = proc->free_buffers.rb_node;
696         struct binder_buffer *buffer;
697         size_t buffer_size;
698         struct rb_node *best_fit = NULL;
699         void *has_page_addr;
700         void *end_page_addr;
701         size_t size, data_offsets_size;
702
703         if (proc->vma == NULL) {
704                 pr_err("%d: binder_alloc_buf, no vma\n",
705                        proc->pid);
706                 return NULL;
707         }
708
709         data_offsets_size = ALIGN(data_size, sizeof(void *)) +
710                 ALIGN(offsets_size, sizeof(void *));
711
712         if (data_offsets_size < data_size || data_offsets_size < offsets_size) {
713                 binder_user_error("%d: got transaction with invalid size %zd-%zd\n",
714                                 proc->pid, data_size, offsets_size);
715                 return NULL;
716         }
717         size = data_offsets_size + ALIGN(extra_buffers_size, sizeof(void *));
718         if (size < data_offsets_size || size < extra_buffers_size) {
719                 binder_user_error("%d: got transaction with invalid extra_buffers_size %zd\n",
720                                   proc->pid, extra_buffers_size);
721                 return NULL;
722         }
723         if (is_async &&
724             proc->free_async_space < size + sizeof(struct binder_buffer)) {
725                 binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
726                              "%d: binder_alloc_buf size %zd failed, no async space left\n",
727                               proc->pid, size);
728                 return NULL;
729         }
730
731         while (n) {
732                 buffer = rb_entry(n, struct binder_buffer, rb_node);
733                 BUG_ON(!buffer->free);
734                 buffer_size = binder_buffer_size(proc, buffer);
735
736                 if (size < buffer_size) {
737                         best_fit = n;
738                         n = n->rb_left;
739                 } else if (size > buffer_size)
740                         n = n->rb_right;
741                 else {
742                         best_fit = n;
743                         break;
744                 }
745         }
746         if (best_fit == NULL) {
747                 pr_err("%d: binder_alloc_buf size %zd failed, no address space\n",
748                         proc->pid, size);
749                 return NULL;
750         }
751         if (n == NULL) {
752                 buffer = rb_entry(best_fit, struct binder_buffer, rb_node);
753                 buffer_size = binder_buffer_size(proc, buffer);
754         }
755
756         binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
757                      "%d: binder_alloc_buf size %zd got buffer %p size %zd\n",
758                       proc->pid, size, buffer, buffer_size);
759
760         has_page_addr =
761                 (void *)(((uintptr_t)buffer->data + buffer_size) & PAGE_MASK);
762         if (n == NULL) {
763                 if (size + sizeof(struct binder_buffer) + 4 >= buffer_size)
764                         buffer_size = size; /* no room for other buffers */
765                 else
766                         buffer_size = size + sizeof(struct binder_buffer);
767         }
768         end_page_addr =
769                 (void *)PAGE_ALIGN((uintptr_t)buffer->data + buffer_size);
770         if (end_page_addr > has_page_addr)
771                 end_page_addr = has_page_addr;
772         if (binder_update_page_range(proc, 1,
773             (void *)PAGE_ALIGN((uintptr_t)buffer->data), end_page_addr, NULL))
774                 return NULL;
775
776         rb_erase(best_fit, &proc->free_buffers);
777         buffer->free = 0;
778         binder_insert_allocated_buffer(proc, buffer);
779         if (buffer_size != size) {
780                 struct binder_buffer *new_buffer = (void *)buffer->data + size;
781
782                 list_add(&new_buffer->entry, &buffer->entry);
783                 new_buffer->free = 1;
784                 binder_insert_free_buffer(proc, new_buffer);
785         }
786         binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
787                      "%d: binder_alloc_buf size %zd got %p\n",
788                       proc->pid, size, buffer);
789         buffer->data_size = data_size;
790         buffer->offsets_size = offsets_size;
791         buffer->extra_buffers_size = extra_buffers_size;
792         buffer->async_transaction = is_async;
793         if (is_async) {
794                 proc->free_async_space -= size + sizeof(struct binder_buffer);
795                 binder_debug(BINDER_DEBUG_BUFFER_ALLOC_ASYNC,
796                              "%d: binder_alloc_buf size %zd async free %zd\n",
797                               proc->pid, size, proc->free_async_space);
798         }
799
800         return buffer;
801 }
802
803 static void *buffer_start_page(struct binder_buffer *buffer)
804 {
805         return (void *)((uintptr_t)buffer & PAGE_MASK);
806 }
807
808 static void *buffer_end_page(struct binder_buffer *buffer)
809 {
810         return (void *)(((uintptr_t)(buffer + 1) - 1) & PAGE_MASK);
811 }
812
813 static void binder_delete_free_buffer(struct binder_proc *proc,
814                                       struct binder_buffer *buffer)
815 {
816         struct binder_buffer *prev, *next = NULL;
817         int free_page_end = 1;
818         int free_page_start = 1;
819
820         BUG_ON(proc->buffers.next == &buffer->entry);
821         prev = list_entry(buffer->entry.prev, struct binder_buffer, entry);
822         BUG_ON(!prev->free);
823         if (buffer_end_page(prev) == buffer_start_page(buffer)) {
824                 free_page_start = 0;
825                 if (buffer_end_page(prev) == buffer_end_page(buffer))
826                         free_page_end = 0;
827                 binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
828                              "%d: merge free, buffer %p share page with %p\n",
829                               proc->pid, buffer, prev);
830         }
831
832         if (!list_is_last(&buffer->entry, &proc->buffers)) {
833                 next = list_entry(buffer->entry.next,
834                                   struct binder_buffer, entry);
835                 if (buffer_start_page(next) == buffer_end_page(buffer)) {
836                         free_page_end = 0;
837                         if (buffer_start_page(next) ==
838                             buffer_start_page(buffer))
839                                 free_page_start = 0;
840                         binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
841                                      "%d: merge free, buffer %p share page with %p\n",
842                                       proc->pid, buffer, prev);
843                 }
844         }
845         list_del(&buffer->entry);
846         if (free_page_start || free_page_end) {
847                 binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
848                              "%d: merge free, buffer %p do not share page%s%s with %p or %p\n",
849                              proc->pid, buffer, free_page_start ? "" : " end",
850                              free_page_end ? "" : " start", prev, next);
851                 binder_update_page_range(proc, 0, free_page_start ?
852                         buffer_start_page(buffer) : buffer_end_page(buffer),
853                         (free_page_end ? buffer_end_page(buffer) :
854                         buffer_start_page(buffer)) + PAGE_SIZE, NULL);
855         }
856 }
857
858 static void binder_free_buf(struct binder_proc *proc,
859                             struct binder_buffer *buffer)
860 {
861         size_t size, buffer_size;
862
863         buffer_size = binder_buffer_size(proc, buffer);
864
865         size = ALIGN(buffer->data_size, sizeof(void *)) +
866                 ALIGN(buffer->offsets_size, sizeof(void *)) +
867                 ALIGN(buffer->extra_buffers_size, sizeof(void *));
868
869         binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
870                      "%d: binder_free_buf %p size %zd buffer_size %zd\n",
871                       proc->pid, buffer, size, buffer_size);
872
873         BUG_ON(buffer->free);
874         BUG_ON(size > buffer_size);
875         BUG_ON(buffer->transaction != NULL);
876         BUG_ON((void *)buffer < proc->buffer);
877         BUG_ON((void *)buffer > proc->buffer + proc->buffer_size);
878
879         if (buffer->async_transaction) {
880                 proc->free_async_space += size + sizeof(struct binder_buffer);
881
882                 binder_debug(BINDER_DEBUG_BUFFER_ALLOC_ASYNC,
883                              "%d: binder_free_buf size %zd async free %zd\n",
884                               proc->pid, size, proc->free_async_space);
885         }
886
887         binder_update_page_range(proc, 0,
888                 (void *)PAGE_ALIGN((uintptr_t)buffer->data),
889                 (void *)(((uintptr_t)buffer->data + buffer_size) & PAGE_MASK),
890                 NULL);
891         rb_erase(&buffer->rb_node, &proc->allocated_buffers);
892         buffer->free = 1;
893         if (!list_is_last(&buffer->entry, &proc->buffers)) {
894                 struct binder_buffer *next = list_entry(buffer->entry.next,
895                                                 struct binder_buffer, entry);
896
897                 if (next->free) {
898                         rb_erase(&next->rb_node, &proc->free_buffers);
899                         binder_delete_free_buffer(proc, next);
900                 }
901         }
902         if (proc->buffers.next != &buffer->entry) {
903                 struct binder_buffer *prev = list_entry(buffer->entry.prev,
904                                                 struct binder_buffer, entry);
905
906                 if (prev->free) {
907                         binder_delete_free_buffer(proc, buffer);
908                         rb_erase(&prev->rb_node, &proc->free_buffers);
909                         buffer = prev;
910                 }
911         }
912         binder_insert_free_buffer(proc, buffer);
913 }
914
915 static struct binder_node *binder_get_node(struct binder_proc *proc,
916                                            binder_uintptr_t ptr)
917 {
918         struct rb_node *n = proc->nodes.rb_node;
919         struct binder_node *node;
920
921         while (n) {
922                 node = rb_entry(n, struct binder_node, rb_node);
923
924                 if (ptr < node->ptr)
925                         n = n->rb_left;
926                 else if (ptr > node->ptr)
927                         n = n->rb_right;
928                 else
929                         return node;
930         }
931         return NULL;
932 }
933
934 static struct binder_node *binder_new_node(struct binder_proc *proc,
935                                            binder_uintptr_t ptr,
936                                            binder_uintptr_t cookie)
937 {
938         struct rb_node **p = &proc->nodes.rb_node;
939         struct rb_node *parent = NULL;
940         struct binder_node *node;
941
942         while (*p) {
943                 parent = *p;
944                 node = rb_entry(parent, struct binder_node, rb_node);
945
946                 if (ptr < node->ptr)
947                         p = &(*p)->rb_left;
948                 else if (ptr > node->ptr)
949                         p = &(*p)->rb_right;
950                 else
951                         return NULL;
952         }
953
954         node = kzalloc(sizeof(*node), GFP_KERNEL);
955         if (node == NULL)
956                 return NULL;
957         binder_stats_created(BINDER_STAT_NODE);
958         rb_link_node(&node->rb_node, parent, p);
959         rb_insert_color(&node->rb_node, &proc->nodes);
960         node->debug_id = atomic_inc_return(&binder_last_id);
961         node->proc = proc;
962         node->ptr = ptr;
963         node->cookie = cookie;
964         node->work.type = BINDER_WORK_NODE;
965         INIT_LIST_HEAD(&node->work.entry);
966         INIT_LIST_HEAD(&node->async_todo);
967         binder_debug(BINDER_DEBUG_INTERNAL_REFS,
968                      "%d:%d node %d u%016llx c%016llx created\n",
969                      proc->pid, current->pid, node->debug_id,
970                      (u64)node->ptr, (u64)node->cookie);
971         return node;
972 }
973
974 static int binder_inc_node(struct binder_node *node, int strong, int internal,
975                            struct list_head *target_list)
976 {
977         if (strong) {
978                 if (internal) {
979                         if (target_list == NULL &&
980                             node->internal_strong_refs == 0 &&
981                             !(node->proc &&
982                               node == node->proc->context->
983                                       binder_context_mgr_node &&
984                               node->has_strong_ref)) {
985                                 pr_err("invalid inc strong node for %d\n",
986                                         node->debug_id);
987                                 return -EINVAL;
988                         }
989                         node->internal_strong_refs++;
990                 } else
991                         node->local_strong_refs++;
992                 if (!node->has_strong_ref && target_list) {
993                         list_del_init(&node->work.entry);
994                         list_add_tail(&node->work.entry, target_list);
995                 }
996         } else {
997                 if (!internal)
998                         node->local_weak_refs++;
999                 if (!node->has_weak_ref && list_empty(&node->work.entry)) {
1000                         if (target_list == NULL) {
1001                                 pr_err("invalid inc weak node for %d\n",
1002                                         node->debug_id);
1003                                 return -EINVAL;
1004                         }
1005                         list_add_tail(&node->work.entry, target_list);
1006                 }
1007         }
1008         return 0;
1009 }
1010
1011 static int binder_dec_node(struct binder_node *node, int strong, int internal)
1012 {
1013         if (strong) {
1014                 if (internal)
1015                         node->internal_strong_refs--;
1016                 else
1017                         node->local_strong_refs--;
1018                 if (node->local_strong_refs || node->internal_strong_refs)
1019                         return 0;
1020         } else {
1021                 if (!internal)
1022                         node->local_weak_refs--;
1023                 if (node->local_weak_refs || !hlist_empty(&node->refs))
1024                         return 0;
1025         }
1026         if (node->proc && (node->has_strong_ref || node->has_weak_ref)) {
1027                 if (list_empty(&node->work.entry)) {
1028                         list_add_tail(&node->work.entry, &node->proc->todo);
1029                         wake_up_interruptible(&node->proc->wait);
1030                 }
1031         } else {
1032                 if (hlist_empty(&node->refs) && !node->local_strong_refs &&
1033                     !node->local_weak_refs) {
1034                         list_del_init(&node->work.entry);
1035                         if (node->proc) {
1036                                 rb_erase(&node->rb_node, &node->proc->nodes);
1037                                 binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1038                                              "refless node %d deleted\n",
1039                                              node->debug_id);
1040                         } else {
1041                                 hlist_del(&node->dead_node);
1042                                 binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1043                                              "dead node %d deleted\n",
1044                                              node->debug_id);
1045                         }
1046                         kfree(node);
1047                         binder_stats_deleted(BINDER_STAT_NODE);
1048                 }
1049         }
1050
1051         return 0;
1052 }
1053
1054
1055 static struct binder_ref *binder_get_ref(struct binder_proc *proc,
1056                                          u32 desc, bool need_strong_ref)
1057 {
1058         struct rb_node *n = proc->refs_by_desc.rb_node;
1059         struct binder_ref *ref;
1060
1061         while (n) {
1062                 ref = rb_entry(n, struct binder_ref, rb_node_desc);
1063
1064                 if (desc < ref->desc) {
1065                         n = n->rb_left;
1066                 } else if (desc > ref->desc) {
1067                         n = n->rb_right;
1068                 } else if (need_strong_ref && !ref->strong) {
1069                         binder_user_error("tried to use weak ref as strong ref\n");
1070                         return NULL;
1071                 } else {
1072                         return ref;
1073                 }
1074         }
1075         return NULL;
1076 }
1077
1078 static struct binder_ref *binder_get_ref_for_node(struct binder_proc *proc,
1079                                                   struct binder_node *node)
1080 {
1081         struct rb_node *n;
1082         struct rb_node **p = &proc->refs_by_node.rb_node;
1083         struct rb_node *parent = NULL;
1084         struct binder_ref *ref, *new_ref;
1085         struct binder_context *context = proc->context;
1086
1087         while (*p) {
1088                 parent = *p;
1089                 ref = rb_entry(parent, struct binder_ref, rb_node_node);
1090
1091                 if (node < ref->node)
1092                         p = &(*p)->rb_left;
1093                 else if (node > ref->node)
1094                         p = &(*p)->rb_right;
1095                 else
1096                         return ref;
1097         }
1098         new_ref = kzalloc(sizeof(*ref), GFP_KERNEL);
1099         if (new_ref == NULL)
1100                 return NULL;
1101         binder_stats_created(BINDER_STAT_REF);
1102         new_ref->debug_id = atomic_inc_return(&binder_last_id);
1103         new_ref->proc = proc;
1104         new_ref->node = node;
1105         rb_link_node(&new_ref->rb_node_node, parent, p);
1106         rb_insert_color(&new_ref->rb_node_node, &proc->refs_by_node);
1107
1108         new_ref->desc = (node == context->binder_context_mgr_node) ? 0 : 1;
1109         for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {
1110                 ref = rb_entry(n, struct binder_ref, rb_node_desc);
1111                 if (ref->desc > new_ref->desc)
1112                         break;
1113                 new_ref->desc = ref->desc + 1;
1114         }
1115
1116         p = &proc->refs_by_desc.rb_node;
1117         while (*p) {
1118                 parent = *p;
1119                 ref = rb_entry(parent, struct binder_ref, rb_node_desc);
1120
1121                 if (new_ref->desc < ref->desc)
1122                         p = &(*p)->rb_left;
1123                 else if (new_ref->desc > ref->desc)
1124                         p = &(*p)->rb_right;
1125                 else
1126                         BUG();
1127         }
1128         rb_link_node(&new_ref->rb_node_desc, parent, p);
1129         rb_insert_color(&new_ref->rb_node_desc, &proc->refs_by_desc);
1130         if (node) {
1131                 hlist_add_head(&new_ref->node_entry, &node->refs);
1132
1133                 binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1134                              "%d new ref %d desc %d for node %d\n",
1135                               proc->pid, new_ref->debug_id, new_ref->desc,
1136                               node->debug_id);
1137         } else {
1138                 binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1139                              "%d new ref %d desc %d for dead node\n",
1140                               proc->pid, new_ref->debug_id, new_ref->desc);
1141         }
1142         return new_ref;
1143 }
1144
1145 static void binder_delete_ref(struct binder_ref *ref)
1146 {
1147         binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1148                      "%d delete ref %d desc %d for node %d\n",
1149                       ref->proc->pid, ref->debug_id, ref->desc,
1150                       ref->node->debug_id);
1151
1152         rb_erase(&ref->rb_node_desc, &ref->proc->refs_by_desc);
1153         rb_erase(&ref->rb_node_node, &ref->proc->refs_by_node);
1154         if (ref->strong)
1155                 binder_dec_node(ref->node, 1, 1);
1156         hlist_del(&ref->node_entry);
1157         binder_dec_node(ref->node, 0, 1);
1158         if (ref->death) {
1159                 binder_debug(BINDER_DEBUG_DEAD_BINDER,
1160                              "%d delete ref %d desc %d has death notification\n",
1161                               ref->proc->pid, ref->debug_id, ref->desc);
1162                 list_del(&ref->death->work.entry);
1163                 kfree(ref->death);
1164                 binder_stats_deleted(BINDER_STAT_DEATH);
1165         }
1166         kfree(ref);
1167         binder_stats_deleted(BINDER_STAT_REF);
1168 }
1169
1170 static int binder_inc_ref(struct binder_ref *ref, int strong,
1171                           struct list_head *target_list)
1172 {
1173         int ret;
1174
1175         if (strong) {
1176                 if (ref->strong == 0) {
1177                         ret = binder_inc_node(ref->node, 1, 1, target_list);
1178                         if (ret)
1179                                 return ret;
1180                 }
1181                 ref->strong++;
1182         } else {
1183                 if (ref->weak == 0) {
1184                         ret = binder_inc_node(ref->node, 0, 1, target_list);
1185                         if (ret)
1186                                 return ret;
1187                 }
1188                 ref->weak++;
1189         }
1190         return 0;
1191 }
1192
1193
1194 static int binder_dec_ref(struct binder_ref *ref, int strong)
1195 {
1196         if (strong) {
1197                 if (ref->strong == 0) {
1198                         binder_user_error("%d invalid dec strong, ref %d desc %d s %d w %d\n",
1199                                           ref->proc->pid, ref->debug_id,
1200                                           ref->desc, ref->strong, ref->weak);
1201                         return -EINVAL;
1202                 }
1203                 ref->strong--;
1204                 if (ref->strong == 0) {
1205                         int ret;
1206
1207                         ret = binder_dec_node(ref->node, strong, 1);
1208                         if (ret)
1209                                 return ret;
1210                 }
1211         } else {
1212                 if (ref->weak == 0) {
1213                         binder_user_error("%d invalid dec weak, ref %d desc %d s %d w %d\n",
1214                                           ref->proc->pid, ref->debug_id,
1215                                           ref->desc, ref->strong, ref->weak);
1216                         return -EINVAL;
1217                 }
1218                 ref->weak--;
1219         }
1220         if (ref->strong == 0 && ref->weak == 0)
1221                 binder_delete_ref(ref);
1222         return 0;
1223 }
1224
1225 static void binder_pop_transaction(struct binder_thread *target_thread,
1226                                    struct binder_transaction *t)
1227 {
1228         if (target_thread) {
1229                 BUG_ON(target_thread->transaction_stack != t);
1230                 BUG_ON(target_thread->transaction_stack->from != target_thread);
1231                 target_thread->transaction_stack =
1232                         target_thread->transaction_stack->from_parent;
1233                 t->from = NULL;
1234         }
1235         t->need_reply = 0;
1236         if (t->buffer)
1237                 t->buffer->transaction = NULL;
1238         kfree(t);
1239         binder_stats_deleted(BINDER_STAT_TRANSACTION);
1240 }
1241
1242 static void binder_send_failed_reply(struct binder_transaction *t,
1243                                      uint32_t error_code)
1244 {
1245         struct binder_thread *target_thread;
1246         struct binder_transaction *next;
1247
1248         BUG_ON(t->flags & TF_ONE_WAY);
1249         while (1) {
1250                 target_thread = t->from;
1251                 if (target_thread) {
1252                         if (target_thread->return_error != BR_OK &&
1253                            target_thread->return_error2 == BR_OK) {
1254                                 target_thread->return_error2 =
1255                                         target_thread->return_error;
1256                                 target_thread->return_error = BR_OK;
1257                         }
1258                         if (target_thread->return_error == BR_OK) {
1259                                 binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
1260                                              "send failed reply for transaction %d to %d:%d\n",
1261                                               t->debug_id,
1262                                               target_thread->proc->pid,
1263                                               target_thread->pid);
1264
1265                                 binder_pop_transaction(target_thread, t);
1266                                 target_thread->return_error = error_code;
1267                                 wake_up_interruptible(&target_thread->wait);
1268                         } else {
1269                                 pr_err("reply failed, target thread, %d:%d, has error code %d already\n",
1270                                         target_thread->proc->pid,
1271                                         target_thread->pid,
1272                                         target_thread->return_error);
1273                         }
1274                         return;
1275                 }
1276                 next = t->from_parent;
1277
1278                 binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
1279                              "send failed reply for transaction %d, target dead\n",
1280                              t->debug_id);
1281
1282                 binder_pop_transaction(target_thread, t);
1283                 if (next == NULL) {
1284                         binder_debug(BINDER_DEBUG_DEAD_BINDER,
1285                                      "reply failed, no target thread at root\n");
1286                         return;
1287                 }
1288                 t = next;
1289                 binder_debug(BINDER_DEBUG_DEAD_BINDER,
1290                              "reply failed, no target thread -- retry %d\n",
1291                               t->debug_id);
1292         }
1293 }
1294
1295 /**
1296  * binder_validate_object() - checks for a valid metadata object in a buffer.
1297  * @buffer:     binder_buffer that we're parsing.
1298  * @offset:     offset in the buffer at which to validate an object.
1299  *
1300  * Return:      If there's a valid metadata object at @offset in @buffer, the
1301  *              size of that object. Otherwise, it returns zero.
1302  */
1303 static size_t binder_validate_object(struct binder_buffer *buffer, u64 offset)
1304 {
1305         /* Check if we can read a header first */
1306         struct binder_object_header *hdr;
1307         size_t object_size = 0;
1308
1309         if (offset > buffer->data_size - sizeof(*hdr) ||
1310             buffer->data_size < sizeof(*hdr) ||
1311             !IS_ALIGNED(offset, sizeof(u32)))
1312                 return 0;
1313
1314         /* Ok, now see if we can read a complete object. */
1315         hdr = (struct binder_object_header *)(buffer->data + offset);
1316         switch (hdr->type) {
1317         case BINDER_TYPE_BINDER:
1318         case BINDER_TYPE_WEAK_BINDER:
1319         case BINDER_TYPE_HANDLE:
1320         case BINDER_TYPE_WEAK_HANDLE:
1321                 object_size = sizeof(struct flat_binder_object);
1322                 break;
1323         case BINDER_TYPE_FD:
1324                 object_size = sizeof(struct binder_fd_object);
1325                 break;
1326         case BINDER_TYPE_PTR:
1327                 object_size = sizeof(struct binder_buffer_object);
1328                 break;
1329         case BINDER_TYPE_FDA:
1330                 object_size = sizeof(struct binder_fd_array_object);
1331                 break;
1332         default:
1333                 return 0;
1334         }
1335         if (offset <= buffer->data_size - object_size &&
1336             buffer->data_size >= object_size)
1337                 return object_size;
1338         else
1339                 return 0;
1340 }
1341
1342 /**
1343  * binder_validate_ptr() - validates binder_buffer_object in a binder_buffer.
1344  * @b:          binder_buffer containing the object
1345  * @index:      index in offset array at which the binder_buffer_object is
1346  *              located
1347  * @start:      points to the start of the offset array
1348  * @num_valid:  the number of valid offsets in the offset array
1349  *
1350  * Return:      If @index is within the valid range of the offset array
1351  *              described by @start and @num_valid, and if there's a valid
1352  *              binder_buffer_object at the offset found in index @index
1353  *              of the offset array, that object is returned. Otherwise,
1354  *              %NULL is returned.
1355  *              Note that the offset found in index @index itself is not
1356  *              verified; this function assumes that @num_valid elements
1357  *              from @start were previously verified to have valid offsets.
1358  */
1359 static struct binder_buffer_object *binder_validate_ptr(struct binder_buffer *b,
1360                                                         binder_size_t index,
1361                                                         binder_size_t *start,
1362                                                         binder_size_t num_valid)
1363 {
1364         struct binder_buffer_object *buffer_obj;
1365         binder_size_t *offp;
1366
1367         if (index >= num_valid)
1368                 return NULL;
1369
1370         offp = start + index;
1371         buffer_obj = (struct binder_buffer_object *)(b->data + *offp);
1372         if (buffer_obj->hdr.type != BINDER_TYPE_PTR)
1373                 return NULL;
1374
1375         return buffer_obj;
1376 }
1377
1378 /**
1379  * binder_validate_fixup() - validates pointer/fd fixups happen in order.
1380  * @b:                  transaction buffer
1381  * @objects_start       start of objects buffer
1382  * @buffer:             binder_buffer_object in which to fix up
1383  * @offset:             start offset in @buffer to fix up
1384  * @last_obj:           last binder_buffer_object that we fixed up in
1385  * @last_min_offset:    minimum fixup offset in @last_obj
1386  *
1387  * Return:              %true if a fixup in buffer @buffer at offset @offset is
1388  *                      allowed.
1389  *
1390  * For safety reasons, we only allow fixups inside a buffer to happen
1391  * at increasing offsets; additionally, we only allow fixup on the last
1392  * buffer object that was verified, or one of its parents.
1393  *
1394  * Example of what is allowed:
1395  *
1396  * A
1397  *   B (parent = A, offset = 0)
1398  *   C (parent = A, offset = 16)
1399  *     D (parent = C, offset = 0)
1400  *   E (parent = A, offset = 32) // min_offset is 16 (C.parent_offset)
1401  *
1402  * Examples of what is not allowed:
1403  *
1404  * Decreasing offsets within the same parent:
1405  * A
1406  *   C (parent = A, offset = 16)
1407  *   B (parent = A, offset = 0) // decreasing offset within A
1408  *
1409  * Referring to a parent that wasn't the last object or any of its parents:
1410  * A
1411  *   B (parent = A, offset = 0)
1412  *   C (parent = A, offset = 0)
1413  *   C (parent = A, offset = 16)
1414  *     D (parent = B, offset = 0) // B is not A or any of A's parents
1415  */
1416 static bool binder_validate_fixup(struct binder_buffer *b,
1417                                   binder_size_t *objects_start,
1418                                   struct binder_buffer_object *buffer,
1419                                   binder_size_t fixup_offset,
1420                                   struct binder_buffer_object *last_obj,
1421                                   binder_size_t last_min_offset)
1422 {
1423         if (!last_obj) {
1424                 /* Nothing to fix up in */
1425                 return false;
1426         }
1427
1428         while (last_obj != buffer) {
1429                 /*
1430                  * Safe to retrieve the parent of last_obj, since it
1431                  * was already previously verified by the driver.
1432                  */
1433                 if ((last_obj->flags & BINDER_BUFFER_FLAG_HAS_PARENT) == 0)
1434                         return false;
1435                 last_min_offset = last_obj->parent_offset + sizeof(uintptr_t);
1436                 last_obj = (struct binder_buffer_object *)
1437                         (b->data + *(objects_start + last_obj->parent));
1438         }
1439         return (fixup_offset >= last_min_offset);
1440 }
1441
1442 static void binder_transaction_buffer_release(struct binder_proc *proc,
1443                                               struct binder_buffer *buffer,
1444                                               binder_size_t *failed_at)
1445 {
1446         binder_size_t *offp, *off_start, *off_end;
1447         int debug_id = buffer->debug_id;
1448
1449         binder_debug(BINDER_DEBUG_TRANSACTION,
1450                      "%d buffer release %d, size %zd-%zd, failed at %p\n",
1451                      proc->pid, buffer->debug_id,
1452                      buffer->data_size, buffer->offsets_size, failed_at);
1453
1454         if (buffer->target_node)
1455                 binder_dec_node(buffer->target_node, 1, 0);
1456
1457         off_start = (binder_size_t *)(buffer->data +
1458                                       ALIGN(buffer->data_size, sizeof(void *)));
1459         if (failed_at)
1460                 off_end = failed_at;
1461         else
1462                 off_end = (void *)off_start + buffer->offsets_size;
1463         for (offp = off_start; offp < off_end; offp++) {
1464                 struct binder_object_header *hdr;
1465                 size_t object_size = binder_validate_object(buffer, *offp);
1466
1467                 if (object_size == 0) {
1468                         pr_err("transaction release %d bad object at offset %lld, size %zd\n",
1469                                debug_id, (u64)*offp, buffer->data_size);
1470                         continue;
1471                 }
1472                 hdr = (struct binder_object_header *)(buffer->data + *offp);
1473                 switch (hdr->type) {
1474                 case BINDER_TYPE_BINDER:
1475                 case BINDER_TYPE_WEAK_BINDER: {
1476                         struct flat_binder_object *fp;
1477                         struct binder_node *node;
1478
1479                         fp = to_flat_binder_object(hdr);
1480                         node = binder_get_node(proc, fp->binder);
1481                         if (node == NULL) {
1482                                 pr_err("transaction release %d bad node %016llx\n",
1483                                        debug_id, (u64)fp->binder);
1484                                 break;
1485                         }
1486                         binder_debug(BINDER_DEBUG_TRANSACTION,
1487                                      "        node %d u%016llx\n",
1488                                      node->debug_id, (u64)node->ptr);
1489                         binder_dec_node(node, hdr->type == BINDER_TYPE_BINDER,
1490                                         0);
1491                 } break;
1492                 case BINDER_TYPE_HANDLE:
1493                 case BINDER_TYPE_WEAK_HANDLE: {
1494                         struct flat_binder_object *fp;
1495                         struct binder_ref *ref;
1496
1497                         fp = to_flat_binder_object(hdr);
1498                         ref = binder_get_ref(proc, fp->handle,
1499                                              hdr->type == BINDER_TYPE_HANDLE);
1500                         if (ref == NULL) {
1501                                 pr_err("transaction release %d bad handle %d\n",
1502                                  debug_id, fp->handle);
1503                                 break;
1504                         }
1505                         binder_debug(BINDER_DEBUG_TRANSACTION,
1506                                      "        ref %d desc %d (node %d)\n",
1507                                      ref->debug_id, ref->desc, ref->node->debug_id);
1508                         binder_dec_ref(ref, hdr->type == BINDER_TYPE_HANDLE);
1509                 } break;
1510
1511                 case BINDER_TYPE_FD: {
1512                         struct binder_fd_object *fp = to_binder_fd_object(hdr);
1513
1514                         binder_debug(BINDER_DEBUG_TRANSACTION,
1515                                      "        fd %d\n", fp->fd);
1516                         if (failed_at)
1517                                 task_close_fd(proc, fp->fd);
1518                 } break;
1519                 case BINDER_TYPE_PTR:
1520                         /*
1521                          * Nothing to do here, this will get cleaned up when the
1522                          * transaction buffer gets freed
1523                          */
1524                         break;
1525                 case BINDER_TYPE_FDA: {
1526                         struct binder_fd_array_object *fda;
1527                         struct binder_buffer_object *parent;
1528                         uintptr_t parent_buffer;
1529                         u32 *fd_array;
1530                         size_t fd_index;
1531                         binder_size_t fd_buf_size;
1532
1533                         fda = to_binder_fd_array_object(hdr);
1534                         parent = binder_validate_ptr(buffer, fda->parent,
1535                                                      off_start,
1536                                                      offp - off_start);
1537                         if (!parent) {
1538                                 pr_err("transaction release %d bad parent offset",
1539                                        debug_id);
1540                                 continue;
1541                         }
1542                         /*
1543                          * Since the parent was already fixed up, convert it
1544                          * back to kernel address space to access it
1545                          */
1546                         parent_buffer = parent->buffer -
1547                                 proc->user_buffer_offset;
1548
1549                         fd_buf_size = sizeof(u32) * fda->num_fds;
1550                         if (fda->num_fds >= SIZE_MAX / sizeof(u32)) {
1551                                 pr_err("transaction release %d invalid number of fds (%lld)\n",
1552                                        debug_id, (u64)fda->num_fds);
1553                                 continue;
1554                         }
1555                         if (fd_buf_size > parent->length ||
1556                             fda->parent_offset > parent->length - fd_buf_size) {
1557                                 /* No space for all file descriptors here. */
1558                                 pr_err("transaction release %d not enough space for %lld fds in buffer\n",
1559                                        debug_id, (u64)fda->num_fds);
1560                                 continue;
1561                         }
1562                         fd_array = (u32 *)(parent_buffer + fda->parent_offset);
1563                         for (fd_index = 0; fd_index < fda->num_fds; fd_index++)
1564                                 task_close_fd(proc, fd_array[fd_index]);
1565                 } break;
1566                 default:
1567                         pr_err("transaction release %d bad object type %x\n",
1568                                 debug_id, hdr->type);
1569                         break;
1570                 }
1571         }
1572 }
1573
1574 static int binder_translate_binder(struct flat_binder_object *fp,
1575                                    struct binder_transaction *t,
1576                                    struct binder_thread *thread)
1577 {
1578         struct binder_node *node;
1579         struct binder_ref *ref;
1580         struct binder_proc *proc = thread->proc;
1581         struct binder_proc *target_proc = t->to_proc;
1582
1583         node = binder_get_node(proc, fp->binder);
1584         if (!node) {
1585                 node = binder_new_node(proc, fp->binder, fp->cookie);
1586                 if (!node)
1587                         return -ENOMEM;
1588
1589                 node->min_priority = fp->flags & FLAT_BINDER_FLAG_PRIORITY_MASK;
1590                 node->accept_fds = !!(fp->flags & FLAT_BINDER_FLAG_ACCEPTS_FDS);
1591         }
1592         if (fp->cookie != node->cookie) {
1593                 binder_user_error("%d:%d sending u%016llx node %d, cookie mismatch %016llx != %016llx\n",
1594                                   proc->pid, thread->pid, (u64)fp->binder,
1595                                   node->debug_id, (u64)fp->cookie,
1596                                   (u64)node->cookie);
1597                 return -EINVAL;
1598         }
1599         if (security_binder_transfer_binder(proc->tsk, target_proc->tsk))
1600                 return -EPERM;
1601
1602         ref = binder_get_ref_for_node(target_proc, node);
1603         if (!ref)
1604                 return -EINVAL;
1605
1606         if (fp->hdr.type == BINDER_TYPE_BINDER)
1607                 fp->hdr.type = BINDER_TYPE_HANDLE;
1608         else
1609                 fp->hdr.type = BINDER_TYPE_WEAK_HANDLE;
1610         fp->binder = 0;
1611         fp->handle = ref->desc;
1612         fp->cookie = 0;
1613         binder_inc_ref(ref, fp->hdr.type == BINDER_TYPE_HANDLE, &thread->todo);
1614
1615         trace_binder_transaction_node_to_ref(t, node, ref);
1616         binder_debug(BINDER_DEBUG_TRANSACTION,
1617                      "        node %d u%016llx -> ref %d desc %d\n",
1618                      node->debug_id, (u64)node->ptr,
1619                      ref->debug_id, ref->desc);
1620
1621         return 0;
1622 }
1623
1624 static int binder_translate_handle(struct flat_binder_object *fp,
1625                                    struct binder_transaction *t,
1626                                    struct binder_thread *thread)
1627 {
1628         struct binder_ref *ref;
1629         struct binder_proc *proc = thread->proc;
1630         struct binder_proc *target_proc = t->to_proc;
1631
1632         ref = binder_get_ref(proc, fp->handle,
1633                              fp->hdr.type == BINDER_TYPE_HANDLE);
1634         if (!ref) {
1635                 binder_user_error("%d:%d got transaction with invalid handle, %d\n",
1636                                   proc->pid, thread->pid, fp->handle);
1637                 return -EINVAL;
1638         }
1639         if (security_binder_transfer_binder(proc->tsk, target_proc->tsk))
1640                 return -EPERM;
1641
1642         if (ref->node->proc == target_proc) {
1643                 if (fp->hdr.type == BINDER_TYPE_HANDLE)
1644                         fp->hdr.type = BINDER_TYPE_BINDER;
1645                 else
1646                         fp->hdr.type = BINDER_TYPE_WEAK_BINDER;
1647                 fp->binder = ref->node->ptr;
1648                 fp->cookie = ref->node->cookie;
1649                 binder_inc_node(ref->node, fp->hdr.type == BINDER_TYPE_BINDER,
1650                                 0, NULL);
1651                 trace_binder_transaction_ref_to_node(t, ref);
1652                 binder_debug(BINDER_DEBUG_TRANSACTION,
1653                              "        ref %d desc %d -> node %d u%016llx\n",
1654                              ref->debug_id, ref->desc, ref->node->debug_id,
1655                              (u64)ref->node->ptr);
1656         } else {
1657                 struct binder_ref *new_ref;
1658
1659                 new_ref = binder_get_ref_for_node(target_proc, ref->node);
1660                 if (!new_ref)
1661                         return -EINVAL;
1662
1663                 fp->binder = 0;
1664                 fp->handle = new_ref->desc;
1665                 fp->cookie = 0;
1666                 binder_inc_ref(new_ref, fp->hdr.type == BINDER_TYPE_HANDLE,
1667                                NULL);
1668                 trace_binder_transaction_ref_to_ref(t, ref, new_ref);
1669                 binder_debug(BINDER_DEBUG_TRANSACTION,
1670                              "        ref %d desc %d -> ref %d desc %d (node %d)\n",
1671                              ref->debug_id, ref->desc, new_ref->debug_id,
1672                              new_ref->desc, ref->node->debug_id);
1673         }
1674         return 0;
1675 }
1676
1677 static int binder_translate_fd(int fd,
1678                                struct binder_transaction *t,
1679                                struct binder_thread *thread,
1680                                struct binder_transaction *in_reply_to)
1681 {
1682         struct binder_proc *proc = thread->proc;
1683         struct binder_proc *target_proc = t->to_proc;
1684         int target_fd;
1685         struct file *file;
1686         int ret;
1687         bool target_allows_fd;
1688
1689         if (in_reply_to)
1690                 target_allows_fd = !!(in_reply_to->flags & TF_ACCEPT_FDS);
1691         else
1692                 target_allows_fd = t->buffer->target_node->accept_fds;
1693         if (!target_allows_fd) {
1694                 binder_user_error("%d:%d got %s with fd, %d, but target does not allow fds\n",
1695                                   proc->pid, thread->pid,
1696                                   in_reply_to ? "reply" : "transaction",
1697                                   fd);
1698                 ret = -EPERM;
1699                 goto err_fd_not_accepted;
1700         }
1701
1702         file = fget(fd);
1703         if (!file) {
1704                 binder_user_error("%d:%d got transaction with invalid fd, %d\n",
1705                                   proc->pid, thread->pid, fd);
1706                 ret = -EBADF;
1707                 goto err_fget;
1708         }
1709         ret = security_binder_transfer_file(proc->tsk, target_proc->tsk, file);
1710         if (ret < 0) {
1711                 ret = -EPERM;
1712                 goto err_security;
1713         }
1714
1715         target_fd = task_get_unused_fd_flags(target_proc, O_CLOEXEC);
1716         if (target_fd < 0) {
1717                 ret = -ENOMEM;
1718                 goto err_get_unused_fd;
1719         }
1720         task_fd_install(target_proc, target_fd, file);
1721         trace_binder_transaction_fd(t, fd, target_fd);
1722         binder_debug(BINDER_DEBUG_TRANSACTION, "        fd %d -> %d\n",
1723                      fd, target_fd);
1724
1725         return target_fd;
1726
1727 err_get_unused_fd:
1728 err_security:
1729         fput(file);
1730 err_fget:
1731 err_fd_not_accepted:
1732         return ret;
1733 }
1734
1735 static int binder_translate_fd_array(struct binder_fd_array_object *fda,
1736                                      struct binder_buffer_object *parent,
1737                                      struct binder_transaction *t,
1738                                      struct binder_thread *thread,
1739                                      struct binder_transaction *in_reply_to)
1740 {
1741         binder_size_t fdi, fd_buf_size, num_installed_fds;
1742         int target_fd;
1743         uintptr_t parent_buffer;
1744         u32 *fd_array;
1745         struct binder_proc *proc = thread->proc;
1746         struct binder_proc *target_proc = t->to_proc;
1747
1748         fd_buf_size = sizeof(u32) * fda->num_fds;
1749         if (fda->num_fds >= SIZE_MAX / sizeof(u32)) {
1750                 binder_user_error("%d:%d got transaction with invalid number of fds (%lld)\n",
1751                                   proc->pid, thread->pid, (u64)fda->num_fds);
1752                 return -EINVAL;
1753         }
1754         if (fd_buf_size > parent->length ||
1755             fda->parent_offset > parent->length - fd_buf_size) {
1756                 /* No space for all file descriptors here. */
1757                 binder_user_error("%d:%d not enough space to store %lld fds in buffer\n",
1758                                   proc->pid, thread->pid, (u64)fda->num_fds);
1759                 return -EINVAL;
1760         }
1761         /*
1762          * Since the parent was already fixed up, convert it
1763          * back to the kernel address space to access it
1764          */
1765         parent_buffer = parent->buffer - target_proc->user_buffer_offset;
1766         fd_array = (u32 *)(parent_buffer + fda->parent_offset);
1767         if (!IS_ALIGNED((unsigned long)fd_array, sizeof(u32))) {
1768                 binder_user_error("%d:%d parent offset not aligned correctly.\n",
1769                                   proc->pid, thread->pid);
1770                 return -EINVAL;
1771         }
1772         for (fdi = 0; fdi < fda->num_fds; fdi++) {
1773                 target_fd = binder_translate_fd(fd_array[fdi], t, thread,
1774                                                 in_reply_to);
1775                 if (target_fd < 0)
1776                         goto err_translate_fd_failed;
1777                 fd_array[fdi] = target_fd;
1778         }
1779         return 0;
1780
1781 err_translate_fd_failed:
1782         /*
1783          * Failed to allocate fd or security error, free fds
1784          * installed so far.
1785          */
1786         num_installed_fds = fdi;
1787         for (fdi = 0; fdi < num_installed_fds; fdi++)
1788                 task_close_fd(target_proc, fd_array[fdi]);
1789         return target_fd;
1790 }
1791
1792 static int binder_fixup_parent(struct binder_transaction *t,
1793                                struct binder_thread *thread,
1794                                struct binder_buffer_object *bp,
1795                                binder_size_t *off_start,
1796                                binder_size_t num_valid,
1797                                struct binder_buffer_object *last_fixup_obj,
1798                                binder_size_t last_fixup_min_off)
1799 {
1800         struct binder_buffer_object *parent;
1801         u8 *parent_buffer;
1802         struct binder_buffer *b = t->buffer;
1803         struct binder_proc *proc = thread->proc;
1804         struct binder_proc *target_proc = t->to_proc;
1805
1806         if (!(bp->flags & BINDER_BUFFER_FLAG_HAS_PARENT))
1807                 return 0;
1808
1809         parent = binder_validate_ptr(b, bp->parent, off_start, num_valid);
1810         if (!parent) {
1811                 binder_user_error("%d:%d got transaction with invalid parent offset or type\n",
1812                                   proc->pid, thread->pid);
1813                 return -EINVAL;
1814         }
1815
1816         if (!binder_validate_fixup(b, off_start,
1817                                    parent, bp->parent_offset,
1818                                    last_fixup_obj,
1819                                    last_fixup_min_off)) {
1820                 binder_user_error("%d:%d got transaction with out-of-order buffer fixup\n",
1821                                   proc->pid, thread->pid);
1822                 return -EINVAL;
1823         }
1824
1825         if (parent->length < sizeof(binder_uintptr_t) ||
1826             bp->parent_offset > parent->length - sizeof(binder_uintptr_t)) {
1827                 /* No space for a pointer here! */
1828                 binder_user_error("%d:%d got transaction with invalid parent offset\n",
1829                                   proc->pid, thread->pid);
1830                 return -EINVAL;
1831         }
1832         parent_buffer = (u8 *)(parent->buffer -
1833                                target_proc->user_buffer_offset);
1834         *(binder_uintptr_t *)(parent_buffer + bp->parent_offset) = bp->buffer;
1835
1836         return 0;
1837 }
1838
1839 static void binder_transaction(struct binder_proc *proc,
1840                                struct binder_thread *thread,
1841                                struct binder_transaction_data *tr, int reply,
1842                                binder_size_t extra_buffers_size)
1843 {
1844         int ret;
1845         struct binder_transaction *t;
1846         struct binder_work *tcomplete;
1847         binder_size_t *offp, *off_end, *off_start;
1848         binder_size_t off_min;
1849         u8 *sg_bufp, *sg_buf_end;
1850         struct binder_proc *target_proc;
1851         struct binder_thread *target_thread = NULL;
1852         struct binder_node *target_node = NULL;
1853         struct list_head *target_list;
1854         wait_queue_head_t *target_wait;
1855         struct binder_transaction *in_reply_to = NULL;
1856         struct binder_transaction_log_entry *e;
1857         uint32_t return_error;
1858         struct binder_buffer_object *last_fixup_obj = NULL;
1859         binder_size_t last_fixup_min_off = 0;
1860         struct binder_context *context = proc->context;
1861
1862         e = binder_transaction_log_add(&context->transaction_log);
1863         e->call_type = reply ? 2 : !!(tr->flags & TF_ONE_WAY);
1864         e->from_proc = proc->pid;
1865         e->from_thread = thread->pid;
1866         e->target_handle = tr->target.handle;
1867         e->data_size = tr->data_size;
1868         e->offsets_size = tr->offsets_size;
1869         e->context_name = proc->context->name;
1870
1871         if (reply) {
1872                 in_reply_to = thread->transaction_stack;
1873                 if (in_reply_to == NULL) {
1874                         binder_user_error("%d:%d got reply transaction with no transaction stack\n",
1875                                           proc->pid, thread->pid);
1876                         return_error = BR_FAILED_REPLY;
1877                         goto err_empty_call_stack;
1878                 }
1879                 binder_set_nice(in_reply_to->saved_priority);
1880                 if (in_reply_to->to_thread != thread) {
1881                         binder_user_error("%d:%d got reply transaction with bad transaction stack, transaction %d has target %d:%d\n",
1882                                 proc->pid, thread->pid, in_reply_to->debug_id,
1883                                 in_reply_to->to_proc ?
1884                                 in_reply_to->to_proc->pid : 0,
1885                                 in_reply_to->to_thread ?
1886                                 in_reply_to->to_thread->pid : 0);
1887                         return_error = BR_FAILED_REPLY;
1888                         in_reply_to = NULL;
1889                         goto err_bad_call_stack;
1890                 }
1891                 thread->transaction_stack = in_reply_to->to_parent;
1892                 target_thread = in_reply_to->from;
1893                 if (target_thread == NULL) {
1894                         return_error = BR_DEAD_REPLY;
1895                         goto err_dead_binder;
1896                 }
1897                 if (target_thread->transaction_stack != in_reply_to) {
1898                         binder_user_error("%d:%d got reply transaction with bad target transaction stack %d, expected %d\n",
1899                                 proc->pid, thread->pid,
1900                                 target_thread->transaction_stack ?
1901                                 target_thread->transaction_stack->debug_id : 0,
1902                                 in_reply_to->debug_id);
1903                         return_error = BR_FAILED_REPLY;
1904                         in_reply_to = NULL;
1905                         target_thread = NULL;
1906                         goto err_dead_binder;
1907                 }
1908                 target_proc = target_thread->proc;
1909         } else {
1910                 if (tr->target.handle) {
1911                         struct binder_ref *ref;
1912
1913                         ref = binder_get_ref(proc, tr->target.handle, true);
1914                         if (ref == NULL) {
1915                                 binder_user_error("%d:%d got transaction to invalid handle\n",
1916                                         proc->pid, thread->pid);
1917                                 return_error = BR_FAILED_REPLY;
1918                                 goto err_invalid_target_handle;
1919                         }
1920                         target_node = ref->node;
1921                 } else {
1922                         target_node = context->binder_context_mgr_node;
1923                         if (target_node == NULL) {
1924                                 return_error = BR_DEAD_REPLY;
1925                                 goto err_no_context_mgr_node;
1926                         }
1927                 }
1928                 e->to_node = target_node->debug_id;
1929                 target_proc = target_node->proc;
1930                 if (target_proc == NULL) {
1931                         return_error = BR_DEAD_REPLY;
1932                         goto err_dead_binder;
1933                 }
1934                 if (security_binder_transaction(proc->tsk,
1935                                                 target_proc->tsk) < 0) {
1936                         return_error = BR_FAILED_REPLY;
1937                         goto err_invalid_target_handle;
1938                 }
1939                 if (!(tr->flags & TF_ONE_WAY) && thread->transaction_stack) {
1940                         struct binder_transaction *tmp;
1941
1942                         tmp = thread->transaction_stack;
1943                         if (tmp->to_thread != thread) {
1944                                 binder_user_error("%d:%d got new transaction with bad transaction stack, transaction %d has target %d:%d\n",
1945                                         proc->pid, thread->pid, tmp->debug_id,
1946                                         tmp->to_proc ? tmp->to_proc->pid : 0,
1947                                         tmp->to_thread ?
1948                                         tmp->to_thread->pid : 0);
1949                                 return_error = BR_FAILED_REPLY;
1950                                 goto err_bad_call_stack;
1951                         }
1952                         while (tmp) {
1953                                 if (tmp->from && tmp->from->proc == target_proc)
1954                                         target_thread = tmp->from;
1955                                 tmp = tmp->from_parent;
1956                         }
1957                 }
1958         }
1959         if (target_thread) {
1960                 e->to_thread = target_thread->pid;
1961                 target_list = &target_thread->todo;
1962                 target_wait = &target_thread->wait;
1963         } else {
1964                 target_list = &target_proc->todo;
1965                 target_wait = &target_proc->wait;
1966         }
1967         e->to_proc = target_proc->pid;
1968
1969         /* TODO: reuse incoming transaction for reply */
1970         t = kzalloc(sizeof(*t), GFP_KERNEL);
1971         if (t == NULL) {
1972                 return_error = BR_FAILED_REPLY;
1973                 goto err_alloc_t_failed;
1974         }
1975         binder_stats_created(BINDER_STAT_TRANSACTION);
1976
1977         tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);
1978         if (tcomplete == NULL) {
1979                 return_error = BR_FAILED_REPLY;
1980                 goto err_alloc_tcomplete_failed;
1981         }
1982         binder_stats_created(BINDER_STAT_TRANSACTION_COMPLETE);
1983
1984         t->debug_id = atomic_inc_return(&binder_last_id);
1985         e->debug_id = t->debug_id;
1986
1987         if (reply)
1988                 binder_debug(BINDER_DEBUG_TRANSACTION,
1989                              "%d:%d BC_REPLY %d -> %d:%d, data %016llx-%016llx size %lld-%lld-%lld\n",
1990                              proc->pid, thread->pid, t->debug_id,
1991                              target_proc->pid, target_thread->pid,
1992                              (u64)tr->data.ptr.buffer,
1993                              (u64)tr->data.ptr.offsets,
1994                              (u64)tr->data_size, (u64)tr->offsets_size,
1995                              (u64)extra_buffers_size);
1996         else
1997                 binder_debug(BINDER_DEBUG_TRANSACTION,
1998                              "%d:%d BC_TRANSACTION %d -> %d - node %d, data %016llx-%016llx size %lld-%lld-%lld\n",
1999                              proc->pid, thread->pid, t->debug_id,
2000                              target_proc->pid, target_node->debug_id,
2001                              (u64)tr->data.ptr.buffer,
2002                              (u64)tr->data.ptr.offsets,
2003                              (u64)tr->data_size, (u64)tr->offsets_size,
2004                              (u64)extra_buffers_size);
2005
2006         if (!reply && !(tr->flags & TF_ONE_WAY))
2007                 t->from = thread;
2008         else
2009                 t->from = NULL;
2010         t->sender_euid = task_euid(proc->tsk);
2011         t->to_proc = target_proc;
2012         t->to_thread = target_thread;
2013         t->code = tr->code;
2014         t->flags = tr->flags;
2015         t->priority = task_nice(current);
2016
2017         trace_binder_transaction(reply, t, target_node);
2018
2019         t->buffer = binder_alloc_buf(target_proc, tr->data_size,
2020                 tr->offsets_size, extra_buffers_size,
2021                 !reply && (t->flags & TF_ONE_WAY));
2022         if (t->buffer == NULL) {
2023                 return_error = BR_FAILED_REPLY;
2024                 goto err_binder_alloc_buf_failed;
2025         }
2026         t->buffer->allow_user_free = 0;
2027         t->buffer->debug_id = t->debug_id;
2028         t->buffer->transaction = t;
2029         t->buffer->target_node = target_node;
2030         trace_binder_transaction_alloc_buf(t->buffer);
2031         if (target_node)
2032                 binder_inc_node(target_node, 1, 0, NULL);
2033
2034         off_start = (binder_size_t *)(t->buffer->data +
2035                                       ALIGN(tr->data_size, sizeof(void *)));
2036         offp = off_start;
2037
2038         if (copy_from_user(t->buffer->data, (const void __user *)(uintptr_t)
2039                            tr->data.ptr.buffer, tr->data_size)) {
2040                 binder_user_error("%d:%d got transaction with invalid data ptr\n",
2041                                 proc->pid, thread->pid);
2042                 return_error = BR_FAILED_REPLY;
2043                 goto err_copy_data_failed;
2044         }
2045         if (copy_from_user(offp, (const void __user *)(uintptr_t)
2046                            tr->data.ptr.offsets, tr->offsets_size)) {
2047                 binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
2048                                 proc->pid, thread->pid);
2049                 return_error = BR_FAILED_REPLY;
2050                 goto err_copy_data_failed;
2051         }
2052         if (!IS_ALIGNED(tr->offsets_size, sizeof(binder_size_t))) {
2053                 binder_user_error("%d:%d got transaction with invalid offsets size, %lld\n",
2054                                 proc->pid, thread->pid, (u64)tr->offsets_size);
2055                 return_error = BR_FAILED_REPLY;
2056                 goto err_bad_offset;
2057         }
2058         if (!IS_ALIGNED(extra_buffers_size, sizeof(u64))) {
2059                 binder_user_error("%d:%d got transaction with unaligned buffers size, %lld\n",
2060                                   proc->pid, thread->pid,
2061                                   (u64)extra_buffers_size);
2062                 return_error = BR_FAILED_REPLY;
2063                 goto err_bad_offset;
2064         }
2065         off_end = (void *)off_start + tr->offsets_size;
2066         sg_bufp = (u8 *)(PTR_ALIGN(off_end, sizeof(void *)));
2067         sg_buf_end = sg_bufp + extra_buffers_size;
2068         off_min = 0;
2069         for (; offp < off_end; offp++) {
2070                 struct binder_object_header *hdr;
2071                 size_t object_size = binder_validate_object(t->buffer, *offp);
2072
2073                 if (object_size == 0 || *offp < off_min) {
2074                         binder_user_error("%d:%d got transaction with invalid offset (%lld, min %lld max %lld) or object.\n",
2075                                           proc->pid, thread->pid, (u64)*offp,
2076                                           (u64)off_min,
2077                                           (u64)t->buffer->data_size);
2078                         return_error = BR_FAILED_REPLY;
2079                         goto err_bad_offset;
2080                 }
2081
2082                 hdr = (struct binder_object_header *)(t->buffer->data + *offp);
2083                 off_min = *offp + object_size;
2084                 switch (hdr->type) {
2085                 case BINDER_TYPE_BINDER:
2086                 case BINDER_TYPE_WEAK_BINDER: {
2087                         struct flat_binder_object *fp;
2088
2089                         fp = to_flat_binder_object(hdr);
2090                         ret = binder_translate_binder(fp, t, thread);
2091                         if (ret < 0) {
2092                                 return_error = BR_FAILED_REPLY;
2093                                 goto err_translate_failed;
2094                         }
2095                 } break;
2096                 case BINDER_TYPE_HANDLE:
2097                 case BINDER_TYPE_WEAK_HANDLE: {
2098                         struct flat_binder_object *fp;
2099
2100                         fp = to_flat_binder_object(hdr);
2101                         ret = binder_translate_handle(fp, t, thread);
2102                         if (ret < 0) {
2103                                 return_error = BR_FAILED_REPLY;
2104                                 goto err_translate_failed;
2105                         }
2106                 } break;
2107
2108                 case BINDER_TYPE_FD: {
2109                         struct binder_fd_object *fp = to_binder_fd_object(hdr);
2110                         int target_fd = binder_translate_fd(fp->fd, t, thread,
2111                                                             in_reply_to);
2112
2113                         if (target_fd < 0) {
2114                                 return_error = BR_FAILED_REPLY;
2115                                 goto err_translate_failed;
2116                         }
2117                         fp->pad_binder = 0;
2118                         fp->fd = target_fd;
2119                 } break;
2120                 case BINDER_TYPE_FDA: {
2121                         struct binder_fd_array_object *fda =
2122                                 to_binder_fd_array_object(hdr);
2123                         struct binder_buffer_object *parent =
2124                                 binder_validate_ptr(t->buffer, fda->parent,
2125                                                     off_start,
2126                                                     offp - off_start);
2127                         if (!parent) {
2128                                 binder_user_error("%d:%d got transaction with invalid parent offset or type\n",
2129                                                   proc->pid, thread->pid);
2130                                 return_error = BR_FAILED_REPLY;
2131                                 goto err_bad_parent;
2132                         }
2133                         if (!binder_validate_fixup(t->buffer, off_start,
2134                                                    parent, fda->parent_offset,
2135                                                    last_fixup_obj,
2136                                                    last_fixup_min_off)) {
2137                                 binder_user_error("%d:%d got transaction with out-of-order buffer fixup\n",
2138                                                   proc->pid, thread->pid);
2139                                 return_error = BR_FAILED_REPLY;
2140                                 goto err_bad_parent;
2141                         }
2142                         ret = binder_translate_fd_array(fda, parent, t, thread,
2143                                                         in_reply_to);
2144                         if (ret < 0) {
2145                                 return_error = BR_FAILED_REPLY;
2146                                 goto err_translate_failed;
2147                         }
2148                         last_fixup_obj = parent;
2149                         last_fixup_min_off =
2150                                 fda->parent_offset + sizeof(u32) * fda->num_fds;
2151                 } break;
2152                 case BINDER_TYPE_PTR: {
2153                         struct binder_buffer_object *bp =
2154                                 to_binder_buffer_object(hdr);
2155                         size_t buf_left = sg_buf_end - sg_bufp;
2156
2157                         if (bp->length > buf_left) {
2158                                 binder_user_error("%d:%d got transaction with too large buffer\n",
2159                                                   proc->pid, thread->pid);
2160                                 return_error = BR_FAILED_REPLY;
2161                                 goto err_bad_offset;
2162                         }
2163                         if (copy_from_user(sg_bufp,
2164                                            (const void __user *)(uintptr_t)
2165                                            bp->buffer, bp->length)) {
2166                                 binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
2167                                                   proc->pid, thread->pid);
2168                                 return_error = BR_FAILED_REPLY;
2169                                 goto err_copy_data_failed;
2170                         }
2171                         /* Fixup buffer pointer to target proc address space */
2172                         bp->buffer = (uintptr_t)sg_bufp +
2173                                 target_proc->user_buffer_offset;
2174                         sg_bufp += ALIGN(bp->length, sizeof(u64));
2175
2176                         ret = binder_fixup_parent(t, thread, bp, off_start,
2177                                                   offp - off_start,
2178                                                   last_fixup_obj,
2179                                                   last_fixup_min_off);
2180                         if (ret < 0) {
2181                                 return_error = BR_FAILED_REPLY;
2182                                 goto err_translate_failed;
2183                         }
2184                         last_fixup_obj = bp;
2185                         last_fixup_min_off = 0;
2186                 } break;
2187                 default:
2188                         binder_user_error("%d:%d got transaction with invalid object type, %x\n",
2189                                 proc->pid, thread->pid, hdr->type);
2190                         return_error = BR_FAILED_REPLY;
2191                         goto err_bad_object_type;
2192                 }
2193         }
2194         if (reply) {
2195                 BUG_ON(t->buffer->async_transaction != 0);
2196                 binder_pop_transaction(target_thread, in_reply_to);
2197         } else if (!(t->flags & TF_ONE_WAY)) {
2198                 BUG_ON(t->buffer->async_transaction != 0);
2199                 t->need_reply = 1;
2200                 t->from_parent = thread->transaction_stack;
2201                 thread->transaction_stack = t;
2202         } else {
2203                 BUG_ON(target_node == NULL);
2204                 BUG_ON(t->buffer->async_transaction != 1);
2205                 if (target_node->has_async_transaction) {
2206                         target_list = &target_node->async_todo;
2207                         target_wait = NULL;
2208                 } else
2209                         target_node->has_async_transaction = 1;
2210         }
2211         t->work.type = BINDER_WORK_TRANSACTION;
2212         list_add_tail(&t->work.entry, target_list);
2213         tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;
2214         list_add_tail(&tcomplete->entry, &thread->todo);
2215         if (target_wait)
2216                 wake_up_interruptible(target_wait);
2217         return;
2218
2219 err_translate_failed:
2220 err_bad_object_type:
2221 err_bad_offset:
2222 err_bad_parent:
2223 err_copy_data_failed:
2224         trace_binder_transaction_failed_buffer_release(t->buffer);
2225         binder_transaction_buffer_release(target_proc, t->buffer, offp);
2226         t->buffer->transaction = NULL;
2227         binder_free_buf(target_proc, t->buffer);
2228 err_binder_alloc_buf_failed:
2229         kfree(tcomplete);
2230         binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
2231 err_alloc_tcomplete_failed:
2232         kfree(t);
2233         binder_stats_deleted(BINDER_STAT_TRANSACTION);
2234 err_alloc_t_failed:
2235 err_bad_call_stack:
2236 err_empty_call_stack:
2237 err_dead_binder:
2238 err_invalid_target_handle:
2239 err_no_context_mgr_node:
2240         binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
2241                      "%d:%d transaction failed %d, size %lld-%lld\n",
2242                      proc->pid, thread->pid, return_error,
2243                      (u64)tr->data_size, (u64)tr->offsets_size);
2244
2245         {
2246                 struct binder_transaction_log_entry *fe;
2247
2248                 fe = binder_transaction_log_add(
2249                                 &context->transaction_log_failed);
2250                 *fe = *e;
2251         }
2252
2253         BUG_ON(thread->return_error != BR_OK);
2254         if (in_reply_to) {
2255                 thread->return_error = BR_TRANSACTION_COMPLETE;
2256                 binder_send_failed_reply(in_reply_to, return_error);
2257         } else
2258                 thread->return_error = return_error;
2259 }
2260
2261 static int binder_thread_write(struct binder_proc *proc,
2262                         struct binder_thread *thread,
2263                         binder_uintptr_t binder_buffer, size_t size,
2264                         binder_size_t *consumed)
2265 {
2266         uint32_t cmd;
2267         struct binder_context *context = proc->context;
2268         void __user *buffer = (void __user *)(uintptr_t)binder_buffer;
2269         void __user *ptr = buffer + *consumed;
2270         void __user *end = buffer + size;
2271
2272         while (ptr < end && thread->return_error == BR_OK) {
2273                 if (get_user(cmd, (uint32_t __user *)ptr))
2274                         return -EFAULT;
2275                 ptr += sizeof(uint32_t);
2276                 trace_binder_command(cmd);
2277                 if (_IOC_NR(cmd) < ARRAY_SIZE(context->binder_stats.bc)) {
2278                         context->binder_stats.bc[_IOC_NR(cmd)]++;
2279                         proc->stats.bc[_IOC_NR(cmd)]++;
2280                         thread->stats.bc[_IOC_NR(cmd)]++;
2281                 }
2282                 switch (cmd) {
2283                 case BC_INCREFS:
2284                 case BC_ACQUIRE:
2285                 case BC_RELEASE:
2286                 case BC_DECREFS: {
2287                         uint32_t target;
2288                         struct binder_ref *ref;
2289                         const char *debug_string;
2290
2291                         if (get_user(target, (uint32_t __user *)ptr))
2292                                 return -EFAULT;
2293                         ptr += sizeof(uint32_t);
2294                         if (target == 0 && context->binder_context_mgr_node &&
2295                             (cmd == BC_INCREFS || cmd == BC_ACQUIRE)) {
2296                                 ref = binder_get_ref_for_node(proc,
2297                                         context->binder_context_mgr_node);
2298                                 if (ref->desc != target) {
2299                                         binder_user_error("%d:%d tried to acquire reference to desc 0, got %d instead\n",
2300                                                 proc->pid, thread->pid,
2301                                                 ref->desc);
2302                                 }
2303                         } else
2304                                 ref = binder_get_ref(proc, target,
2305                                                      cmd == BC_ACQUIRE ||
2306                                                      cmd == BC_RELEASE);
2307                         if (ref == NULL) {
2308                                 binder_user_error("%d:%d refcount change on invalid ref %d\n",
2309                                         proc->pid, thread->pid, target);
2310                                 break;
2311                         }
2312                         switch (cmd) {
2313                         case BC_INCREFS:
2314                                 debug_string = "IncRefs";
2315                                 binder_inc_ref(ref, 0, NULL);
2316                                 break;
2317                         case BC_ACQUIRE:
2318                                 debug_string = "Acquire";
2319                                 binder_inc_ref(ref, 1, NULL);
2320                                 break;
2321                         case BC_RELEASE:
2322                                 debug_string = "Release";
2323                                 binder_dec_ref(ref, 1);
2324                                 break;
2325                         case BC_DECREFS:
2326                         default:
2327                                 debug_string = "DecRefs";
2328                                 binder_dec_ref(ref, 0);
2329                                 break;
2330                         }
2331                         binder_debug(BINDER_DEBUG_USER_REFS,
2332                                      "%d:%d %s ref %d desc %d s %d w %d for node %d\n",
2333                                      proc->pid, thread->pid, debug_string, ref->debug_id,
2334                                      ref->desc, ref->strong, ref->weak, ref->node->debug_id);
2335                         break;
2336                 }
2337                 case BC_INCREFS_DONE:
2338                 case BC_ACQUIRE_DONE: {
2339                         binder_uintptr_t node_ptr;
2340                         binder_uintptr_t cookie;
2341                         struct binder_node *node;
2342
2343                         if (get_user(node_ptr, (binder_uintptr_t __user *)ptr))
2344                                 return -EFAULT;
2345                         ptr += sizeof(binder_uintptr_t);
2346                         if (get_user(cookie, (binder_uintptr_t __user *)ptr))
2347                                 return -EFAULT;
2348                         ptr += sizeof(binder_uintptr_t);
2349                         node = binder_get_node(proc, node_ptr);
2350                         if (node == NULL) {
2351                                 binder_user_error("%d:%d %s u%016llx no match\n",
2352                                         proc->pid, thread->pid,
2353                                         cmd == BC_INCREFS_DONE ?
2354                                         "BC_INCREFS_DONE" :
2355                                         "BC_ACQUIRE_DONE",
2356                                         (u64)node_ptr);
2357                                 break;
2358                         }
2359                         if (cookie != node->cookie) {
2360                                 binder_user_error("%d:%d %s u%016llx node %d cookie mismatch %016llx != %016llx\n",
2361                                         proc->pid, thread->pid,
2362                                         cmd == BC_INCREFS_DONE ?
2363                                         "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE",
2364                                         (u64)node_ptr, node->debug_id,
2365                                         (u64)cookie, (u64)node->cookie);
2366                                 break;
2367                         }
2368                         if (cmd == BC_ACQUIRE_DONE) {
2369                                 if (node->pending_strong_ref == 0) {
2370                                         binder_user_error("%d:%d BC_ACQUIRE_DONE node %d has no pending acquire request\n",
2371                                                 proc->pid, thread->pid,
2372                                                 node->debug_id);
2373                                         break;
2374                                 }
2375                                 node->pending_strong_ref = 0;
2376                         } else {
2377                                 if (node->pending_weak_ref == 0) {
2378                                         binder_user_error("%d:%d BC_INCREFS_DONE node %d has no pending increfs request\n",
2379                                                 proc->pid, thread->pid,
2380                                                 node->debug_id);
2381                                         break;
2382                                 }
2383                                 node->pending_weak_ref = 0;
2384                         }
2385                         binder_dec_node(node, cmd == BC_ACQUIRE_DONE, 0);
2386                         binder_debug(BINDER_DEBUG_USER_REFS,
2387                                      "%d:%d %s node %d ls %d lw %d\n",
2388                                      proc->pid, thread->pid,
2389                                      cmd == BC_INCREFS_DONE ? "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE",
2390                                      node->debug_id, node->local_strong_refs, node->local_weak_refs);
2391                         break;
2392                 }
2393                 case BC_ATTEMPT_ACQUIRE:
2394                         pr_err("BC_ATTEMPT_ACQUIRE not supported\n");
2395                         return -EINVAL;
2396                 case BC_ACQUIRE_RESULT:
2397                         pr_err("BC_ACQUIRE_RESULT not supported\n");
2398                         return -EINVAL;
2399
2400                 case BC_FREE_BUFFER: {
2401                         binder_uintptr_t data_ptr;
2402                         struct binder_buffer *buffer;
2403
2404                         if (get_user(data_ptr, (binder_uintptr_t __user *)ptr))
2405                                 return -EFAULT;
2406                         ptr += sizeof(binder_uintptr_t);
2407
2408                         buffer = binder_buffer_lookup(proc, data_ptr);
2409                         if (buffer == NULL) {
2410                                 binder_user_error("%d:%d BC_FREE_BUFFER u%016llx no match\n",
2411                                         proc->pid, thread->pid, (u64)data_ptr);
2412                                 break;
2413                         }
2414                         if (!buffer->allow_user_free) {
2415                                 binder_user_error("%d:%d BC_FREE_BUFFER u%016llx matched unreturned buffer\n",
2416                                         proc->pid, thread->pid, (u64)data_ptr);
2417                                 break;
2418                         }
2419                         binder_debug(BINDER_DEBUG_FREE_BUFFER,
2420                                      "%d:%d BC_FREE_BUFFER u%016llx found buffer %d for %s transaction\n",
2421                                      proc->pid, thread->pid, (u64)data_ptr,
2422                                      buffer->debug_id,
2423                                      buffer->transaction ? "active" : "finished");
2424
2425                         if (buffer->transaction) {
2426                                 buffer->transaction->buffer = NULL;
2427                                 buffer->transaction = NULL;
2428                         }
2429                         if (buffer->async_transaction && buffer->target_node) {
2430                                 BUG_ON(!buffer->target_node->has_async_transaction);
2431                                 if (list_empty(&buffer->target_node->async_todo))
2432                                         buffer->target_node->has_async_transaction = 0;
2433                                 else
2434                                         list_move_tail(buffer->target_node->async_todo.next, &thread->todo);
2435                         }
2436                         trace_binder_transaction_buffer_release(buffer);
2437                         binder_transaction_buffer_release(proc, buffer, NULL);
2438                         binder_free_buf(proc, buffer);
2439                         break;
2440                 }
2441
2442                 case BC_TRANSACTION_SG:
2443                 case BC_REPLY_SG: {
2444                         struct binder_transaction_data_sg tr;
2445
2446                         if (copy_from_user(&tr, ptr, sizeof(tr)))
2447                                 return -EFAULT;
2448                         ptr += sizeof(tr);
2449                         binder_transaction(proc, thread, &tr.transaction_data,
2450                                            cmd == BC_REPLY_SG, tr.buffers_size);
2451                         break;
2452                 }
2453                 case BC_TRANSACTION:
2454                 case BC_REPLY: {
2455                         struct binder_transaction_data tr;
2456
2457                         if (copy_from_user(&tr, ptr, sizeof(tr)))
2458                                 return -EFAULT;
2459                         ptr += sizeof(tr);
2460                         binder_transaction(proc, thread, &tr,
2461                                            cmd == BC_REPLY, 0);
2462                         break;
2463                 }
2464
2465                 case BC_REGISTER_LOOPER:
2466                         binder_debug(BINDER_DEBUG_THREADS,
2467                                      "%d:%d BC_REGISTER_LOOPER\n",
2468                                      proc->pid, thread->pid);
2469                         if (thread->looper & BINDER_LOOPER_STATE_ENTERED) {
2470                                 thread->looper |= BINDER_LOOPER_STATE_INVALID;
2471                                 binder_user_error("%d:%d ERROR: BC_REGISTER_LOOPER called after BC_ENTER_LOOPER\n",
2472                                         proc->pid, thread->pid);
2473                         } else if (proc->requested_threads == 0) {
2474                                 thread->looper |= BINDER_LOOPER_STATE_INVALID;
2475                                 binder_user_error("%d:%d ERROR: BC_REGISTER_LOOPER called without request\n",
2476                                         proc->pid, thread->pid);
2477                         } else {
2478                                 proc->requested_threads--;
2479                                 proc->requested_threads_started++;
2480                         }
2481                         thread->looper |= BINDER_LOOPER_STATE_REGISTERED;
2482                         break;
2483                 case BC_ENTER_LOOPER:
2484                         binder_debug(BINDER_DEBUG_THREADS,
2485                                      "%d:%d BC_ENTER_LOOPER\n",
2486                                      proc->pid, thread->pid);
2487                         if (thread->looper & BINDER_LOOPER_STATE_REGISTERED) {
2488                                 thread->looper |= BINDER_LOOPER_STATE_INVALID;
2489                                 binder_user_error("%d:%d ERROR: BC_ENTER_LOOPER called after BC_REGISTER_LOOPER\n",
2490                                         proc->pid, thread->pid);
2491                         }
2492                         thread->looper |= BINDER_LOOPER_STATE_ENTERED;
2493                         break;
2494                 case BC_EXIT_LOOPER:
2495                         binder_debug(BINDER_DEBUG_THREADS,
2496                                      "%d:%d BC_EXIT_LOOPER\n",
2497                                      proc->pid, thread->pid);
2498                         thread->looper |= BINDER_LOOPER_STATE_EXITED;
2499                         break;
2500
2501                 case BC_REQUEST_DEATH_NOTIFICATION:
2502                 case BC_CLEAR_DEATH_NOTIFICATION: {
2503                         uint32_t target;
2504                         binder_uintptr_t cookie;
2505                         struct binder_ref *ref;
2506                         struct binder_ref_death *death;
2507
2508                         if (get_user(target, (uint32_t __user *)ptr))
2509                                 return -EFAULT;
2510                         ptr += sizeof(uint32_t);
2511                         if (get_user(cookie, (binder_uintptr_t __user *)ptr))
2512                                 return -EFAULT;
2513                         ptr += sizeof(binder_uintptr_t);
2514                         ref = binder_get_ref(proc, target, false);
2515                         if (ref == NULL) {
2516                                 binder_user_error("%d:%d %s invalid ref %d\n",
2517                                         proc->pid, thread->pid,
2518                                         cmd == BC_REQUEST_DEATH_NOTIFICATION ?
2519                                         "BC_REQUEST_DEATH_NOTIFICATION" :
2520                                         "BC_CLEAR_DEATH_NOTIFICATION",
2521                                         target);
2522                                 break;
2523                         }
2524
2525                         binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION,
2526                                      "%d:%d %s %016llx ref %d desc %d s %d w %d for node %d\n",
2527                                      proc->pid, thread->pid,
2528                                      cmd == BC_REQUEST_DEATH_NOTIFICATION ?
2529                                      "BC_REQUEST_DEATH_NOTIFICATION" :
2530                                      "BC_CLEAR_DEATH_NOTIFICATION",
2531                                      (u64)cookie, ref->debug_id, ref->desc,
2532                                      ref->strong, ref->weak, ref->node->debug_id);
2533
2534                         if (cmd == BC_REQUEST_DEATH_NOTIFICATION) {
2535                                 if (ref->death) {
2536                                         binder_user_error("%d:%d BC_REQUEST_DEATH_NOTIFICATION death notification already set\n",
2537                                                 proc->pid, thread->pid);
2538                                         break;
2539                                 }
2540                                 death = kzalloc(sizeof(*death), GFP_KERNEL);
2541                                 if (death == NULL) {
2542                                         thread->return_error = BR_ERROR;
2543                                         binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
2544                                                      "%d:%d BC_REQUEST_DEATH_NOTIFICATION failed\n",
2545                                                      proc->pid, thread->pid);
2546                                         break;
2547                                 }
2548                                 binder_stats_created(BINDER_STAT_DEATH);
2549                                 INIT_LIST_HEAD(&death->work.entry);
2550                                 death->cookie = cookie;
2551                                 ref->death = death;
2552                                 if (ref->node->proc == NULL) {
2553                                         ref->death->work.type = BINDER_WORK_DEAD_BINDER;
2554                                         if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
2555                                                 list_add_tail(&ref->death->work.entry, &thread->todo);
2556                                         } else {
2557                                                 list_add_tail(&ref->death->work.entry, &proc->todo);
2558                                                 wake_up_interruptible(&proc->wait);
2559                                         }
2560                                 }
2561                         } else {
2562                                 if (ref->death == NULL) {
2563                                         binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification not active\n",
2564                                                 proc->pid, thread->pid);
2565                                         break;
2566                                 }
2567                                 death = ref->death;
2568                                 if (death->cookie != cookie) {
2569                                         binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification cookie mismatch %016llx != %016llx\n",
2570                                                 proc->pid, thread->pid,
2571                                                 (u64)death->cookie,
2572                                                 (u64)cookie);
2573                                         break;
2574                                 }
2575                                 ref->death = NULL;
2576                                 if (list_empty(&death->work.entry)) {
2577                                         death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION;
2578                                         if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
2579                                                 list_add_tail(&death->work.entry, &thread->todo);
2580                                         } else {
2581                                                 list_add_tail(&death->work.entry, &proc->todo);
2582                                                 wake_up_interruptible(&proc->wait);
2583                                         }
2584                                 } else {
2585                                         BUG_ON(death->work.type != BINDER_WORK_DEAD_BINDER);
2586                                         death->work.type = BINDER_WORK_DEAD_BINDER_AND_CLEAR;
2587                                 }
2588                         }
2589                 } break;
2590                 case BC_DEAD_BINDER_DONE: {
2591                         struct binder_work *w;
2592                         binder_uintptr_t cookie;
2593                         struct binder_ref_death *death = NULL;
2594
2595                         if (get_user(cookie, (binder_uintptr_t __user *)ptr))
2596                                 return -EFAULT;
2597
2598                         ptr += sizeof(cookie);
2599                         list_for_each_entry(w, &proc->delivered_death, entry) {
2600                                 struct binder_ref_death *tmp_death = container_of(w, struct binder_ref_death, work);
2601
2602                                 if (tmp_death->cookie == cookie) {
2603                                         death = tmp_death;
2604                                         break;
2605                                 }
2606                         }
2607                         binder_debug(BINDER_DEBUG_DEAD_BINDER,
2608                                      "%d:%d BC_DEAD_BINDER_DONE %016llx found %p\n",
2609                                      proc->pid, thread->pid, (u64)cookie,
2610                                      death);
2611                         if (death == NULL) {
2612                                 binder_user_error("%d:%d BC_DEAD_BINDER_DONE %016llx not found\n",
2613                                         proc->pid, thread->pid, (u64)cookie);
2614                                 break;
2615                         }
2616
2617                         list_del_init(&death->work.entry);
2618                         if (death->work.type == BINDER_WORK_DEAD_BINDER_AND_CLEAR) {
2619                                 death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION;
2620                                 if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
2621                                         list_add_tail(&death->work.entry, &thread->todo);
2622                                 } else {
2623                                         list_add_tail(&death->work.entry, &proc->todo);
2624                                         wake_up_interruptible(&proc->wait);
2625                                 }
2626                         }
2627                 } break;
2628
2629                 default:
2630                         pr_err("%d:%d unknown command %d\n",
2631                                proc->pid, thread->pid, cmd);
2632                         return -EINVAL;
2633                 }
2634                 *consumed = ptr - buffer;
2635         }
2636         return 0;
2637 }
2638
2639 static void binder_stat_br(struct binder_proc *proc,
2640                            struct binder_thread *thread, uint32_t cmd)
2641 {
2642         trace_binder_return(cmd);
2643         if (_IOC_NR(cmd) < ARRAY_SIZE(proc->stats.br)) {
2644                 proc->context->binder_stats.br[_IOC_NR(cmd)]++;
2645                 proc->stats.br[_IOC_NR(cmd)]++;
2646                 thread->stats.br[_IOC_NR(cmd)]++;
2647         }
2648 }
2649
2650 static int binder_has_proc_work(struct binder_proc *proc,
2651                                 struct binder_thread *thread)
2652 {
2653         return !list_empty(&proc->todo) ||
2654                 (thread->looper & BINDER_LOOPER_STATE_NEED_RETURN);
2655 }
2656
2657 static int binder_has_thread_work(struct binder_thread *thread)
2658 {
2659         return !list_empty(&thread->todo) || thread->return_error != BR_OK ||
2660                 (thread->looper & BINDER_LOOPER_STATE_NEED_RETURN);
2661 }
2662
2663 static int binder_thread_read(struct binder_proc *proc,
2664                               struct binder_thread *thread,
2665                               binder_uintptr_t binder_buffer, size_t size,
2666                               binder_size_t *consumed, int non_block)
2667 {
2668         void __user *buffer = (void __user *)(uintptr_t)binder_buffer;
2669         void __user *ptr = buffer + *consumed;
2670         void __user *end = buffer + size;
2671
2672         int ret = 0;
2673         int wait_for_proc_work;
2674
2675         if (*consumed == 0) {
2676                 if (put_user(BR_NOOP, (uint32_t __user *)ptr))
2677                         return -EFAULT;
2678                 ptr += sizeof(uint32_t);
2679         }
2680
2681 retry:
2682         wait_for_proc_work = thread->transaction_stack == NULL &&
2683                                 list_empty(&thread->todo);
2684
2685         if (thread->return_error != BR_OK && ptr < end) {
2686                 if (thread->return_error2 != BR_OK) {
2687                         if (put_user(thread->return_error2, (uint32_t __user *)ptr))
2688                                 return -EFAULT;
2689                         ptr += sizeof(uint32_t);
2690                         binder_stat_br(proc, thread, thread->return_error2);
2691                         if (ptr == end)
2692                                 goto done;
2693                         thread->return_error2 = BR_OK;
2694                 }
2695                 if (put_user(thread->return_error, (uint32_t __user *)ptr))
2696                         return -EFAULT;
2697                 ptr += sizeof(uint32_t);
2698                 binder_stat_br(proc, thread, thread->return_error);
2699                 thread->return_error = BR_OK;
2700                 goto done;
2701         }
2702
2703
2704         thread->looper |= BINDER_LOOPER_STATE_WAITING;
2705         if (wait_for_proc_work)
2706                 proc->ready_threads++;
2707
2708         binder_unlock(proc->context, __func__);
2709
2710         trace_binder_wait_for_work(wait_for_proc_work,
2711                                    !!thread->transaction_stack,
2712                                    !list_empty(&thread->todo));
2713         if (wait_for_proc_work) {
2714                 if (!(thread->looper & (BINDER_LOOPER_STATE_REGISTERED |
2715                                         BINDER_LOOPER_STATE_ENTERED))) {
2716                         binder_user_error("%d:%d ERROR: Thread waiting for process work before calling BC_REGISTER_LOOPER or BC_ENTER_LOOPER (state %x)\n",
2717                                 proc->pid, thread->pid, thread->looper);
2718                         wait_event_interruptible(binder_user_error_wait,
2719                                                  binder_stop_on_user_error < 2);
2720                 }
2721                 binder_set_nice(proc->default_priority);
2722                 if (non_block) {
2723                         if (!binder_has_proc_work(proc, thread))
2724                                 ret = -EAGAIN;
2725                 } else
2726                         ret = wait_event_freezable_exclusive(proc->wait, binder_has_proc_work(proc, thread));
2727         } else {
2728                 if (non_block) {
2729                         if (!binder_has_thread_work(thread))
2730                                 ret = -EAGAIN;
2731                 } else
2732                         ret = wait_event_freezable(thread->wait, binder_has_thread_work(thread));
2733         }
2734
2735         binder_lock(proc->context, __func__);
2736
2737         if (wait_for_proc_work)
2738                 proc->ready_threads--;
2739         thread->looper &= ~BINDER_LOOPER_STATE_WAITING;
2740
2741         if (ret)
2742                 return ret;
2743
2744         while (1) {
2745                 uint32_t cmd;
2746                 struct binder_transaction_data tr;
2747                 struct binder_work *w;
2748                 struct binder_transaction *t = NULL;
2749
2750                 if (!list_empty(&thread->todo)) {
2751                         w = list_first_entry(&thread->todo, struct binder_work,
2752                                              entry);
2753                 } else if (!list_empty(&proc->todo) && wait_for_proc_work) {
2754                         w = list_first_entry(&proc->todo, struct binder_work,
2755                                              entry);
2756                 } else {
2757                         /* no data added */
2758                         if (ptr - buffer == 4 &&
2759                             !(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN))
2760                                 goto retry;
2761                         break;
2762                 }
2763
2764                 if (end - ptr < sizeof(tr) + 4)
2765                         break;
2766
2767                 switch (w->type) {
2768                 case BINDER_WORK_TRANSACTION: {
2769                         t = container_of(w, struct binder_transaction, work);
2770                 } break;
2771                 case BINDER_WORK_TRANSACTION_COMPLETE: {
2772                         cmd = BR_TRANSACTION_COMPLETE;
2773                         if (put_user(cmd, (uint32_t __user *)ptr))
2774                                 return -EFAULT;
2775                         ptr += sizeof(uint32_t);
2776
2777                         binder_stat_br(proc, thread, cmd);
2778                         binder_debug(BINDER_DEBUG_TRANSACTION_COMPLETE,
2779                                      "%d:%d BR_TRANSACTION_COMPLETE\n",
2780                                      proc->pid, thread->pid);
2781
2782                         list_del(&w->entry);
2783                         kfree(w);
2784                         binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
2785                 } break;
2786                 case BINDER_WORK_NODE: {
2787                         struct binder_node *node = container_of(w, struct binder_node, work);
2788                         uint32_t cmd = BR_NOOP;
2789                         const char *cmd_name;
2790                         int strong = node->internal_strong_refs || node->local_strong_refs;
2791                         int weak = !hlist_empty(&node->refs) || node->local_weak_refs || strong;
2792
2793                         if (weak && !node->has_weak_ref) {
2794                                 cmd = BR_INCREFS;
2795                                 cmd_name = "BR_INCREFS";
2796                                 node->has_weak_ref = 1;
2797                                 node->pending_weak_ref = 1;
2798                                 node->local_weak_refs++;
2799                         } else if (strong && !node->has_strong_ref) {
2800                                 cmd = BR_ACQUIRE;
2801                                 cmd_name = "BR_ACQUIRE";
2802                                 node->has_strong_ref = 1;
2803                                 node->pending_strong_ref = 1;
2804                                 node->local_strong_refs++;
2805                         } else if (!strong && node->has_strong_ref) {
2806                                 cmd = BR_RELEASE;
2807                                 cmd_name = "BR_RELEASE";
2808                                 node->has_strong_ref = 0;
2809                         } else if (!weak && node->has_weak_ref) {
2810                                 cmd = BR_DECREFS;
2811                                 cmd_name = "BR_DECREFS";
2812                                 node->has_weak_ref = 0;
2813                         }
2814                         if (cmd != BR_NOOP) {
2815                                 if (put_user(cmd, (uint32_t __user *)ptr))
2816                                         return -EFAULT;
2817                                 ptr += sizeof(uint32_t);
2818                                 if (put_user(node->ptr,
2819                                              (binder_uintptr_t __user *)ptr))
2820                                         return -EFAULT;
2821                                 ptr += sizeof(binder_uintptr_t);
2822                                 if (put_user(node->cookie,
2823                                              (binder_uintptr_t __user *)ptr))
2824                                         return -EFAULT;
2825                                 ptr += sizeof(binder_uintptr_t);
2826
2827                                 binder_stat_br(proc, thread, cmd);
2828                                 binder_debug(BINDER_DEBUG_USER_REFS,
2829                                              "%d:%d %s %d u%016llx c%016llx\n",
2830                                              proc->pid, thread->pid, cmd_name,
2831                                              node->debug_id,
2832                                              (u64)node->ptr, (u64)node->cookie);
2833                         } else {
2834                                 list_del_init(&w->entry);
2835                                 if (!weak && !strong) {
2836                                         binder_debug(BINDER_DEBUG_INTERNAL_REFS,
2837                                                      "%d:%d node %d u%016llx c%016llx deleted\n",
2838                                                      proc->pid, thread->pid,
2839                                                      node->debug_id,
2840                                                      (u64)node->ptr,
2841                                                      (u64)node->cookie);
2842                                         rb_erase(&node->rb_node, &proc->nodes);
2843                                         kfree(node);
2844                                         binder_stats_deleted(BINDER_STAT_NODE);
2845                                 } else {
2846                                         binder_debug(BINDER_DEBUG_INTERNAL_REFS,
2847                                                      "%d:%d node %d u%016llx c%016llx state unchanged\n",
2848                                                      proc->pid, thread->pid,
2849                                                      node->debug_id,
2850                                                      (u64)node->ptr,
2851                                                      (u64)node->cookie);
2852                                 }
2853                         }
2854                 } break;
2855                 case BINDER_WORK_DEAD_BINDER:
2856                 case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
2857                 case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: {
2858                         struct binder_ref_death *death;
2859                         uint32_t cmd;
2860
2861                         death = container_of(w, struct binder_ref_death, work);
2862                         if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION)
2863                                 cmd = BR_CLEAR_DEATH_NOTIFICATION_DONE;
2864                         else
2865                                 cmd = BR_DEAD_BINDER;
2866                         if (put_user(cmd, (uint32_t __user *)ptr))
2867                                 return -EFAULT;
2868                         ptr += sizeof(uint32_t);
2869                         if (put_user(death->cookie,
2870                                      (binder_uintptr_t __user *)ptr))
2871                                 return -EFAULT;
2872                         ptr += sizeof(binder_uintptr_t);
2873                         binder_stat_br(proc, thread, cmd);
2874                         binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION,
2875                                      "%d:%d %s %016llx\n",
2876                                       proc->pid, thread->pid,
2877                                       cmd == BR_DEAD_BINDER ?
2878                                       "BR_DEAD_BINDER" :
2879                                       "BR_CLEAR_DEATH_NOTIFICATION_DONE",
2880                                       (u64)death->cookie);
2881
2882                         if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION) {
2883                                 list_del(&w->entry);
2884                                 kfree(death);
2885                                 binder_stats_deleted(BINDER_STAT_DEATH);
2886                         } else
2887                                 list_move(&w->entry, &proc->delivered_death);
2888                         if (cmd == BR_DEAD_BINDER)
2889                                 goto done; /* DEAD_BINDER notifications can cause transactions */
2890                 } break;
2891                 }
2892
2893                 if (!t)
2894                         continue;
2895
2896                 BUG_ON(t->buffer == NULL);
2897                 if (t->buffer->target_node) {
2898                         struct binder_node *target_node = t->buffer->target_node;
2899
2900                         tr.target.ptr = target_node->ptr;
2901                         tr.cookie =  target_node->cookie;
2902                         t->saved_priority = task_nice(current);
2903                         if (t->priority < target_node->min_priority &&
2904                             !(t->flags & TF_ONE_WAY))
2905                                 binder_set_nice(t->priority);
2906                         else if (!(t->flags & TF_ONE_WAY) ||
2907                                  t->saved_priority > target_node->min_priority)
2908                                 binder_set_nice(target_node->min_priority);
2909                         cmd = BR_TRANSACTION;
2910                 } else {
2911                         tr.target.ptr = 0;
2912                         tr.cookie = 0;
2913                         cmd = BR_REPLY;
2914                 }
2915                 tr.code = t->code;
2916                 tr.flags = t->flags;
2917                 tr.sender_euid = from_kuid(current_user_ns(), t->sender_euid);
2918
2919                 if (t->from) {
2920                         struct task_struct *sender = t->from->proc->tsk;
2921
2922                         tr.sender_pid = task_tgid_nr_ns(sender,
2923                                                         task_active_pid_ns(current));
2924                 } else {
2925                         tr.sender_pid = 0;
2926                 }
2927
2928                 tr.data_size = t->buffer->data_size;
2929                 tr.offsets_size = t->buffer->offsets_size;
2930                 tr.data.ptr.buffer = (binder_uintptr_t)(
2931                                         (uintptr_t)t->buffer->data +
2932                                         proc->user_buffer_offset);
2933                 tr.data.ptr.offsets = tr.data.ptr.buffer +
2934                                         ALIGN(t->buffer->data_size,
2935                                             sizeof(void *));
2936
2937                 if (put_user(cmd, (uint32_t __user *)ptr))
2938                         return -EFAULT;
2939                 ptr += sizeof(uint32_t);
2940                 if (copy_to_user(ptr, &tr, sizeof(tr)))
2941                         return -EFAULT;
2942                 ptr += sizeof(tr);
2943
2944                 trace_binder_transaction_received(t);
2945                 binder_stat_br(proc, thread, cmd);
2946                 binder_debug(BINDER_DEBUG_TRANSACTION,
2947                              "%d:%d %s %d %d:%d, cmd %d size %zd-%zd ptr %016llx-%016llx\n",
2948                              proc->pid, thread->pid,
2949                              (cmd == BR_TRANSACTION) ? "BR_TRANSACTION" :
2950                              "BR_REPLY",
2951                              t->debug_id, t->from ? t->from->proc->pid : 0,
2952                              t->from ? t->from->pid : 0, cmd,
2953                              t->buffer->data_size, t->buffer->offsets_size,
2954                              (u64)tr.data.ptr.buffer, (u64)tr.data.ptr.offsets);
2955
2956                 list_del(&t->work.entry);
2957                 t->buffer->allow_user_free = 1;
2958                 if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {
2959                         t->to_parent = thread->transaction_stack;
2960                         t->to_thread = thread;
2961                         thread->transaction_stack = t;
2962                 } else {
2963                         t->buffer->transaction = NULL;
2964                         kfree(t);
2965                         binder_stats_deleted(BINDER_STAT_TRANSACTION);
2966                 }
2967                 break;
2968         }
2969
2970 done:
2971
2972         *consumed = ptr - buffer;
2973         if (proc->requested_threads + proc->ready_threads == 0 &&
2974             proc->requested_threads_started < proc->max_threads &&
2975             (thread->looper & (BINDER_LOOPER_STATE_REGISTERED |
2976              BINDER_LOOPER_STATE_ENTERED)) /* the user-space code fails to */
2977              /*spawn a new thread if we leave this out */) {
2978                 proc->requested_threads++;
2979                 binder_debug(BINDER_DEBUG_THREADS,
2980                              "%d:%d BR_SPAWN_LOOPER\n",
2981                              proc->pid, thread->pid);
2982                 if (put_user(BR_SPAWN_LOOPER, (uint32_t __user *)buffer))
2983                         return -EFAULT;
2984                 binder_stat_br(proc, thread, BR_SPAWN_LOOPER);
2985         }
2986         return 0;
2987 }
2988
2989 static void binder_release_work(struct list_head *list)
2990 {
2991         struct binder_work *w;
2992
2993         while (!list_empty(list)) {
2994                 w = list_first_entry(list, struct binder_work, entry);
2995                 list_del_init(&w->entry);
2996                 switch (w->type) {
2997                 case BINDER_WORK_TRANSACTION: {
2998                         struct binder_transaction *t;
2999
3000                         t = container_of(w, struct binder_transaction, work);
3001                         if (t->buffer->target_node &&
3002                             !(t->flags & TF_ONE_WAY)) {
3003                                 binder_send_failed_reply(t, BR_DEAD_REPLY);
3004                         } else {
3005                                 binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
3006                                         "undelivered transaction %d\n",
3007                                         t->debug_id);
3008                                 t->buffer->transaction = NULL;
3009                                 kfree(t);
3010                                 binder_stats_deleted(BINDER_STAT_TRANSACTION);
3011                         }
3012                 } break;
3013                 case BINDER_WORK_TRANSACTION_COMPLETE: {
3014                         binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
3015                                 "undelivered TRANSACTION_COMPLETE\n");
3016                         kfree(w);
3017                         binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
3018                 } break;
3019                 case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
3020                 case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: {
3021                         struct binder_ref_death *death;
3022
3023                         death = container_of(w, struct binder_ref_death, work);
3024                         binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
3025                                 "undelivered death notification, %016llx\n",
3026                                 (u64)death->cookie);
3027                         kfree(death);
3028                         binder_stats_deleted(BINDER_STAT_DEATH);
3029                 } break;
3030                 default:
3031                         pr_err("unexpected work type, %d, not freed\n",
3032                                w->type);
3033                         break;
3034                 }
3035         }
3036
3037 }
3038
3039 static struct binder_thread *binder_get_thread(struct binder_proc *proc)
3040 {
3041         struct binder_thread *thread = NULL;
3042         struct rb_node *parent = NULL;
3043         struct rb_node **p = &proc->threads.rb_node;
3044
3045         while (*p) {
3046                 parent = *p;
3047                 thread = rb_entry(parent, struct binder_thread, rb_node);
3048
3049                 if (current->pid < thread->pid)
3050                         p = &(*p)->rb_left;
3051                 else if (current->pid > thread->pid)
3052                         p = &(*p)->rb_right;
3053                 else
3054                         break;
3055         }
3056         if (*p == NULL) {
3057                 thread = kzalloc(sizeof(*thread), GFP_KERNEL);
3058                 if (thread == NULL)
3059                         return NULL;
3060                 binder_stats_created(BINDER_STAT_THREAD);
3061                 thread->proc = proc;
3062                 thread->pid = current->pid;
3063                 init_waitqueue_head(&thread->wait);
3064                 INIT_LIST_HEAD(&thread->todo);
3065                 rb_link_node(&thread->rb_node, parent, p);
3066                 rb_insert_color(&thread->rb_node, &proc->threads);
3067                 thread->looper |= BINDER_LOOPER_STATE_NEED_RETURN;
3068                 thread->return_error = BR_OK;
3069                 thread->return_error2 = BR_OK;
3070         }
3071         return thread;
3072 }
3073
3074 static int binder_free_thread(struct binder_proc *proc,
3075                               struct binder_thread *thread)
3076 {
3077         struct binder_transaction *t;
3078         struct binder_transaction *send_reply = NULL;
3079         int active_transactions = 0;
3080
3081         rb_erase(&thread->rb_node, &proc->threads);
3082         t = thread->transaction_stack;
3083         if (t && t->to_thread == thread)
3084                 send_reply = t;
3085         while (t) {
3086                 active_transactions++;
3087                 binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
3088                              "release %d:%d transaction %d %s, still active\n",
3089                               proc->pid, thread->pid,
3090                              t->debug_id,
3091                              (t->to_thread == thread) ? "in" : "out");
3092
3093                 if (t->to_thread == thread) {
3094                         t->to_proc = NULL;
3095                         t->to_thread = NULL;
3096                         if (t->buffer) {
3097                                 t->buffer->transaction = NULL;
3098                                 t->buffer = NULL;
3099                         }
3100                         t = t->to_parent;
3101                 } else if (t->from == thread) {
3102                         t->from = NULL;
3103                         t = t->from_parent;
3104                 } else
3105                         BUG();
3106         }
3107         if (send_reply)
3108                 binder_send_failed_reply(send_reply, BR_DEAD_REPLY);
3109         binder_release_work(&thread->todo);
3110         kfree(thread);
3111         binder_stats_deleted(BINDER_STAT_THREAD);
3112         return active_transactions;
3113 }
3114
3115 static unsigned int binder_poll(struct file *filp,
3116                                 struct poll_table_struct *wait)
3117 {
3118         struct binder_proc *proc = filp->private_data;
3119         struct binder_thread *thread = NULL;
3120         int wait_for_proc_work;
3121
3122         binder_lock(proc->context, __func__);
3123
3124         thread = binder_get_thread(proc);
3125
3126         wait_for_proc_work = thread->transaction_stack == NULL &&
3127                 list_empty(&thread->todo) && thread->return_error == BR_OK;
3128
3129         binder_unlock(proc->context, __func__);
3130
3131         if (wait_for_proc_work) {
3132                 if (binder_has_proc_work(proc, thread))
3133                         return POLLIN;
3134                 poll_wait(filp, &proc->wait, wait);
3135                 if (binder_has_proc_work(proc, thread))
3136                         return POLLIN;
3137         } else {
3138                 if (binder_has_thread_work(thread))
3139                         return POLLIN;
3140                 poll_wait(filp, &thread->wait, wait);
3141                 if (binder_has_thread_work(thread))
3142                         return POLLIN;
3143         }
3144         return 0;
3145 }
3146
3147 static int binder_ioctl_write_read(struct file *filp,
3148                                 unsigned int cmd, unsigned long arg,
3149                                 struct binder_thread *thread)
3150 {
3151         int ret = 0;
3152         struct binder_proc *proc = filp->private_data;
3153         unsigned int size = _IOC_SIZE(cmd);
3154         void __user *ubuf = (void __user *)arg;
3155         struct binder_write_read bwr;
3156
3157         if (size != sizeof(struct binder_write_read)) {
3158                 ret = -EINVAL;
3159                 goto out;
3160         }
3161         if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {
3162                 ret = -EFAULT;
3163                 goto out;
3164         }
3165         binder_debug(BINDER_DEBUG_READ_WRITE,
3166                      "%d:%d write %lld at %016llx, read %lld at %016llx\n",
3167                      proc->pid, thread->pid,
3168                      (u64)bwr.write_size, (u64)bwr.write_buffer,
3169                      (u64)bwr.read_size, (u64)bwr.read_buffer);
3170
3171         if (bwr.write_size > 0) {
3172                 ret = binder_thread_write(proc, thread,
3173                                           bwr.write_buffer,
3174                                           bwr.write_size,
3175                                           &bwr.write_consumed);
3176                 trace_binder_write_done(ret);
3177                 if (ret < 0) {
3178                         bwr.read_consumed = 0;
3179                         if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
3180                                 ret = -EFAULT;
3181                         goto out;
3182                 }
3183         }
3184         if (bwr.read_size > 0) {
3185                 ret = binder_thread_read(proc, thread, bwr.read_buffer,
3186                                          bwr.read_size,
3187                                          &bwr.read_consumed,
3188                                          filp->f_flags & O_NONBLOCK);
3189                 trace_binder_read_done(ret);
3190                 if (!list_empty(&proc->todo))
3191                         wake_up_interruptible(&proc->wait);
3192                 if (ret < 0) {
3193                         if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
3194                                 ret = -EFAULT;
3195                         goto out;
3196                 }
3197         }
3198         binder_debug(BINDER_DEBUG_READ_WRITE,
3199                      "%d:%d wrote %lld of %lld, read return %lld of %lld\n",
3200                      proc->pid, thread->pid,
3201                      (u64)bwr.write_consumed, (u64)bwr.write_size,
3202                      (u64)bwr.read_consumed, (u64)bwr.read_size);
3203         if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
3204                 ret = -EFAULT;
3205                 goto out;
3206         }
3207 out:
3208         return ret;
3209 }
3210
3211 static int binder_ioctl_set_ctx_mgr(struct file *filp)
3212 {
3213         int ret = 0;
3214         struct binder_proc *proc = filp->private_data;
3215         struct binder_context *context = proc->context;
3216
3217         kuid_t curr_euid = current_euid();
3218
3219         if (context->binder_context_mgr_node) {
3220                 pr_err("BINDER_SET_CONTEXT_MGR already set\n");
3221                 ret = -EBUSY;
3222                 goto out;
3223         }
3224         ret = security_binder_set_context_mgr(proc->tsk);
3225         if (ret < 0)
3226                 goto out;
3227         if (uid_valid(context->binder_context_mgr_uid)) {
3228                 if (!uid_eq(context->binder_context_mgr_uid, curr_euid)) {
3229                         pr_err("BINDER_SET_CONTEXT_MGR bad uid %d != %d\n",
3230                                from_kuid(&init_user_ns, curr_euid),
3231                                from_kuid(&init_user_ns,
3232                                          context->binder_context_mgr_uid));
3233                         ret = -EPERM;
3234                         goto out;
3235                 }
3236         } else {
3237                 context->binder_context_mgr_uid = curr_euid;
3238         }
3239         context->binder_context_mgr_node = binder_new_node(proc, 0, 0);
3240         if (!context->binder_context_mgr_node) {
3241                 ret = -ENOMEM;
3242                 goto out;
3243         }
3244         context->binder_context_mgr_node->local_weak_refs++;
3245         context->binder_context_mgr_node->local_strong_refs++;
3246         context->binder_context_mgr_node->has_strong_ref = 1;
3247         context->binder_context_mgr_node->has_weak_ref = 1;
3248 out:
3249         return ret;
3250 }
3251
3252 static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
3253 {
3254         int ret;
3255         struct binder_proc *proc = filp->private_data;
3256         struct binder_context *context = proc->context;
3257         struct binder_thread *thread;
3258         unsigned int size = _IOC_SIZE(cmd);
3259         void __user *ubuf = (void __user *)arg;
3260
3261         /*pr_info("binder_ioctl: %d:%d %x %lx\n",
3262                         proc->pid, current->pid, cmd, arg);*/
3263
3264         trace_binder_ioctl(cmd, arg);
3265
3266         ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
3267         if (ret)
3268                 goto err_unlocked;
3269
3270         binder_lock(context, __func__);
3271         thread = binder_get_thread(proc);
3272         if (thread == NULL) {
3273                 ret = -ENOMEM;
3274                 goto err;
3275         }
3276
3277         switch (cmd) {
3278         case BINDER_WRITE_READ:
3279                 ret = binder_ioctl_write_read(filp, cmd, arg, thread);
3280                 if (ret)
3281                         goto err;
3282                 break;
3283         case BINDER_SET_MAX_THREADS:
3284                 if (copy_from_user(&proc->max_threads, ubuf, sizeof(proc->max_threads))) {
3285                         ret = -EINVAL;
3286                         goto err;
3287                 }
3288                 break;
3289         case BINDER_SET_CONTEXT_MGR:
3290                 ret = binder_ioctl_set_ctx_mgr(filp);
3291                 if (ret)
3292                         goto err;
3293                 break;
3294         case BINDER_THREAD_EXIT:
3295                 binder_debug(BINDER_DEBUG_THREADS, "%d:%d exit\n",
3296                              proc->pid, thread->pid);
3297                 binder_free_thread(proc, thread);
3298                 thread = NULL;
3299                 break;
3300         case BINDER_VERSION: {
3301                 struct binder_version __user *ver = ubuf;
3302
3303                 if (size != sizeof(struct binder_version)) {
3304                         ret = -EINVAL;
3305                         goto err;
3306                 }
3307                 if (put_user(BINDER_CURRENT_PROTOCOL_VERSION,
3308                              &ver->protocol_version)) {
3309                         ret = -EINVAL;
3310                         goto err;
3311                 }
3312                 break;
3313         }
3314         default:
3315                 ret = -EINVAL;
3316                 goto err;
3317         }
3318         ret = 0;
3319 err:
3320         if (thread)
3321                 thread->looper &= ~BINDER_LOOPER_STATE_NEED_RETURN;
3322         binder_unlock(context, __func__);
3323         wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
3324         if (ret && ret != -ERESTARTSYS)
3325                 pr_info("%d:%d ioctl %x %lx returned %d\n", proc->pid, current->pid, cmd, arg, ret);
3326 err_unlocked:
3327         trace_binder_ioctl_done(ret);
3328         return ret;
3329 }
3330
3331 static void binder_vma_open(struct vm_area_struct *vma)
3332 {
3333         struct binder_proc *proc = vma->vm_private_data;
3334
3335         binder_debug(BINDER_DEBUG_OPEN_CLOSE,
3336                      "%d open vm area %lx-%lx (%ld K) vma %lx pagep %lx\n",
3337                      proc->pid, vma->vm_start, vma->vm_end,
3338                      (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
3339                      (unsigned long)pgprot_val(vma->vm_page_prot));
3340 }
3341
3342 static void binder_vma_close(struct vm_area_struct *vma)
3343 {
3344         struct binder_proc *proc = vma->vm_private_data;
3345
3346         binder_debug(BINDER_DEBUG_OPEN_CLOSE,
3347                      "%d close vm area %lx-%lx (%ld K) vma %lx pagep %lx\n",
3348                      proc->pid, vma->vm_start, vma->vm_end,
3349                      (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
3350                      (unsigned long)pgprot_val(vma->vm_page_prot));
3351         proc->vma = NULL;
3352         proc->vma_vm_mm = NULL;
3353         binder_defer_work(proc, BINDER_DEFERRED_PUT_FILES);
3354 }
3355
3356 static int binder_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3357 {
3358         return VM_FAULT_SIGBUS;
3359 }
3360
3361 static const struct vm_operations_struct binder_vm_ops = {
3362         .open = binder_vma_open,
3363         .close = binder_vma_close,
3364         .fault = binder_vm_fault,
3365 };
3366
3367 static int binder_mmap(struct file *filp, struct vm_area_struct *vma)
3368 {
3369         int ret;
3370         struct vm_struct *area;
3371         struct binder_proc *proc = filp->private_data;
3372         const char *failure_string;
3373         struct binder_buffer *buffer;
3374
3375         if (proc->tsk != current->group_leader)
3376                 return -EINVAL;
3377
3378         if ((vma->vm_end - vma->vm_start) > SZ_4M)
3379                 vma->vm_end = vma->vm_start + SZ_4M;
3380
3381         binder_debug(BINDER_DEBUG_OPEN_CLOSE,
3382                      "binder_mmap: %d %lx-%lx (%ld K) vma %lx pagep %lx\n",
3383                      proc->pid, vma->vm_start, vma->vm_end,
3384                      (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
3385                      (unsigned long)pgprot_val(vma->vm_page_prot));
3386
3387         if (vma->vm_flags & FORBIDDEN_MMAP_FLAGS) {
3388                 ret = -EPERM;
3389                 failure_string = "bad vm_flags";
3390                 goto err_bad_arg;
3391         }
3392         vma->vm_flags = (vma->vm_flags | VM_DONTCOPY) & ~VM_MAYWRITE;
3393
3394         mutex_lock(&proc->context->binder_mmap_lock);
3395         if (proc->buffer) {
3396                 ret = -EBUSY;
3397                 failure_string = "already mapped";
3398                 goto err_already_mapped;
3399         }
3400
3401         area = get_vm_area(vma->vm_end - vma->vm_start, VM_IOREMAP);
3402         if (area == NULL) {
3403                 ret = -ENOMEM;
3404                 failure_string = "get_vm_area";
3405                 goto err_get_vm_area_failed;
3406         }
3407         proc->buffer = area->addr;
3408         proc->user_buffer_offset = vma->vm_start - (uintptr_t)proc->buffer;
3409         mutex_unlock(&proc->context->binder_mmap_lock);
3410
3411 #ifdef CONFIG_CPU_CACHE_VIPT
3412         if (cache_is_vipt_aliasing()) {
3413                 while (CACHE_COLOUR((vma->vm_start ^ (uint32_t)proc->buffer))) {
3414                         pr_info("binder_mmap: %d %lx-%lx maps %p bad alignment\n", proc->pid, vma->vm_start, vma->vm_end, proc->buffer);
3415                         vma->vm_start += PAGE_SIZE;
3416                 }
3417         }
3418 #endif
3419         proc->pages = kzalloc(sizeof(proc->pages[0]) * ((vma->vm_end - vma->vm_start) / PAGE_SIZE), GFP_KERNEL);
3420         if (proc->pages == NULL) {
3421                 ret = -ENOMEM;
3422                 failure_string = "alloc page array";
3423                 goto err_alloc_pages_failed;
3424         }
3425         proc->buffer_size = vma->vm_end - vma->vm_start;
3426
3427         vma->vm_ops = &binder_vm_ops;
3428         vma->vm_private_data = proc;
3429
3430         if (binder_update_page_range(proc, 1, proc->buffer, proc->buffer + PAGE_SIZE, vma)) {
3431                 ret = -ENOMEM;
3432                 failure_string = "alloc small buf";
3433                 goto err_alloc_small_buf_failed;
3434         }
3435         buffer = proc->buffer;
3436         INIT_LIST_HEAD(&proc->buffers);
3437         list_add(&buffer->entry, &proc->buffers);
3438         buffer->free = 1;
3439         binder_insert_free_buffer(proc, buffer);
3440         proc->free_async_space = proc->buffer_size / 2;
3441         barrier();
3442         proc->files = get_files_struct(current);
3443         proc->vma = vma;
3444         proc->vma_vm_mm = vma->vm_mm;
3445
3446         /*pr_info("binder_mmap: %d %lx-%lx maps %p\n",
3447                  proc->pid, vma->vm_start, vma->vm_end, proc->buffer);*/
3448         return 0;
3449
3450 err_alloc_small_buf_failed:
3451         kfree(proc->pages);
3452         proc->pages = NULL;
3453 err_alloc_pages_failed:
3454         mutex_lock(&proc->context->binder_mmap_lock);
3455         vfree(proc->buffer);
3456         proc->buffer = NULL;
3457 err_get_vm_area_failed:
3458 err_already_mapped:
3459         mutex_unlock(&proc->context->binder_mmap_lock);
3460 err_bad_arg:
3461         pr_err("binder_mmap: %d %lx-%lx %s failed %d\n",
3462                proc->pid, vma->vm_start, vma->vm_end, failure_string, ret);
3463         return ret;
3464 }
3465
3466 static int binder_open(struct inode *nodp, struct file *filp)
3467 {
3468         struct binder_proc *proc;
3469         struct binder_device *binder_dev;
3470
3471         binder_debug(BINDER_DEBUG_OPEN_CLOSE, "binder_open: %d:%d\n",
3472                      current->group_leader->pid, current->pid);
3473
3474         proc = kzalloc(sizeof(*proc), GFP_KERNEL);
3475         if (proc == NULL)
3476                 return -ENOMEM;
3477         get_task_struct(current->group_leader);
3478         proc->tsk = current->group_leader;
3479         INIT_LIST_HEAD(&proc->todo);
3480         init_waitqueue_head(&proc->wait);
3481         proc->default_priority = task_nice(current);
3482         binder_dev = container_of(filp->private_data, struct binder_device,
3483                                   miscdev);
3484         proc->context = &binder_dev->context;
3485
3486         binder_lock(proc->context, __func__);
3487
3488         binder_stats_created(BINDER_STAT_PROC);
3489         hlist_add_head(&proc->proc_node, &proc->context->binder_procs);
3490         proc->pid = current->group_leader->pid;
3491         INIT_LIST_HEAD(&proc->delivered_death);
3492         filp->private_data = proc;
3493
3494         binder_unlock(proc->context, __func__);
3495
3496         if (binder_debugfs_dir_entry_proc) {
3497                 char strbuf[11];
3498
3499                 snprintf(strbuf, sizeof(strbuf), "%u", proc->pid);
3500                 /*
3501                  * proc debug entries are shared between contexts, so
3502                  * this will fail if the process tries to open the driver
3503                  * again with a different context. The priting code will
3504                  * anyway print all contexts that a given PID has, so this
3505                  * is not a problem.
3506                  */
3507                 proc->debugfs_entry = debugfs_create_file(strbuf, S_IRUGO,
3508                         binder_debugfs_dir_entry_proc,
3509                         (void *)(unsigned long)proc->pid,
3510                         &binder_proc_fops);
3511         }
3512
3513         return 0;
3514 }
3515
3516 static int binder_flush(struct file *filp, fl_owner_t id)
3517 {
3518         struct binder_proc *proc = filp->private_data;
3519
3520         binder_defer_work(proc, BINDER_DEFERRED_FLUSH);
3521
3522         return 0;
3523 }
3524
3525 static void binder_deferred_flush(struct binder_proc *proc)
3526 {
3527         struct rb_node *n;
3528         int wake_count = 0;
3529
3530         for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n)) {
3531                 struct binder_thread *thread = rb_entry(n, struct binder_thread, rb_node);
3532
3533                 thread->looper |= BINDER_LOOPER_STATE_NEED_RETURN;
3534                 if (thread->looper & BINDER_LOOPER_STATE_WAITING) {
3535                         wake_up_interruptible(&thread->wait);
3536                         wake_count++;
3537                 }
3538         }
3539         wake_up_interruptible_all(&proc->wait);
3540
3541         binder_debug(BINDER_DEBUG_OPEN_CLOSE,
3542                      "binder_flush: %d woke %d threads\n", proc->pid,
3543                      wake_count);
3544 }
3545
3546 static int binder_release(struct inode *nodp, struct file *filp)
3547 {
3548         struct binder_proc *proc = filp->private_data;
3549
3550         debugfs_remove(proc->debugfs_entry);
3551         binder_defer_work(proc, BINDER_DEFERRED_RELEASE);
3552
3553         return 0;
3554 }
3555
3556 static int binder_node_release(struct binder_node *node, int refs)
3557 {
3558         struct binder_ref *ref;
3559         struct binder_context *context = node->proc->context;
3560         int death = 0;
3561
3562         list_del_init(&node->work.entry);
3563         binder_release_work(&node->async_todo);
3564
3565         if (hlist_empty(&node->refs)) {
3566                 kfree(node);
3567                 binder_stats_deleted(BINDER_STAT_NODE);
3568
3569                 return refs;
3570         }
3571
3572         node->proc = NULL;
3573         node->local_strong_refs = 0;
3574         node->local_weak_refs = 0;
3575         hlist_add_head(&node->dead_node, &context->binder_dead_nodes);
3576
3577         hlist_for_each_entry(ref, &node->refs, node_entry) {
3578                 refs++;
3579
3580                 if (!ref->death)
3581                         continue;
3582
3583                 death++;
3584
3585                 if (list_empty(&ref->death->work.entry)) {
3586                         ref->death->work.type = BINDER_WORK_DEAD_BINDER;
3587                         list_add_tail(&ref->death->work.entry,
3588                                       &ref->proc->todo);
3589                         wake_up_interruptible(&ref->proc->wait);
3590                 } else
3591                         BUG();
3592         }
3593
3594         binder_debug(BINDER_DEBUG_DEAD_BINDER,
3595                      "node %d now dead, refs %d, death %d\n",
3596                      node->debug_id, refs, death);
3597
3598         return refs;
3599 }
3600
3601 static void binder_deferred_release(struct binder_proc *proc)
3602 {
3603         struct binder_transaction *t;
3604         struct binder_context *context = proc->context;
3605         struct rb_node *n;
3606         int threads, nodes, incoming_refs, outgoing_refs, buffers,
3607                 active_transactions, page_count;
3608
3609         BUG_ON(proc->vma);
3610         BUG_ON(proc->files);
3611
3612         hlist_del(&proc->proc_node);
3613
3614         if (context->binder_context_mgr_node &&
3615             context->binder_context_mgr_node->proc == proc) {
3616                 binder_debug(BINDER_DEBUG_DEAD_BINDER,
3617                              "%s: %d context_mgr_node gone\n",
3618                              __func__, proc->pid);
3619                 context->binder_context_mgr_node = NULL;
3620         }
3621
3622         threads = 0;
3623         active_transactions = 0;
3624         while ((n = rb_first(&proc->threads))) {
3625                 struct binder_thread *thread;
3626
3627                 thread = rb_entry(n, struct binder_thread, rb_node);
3628                 threads++;
3629                 active_transactions += binder_free_thread(proc, thread);
3630         }
3631
3632         nodes = 0;
3633         incoming_refs = 0;
3634         while ((n = rb_first(&proc->nodes))) {
3635                 struct binder_node *node;
3636
3637                 node = rb_entry(n, struct binder_node, rb_node);
3638                 nodes++;
3639                 rb_erase(&node->rb_node, &proc->nodes);
3640                 incoming_refs = binder_node_release(node,
3641                                                     incoming_refs);
3642         }
3643
3644         outgoing_refs = 0;
3645         while ((n = rb_first(&proc->refs_by_desc))) {
3646                 struct binder_ref *ref;
3647
3648                 ref = rb_entry(n, struct binder_ref, rb_node_desc);
3649                 outgoing_refs++;
3650                 binder_delete_ref(ref);
3651         }
3652
3653         binder_release_work(&proc->todo);
3654         binder_release_work(&proc->delivered_death);
3655
3656         buffers = 0;
3657         while ((n = rb_first(&proc->allocated_buffers))) {
3658                 struct binder_buffer *buffer;
3659
3660                 buffer = rb_entry(n, struct binder_buffer, rb_node);
3661
3662                 t = buffer->transaction;
3663                 if (t) {
3664                         t->buffer = NULL;
3665                         buffer->transaction = NULL;
3666                         pr_err("release proc %d, transaction %d, not freed\n",
3667                                proc->pid, t->debug_id);
3668                         /*BUG();*/
3669                 }
3670
3671                 binder_free_buf(proc, buffer);
3672                 buffers++;
3673         }
3674
3675         binder_stats_deleted(BINDER_STAT_PROC);
3676
3677         page_count = 0;
3678         if (proc->pages) {
3679                 int i;
3680
3681                 for (i = 0; i < proc->buffer_size / PAGE_SIZE; i++) {
3682                         void *page_addr;
3683
3684                         if (!proc->pages[i])
3685                                 continue;
3686
3687                         page_addr = proc->buffer + i * PAGE_SIZE;
3688                         binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
3689                                      "%s: %d: page %d at %p not freed\n",
3690                                      __func__, proc->pid, i, page_addr);
3691                         unmap_kernel_range((unsigned long)page_addr, PAGE_SIZE);
3692                         __free_page(proc->pages[i]);
3693                         page_count++;
3694                 }
3695                 kfree(proc->pages);
3696                 vfree(proc->buffer);
3697         }
3698
3699         put_task_struct(proc->tsk);
3700
3701         binder_debug(BINDER_DEBUG_OPEN_CLOSE,
3702                      "%s: %d threads %d, nodes %d (ref %d), refs %d, active transactions %d, buffers %d, pages %d\n",
3703                      __func__, proc->pid, threads, nodes, incoming_refs,
3704                      outgoing_refs, active_transactions, buffers, page_count);
3705
3706         kfree(proc);
3707 }
3708
3709 static void binder_deferred_func(struct work_struct *work)
3710 {
3711         struct binder_proc *proc;
3712         struct files_struct *files;
3713         struct binder_context *context =
3714                 container_of(work, struct binder_context, deferred_work);
3715
3716         int defer;
3717
3718         do {
3719                 binder_lock(context, __func__);
3720                 mutex_lock(&context->binder_deferred_lock);
3721                 if (!hlist_empty(&context->binder_deferred_list)) {
3722                         proc = hlist_entry(context->binder_deferred_list.first,
3723                                         struct binder_proc, deferred_work_node);
3724                         hlist_del_init(&proc->deferred_work_node);
3725                         defer = proc->deferred_work;
3726                         proc->deferred_work = 0;
3727                 } else {
3728                         proc = NULL;
3729                         defer = 0;
3730                 }
3731                 mutex_unlock(&context->binder_deferred_lock);
3732
3733                 files = NULL;
3734                 if (defer & BINDER_DEFERRED_PUT_FILES) {
3735                         files = proc->files;
3736                         if (files)
3737                                 proc->files = NULL;
3738                 }
3739
3740                 if (defer & BINDER_DEFERRED_FLUSH)
3741                         binder_deferred_flush(proc);
3742
3743                 if (defer & BINDER_DEFERRED_RELEASE)
3744                         binder_deferred_release(proc); /* frees proc */
3745
3746                 binder_unlock(context, __func__);
3747                 if (files)
3748                         put_files_struct(files);
3749         } while (proc);
3750 }
3751
3752 static void
3753 binder_defer_work(struct binder_proc *proc, enum binder_deferred_state defer)
3754 {
3755         mutex_lock(&proc->context->binder_deferred_lock);
3756         proc->deferred_work |= defer;
3757         if (hlist_unhashed(&proc->deferred_work_node)) {
3758                 hlist_add_head(&proc->deferred_work_node,
3759                                 &proc->context->binder_deferred_list);
3760                 queue_work(proc->context->binder_deferred_workqueue,
3761                            &proc->context->deferred_work);
3762         }
3763         mutex_unlock(&proc->context->binder_deferred_lock);
3764 }
3765
3766 static void print_binder_transaction(struct seq_file *m, const char *prefix,
3767                                      struct binder_transaction *t)
3768 {
3769         seq_printf(m,
3770                    "%s %d: %p from %d:%d to %d:%d code %x flags %x pri %ld r%d",
3771                    prefix, t->debug_id, t,
3772                    t->from ? t->from->proc->pid : 0,
3773                    t->from ? t->from->pid : 0,
3774                    t->to_proc ? t->to_proc->pid : 0,
3775                    t->to_thread ? t->to_thread->pid : 0,
3776                    t->code, t->flags, t->priority, t->need_reply);
3777         if (t->buffer == NULL) {
3778                 seq_puts(m, " buffer free\n");
3779                 return;
3780         }
3781         if (t->buffer->target_node)
3782                 seq_printf(m, " node %d",
3783                            t->buffer->target_node->debug_id);
3784         seq_printf(m, " size %zd:%zd data %p\n",
3785                    t->buffer->data_size, t->buffer->offsets_size,
3786                    t->buffer->data);
3787 }
3788
3789 static void print_binder_buffer(struct seq_file *m, const char *prefix,
3790                                 struct binder_buffer *buffer)
3791 {
3792         seq_printf(m, "%s %d: %p size %zd:%zd %s\n",
3793                    prefix, buffer->debug_id, buffer->data,
3794                    buffer->data_size, buffer->offsets_size,
3795                    buffer->transaction ? "active" : "delivered");
3796 }
3797
3798 static void print_binder_work(struct seq_file *m, const char *prefix,
3799                               const char *transaction_prefix,
3800                               struct binder_work *w)
3801 {
3802         struct binder_node *node;
3803         struct binder_transaction *t;
3804
3805         switch (w->type) {
3806         case BINDER_WORK_TRANSACTION:
3807                 t = container_of(w, struct binder_transaction, work);
3808                 print_binder_transaction(m, transaction_prefix, t);
3809                 break;
3810         case BINDER_WORK_TRANSACTION_COMPLETE:
3811                 seq_printf(m, "%stransaction complete\n", prefix);
3812                 break;
3813         case BINDER_WORK_NODE:
3814                 node = container_of(w, struct binder_node, work);
3815                 seq_printf(m, "%snode work %d: u%016llx c%016llx\n",
3816                            prefix, node->debug_id,
3817                            (u64)node->ptr, (u64)node->cookie);
3818                 break;
3819         case BINDER_WORK_DEAD_BINDER:
3820                 seq_printf(m, "%shas dead binder\n", prefix);
3821                 break;
3822         case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
3823                 seq_printf(m, "%shas cleared dead binder\n", prefix);
3824                 break;
3825         case BINDER_WORK_CLEAR_DEATH_NOTIFICATION:
3826                 seq_printf(m, "%shas cleared death notification\n", prefix);
3827                 break;
3828         default:
3829                 seq_printf(m, "%sunknown work: type %d\n", prefix, w->type);
3830                 break;
3831         }
3832 }
3833
3834 static void print_binder_thread(struct seq_file *m,
3835                                 struct binder_thread *thread,
3836                                 int print_always)
3837 {
3838         struct binder_transaction *t;
3839         struct binder_work *w;
3840         size_t start_pos = m->count;
3841         size_t header_pos;
3842
3843         seq_printf(m, "  thread %d: l %02x\n", thread->pid, thread->looper);
3844         header_pos = m->count;
3845         t = thread->transaction_stack;
3846         while (t) {
3847                 if (t->from == thread) {
3848                         print_binder_transaction(m,
3849                                                  "    outgoing transaction", t);
3850                         t = t->from_parent;
3851                 } else if (t->to_thread == thread) {
3852                         print_binder_transaction(m,
3853                                                  "    incoming transaction", t);
3854                         t = t->to_parent;
3855                 } else {
3856                         print_binder_transaction(m, "    bad transaction", t);
3857                         t = NULL;
3858                 }
3859         }
3860         list_for_each_entry(w, &thread->todo, entry) {
3861                 print_binder_work(m, "    ", "    pending transaction", w);
3862         }
3863         if (!print_always && m->count == header_pos)
3864                 m->count = start_pos;
3865 }
3866
3867 static void print_binder_node(struct seq_file *m, struct binder_node *node)
3868 {
3869         struct binder_ref *ref;
3870         struct binder_work *w;
3871         int count;
3872
3873         count = 0;
3874         hlist_for_each_entry(ref, &node->refs, node_entry)
3875                 count++;
3876
3877         seq_printf(m, "  node %d: u%016llx c%016llx hs %d hw %d ls %d lw %d is %d iw %d",
3878                    node->debug_id, (u64)node->ptr, (u64)node->cookie,
3879                    node->has_strong_ref, node->has_weak_ref,
3880                    node->local_strong_refs, node->local_weak_refs,
3881                    node->internal_strong_refs, count);
3882         if (count) {
3883                 seq_puts(m, " proc");
3884                 hlist_for_each_entry(ref, &node->refs, node_entry)
3885                         seq_printf(m, " %d", ref->proc->pid);
3886         }
3887         seq_puts(m, "\n");
3888         list_for_each_entry(w, &node->async_todo, entry)
3889                 print_binder_work(m, "    ",
3890                                   "    pending async transaction", w);
3891 }
3892
3893 static void print_binder_ref(struct seq_file *m, struct binder_ref *ref)
3894 {
3895         seq_printf(m, "  ref %d: desc %d %snode %d s %d w %d d %p\n",
3896                    ref->debug_id, ref->desc, ref->node->proc ? "" : "dead ",
3897                    ref->node->debug_id, ref->strong, ref->weak, ref->death);
3898 }
3899
3900 static void print_binder_proc(struct seq_file *m,
3901                               struct binder_proc *proc, int print_all)
3902 {
3903         struct binder_work *w;
3904         struct rb_node *n;
3905         size_t start_pos = m->count;
3906         size_t header_pos;
3907
3908         seq_printf(m, "proc %d\n", proc->pid);
3909         seq_printf(m, "context %s\n", proc->context->name);
3910         header_pos = m->count;
3911
3912         for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n))
3913                 print_binder_thread(m, rb_entry(n, struct binder_thread,
3914                                                 rb_node), print_all);
3915         for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n)) {
3916                 struct binder_node *node = rb_entry(n, struct binder_node,
3917                                                     rb_node);
3918                 if (print_all || node->has_async_transaction)
3919                         print_binder_node(m, node);
3920         }
3921         if (print_all) {
3922                 for (n = rb_first(&proc->refs_by_desc);
3923                      n != NULL;
3924                      n = rb_next(n))
3925                         print_binder_ref(m, rb_entry(n, struct binder_ref,
3926                                                      rb_node_desc));
3927         }
3928         for (n = rb_first(&proc->allocated_buffers); n != NULL; n = rb_next(n))
3929                 print_binder_buffer(m, "  buffer",
3930                                     rb_entry(n, struct binder_buffer, rb_node));
3931         list_for_each_entry(w, &proc->todo, entry)
3932                 print_binder_work(m, "  ", "  pending transaction", w);
3933         list_for_each_entry(w, &proc->delivered_death, entry) {
3934                 seq_puts(m, "  has delivered dead binder\n");
3935                 break;
3936         }
3937         if (!print_all && m->count == header_pos)
3938                 m->count = start_pos;
3939 }
3940
3941 static const char * const binder_return_strings[] = {
3942         "BR_ERROR",
3943         "BR_OK",
3944         "BR_TRANSACTION",
3945         "BR_REPLY",
3946         "BR_ACQUIRE_RESULT",
3947         "BR_DEAD_REPLY",
3948         "BR_TRANSACTION_COMPLETE",
3949         "BR_INCREFS",
3950         "BR_ACQUIRE",
3951         "BR_RELEASE",
3952         "BR_DECREFS",
3953         "BR_ATTEMPT_ACQUIRE",
3954         "BR_NOOP",
3955         "BR_SPAWN_LOOPER",
3956         "BR_FINISHED",
3957         "BR_DEAD_BINDER",
3958         "BR_CLEAR_DEATH_NOTIFICATION_DONE",
3959         "BR_FAILED_REPLY"
3960 };
3961
3962 static const char * const binder_command_strings[] = {
3963         "BC_TRANSACTION",
3964         "BC_REPLY",
3965         "BC_ACQUIRE_RESULT",
3966         "BC_FREE_BUFFER",
3967         "BC_INCREFS",
3968         "BC_ACQUIRE",
3969         "BC_RELEASE",
3970         "BC_DECREFS",
3971         "BC_INCREFS_DONE",
3972         "BC_ACQUIRE_DONE",
3973         "BC_ATTEMPT_ACQUIRE",
3974         "BC_REGISTER_LOOPER",
3975         "BC_ENTER_LOOPER",
3976         "BC_EXIT_LOOPER",
3977         "BC_REQUEST_DEATH_NOTIFICATION",
3978         "BC_CLEAR_DEATH_NOTIFICATION",
3979         "BC_DEAD_BINDER_DONE",
3980         "BC_TRANSACTION_SG",
3981         "BC_REPLY_SG",
3982 };
3983
3984 static const char * const binder_objstat_strings[] = {
3985         "proc",
3986         "thread",
3987         "node",
3988         "ref",
3989         "death",
3990         "transaction",
3991         "transaction_complete"
3992 };
3993
3994 static void add_binder_stats(struct binder_stats *from, struct binder_stats *to)
3995 {
3996         int i;
3997
3998         for (i = 0; i < ARRAY_SIZE(to->bc); i++)
3999                 to->bc[i] += from->bc[i];
4000
4001         for (i = 0; i < ARRAY_SIZE(to->br); i++)
4002                 to->br[i] += from->br[i];
4003 }
4004
4005 static void print_binder_stats(struct seq_file *m, const char *prefix,
4006                                struct binder_stats *stats,
4007                                struct binder_obj_stats *obj_stats)
4008 {
4009         int i;
4010
4011         BUILD_BUG_ON(ARRAY_SIZE(stats->bc) !=
4012                      ARRAY_SIZE(binder_command_strings));
4013         for (i = 0; i < ARRAY_SIZE(stats->bc); i++) {
4014                 if (stats->bc[i])
4015                         seq_printf(m, "%s%s: %d\n", prefix,
4016                                    binder_command_strings[i], stats->bc[i]);
4017         }
4018
4019         BUILD_BUG_ON(ARRAY_SIZE(stats->br) !=
4020                      ARRAY_SIZE(binder_return_strings));
4021         for (i = 0; i < ARRAY_SIZE(stats->br); i++) {
4022                 if (stats->br[i])
4023                         seq_printf(m, "%s%s: %d\n", prefix,
4024                                    binder_return_strings[i], stats->br[i]);
4025         }
4026
4027         if (!obj_stats)
4028                 return;
4029
4030         BUILD_BUG_ON(ARRAY_SIZE(obj_stats->obj_created) !=
4031                      ARRAY_SIZE(binder_objstat_strings));
4032         BUILD_BUG_ON(ARRAY_SIZE(obj_stats->obj_created) !=
4033                      ARRAY_SIZE(obj_stats->obj_deleted));
4034         for (i = 0; i < ARRAY_SIZE(obj_stats->obj_created); i++) {
4035                 int obj_created = atomic_read(&obj_stats->obj_created[i]);
4036                 int obj_deleted = atomic_read(&obj_stats->obj_deleted[i]);
4037
4038                 if (obj_created || obj_deleted)
4039                         seq_printf(m, "%s%s: active %d total %d\n", prefix,
4040                                    binder_objstat_strings[i],
4041                                    obj_created - obj_deleted, obj_created);
4042         }
4043 }
4044
4045 static void print_binder_proc_stats(struct seq_file *m,
4046                                     struct binder_proc *proc)
4047 {
4048         struct binder_work *w;
4049         struct rb_node *n;
4050         int count, strong, weak;
4051
4052         seq_printf(m, "proc %d\n", proc->pid);
4053         seq_printf(m, "context %s\n", proc->context->name);
4054         count = 0;
4055         for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n))
4056                 count++;
4057         seq_printf(m, "  threads: %d\n", count);
4058         seq_printf(m, "  requested threads: %d+%d/%d\n"
4059                         "  ready threads %d\n"
4060                         "  free async space %zd\n", proc->requested_threads,
4061                         proc->requested_threads_started, proc->max_threads,
4062                         proc->ready_threads, proc->free_async_space);
4063         count = 0;
4064         for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n))
4065                 count++;
4066         seq_printf(m, "  nodes: %d\n", count);
4067         count = 0;
4068         strong = 0;
4069         weak = 0;
4070         for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {
4071                 struct binder_ref *ref = rb_entry(n, struct binder_ref,
4072                                                   rb_node_desc);
4073                 count++;
4074                 strong += ref->strong;
4075                 weak += ref->weak;
4076         }
4077         seq_printf(m, "  refs: %d s %d w %d\n", count, strong, weak);
4078
4079         count = 0;
4080         for (n = rb_first(&proc->allocated_buffers); n != NULL; n = rb_next(n))
4081                 count++;
4082         seq_printf(m, "  buffers: %d\n", count);
4083
4084         count = 0;
4085         list_for_each_entry(w, &proc->todo, entry) {
4086                 switch (w->type) {
4087                 case BINDER_WORK_TRANSACTION:
4088                         count++;
4089                         break;
4090                 default:
4091                         break;
4092                 }
4093         }
4094         seq_printf(m, "  pending transactions: %d\n", count);
4095
4096         print_binder_stats(m, "  ", &proc->stats, NULL);
4097 }
4098
4099
4100 static int binder_state_show(struct seq_file *m, void *unused)
4101 {
4102         struct binder_device *device;
4103         struct binder_context *context;
4104         struct binder_proc *proc;
4105         struct binder_node *node;
4106         int do_lock = !binder_debug_no_lock;
4107         bool wrote_dead_nodes_header = false;
4108
4109         seq_puts(m, "binder state:\n");
4110
4111         hlist_for_each_entry(device, &binder_devices, hlist) {
4112                 context = &device->context;
4113                 if (do_lock)
4114                         binder_lock(context, __func__);
4115                 if (!wrote_dead_nodes_header &&
4116                     !hlist_empty(&context->binder_dead_nodes)) {
4117                         seq_puts(m, "dead nodes:\n");
4118                         wrote_dead_nodes_header = true;
4119                 }
4120                 hlist_for_each_entry(node, &context->binder_dead_nodes,
4121                                      dead_node)
4122                         print_binder_node(m, node);
4123
4124                 if (do_lock)
4125                         binder_unlock(context, __func__);
4126         }
4127
4128         hlist_for_each_entry(device, &binder_devices, hlist) {
4129                 context = &device->context;
4130                 if (do_lock)
4131                         binder_lock(context, __func__);
4132
4133                 hlist_for_each_entry(proc, &context->binder_procs, proc_node)
4134                         print_binder_proc(m, proc, 1);
4135                 if (do_lock)
4136                         binder_unlock(context, __func__);
4137         }
4138         return 0;
4139 }
4140
4141 static int binder_stats_show(struct seq_file *m, void *unused)
4142 {
4143         struct binder_device *device;
4144         struct binder_context *context;
4145         struct binder_proc *proc;
4146         struct binder_stats total_binder_stats;
4147         int do_lock = !binder_debug_no_lock;
4148
4149         memset(&total_binder_stats, 0, sizeof(struct binder_stats));
4150
4151         hlist_for_each_entry(device, &binder_devices, hlist) {
4152                 context = &device->context;
4153                 if (do_lock)
4154                         binder_lock(context, __func__);
4155
4156                 add_binder_stats(&context->binder_stats, &total_binder_stats);
4157
4158                 if (do_lock)
4159                         binder_unlock(context, __func__);
4160         }
4161
4162         seq_puts(m, "binder stats:\n");
4163         print_binder_stats(m, "", &total_binder_stats, &binder_obj_stats);
4164
4165         hlist_for_each_entry(device, &binder_devices, hlist) {
4166                 context = &device->context;
4167                 if (do_lock)
4168                         binder_lock(context, __func__);
4169
4170                 hlist_for_each_entry(proc, &context->binder_procs, proc_node)
4171                         print_binder_proc_stats(m, proc);
4172                 if (do_lock)
4173                         binder_unlock(context, __func__);
4174         }
4175         return 0;
4176 }
4177
4178 static int binder_transactions_show(struct seq_file *m, void *unused)
4179 {
4180         struct binder_device *device;
4181         struct binder_context *context;
4182         struct binder_proc *proc;
4183         int do_lock = !binder_debug_no_lock;
4184
4185         seq_puts(m, "binder transactions:\n");
4186         hlist_for_each_entry(device, &binder_devices, hlist) {
4187                 context = &device->context;
4188                 if (do_lock)
4189                         binder_lock(context, __func__);
4190
4191                 hlist_for_each_entry(proc, &context->binder_procs, proc_node)
4192                         print_binder_proc(m, proc, 0);
4193                 if (do_lock)
4194                         binder_unlock(context, __func__);
4195         }
4196         return 0;
4197 }
4198
4199 static int binder_proc_show(struct seq_file *m, void *unused)
4200 {
4201         struct binder_device *device;
4202         struct binder_context *context;
4203         struct binder_proc *itr;
4204         int pid = (unsigned long)m->private;
4205         int do_lock = !binder_debug_no_lock;
4206
4207         hlist_for_each_entry(device, &binder_devices, hlist) {
4208                 context = &device->context;
4209                 if (do_lock)
4210                         binder_lock(context, __func__);
4211
4212                 hlist_for_each_entry(itr, &context->binder_procs, proc_node) {
4213                         if (itr->pid == pid) {
4214                                 seq_puts(m, "binder proc state:\n");
4215                                 print_binder_proc(m, itr, 1);
4216                         }
4217                 }
4218                 if (do_lock)
4219                         binder_unlock(context, __func__);
4220         }
4221         return 0;
4222 }
4223
4224 static void print_binder_transaction_log_entry(struct seq_file *m,
4225                                         struct binder_transaction_log_entry *e)
4226 {
4227         seq_printf(m,
4228                    "%d: %s from %d:%d to %d:%d context %s node %d handle %d size %d:%d\n",
4229                    e->debug_id, (e->call_type == 2) ? "reply" :
4230                    ((e->call_type == 1) ? "async" : "call "), e->from_proc,
4231                    e->from_thread, e->to_proc, e->to_thread, e->context_name,
4232                    e->to_node, e->target_handle, e->data_size, e->offsets_size);
4233 }
4234
4235 static int print_binder_transaction_log(struct seq_file *m,
4236                                         struct binder_transaction_log *log)
4237 {
4238         int i;
4239         if (log->full) {
4240                 for (i = log->next; i < ARRAY_SIZE(log->entry); i++)
4241                         print_binder_transaction_log_entry(m, &log->entry[i]);
4242         }
4243         for (i = 0; i < log->next; i++)
4244                 print_binder_transaction_log_entry(m, &log->entry[i]);
4245         return 0;
4246 }
4247
4248 static int binder_transaction_log_show(struct seq_file *m, void *unused)
4249 {
4250         struct binder_device *device;
4251         struct binder_context *context;
4252
4253         hlist_for_each_entry(device, &binder_devices, hlist) {
4254                 context = &device->context;
4255                 print_binder_transaction_log(m, &context->transaction_log);
4256         }
4257         return 0;
4258 }
4259
4260 static int binder_failed_transaction_log_show(struct seq_file *m, void *unused)
4261 {
4262         struct binder_device *device;
4263         struct binder_context *context;
4264
4265         hlist_for_each_entry(device, &binder_devices, hlist) {
4266                 context = &device->context;
4267                 print_binder_transaction_log(m,
4268                                              &context->transaction_log_failed);
4269         }
4270         return 0;
4271 }
4272
4273 static const struct file_operations binder_fops = {
4274         .owner = THIS_MODULE,
4275         .poll = binder_poll,
4276         .unlocked_ioctl = binder_ioctl,
4277         .compat_ioctl = binder_ioctl,
4278         .mmap = binder_mmap,
4279         .open = binder_open,
4280         .flush = binder_flush,
4281         .release = binder_release,
4282 };
4283
4284 BINDER_DEBUG_ENTRY(state);
4285 BINDER_DEBUG_ENTRY(stats);
4286 BINDER_DEBUG_ENTRY(transactions);
4287 BINDER_DEBUG_ENTRY(transaction_log);
4288 BINDER_DEBUG_ENTRY(failed_transaction_log);
4289
4290 static void __init free_binder_device(struct binder_device *device)
4291 {
4292         if (device->context.binder_deferred_workqueue)
4293                 destroy_workqueue(device->context.binder_deferred_workqueue);
4294         kfree(device);
4295 }
4296
4297 static int __init init_binder_device(const char *name)
4298 {
4299         int ret;
4300         struct binder_device *binder_device;
4301         struct binder_context *context;
4302
4303         binder_device = kzalloc(sizeof(*binder_device), GFP_KERNEL);
4304         if (!binder_device)
4305                 return -ENOMEM;
4306
4307         binder_device->miscdev.fops = &binder_fops;
4308         binder_device->miscdev.minor = MISC_DYNAMIC_MINOR;
4309         binder_device->miscdev.name = name;
4310
4311         context = &binder_device->context;
4312         context->binder_context_mgr_uid = INVALID_UID;
4313         context->name = name;
4314
4315         mutex_init(&context->binder_main_lock);
4316         mutex_init(&context->binder_deferred_lock);
4317         mutex_init(&context->binder_mmap_lock);
4318
4319         context->binder_deferred_workqueue =
4320                 create_singlethread_workqueue(name);
4321
4322         if (!context->binder_deferred_workqueue) {
4323                 ret = -ENOMEM;
4324                 goto err_create_singlethread_workqueue_failed;
4325         }
4326
4327         INIT_HLIST_HEAD(&context->binder_procs);
4328         INIT_HLIST_HEAD(&context->binder_dead_nodes);
4329         INIT_HLIST_HEAD(&context->binder_deferred_list);
4330         INIT_WORK(&context->deferred_work, binder_deferred_func);
4331
4332         ret = misc_register(&binder_device->miscdev);
4333         if (ret < 0) {
4334                 goto err_misc_register_failed;
4335         }
4336
4337         hlist_add_head(&binder_device->hlist, &binder_devices);
4338         return ret;
4339
4340 err_create_singlethread_workqueue_failed:
4341 err_misc_register_failed:
4342         free_binder_device(binder_device);
4343
4344         return ret;
4345 }
4346
4347 static int __init binder_init(void)
4348 {
4349         int ret = 0;
4350         char *device_name, *device_names;
4351         struct binder_device *device;
4352         struct hlist_node *tmp;
4353
4354         /*
4355          * Copy the module_parameter string, because we don't want to
4356          * tokenize it in-place.
4357          */
4358         device_names = kzalloc(strlen(binder_devices_param) + 1, GFP_KERNEL);
4359         if (!device_names)
4360                 return -ENOMEM;
4361
4362         strcpy(device_names, binder_devices_param);
4363
4364         while ((device_name = strsep(&device_names, ","))) {
4365                 ret = init_binder_device(device_name);
4366                 if (ret)
4367                         goto err_init_binder_device_failed;
4368         }
4369
4370         binder_debugfs_dir_entry_root = debugfs_create_dir("binder", NULL);
4371         if (binder_debugfs_dir_entry_root)
4372                 binder_debugfs_dir_entry_proc = debugfs_create_dir("proc",
4373                                                  binder_debugfs_dir_entry_root);
4374
4375         if (binder_debugfs_dir_entry_root) {
4376                 debugfs_create_file("state",
4377                                     S_IRUGO,
4378                                     binder_debugfs_dir_entry_root,
4379                                     NULL,
4380                                     &binder_state_fops);
4381                 debugfs_create_file("stats",
4382                                     S_IRUGO,
4383                                     binder_debugfs_dir_entry_root,
4384                                     NULL,
4385                                     &binder_stats_fops);
4386                 debugfs_create_file("transactions",
4387                                     S_IRUGO,
4388                                     binder_debugfs_dir_entry_root,
4389                                     NULL,
4390                                     &binder_transactions_fops);
4391                 debugfs_create_file("transaction_log",
4392                                     S_IRUGO,
4393                                     binder_debugfs_dir_entry_root,
4394                                     NULL,
4395                                     &binder_transaction_log_fops);
4396                 debugfs_create_file("failed_transaction_log",
4397                                     S_IRUGO,
4398                                     binder_debugfs_dir_entry_root,
4399                                     NULL,
4400                                     &binder_failed_transaction_log_fops);
4401         }
4402
4403         return ret;
4404
4405 err_init_binder_device_failed:
4406         hlist_for_each_entry_safe(device, tmp, &binder_devices, hlist) {
4407                 misc_deregister(&device->miscdev);
4408                 hlist_del(&device->hlist);
4409                 free_binder_device(device);
4410         }
4411
4412         return ret;
4413 }
4414
4415 device_initcall(binder_init);
4416
4417 #define CREATE_TRACE_POINTS
4418 #include "binder_trace.h"
4419
4420 MODULE_LICENSE("GPL v2");