GNU Linux-libre 4.14.254-gnu1
[releases.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 /*
19  * Locking overview
20  *
21  * There are 3 main spinlocks which must be acquired in the
22  * order shown:
23  *
24  * 1) proc->outer_lock : protects binder_ref
25  *    binder_proc_lock() and binder_proc_unlock() are
26  *    used to acq/rel.
27  * 2) node->lock : protects most fields of binder_node.
28  *    binder_node_lock() and binder_node_unlock() are
29  *    used to acq/rel
30  * 3) proc->inner_lock : protects the thread and node lists
31  *    (proc->threads, proc->waiting_threads, proc->nodes)
32  *    and all todo lists associated with the binder_proc
33  *    (proc->todo, thread->todo, proc->delivered_death and
34  *    node->async_todo), as well as thread->transaction_stack
35  *    binder_inner_proc_lock() and binder_inner_proc_unlock()
36  *    are used to acq/rel
37  *
38  * Any lock under procA must never be nested under any lock at the same
39  * level or below on procB.
40  *
41  * Functions that require a lock held on entry indicate which lock
42  * in the suffix of the function name:
43  *
44  * foo_olocked() : requires node->outer_lock
45  * foo_nlocked() : requires node->lock
46  * foo_ilocked() : requires proc->inner_lock
47  * foo_oilocked(): requires proc->outer_lock and proc->inner_lock
48  * foo_nilocked(): requires node->lock and proc->inner_lock
49  * ...
50  */
51
52 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
53
54 #include <asm/cacheflush.h>
55 #include <linux/fdtable.h>
56 #include <linux/file.h>
57 #include <linux/freezer.h>
58 #include <linux/fs.h>
59 #include <linux/list.h>
60 #include <linux/miscdevice.h>
61 #include <linux/module.h>
62 #include <linux/mutex.h>
63 #include <linux/nsproxy.h>
64 #include <linux/poll.h>
65 #include <linux/debugfs.h>
66 #include <linux/rbtree.h>
67 #include <linux/sched/signal.h>
68 #include <linux/sched/mm.h>
69 #include <linux/seq_file.h>
70 #include <linux/uaccess.h>
71 #include <linux/pid_namespace.h>
72 #include <linux/security.h>
73 #include <linux/spinlock.h>
74
75 #ifdef CONFIG_ANDROID_BINDER_IPC_32BIT
76 #define BINDER_IPC_32BIT 1
77 #endif
78
79 #include <uapi/linux/android/binder.h>
80 #include "binder_alloc.h"
81 #include "binder_trace.h"
82
83 static HLIST_HEAD(binder_deferred_list);
84 static DEFINE_MUTEX(binder_deferred_lock);
85
86 static HLIST_HEAD(binder_devices);
87 static HLIST_HEAD(binder_procs);
88 static DEFINE_MUTEX(binder_procs_lock);
89
90 static HLIST_HEAD(binder_dead_nodes);
91 static DEFINE_SPINLOCK(binder_dead_nodes_lock);
92
93 static struct dentry *binder_debugfs_dir_entry_root;
94 static struct dentry *binder_debugfs_dir_entry_proc;
95 static atomic_t binder_last_id;
96
97 #define BINDER_DEBUG_ENTRY(name) \
98 static int binder_##name##_open(struct inode *inode, struct file *file) \
99 { \
100         return single_open(file, binder_##name##_show, inode->i_private); \
101 } \
102 \
103 static const struct file_operations binder_##name##_fops = { \
104         .owner = THIS_MODULE, \
105         .open = binder_##name##_open, \
106         .read = seq_read, \
107         .llseek = seq_lseek, \
108         .release = single_release, \
109 }
110
111 static int binder_proc_show(struct seq_file *m, void *unused);
112 BINDER_DEBUG_ENTRY(proc);
113
114 /* This is only defined in include/asm-arm/sizes.h */
115 #ifndef SZ_1K
116 #define SZ_1K                               0x400
117 #endif
118
119 #ifndef SZ_4M
120 #define SZ_4M                               0x400000
121 #endif
122
123 #define FORBIDDEN_MMAP_FLAGS                (VM_WRITE)
124
125 enum {
126         BINDER_DEBUG_USER_ERROR             = 1U << 0,
127         BINDER_DEBUG_FAILED_TRANSACTION     = 1U << 1,
128         BINDER_DEBUG_DEAD_TRANSACTION       = 1U << 2,
129         BINDER_DEBUG_OPEN_CLOSE             = 1U << 3,
130         BINDER_DEBUG_DEAD_BINDER            = 1U << 4,
131         BINDER_DEBUG_DEATH_NOTIFICATION     = 1U << 5,
132         BINDER_DEBUG_READ_WRITE             = 1U << 6,
133         BINDER_DEBUG_USER_REFS              = 1U << 7,
134         BINDER_DEBUG_THREADS                = 1U << 8,
135         BINDER_DEBUG_TRANSACTION            = 1U << 9,
136         BINDER_DEBUG_TRANSACTION_COMPLETE   = 1U << 10,
137         BINDER_DEBUG_FREE_BUFFER            = 1U << 11,
138         BINDER_DEBUG_INTERNAL_REFS          = 1U << 12,
139         BINDER_DEBUG_PRIORITY_CAP           = 1U << 13,
140         BINDER_DEBUG_SPINLOCKS              = 1U << 14,
141 };
142 static uint32_t binder_debug_mask = BINDER_DEBUG_USER_ERROR |
143         BINDER_DEBUG_FAILED_TRANSACTION | BINDER_DEBUG_DEAD_TRANSACTION;
144 module_param_named(debug_mask, binder_debug_mask, uint, S_IWUSR | S_IRUGO);
145
146 static char *binder_devices_param = CONFIG_ANDROID_BINDER_DEVICES;
147 module_param_named(devices, binder_devices_param, charp, 0444);
148
149 static DECLARE_WAIT_QUEUE_HEAD(binder_user_error_wait);
150 static int binder_stop_on_user_error;
151
152 static int binder_set_stop_on_user_error(const char *val,
153                                          struct kernel_param *kp)
154 {
155         int ret;
156
157         ret = param_set_int(val, kp);
158         if (binder_stop_on_user_error < 2)
159                 wake_up(&binder_user_error_wait);
160         return ret;
161 }
162 module_param_call(stop_on_user_error, binder_set_stop_on_user_error,
163         param_get_int, &binder_stop_on_user_error, S_IWUSR | S_IRUGO);
164
165 #define binder_debug(mask, x...) \
166         do { \
167                 if (binder_debug_mask & mask) \
168                         pr_info(x); \
169         } while (0)
170
171 #define binder_user_error(x...) \
172         do { \
173                 if (binder_debug_mask & BINDER_DEBUG_USER_ERROR) \
174                         pr_info(x); \
175                 if (binder_stop_on_user_error) \
176                         binder_stop_on_user_error = 2; \
177         } while (0)
178
179 #define to_flat_binder_object(hdr) \
180         container_of(hdr, struct flat_binder_object, hdr)
181
182 #define to_binder_fd_object(hdr) container_of(hdr, struct binder_fd_object, hdr)
183
184 #define to_binder_buffer_object(hdr) \
185         container_of(hdr, struct binder_buffer_object, hdr)
186
187 #define to_binder_fd_array_object(hdr) \
188         container_of(hdr, struct binder_fd_array_object, hdr)
189
190 enum binder_stat_types {
191         BINDER_STAT_PROC,
192         BINDER_STAT_THREAD,
193         BINDER_STAT_NODE,
194         BINDER_STAT_REF,
195         BINDER_STAT_DEATH,
196         BINDER_STAT_TRANSACTION,
197         BINDER_STAT_TRANSACTION_COMPLETE,
198         BINDER_STAT_COUNT
199 };
200
201 struct binder_stats {
202         atomic_t br[_IOC_NR(BR_FAILED_REPLY) + 1];
203         atomic_t bc[_IOC_NR(BC_REPLY_SG) + 1];
204         atomic_t obj_created[BINDER_STAT_COUNT];
205         atomic_t obj_deleted[BINDER_STAT_COUNT];
206 };
207
208 static struct binder_stats binder_stats;
209
210 static inline void binder_stats_deleted(enum binder_stat_types type)
211 {
212         atomic_inc(&binder_stats.obj_deleted[type]);
213 }
214
215 static inline void binder_stats_created(enum binder_stat_types type)
216 {
217         atomic_inc(&binder_stats.obj_created[type]);
218 }
219
220 struct binder_transaction_log_entry {
221         int debug_id;
222         int debug_id_done;
223         int call_type;
224         int from_proc;
225         int from_thread;
226         int target_handle;
227         int to_proc;
228         int to_thread;
229         int to_node;
230         int data_size;
231         int offsets_size;
232         int return_error_line;
233         uint32_t return_error;
234         uint32_t return_error_param;
235         const char *context_name;
236 };
237 struct binder_transaction_log {
238         atomic_t cur;
239         bool full;
240         struct binder_transaction_log_entry entry[32];
241 };
242 static struct binder_transaction_log binder_transaction_log;
243 static struct binder_transaction_log binder_transaction_log_failed;
244
245 static struct binder_transaction_log_entry *binder_transaction_log_add(
246         struct binder_transaction_log *log)
247 {
248         struct binder_transaction_log_entry *e;
249         unsigned int cur = atomic_inc_return(&log->cur);
250
251         if (cur >= ARRAY_SIZE(log->entry))
252                 log->full = 1;
253         e = &log->entry[cur % ARRAY_SIZE(log->entry)];
254         WRITE_ONCE(e->debug_id_done, 0);
255         /*
256          * write-barrier to synchronize access to e->debug_id_done.
257          * We make sure the initialized 0 value is seen before
258          * memset() other fields are zeroed by memset.
259          */
260         smp_wmb();
261         memset(e, 0, sizeof(*e));
262         return e;
263 }
264
265 struct binder_context {
266         struct binder_node *binder_context_mgr_node;
267         struct mutex context_mgr_node_lock;
268
269         kuid_t binder_context_mgr_uid;
270         const char *name;
271 };
272
273 struct binder_device {
274         struct hlist_node hlist;
275         struct miscdevice miscdev;
276         struct binder_context context;
277 };
278
279 /**
280  * struct binder_work - work enqueued on a worklist
281  * @entry:             node enqueued on list
282  * @type:              type of work to be performed
283  *
284  * There are separate work lists for proc, thread, and node (async).
285  */
286 struct binder_work {
287         struct list_head entry;
288
289         enum binder_work_type {
290                 BINDER_WORK_TRANSACTION = 1,
291                 BINDER_WORK_TRANSACTION_COMPLETE,
292                 BINDER_WORK_RETURN_ERROR,
293                 BINDER_WORK_NODE,
294                 BINDER_WORK_DEAD_BINDER,
295                 BINDER_WORK_DEAD_BINDER_AND_CLEAR,
296                 BINDER_WORK_CLEAR_DEATH_NOTIFICATION,
297         } type;
298 };
299
300 struct binder_error {
301         struct binder_work work;
302         uint32_t cmd;
303 };
304
305 /**
306  * struct binder_node - binder node bookkeeping
307  * @debug_id:             unique ID for debugging
308  *                        (invariant after initialized)
309  * @lock:                 lock for node fields
310  * @work:                 worklist element for node work
311  *                        (protected by @proc->inner_lock)
312  * @rb_node:              element for proc->nodes tree
313  *                        (protected by @proc->inner_lock)
314  * @dead_node:            element for binder_dead_nodes list
315  *                        (protected by binder_dead_nodes_lock)
316  * @proc:                 binder_proc that owns this node
317  *                        (invariant after initialized)
318  * @refs:                 list of references on this node
319  *                        (protected by @lock)
320  * @internal_strong_refs: used to take strong references when
321  *                        initiating a transaction
322  *                        (protected by @proc->inner_lock if @proc
323  *                        and by @lock)
324  * @local_weak_refs:      weak user refs from local process
325  *                        (protected by @proc->inner_lock if @proc
326  *                        and by @lock)
327  * @local_strong_refs:    strong user refs from local process
328  *                        (protected by @proc->inner_lock if @proc
329  *                        and by @lock)
330  * @tmp_refs:             temporary kernel refs
331  *                        (protected by @proc->inner_lock while @proc
332  *                        is valid, and by binder_dead_nodes_lock
333  *                        if @proc is NULL. During inc/dec and node release
334  *                        it is also protected by @lock to provide safety
335  *                        as the node dies and @proc becomes NULL)
336  * @ptr:                  userspace pointer for node
337  *                        (invariant, no lock needed)
338  * @cookie:               userspace cookie for node
339  *                        (invariant, no lock needed)
340  * @has_strong_ref:       userspace notified of strong ref
341  *                        (protected by @proc->inner_lock if @proc
342  *                        and by @lock)
343  * @pending_strong_ref:   userspace has acked notification of strong ref
344  *                        (protected by @proc->inner_lock if @proc
345  *                        and by @lock)
346  * @has_weak_ref:         userspace notified of weak ref
347  *                        (protected by @proc->inner_lock if @proc
348  *                        and by @lock)
349  * @pending_weak_ref:     userspace has acked notification of weak ref
350  *                        (protected by @proc->inner_lock if @proc
351  *                        and by @lock)
352  * @has_async_transaction: async transaction to node in progress
353  *                        (protected by @lock)
354  * @accept_fds:           file descriptor operations supported for node
355  *                        (invariant after initialized)
356  * @min_priority:         minimum scheduling priority
357  *                        (invariant after initialized)
358  * @async_todo:           list of async work items
359  *                        (protected by @proc->inner_lock)
360  *
361  * Bookkeeping structure for binder nodes.
362  */
363 struct binder_node {
364         int debug_id;
365         spinlock_t lock;
366         struct binder_work work;
367         union {
368                 struct rb_node rb_node;
369                 struct hlist_node dead_node;
370         };
371         struct binder_proc *proc;
372         struct hlist_head refs;
373         int internal_strong_refs;
374         int local_weak_refs;
375         int local_strong_refs;
376         int tmp_refs;
377         binder_uintptr_t ptr;
378         binder_uintptr_t cookie;
379         struct {
380                 /*
381                  * bitfield elements protected by
382                  * proc inner_lock
383                  */
384                 u8 has_strong_ref:1;
385                 u8 pending_strong_ref:1;
386                 u8 has_weak_ref:1;
387                 u8 pending_weak_ref:1;
388         };
389         struct {
390                 /*
391                  * invariant after initialization
392                  */
393                 u8 accept_fds:1;
394                 u8 min_priority;
395         };
396         bool has_async_transaction;
397         struct list_head async_todo;
398 };
399
400 struct binder_ref_death {
401         /**
402          * @work: worklist element for death notifications
403          *        (protected by inner_lock of the proc that
404          *        this ref belongs to)
405          */
406         struct binder_work work;
407         binder_uintptr_t cookie;
408 };
409
410 /**
411  * struct binder_ref_data - binder_ref counts and id
412  * @debug_id:        unique ID for the ref
413  * @desc:            unique userspace handle for ref
414  * @strong:          strong ref count (debugging only if not locked)
415  * @weak:            weak ref count (debugging only if not locked)
416  *
417  * Structure to hold ref count and ref id information. Since
418  * the actual ref can only be accessed with a lock, this structure
419  * is used to return information about the ref to callers of
420  * ref inc/dec functions.
421  */
422 struct binder_ref_data {
423         int debug_id;
424         uint32_t desc;
425         int strong;
426         int weak;
427 };
428
429 /**
430  * struct binder_ref - struct to track references on nodes
431  * @data:        binder_ref_data containing id, handle, and current refcounts
432  * @rb_node_desc: node for lookup by @data.desc in proc's rb_tree
433  * @rb_node_node: node for lookup by @node in proc's rb_tree
434  * @node_entry:  list entry for node->refs list in target node
435  *               (protected by @node->lock)
436  * @proc:        binder_proc containing ref
437  * @node:        binder_node of target node. When cleaning up a
438  *               ref for deletion in binder_cleanup_ref, a non-NULL
439  *               @node indicates the node must be freed
440  * @death:       pointer to death notification (ref_death) if requested
441  *               (protected by @node->lock)
442  *
443  * Structure to track references from procA to target node (on procB). This
444  * structure is unsafe to access without holding @proc->outer_lock.
445  */
446 struct binder_ref {
447         /* Lookups needed: */
448         /*   node + proc => ref (transaction) */
449         /*   desc + proc => ref (transaction, inc/dec ref) */
450         /*   node => refs + procs (proc exit) */
451         struct binder_ref_data data;
452         struct rb_node rb_node_desc;
453         struct rb_node rb_node_node;
454         struct hlist_node node_entry;
455         struct binder_proc *proc;
456         struct binder_node *node;
457         struct binder_ref_death *death;
458 };
459
460 enum binder_deferred_state {
461         BINDER_DEFERRED_PUT_FILES    = 0x01,
462         BINDER_DEFERRED_FLUSH        = 0x02,
463         BINDER_DEFERRED_RELEASE      = 0x04,
464 };
465
466 /**
467  * struct binder_proc - binder process bookkeeping
468  * @proc_node:            element for binder_procs list
469  * @threads:              rbtree of binder_threads in this proc
470  *                        (protected by @inner_lock)
471  * @nodes:                rbtree of binder nodes associated with
472  *                        this proc ordered by node->ptr
473  *                        (protected by @inner_lock)
474  * @refs_by_desc:         rbtree of refs ordered by ref->desc
475  *                        (protected by @outer_lock)
476  * @refs_by_node:         rbtree of refs ordered by ref->node
477  *                        (protected by @outer_lock)
478  * @waiting_threads:      threads currently waiting for proc work
479  *                        (protected by @inner_lock)
480  * @pid                   PID of group_leader of process
481  *                        (invariant after initialized)
482  * @tsk                   task_struct for group_leader of process
483  *                        (invariant after initialized)
484  * @files                 files_struct for process
485  *                        (protected by @files_lock)
486  * @files_lock            mutex to protect @files
487  * @deferred_work_node:   element for binder_deferred_list
488  *                        (protected by binder_deferred_lock)
489  * @deferred_work:        bitmap of deferred work to perform
490  *                        (protected by binder_deferred_lock)
491  * @is_dead:              process is dead and awaiting free
492  *                        when outstanding transactions are cleaned up
493  *                        (protected by @inner_lock)
494  * @todo:                 list of work for this process
495  *                        (protected by @inner_lock)
496  * @wait:                 wait queue head to wait for proc work
497  *                        (invariant after initialized)
498  * @stats:                per-process binder statistics
499  *                        (atomics, no lock needed)
500  * @delivered_death:      list of delivered death notification
501  *                        (protected by @inner_lock)
502  * @max_threads:          cap on number of binder threads
503  *                        (protected by @inner_lock)
504  * @requested_threads:    number of binder threads requested but not
505  *                        yet started. In current implementation, can
506  *                        only be 0 or 1.
507  *                        (protected by @inner_lock)
508  * @requested_threads_started: number binder threads started
509  *                        (protected by @inner_lock)
510  * @tmp_ref:              temporary reference to indicate proc is in use
511  *                        (protected by @inner_lock)
512  * @default_priority:     default scheduler priority
513  *                        (invariant after initialized)
514  * @debugfs_entry:        debugfs node
515  * @alloc:                binder allocator bookkeeping
516  * @context:              binder_context for this proc
517  *                        (invariant after initialized)
518  * @inner_lock:           can nest under outer_lock and/or node lock
519  * @outer_lock:           no nesting under innor or node lock
520  *                        Lock order: 1) outer, 2) node, 3) inner
521  *
522  * Bookkeeping structure for binder processes
523  */
524 struct binder_proc {
525         struct hlist_node proc_node;
526         struct rb_root threads;
527         struct rb_root nodes;
528         struct rb_root refs_by_desc;
529         struct rb_root refs_by_node;
530         struct list_head waiting_threads;
531         int pid;
532         struct task_struct *tsk;
533         struct files_struct *files;
534         struct mutex files_lock;
535         struct hlist_node deferred_work_node;
536         int deferred_work;
537         bool is_dead;
538
539         struct list_head todo;
540         wait_queue_head_t wait;
541         struct binder_stats stats;
542         struct list_head delivered_death;
543         int max_threads;
544         int requested_threads;
545         int requested_threads_started;
546         int tmp_ref;
547         long default_priority;
548         struct dentry *debugfs_entry;
549         struct binder_alloc alloc;
550         struct binder_context *context;
551         spinlock_t inner_lock;
552         spinlock_t outer_lock;
553 };
554
555 enum {
556         BINDER_LOOPER_STATE_REGISTERED  = 0x01,
557         BINDER_LOOPER_STATE_ENTERED     = 0x02,
558         BINDER_LOOPER_STATE_EXITED      = 0x04,
559         BINDER_LOOPER_STATE_INVALID     = 0x08,
560         BINDER_LOOPER_STATE_WAITING     = 0x10,
561         BINDER_LOOPER_STATE_POLL        = 0x20,
562 };
563
564 /**
565  * struct binder_thread - binder thread bookkeeping
566  * @proc:                 binder process for this thread
567  *                        (invariant after initialization)
568  * @rb_node:              element for proc->threads rbtree
569  *                        (protected by @proc->inner_lock)
570  * @waiting_thread_node:  element for @proc->waiting_threads list
571  *                        (protected by @proc->inner_lock)
572  * @pid:                  PID for this thread
573  *                        (invariant after initialization)
574  * @looper:               bitmap of looping state
575  *                        (only accessed by this thread)
576  * @looper_needs_return:  looping thread needs to exit driver
577  *                        (no lock needed)
578  * @transaction_stack:    stack of in-progress transactions for this thread
579  *                        (protected by @proc->inner_lock)
580  * @todo:                 list of work to do for this thread
581  *                        (protected by @proc->inner_lock)
582  * @return_error:         transaction errors reported by this thread
583  *                        (only accessed by this thread)
584  * @reply_error:          transaction errors reported by target thread
585  *                        (protected by @proc->inner_lock)
586  * @wait:                 wait queue for thread work
587  * @stats:                per-thread statistics
588  *                        (atomics, no lock needed)
589  * @tmp_ref:              temporary reference to indicate thread is in use
590  *                        (atomic since @proc->inner_lock cannot
591  *                        always be acquired)
592  * @is_dead:              thread is dead and awaiting free
593  *                        when outstanding transactions are cleaned up
594  *                        (protected by @proc->inner_lock)
595  *
596  * Bookkeeping structure for binder threads.
597  */
598 struct binder_thread {
599         struct binder_proc *proc;
600         struct rb_node rb_node;
601         struct list_head waiting_thread_node;
602         int pid;
603         int looper;              /* only modified by this thread */
604         bool looper_need_return; /* can be written by other thread */
605         struct binder_transaction *transaction_stack;
606         struct list_head todo;
607         struct binder_error return_error;
608         struct binder_error reply_error;
609         wait_queue_head_t wait;
610         struct binder_stats stats;
611         atomic_t tmp_ref;
612         bool is_dead;
613 };
614
615 struct binder_transaction {
616         int debug_id;
617         struct binder_work work;
618         struct binder_thread *from;
619         struct binder_transaction *from_parent;
620         struct binder_proc *to_proc;
621         struct binder_thread *to_thread;
622         struct binder_transaction *to_parent;
623         unsigned need_reply:1;
624         /* unsigned is_dead:1; */       /* not used at the moment */
625
626         struct binder_buffer *buffer;
627         unsigned int    code;
628         unsigned int    flags;
629         long    priority;
630         long    saved_priority;
631         kuid_t  sender_euid;
632         /**
633          * @lock:  protects @from, @to_proc, and @to_thread
634          *
635          * @from, @to_proc, and @to_thread can be set to NULL
636          * during thread teardown
637          */
638         spinlock_t lock;
639 };
640
641 /**
642  * binder_proc_lock() - Acquire outer lock for given binder_proc
643  * @proc:         struct binder_proc to acquire
644  *
645  * Acquires proc->outer_lock. Used to protect binder_ref
646  * structures associated with the given proc.
647  */
648 #define binder_proc_lock(proc) _binder_proc_lock(proc, __LINE__)
649 static void
650 _binder_proc_lock(struct binder_proc *proc, int line)
651 {
652         binder_debug(BINDER_DEBUG_SPINLOCKS,
653                      "%s: line=%d\n", __func__, line);
654         spin_lock(&proc->outer_lock);
655 }
656
657 /**
658  * binder_proc_unlock() - Release spinlock for given binder_proc
659  * @proc:         struct binder_proc to acquire
660  *
661  * Release lock acquired via binder_proc_lock()
662  */
663 #define binder_proc_unlock(_proc) _binder_proc_unlock(_proc, __LINE__)
664 static void
665 _binder_proc_unlock(struct binder_proc *proc, int line)
666 {
667         binder_debug(BINDER_DEBUG_SPINLOCKS,
668                      "%s: line=%d\n", __func__, line);
669         spin_unlock(&proc->outer_lock);
670 }
671
672 /**
673  * binder_inner_proc_lock() - Acquire inner lock for given binder_proc
674  * @proc:         struct binder_proc to acquire
675  *
676  * Acquires proc->inner_lock. Used to protect todo lists
677  */
678 #define binder_inner_proc_lock(proc) _binder_inner_proc_lock(proc, __LINE__)
679 static void
680 _binder_inner_proc_lock(struct binder_proc *proc, int line)
681 {
682         binder_debug(BINDER_DEBUG_SPINLOCKS,
683                      "%s: line=%d\n", __func__, line);
684         spin_lock(&proc->inner_lock);
685 }
686
687 /**
688  * binder_inner_proc_unlock() - Release inner lock for given binder_proc
689  * @proc:         struct binder_proc to acquire
690  *
691  * Release lock acquired via binder_inner_proc_lock()
692  */
693 #define binder_inner_proc_unlock(proc) _binder_inner_proc_unlock(proc, __LINE__)
694 static void
695 _binder_inner_proc_unlock(struct binder_proc *proc, int line)
696 {
697         binder_debug(BINDER_DEBUG_SPINLOCKS,
698                      "%s: line=%d\n", __func__, line);
699         spin_unlock(&proc->inner_lock);
700 }
701
702 /**
703  * binder_node_lock() - Acquire spinlock for given binder_node
704  * @node:         struct binder_node to acquire
705  *
706  * Acquires node->lock. Used to protect binder_node fields
707  */
708 #define binder_node_lock(node) _binder_node_lock(node, __LINE__)
709 static void
710 _binder_node_lock(struct binder_node *node, int line)
711 {
712         binder_debug(BINDER_DEBUG_SPINLOCKS,
713                      "%s: line=%d\n", __func__, line);
714         spin_lock(&node->lock);
715 }
716
717 /**
718  * binder_node_unlock() - Release spinlock for given binder_proc
719  * @node:         struct binder_node to acquire
720  *
721  * Release lock acquired via binder_node_lock()
722  */
723 #define binder_node_unlock(node) _binder_node_unlock(node, __LINE__)
724 static void
725 _binder_node_unlock(struct binder_node *node, int line)
726 {
727         binder_debug(BINDER_DEBUG_SPINLOCKS,
728                      "%s: line=%d\n", __func__, line);
729         spin_unlock(&node->lock);
730 }
731
732 /**
733  * binder_node_inner_lock() - Acquire node and inner locks
734  * @node:         struct binder_node to acquire
735  *
736  * Acquires node->lock. If node->proc also acquires
737  * proc->inner_lock. Used to protect binder_node fields
738  */
739 #define binder_node_inner_lock(node) _binder_node_inner_lock(node, __LINE__)
740 static void
741 _binder_node_inner_lock(struct binder_node *node, int line)
742 {
743         binder_debug(BINDER_DEBUG_SPINLOCKS,
744                      "%s: line=%d\n", __func__, line);
745         spin_lock(&node->lock);
746         if (node->proc)
747                 binder_inner_proc_lock(node->proc);
748 }
749
750 /**
751  * binder_node_unlock() - Release node and inner locks
752  * @node:         struct binder_node to acquire
753  *
754  * Release lock acquired via binder_node_lock()
755  */
756 #define binder_node_inner_unlock(node) _binder_node_inner_unlock(node, __LINE__)
757 static void
758 _binder_node_inner_unlock(struct binder_node *node, int line)
759 {
760         struct binder_proc *proc = node->proc;
761
762         binder_debug(BINDER_DEBUG_SPINLOCKS,
763                      "%s: line=%d\n", __func__, line);
764         if (proc)
765                 binder_inner_proc_unlock(proc);
766         spin_unlock(&node->lock);
767 }
768
769 static bool binder_worklist_empty_ilocked(struct list_head *list)
770 {
771         return list_empty(list);
772 }
773
774 /**
775  * binder_worklist_empty() - Check if no items on the work list
776  * @proc:       binder_proc associated with list
777  * @list:       list to check
778  *
779  * Return: true if there are no items on list, else false
780  */
781 static bool binder_worklist_empty(struct binder_proc *proc,
782                                   struct list_head *list)
783 {
784         bool ret;
785
786         binder_inner_proc_lock(proc);
787         ret = binder_worklist_empty_ilocked(list);
788         binder_inner_proc_unlock(proc);
789         return ret;
790 }
791
792 static void
793 binder_enqueue_work_ilocked(struct binder_work *work,
794                            struct list_head *target_list)
795 {
796         BUG_ON(target_list == NULL);
797         BUG_ON(work->entry.next && !list_empty(&work->entry));
798         list_add_tail(&work->entry, target_list);
799 }
800
801 /**
802  * binder_enqueue_work() - Add an item to the work list
803  * @proc:         binder_proc associated with list
804  * @work:         struct binder_work to add to list
805  * @target_list:  list to add work to
806  *
807  * Adds the work to the specified list. Asserts that work
808  * is not already on a list.
809  */
810 static void
811 binder_enqueue_work(struct binder_proc *proc,
812                     struct binder_work *work,
813                     struct list_head *target_list)
814 {
815         binder_inner_proc_lock(proc);
816         binder_enqueue_work_ilocked(work, target_list);
817         binder_inner_proc_unlock(proc);
818 }
819
820 static void
821 binder_dequeue_work_ilocked(struct binder_work *work)
822 {
823         list_del_init(&work->entry);
824 }
825
826 /**
827  * binder_dequeue_work() - Removes an item from the work list
828  * @proc:         binder_proc associated with list
829  * @work:         struct binder_work to remove from list
830  *
831  * Removes the specified work item from whatever list it is on.
832  * Can safely be called if work is not on any list.
833  */
834 static void
835 binder_dequeue_work(struct binder_proc *proc, struct binder_work *work)
836 {
837         binder_inner_proc_lock(proc);
838         binder_dequeue_work_ilocked(work);
839         binder_inner_proc_unlock(proc);
840 }
841
842 static struct binder_work *binder_dequeue_work_head_ilocked(
843                                         struct list_head *list)
844 {
845         struct binder_work *w;
846
847         w = list_first_entry_or_null(list, struct binder_work, entry);
848         if (w)
849                 list_del_init(&w->entry);
850         return w;
851 }
852
853 static void
854 binder_defer_work(struct binder_proc *proc, enum binder_deferred_state defer);
855 static void binder_free_thread(struct binder_thread *thread);
856 static void binder_free_proc(struct binder_proc *proc);
857 static void binder_inc_node_tmpref_ilocked(struct binder_node *node);
858
859 static int task_get_unused_fd_flags(struct binder_proc *proc, int flags)
860 {
861         unsigned long rlim_cur;
862         unsigned long irqs;
863         int ret;
864
865         mutex_lock(&proc->files_lock);
866         if (proc->files == NULL) {
867                 ret = -ESRCH;
868                 goto err;
869         }
870         if (!lock_task_sighand(proc->tsk, &irqs)) {
871                 ret = -EMFILE;
872                 goto err;
873         }
874         rlim_cur = task_rlimit(proc->tsk, RLIMIT_NOFILE);
875         unlock_task_sighand(proc->tsk, &irqs);
876
877         ret = __alloc_fd(proc->files, 0, rlim_cur, flags);
878 err:
879         mutex_unlock(&proc->files_lock);
880         return ret;
881 }
882
883 /*
884  * copied from fd_install
885  */
886 static void task_fd_install(
887         struct binder_proc *proc, unsigned int fd, struct file *file)
888 {
889         mutex_lock(&proc->files_lock);
890         if (proc->files)
891                 __fd_install(proc->files, fd, file);
892         mutex_unlock(&proc->files_lock);
893 }
894
895 /*
896  * copied from sys_close
897  */
898 static long task_close_fd(struct binder_proc *proc, unsigned int fd)
899 {
900         int retval;
901
902         mutex_lock(&proc->files_lock);
903         if (proc->files == NULL) {
904                 retval = -ESRCH;
905                 goto err;
906         }
907         retval = __close_fd(proc->files, fd);
908         /* can't restart close syscall because file table entry was cleared */
909         if (unlikely(retval == -ERESTARTSYS ||
910                      retval == -ERESTARTNOINTR ||
911                      retval == -ERESTARTNOHAND ||
912                      retval == -ERESTART_RESTARTBLOCK))
913                 retval = -EINTR;
914 err:
915         mutex_unlock(&proc->files_lock);
916         return retval;
917 }
918
919 static bool binder_has_work_ilocked(struct binder_thread *thread,
920                                     bool do_proc_work)
921 {
922         return !binder_worklist_empty_ilocked(&thread->todo) ||
923                 thread->looper_need_return ||
924                 (do_proc_work &&
925                  !binder_worklist_empty_ilocked(&thread->proc->todo));
926 }
927
928 static bool binder_has_work(struct binder_thread *thread, bool do_proc_work)
929 {
930         bool has_work;
931
932         binder_inner_proc_lock(thread->proc);
933         has_work = binder_has_work_ilocked(thread, do_proc_work);
934         binder_inner_proc_unlock(thread->proc);
935
936         return has_work;
937 }
938
939 static bool binder_available_for_proc_work_ilocked(struct binder_thread *thread)
940 {
941         return !thread->transaction_stack &&
942                 binder_worklist_empty_ilocked(&thread->todo) &&
943                 (thread->looper & (BINDER_LOOPER_STATE_ENTERED |
944                                    BINDER_LOOPER_STATE_REGISTERED));
945 }
946
947 static void binder_wakeup_poll_threads_ilocked(struct binder_proc *proc,
948                                                bool sync)
949 {
950         struct rb_node *n;
951         struct binder_thread *thread;
952
953         for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n)) {
954                 thread = rb_entry(n, struct binder_thread, rb_node);
955                 if (thread->looper & BINDER_LOOPER_STATE_POLL &&
956                     binder_available_for_proc_work_ilocked(thread)) {
957                         if (sync)
958                                 wake_up_interruptible_sync(&thread->wait);
959                         else
960                                 wake_up_interruptible(&thread->wait);
961                 }
962         }
963 }
964
965 /**
966  * binder_select_thread_ilocked() - selects a thread for doing proc work.
967  * @proc:       process to select a thread from
968  *
969  * Note that calling this function moves the thread off the waiting_threads
970  * list, so it can only be woken up by the caller of this function, or a
971  * signal. Therefore, callers *should* always wake up the thread this function
972  * returns.
973  *
974  * Return:      If there's a thread currently waiting for process work,
975  *              returns that thread. Otherwise returns NULL.
976  */
977 static struct binder_thread *
978 binder_select_thread_ilocked(struct binder_proc *proc)
979 {
980         struct binder_thread *thread;
981
982         assert_spin_locked(&proc->inner_lock);
983         thread = list_first_entry_or_null(&proc->waiting_threads,
984                                           struct binder_thread,
985                                           waiting_thread_node);
986
987         if (thread)
988                 list_del_init(&thread->waiting_thread_node);
989
990         return thread;
991 }
992
993 /**
994  * binder_wakeup_thread_ilocked() - wakes up a thread for doing proc work.
995  * @proc:       process to wake up a thread in
996  * @thread:     specific thread to wake-up (may be NULL)
997  * @sync:       whether to do a synchronous wake-up
998  *
999  * This function wakes up a thread in the @proc process.
1000  * The caller may provide a specific thread to wake-up in
1001  * the @thread parameter. If @thread is NULL, this function
1002  * will wake up threads that have called poll().
1003  *
1004  * Note that for this function to work as expected, callers
1005  * should first call binder_select_thread() to find a thread
1006  * to handle the work (if they don't have a thread already),
1007  * and pass the result into the @thread parameter.
1008  */
1009 static void binder_wakeup_thread_ilocked(struct binder_proc *proc,
1010                                          struct binder_thread *thread,
1011                                          bool sync)
1012 {
1013         assert_spin_locked(&proc->inner_lock);
1014
1015         if (thread) {
1016                 if (sync)
1017                         wake_up_interruptible_sync(&thread->wait);
1018                 else
1019                         wake_up_interruptible(&thread->wait);
1020                 return;
1021         }
1022
1023         /* Didn't find a thread waiting for proc work; this can happen
1024          * in two scenarios:
1025          * 1. All threads are busy handling transactions
1026          *    In that case, one of those threads should call back into
1027          *    the kernel driver soon and pick up this work.
1028          * 2. Threads are using the (e)poll interface, in which case
1029          *    they may be blocked on the waitqueue without having been
1030          *    added to waiting_threads. For this case, we just iterate
1031          *    over all threads not handling transaction work, and
1032          *    wake them all up. We wake all because we don't know whether
1033          *    a thread that called into (e)poll is handling non-binder
1034          *    work currently.
1035          */
1036         binder_wakeup_poll_threads_ilocked(proc, sync);
1037 }
1038
1039 static void binder_wakeup_proc_ilocked(struct binder_proc *proc)
1040 {
1041         struct binder_thread *thread = binder_select_thread_ilocked(proc);
1042
1043         binder_wakeup_thread_ilocked(proc, thread, /* sync = */false);
1044 }
1045
1046 static void binder_set_nice(long nice)
1047 {
1048         long min_nice;
1049
1050         if (can_nice(current, nice)) {
1051                 set_user_nice(current, nice);
1052                 return;
1053         }
1054         min_nice = rlimit_to_nice(rlimit(RLIMIT_NICE));
1055         binder_debug(BINDER_DEBUG_PRIORITY_CAP,
1056                      "%d: nice value %ld not allowed use %ld instead\n",
1057                       current->pid, nice, min_nice);
1058         set_user_nice(current, min_nice);
1059         if (min_nice <= MAX_NICE)
1060                 return;
1061         binder_user_error("%d RLIMIT_NICE not set\n", current->pid);
1062 }
1063
1064 static struct binder_node *binder_get_node_ilocked(struct binder_proc *proc,
1065                                                    binder_uintptr_t ptr)
1066 {
1067         struct rb_node *n = proc->nodes.rb_node;
1068         struct binder_node *node;
1069
1070         assert_spin_locked(&proc->inner_lock);
1071
1072         while (n) {
1073                 node = rb_entry(n, struct binder_node, rb_node);
1074
1075                 if (ptr < node->ptr)
1076                         n = n->rb_left;
1077                 else if (ptr > node->ptr)
1078                         n = n->rb_right;
1079                 else {
1080                         /*
1081                          * take an implicit weak reference
1082                          * to ensure node stays alive until
1083                          * call to binder_put_node()
1084                          */
1085                         binder_inc_node_tmpref_ilocked(node);
1086                         return node;
1087                 }
1088         }
1089         return NULL;
1090 }
1091
1092 static struct binder_node *binder_get_node(struct binder_proc *proc,
1093                                            binder_uintptr_t ptr)
1094 {
1095         struct binder_node *node;
1096
1097         binder_inner_proc_lock(proc);
1098         node = binder_get_node_ilocked(proc, ptr);
1099         binder_inner_proc_unlock(proc);
1100         return node;
1101 }
1102
1103 static struct binder_node *binder_init_node_ilocked(
1104                                                 struct binder_proc *proc,
1105                                                 struct binder_node *new_node,
1106                                                 struct flat_binder_object *fp)
1107 {
1108         struct rb_node **p = &proc->nodes.rb_node;
1109         struct rb_node *parent = NULL;
1110         struct binder_node *node;
1111         binder_uintptr_t ptr = fp ? fp->binder : 0;
1112         binder_uintptr_t cookie = fp ? fp->cookie : 0;
1113         __u32 flags = fp ? fp->flags : 0;
1114
1115         assert_spin_locked(&proc->inner_lock);
1116
1117         while (*p) {
1118
1119                 parent = *p;
1120                 node = rb_entry(parent, struct binder_node, rb_node);
1121
1122                 if (ptr < node->ptr)
1123                         p = &(*p)->rb_left;
1124                 else if (ptr > node->ptr)
1125                         p = &(*p)->rb_right;
1126                 else {
1127                         /*
1128                          * A matching node is already in
1129                          * the rb tree. Abandon the init
1130                          * and return it.
1131                          */
1132                         binder_inc_node_tmpref_ilocked(node);
1133                         return node;
1134                 }
1135         }
1136         node = new_node;
1137         binder_stats_created(BINDER_STAT_NODE);
1138         node->tmp_refs++;
1139         rb_link_node(&node->rb_node, parent, p);
1140         rb_insert_color(&node->rb_node, &proc->nodes);
1141         node->debug_id = atomic_inc_return(&binder_last_id);
1142         node->proc = proc;
1143         node->ptr = ptr;
1144         node->cookie = cookie;
1145         node->work.type = BINDER_WORK_NODE;
1146         node->min_priority = flags & FLAT_BINDER_FLAG_PRIORITY_MASK;
1147         node->accept_fds = !!(flags & FLAT_BINDER_FLAG_ACCEPTS_FDS);
1148         spin_lock_init(&node->lock);
1149         INIT_LIST_HEAD(&node->work.entry);
1150         INIT_LIST_HEAD(&node->async_todo);
1151         binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1152                      "%d:%d node %d u%016llx c%016llx created\n",
1153                      proc->pid, current->pid, node->debug_id,
1154                      (u64)node->ptr, (u64)node->cookie);
1155
1156         return node;
1157 }
1158
1159 static struct binder_node *binder_new_node(struct binder_proc *proc,
1160                                            struct flat_binder_object *fp)
1161 {
1162         struct binder_node *node;
1163         struct binder_node *new_node = kzalloc(sizeof(*node), GFP_KERNEL);
1164
1165         if (!new_node)
1166                 return NULL;
1167         binder_inner_proc_lock(proc);
1168         node = binder_init_node_ilocked(proc, new_node, fp);
1169         binder_inner_proc_unlock(proc);
1170         if (node != new_node)
1171                 /*
1172                  * The node was already added by another thread
1173                  */
1174                 kfree(new_node);
1175
1176         return node;
1177 }
1178
1179 static void binder_free_node(struct binder_node *node)
1180 {
1181         kfree(node);
1182         binder_stats_deleted(BINDER_STAT_NODE);
1183 }
1184
1185 static int binder_inc_node_nilocked(struct binder_node *node, int strong,
1186                                     int internal,
1187                                     struct list_head *target_list)
1188 {
1189         struct binder_proc *proc = node->proc;
1190
1191         assert_spin_locked(&node->lock);
1192         if (proc)
1193                 assert_spin_locked(&proc->inner_lock);
1194         if (strong) {
1195                 if (internal) {
1196                         if (target_list == NULL &&
1197                             node->internal_strong_refs == 0 &&
1198                             !(node->proc &&
1199                               node == node->proc->context->binder_context_mgr_node &&
1200                               node->has_strong_ref)) {
1201                                 pr_err("invalid inc strong node for %d\n",
1202                                         node->debug_id);
1203                                 return -EINVAL;
1204                         }
1205                         node->internal_strong_refs++;
1206                 } else
1207                         node->local_strong_refs++;
1208                 if (!node->has_strong_ref && target_list) {
1209                         binder_dequeue_work_ilocked(&node->work);
1210                         binder_enqueue_work_ilocked(&node->work, target_list);
1211                 }
1212         } else {
1213                 if (!internal)
1214                         node->local_weak_refs++;
1215                 if (!node->has_weak_ref && list_empty(&node->work.entry)) {
1216                         if (target_list == NULL) {
1217                                 pr_err("invalid inc weak node for %d\n",
1218                                         node->debug_id);
1219                                 return -EINVAL;
1220                         }
1221                         binder_enqueue_work_ilocked(&node->work, target_list);
1222                 }
1223         }
1224         return 0;
1225 }
1226
1227 static int binder_inc_node(struct binder_node *node, int strong, int internal,
1228                            struct list_head *target_list)
1229 {
1230         int ret;
1231
1232         binder_node_inner_lock(node);
1233         ret = binder_inc_node_nilocked(node, strong, internal, target_list);
1234         binder_node_inner_unlock(node);
1235
1236         return ret;
1237 }
1238
1239 static bool binder_dec_node_nilocked(struct binder_node *node,
1240                                      int strong, int internal)
1241 {
1242         struct binder_proc *proc = node->proc;
1243
1244         assert_spin_locked(&node->lock);
1245         if (proc)
1246                 assert_spin_locked(&proc->inner_lock);
1247         if (strong) {
1248                 if (internal)
1249                         node->internal_strong_refs--;
1250                 else
1251                         node->local_strong_refs--;
1252                 if (node->local_strong_refs || node->internal_strong_refs)
1253                         return false;
1254         } else {
1255                 if (!internal)
1256                         node->local_weak_refs--;
1257                 if (node->local_weak_refs || node->tmp_refs ||
1258                                 !hlist_empty(&node->refs))
1259                         return false;
1260         }
1261
1262         if (proc && (node->has_strong_ref || node->has_weak_ref)) {
1263                 if (list_empty(&node->work.entry)) {
1264                         binder_enqueue_work_ilocked(&node->work, &proc->todo);
1265                         binder_wakeup_proc_ilocked(proc);
1266                 }
1267         } else {
1268                 if (hlist_empty(&node->refs) && !node->local_strong_refs &&
1269                     !node->local_weak_refs && !node->tmp_refs) {
1270                         if (proc) {
1271                                 binder_dequeue_work_ilocked(&node->work);
1272                                 rb_erase(&node->rb_node, &proc->nodes);
1273                                 binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1274                                              "refless node %d deleted\n",
1275                                              node->debug_id);
1276                         } else {
1277                                 BUG_ON(!list_empty(&node->work.entry));
1278                                 spin_lock(&binder_dead_nodes_lock);
1279                                 /*
1280                                  * tmp_refs could have changed so
1281                                  * check it again
1282                                  */
1283                                 if (node->tmp_refs) {
1284                                         spin_unlock(&binder_dead_nodes_lock);
1285                                         return false;
1286                                 }
1287                                 hlist_del(&node->dead_node);
1288                                 spin_unlock(&binder_dead_nodes_lock);
1289                                 binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1290                                              "dead node %d deleted\n",
1291                                              node->debug_id);
1292                         }
1293                         return true;
1294                 }
1295         }
1296         return false;
1297 }
1298
1299 static void binder_dec_node(struct binder_node *node, int strong, int internal)
1300 {
1301         bool free_node;
1302
1303         binder_node_inner_lock(node);
1304         free_node = binder_dec_node_nilocked(node, strong, internal);
1305         binder_node_inner_unlock(node);
1306         if (free_node)
1307                 binder_free_node(node);
1308 }
1309
1310 static void binder_inc_node_tmpref_ilocked(struct binder_node *node)
1311 {
1312         /*
1313          * No call to binder_inc_node() is needed since we
1314          * don't need to inform userspace of any changes to
1315          * tmp_refs
1316          */
1317         node->tmp_refs++;
1318 }
1319
1320 /**
1321  * binder_inc_node_tmpref() - take a temporary reference on node
1322  * @node:       node to reference
1323  *
1324  * Take reference on node to prevent the node from being freed
1325  * while referenced only by a local variable. The inner lock is
1326  * needed to serialize with the node work on the queue (which
1327  * isn't needed after the node is dead). If the node is dead
1328  * (node->proc is NULL), use binder_dead_nodes_lock to protect
1329  * node->tmp_refs against dead-node-only cases where the node
1330  * lock cannot be acquired (eg traversing the dead node list to
1331  * print nodes)
1332  */
1333 static void binder_inc_node_tmpref(struct binder_node *node)
1334 {
1335         binder_node_lock(node);
1336         if (node->proc)
1337                 binder_inner_proc_lock(node->proc);
1338         else
1339                 spin_lock(&binder_dead_nodes_lock);
1340         binder_inc_node_tmpref_ilocked(node);
1341         if (node->proc)
1342                 binder_inner_proc_unlock(node->proc);
1343         else
1344                 spin_unlock(&binder_dead_nodes_lock);
1345         binder_node_unlock(node);
1346 }
1347
1348 /**
1349  * binder_dec_node_tmpref() - remove a temporary reference on node
1350  * @node:       node to reference
1351  *
1352  * Release temporary reference on node taken via binder_inc_node_tmpref()
1353  */
1354 static void binder_dec_node_tmpref(struct binder_node *node)
1355 {
1356         bool free_node;
1357
1358         binder_node_inner_lock(node);
1359         if (!node->proc)
1360                 spin_lock(&binder_dead_nodes_lock);
1361         node->tmp_refs--;
1362         BUG_ON(node->tmp_refs < 0);
1363         if (!node->proc)
1364                 spin_unlock(&binder_dead_nodes_lock);
1365         /*
1366          * Call binder_dec_node() to check if all refcounts are 0
1367          * and cleanup is needed. Calling with strong=0 and internal=1
1368          * causes no actual reference to be released in binder_dec_node().
1369          * If that changes, a change is needed here too.
1370          */
1371         free_node = binder_dec_node_nilocked(node, 0, 1);
1372         binder_node_inner_unlock(node);
1373         if (free_node)
1374                 binder_free_node(node);
1375 }
1376
1377 static void binder_put_node(struct binder_node *node)
1378 {
1379         binder_dec_node_tmpref(node);
1380 }
1381
1382 static struct binder_ref *binder_get_ref_olocked(struct binder_proc *proc,
1383                                                  u32 desc, bool need_strong_ref)
1384 {
1385         struct rb_node *n = proc->refs_by_desc.rb_node;
1386         struct binder_ref *ref;
1387
1388         while (n) {
1389                 ref = rb_entry(n, struct binder_ref, rb_node_desc);
1390
1391                 if (desc < ref->data.desc) {
1392                         n = n->rb_left;
1393                 } else if (desc > ref->data.desc) {
1394                         n = n->rb_right;
1395                 } else if (need_strong_ref && !ref->data.strong) {
1396                         binder_user_error("tried to use weak ref as strong ref\n");
1397                         return NULL;
1398                 } else {
1399                         return ref;
1400                 }
1401         }
1402         return NULL;
1403 }
1404
1405 /**
1406  * binder_get_ref_for_node_olocked() - get the ref associated with given node
1407  * @proc:       binder_proc that owns the ref
1408  * @node:       binder_node of target
1409  * @new_ref:    newly allocated binder_ref to be initialized or %NULL
1410  *
1411  * Look up the ref for the given node and return it if it exists
1412  *
1413  * If it doesn't exist and the caller provides a newly allocated
1414  * ref, initialize the fields of the newly allocated ref and insert
1415  * into the given proc rb_trees and node refs list.
1416  *
1417  * Return:      the ref for node. It is possible that another thread
1418  *              allocated/initialized the ref first in which case the
1419  *              returned ref would be different than the passed-in
1420  *              new_ref. new_ref must be kfree'd by the caller in
1421  *              this case.
1422  */
1423 static struct binder_ref *binder_get_ref_for_node_olocked(
1424                                         struct binder_proc *proc,
1425                                         struct binder_node *node,
1426                                         struct binder_ref *new_ref)
1427 {
1428         struct binder_context *context = proc->context;
1429         struct rb_node **p = &proc->refs_by_node.rb_node;
1430         struct rb_node *parent = NULL;
1431         struct binder_ref *ref;
1432         struct rb_node *n;
1433
1434         while (*p) {
1435                 parent = *p;
1436                 ref = rb_entry(parent, struct binder_ref, rb_node_node);
1437
1438                 if (node < ref->node)
1439                         p = &(*p)->rb_left;
1440                 else if (node > ref->node)
1441                         p = &(*p)->rb_right;
1442                 else
1443                         return ref;
1444         }
1445         if (!new_ref)
1446                 return NULL;
1447
1448         binder_stats_created(BINDER_STAT_REF);
1449         new_ref->data.debug_id = atomic_inc_return(&binder_last_id);
1450         new_ref->proc = proc;
1451         new_ref->node = node;
1452         rb_link_node(&new_ref->rb_node_node, parent, p);
1453         rb_insert_color(&new_ref->rb_node_node, &proc->refs_by_node);
1454
1455         new_ref->data.desc = (node == context->binder_context_mgr_node) ? 0 : 1;
1456         for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {
1457                 ref = rb_entry(n, struct binder_ref, rb_node_desc);
1458                 if (ref->data.desc > new_ref->data.desc)
1459                         break;
1460                 new_ref->data.desc = ref->data.desc + 1;
1461         }
1462
1463         p = &proc->refs_by_desc.rb_node;
1464         while (*p) {
1465                 parent = *p;
1466                 ref = rb_entry(parent, struct binder_ref, rb_node_desc);
1467
1468                 if (new_ref->data.desc < ref->data.desc)
1469                         p = &(*p)->rb_left;
1470                 else if (new_ref->data.desc > ref->data.desc)
1471                         p = &(*p)->rb_right;
1472                 else
1473                         BUG();
1474         }
1475         rb_link_node(&new_ref->rb_node_desc, parent, p);
1476         rb_insert_color(&new_ref->rb_node_desc, &proc->refs_by_desc);
1477
1478         binder_node_lock(node);
1479         hlist_add_head(&new_ref->node_entry, &node->refs);
1480
1481         binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1482                      "%d new ref %d desc %d for node %d\n",
1483                       proc->pid, new_ref->data.debug_id, new_ref->data.desc,
1484                       node->debug_id);
1485         binder_node_unlock(node);
1486         return new_ref;
1487 }
1488
1489 static void binder_cleanup_ref_olocked(struct binder_ref *ref)
1490 {
1491         bool delete_node = false;
1492
1493         binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1494                      "%d delete ref %d desc %d for node %d\n",
1495                       ref->proc->pid, ref->data.debug_id, ref->data.desc,
1496                       ref->node->debug_id);
1497
1498         rb_erase(&ref->rb_node_desc, &ref->proc->refs_by_desc);
1499         rb_erase(&ref->rb_node_node, &ref->proc->refs_by_node);
1500
1501         binder_node_inner_lock(ref->node);
1502         if (ref->data.strong)
1503                 binder_dec_node_nilocked(ref->node, 1, 1);
1504
1505         hlist_del(&ref->node_entry);
1506         delete_node = binder_dec_node_nilocked(ref->node, 0, 1);
1507         binder_node_inner_unlock(ref->node);
1508         /*
1509          * Clear ref->node unless we want the caller to free the node
1510          */
1511         if (!delete_node) {
1512                 /*
1513                  * The caller uses ref->node to determine
1514                  * whether the node needs to be freed. Clear
1515                  * it since the node is still alive.
1516                  */
1517                 ref->node = NULL;
1518         }
1519
1520         if (ref->death) {
1521                 binder_debug(BINDER_DEBUG_DEAD_BINDER,
1522                              "%d delete ref %d desc %d has death notification\n",
1523                               ref->proc->pid, ref->data.debug_id,
1524                               ref->data.desc);
1525                 binder_dequeue_work(ref->proc, &ref->death->work);
1526                 binder_stats_deleted(BINDER_STAT_DEATH);
1527         }
1528         binder_stats_deleted(BINDER_STAT_REF);
1529 }
1530
1531 /**
1532  * binder_inc_ref_olocked() - increment the ref for given handle
1533  * @ref:         ref to be incremented
1534  * @strong:      if true, strong increment, else weak
1535  * @target_list: list to queue node work on
1536  *
1537  * Increment the ref. @ref->proc->outer_lock must be held on entry
1538  *
1539  * Return: 0, if successful, else errno
1540  */
1541 static int binder_inc_ref_olocked(struct binder_ref *ref, int strong,
1542                                   struct list_head *target_list)
1543 {
1544         int ret;
1545
1546         if (strong) {
1547                 if (ref->data.strong == 0) {
1548                         ret = binder_inc_node(ref->node, 1, 1, target_list);
1549                         if (ret)
1550                                 return ret;
1551                 }
1552                 ref->data.strong++;
1553         } else {
1554                 if (ref->data.weak == 0) {
1555                         ret = binder_inc_node(ref->node, 0, 1, target_list);
1556                         if (ret)
1557                                 return ret;
1558                 }
1559                 ref->data.weak++;
1560         }
1561         return 0;
1562 }
1563
1564 /**
1565  * binder_dec_ref() - dec the ref for given handle
1566  * @ref:        ref to be decremented
1567  * @strong:     if true, strong decrement, else weak
1568  *
1569  * Decrement the ref.
1570  *
1571  * Return: true if ref is cleaned up and ready to be freed
1572  */
1573 static bool binder_dec_ref_olocked(struct binder_ref *ref, int strong)
1574 {
1575         if (strong) {
1576                 if (ref->data.strong == 0) {
1577                         binder_user_error("%d invalid dec strong, ref %d desc %d s %d w %d\n",
1578                                           ref->proc->pid, ref->data.debug_id,
1579                                           ref->data.desc, ref->data.strong,
1580                                           ref->data.weak);
1581                         return false;
1582                 }
1583                 ref->data.strong--;
1584                 if (ref->data.strong == 0)
1585                         binder_dec_node(ref->node, strong, 1);
1586         } else {
1587                 if (ref->data.weak == 0) {
1588                         binder_user_error("%d invalid dec weak, ref %d desc %d s %d w %d\n",
1589                                           ref->proc->pid, ref->data.debug_id,
1590                                           ref->data.desc, ref->data.strong,
1591                                           ref->data.weak);
1592                         return false;
1593                 }
1594                 ref->data.weak--;
1595         }
1596         if (ref->data.strong == 0 && ref->data.weak == 0) {
1597                 binder_cleanup_ref_olocked(ref);
1598                 return true;
1599         }
1600         return false;
1601 }
1602
1603 /**
1604  * binder_get_node_from_ref() - get the node from the given proc/desc
1605  * @proc:       proc containing the ref
1606  * @desc:       the handle associated with the ref
1607  * @need_strong_ref: if true, only return node if ref is strong
1608  * @rdata:      the id/refcount data for the ref
1609  *
1610  * Given a proc and ref handle, return the associated binder_node
1611  *
1612  * Return: a binder_node or NULL if not found or not strong when strong required
1613  */
1614 static struct binder_node *binder_get_node_from_ref(
1615                 struct binder_proc *proc,
1616                 u32 desc, bool need_strong_ref,
1617                 struct binder_ref_data *rdata)
1618 {
1619         struct binder_node *node;
1620         struct binder_ref *ref;
1621
1622         binder_proc_lock(proc);
1623         ref = binder_get_ref_olocked(proc, desc, need_strong_ref);
1624         if (!ref)
1625                 goto err_no_ref;
1626         node = ref->node;
1627         /*
1628          * Take an implicit reference on the node to ensure
1629          * it stays alive until the call to binder_put_node()
1630          */
1631         binder_inc_node_tmpref(node);
1632         if (rdata)
1633                 *rdata = ref->data;
1634         binder_proc_unlock(proc);
1635
1636         return node;
1637
1638 err_no_ref:
1639         binder_proc_unlock(proc);
1640         return NULL;
1641 }
1642
1643 /**
1644  * binder_free_ref() - free the binder_ref
1645  * @ref:        ref to free
1646  *
1647  * Free the binder_ref. Free the binder_node indicated by ref->node
1648  * (if non-NULL) and the binder_ref_death indicated by ref->death.
1649  */
1650 static void binder_free_ref(struct binder_ref *ref)
1651 {
1652         if (ref->node)
1653                 binder_free_node(ref->node);
1654         kfree(ref->death);
1655         kfree(ref);
1656 }
1657
1658 /**
1659  * binder_update_ref_for_handle() - inc/dec the ref for given handle
1660  * @proc:       proc containing the ref
1661  * @desc:       the handle associated with the ref
1662  * @increment:  true=inc reference, false=dec reference
1663  * @strong:     true=strong reference, false=weak reference
1664  * @rdata:      the id/refcount data for the ref
1665  *
1666  * Given a proc and ref handle, increment or decrement the ref
1667  * according to "increment" arg.
1668  *
1669  * Return: 0 if successful, else errno
1670  */
1671 static int binder_update_ref_for_handle(struct binder_proc *proc,
1672                 uint32_t desc, bool increment, bool strong,
1673                 struct binder_ref_data *rdata)
1674 {
1675         int ret = 0;
1676         struct binder_ref *ref;
1677         bool delete_ref = false;
1678
1679         binder_proc_lock(proc);
1680         ref = binder_get_ref_olocked(proc, desc, strong);
1681         if (!ref) {
1682                 ret = -EINVAL;
1683                 goto err_no_ref;
1684         }
1685         if (increment)
1686                 ret = binder_inc_ref_olocked(ref, strong, NULL);
1687         else
1688                 delete_ref = binder_dec_ref_olocked(ref, strong);
1689
1690         if (rdata)
1691                 *rdata = ref->data;
1692         binder_proc_unlock(proc);
1693
1694         if (delete_ref)
1695                 binder_free_ref(ref);
1696         return ret;
1697
1698 err_no_ref:
1699         binder_proc_unlock(proc);
1700         return ret;
1701 }
1702
1703 /**
1704  * binder_dec_ref_for_handle() - dec the ref for given handle
1705  * @proc:       proc containing the ref
1706  * @desc:       the handle associated with the ref
1707  * @strong:     true=strong reference, false=weak reference
1708  * @rdata:      the id/refcount data for the ref
1709  *
1710  * Just calls binder_update_ref_for_handle() to decrement the ref.
1711  *
1712  * Return: 0 if successful, else errno
1713  */
1714 static int binder_dec_ref_for_handle(struct binder_proc *proc,
1715                 uint32_t desc, bool strong, struct binder_ref_data *rdata)
1716 {
1717         return binder_update_ref_for_handle(proc, desc, false, strong, rdata);
1718 }
1719
1720
1721 /**
1722  * binder_inc_ref_for_node() - increment the ref for given proc/node
1723  * @proc:        proc containing the ref
1724  * @node:        target node
1725  * @strong:      true=strong reference, false=weak reference
1726  * @target_list: worklist to use if node is incremented
1727  * @rdata:       the id/refcount data for the ref
1728  *
1729  * Given a proc and node, increment the ref. Create the ref if it
1730  * doesn't already exist
1731  *
1732  * Return: 0 if successful, else errno
1733  */
1734 static int binder_inc_ref_for_node(struct binder_proc *proc,
1735                         struct binder_node *node,
1736                         bool strong,
1737                         struct list_head *target_list,
1738                         struct binder_ref_data *rdata)
1739 {
1740         struct binder_ref *ref;
1741         struct binder_ref *new_ref = NULL;
1742         int ret = 0;
1743
1744         binder_proc_lock(proc);
1745         ref = binder_get_ref_for_node_olocked(proc, node, NULL);
1746         if (!ref) {
1747                 binder_proc_unlock(proc);
1748                 new_ref = kzalloc(sizeof(*ref), GFP_KERNEL);
1749                 if (!new_ref)
1750                         return -ENOMEM;
1751                 binder_proc_lock(proc);
1752                 ref = binder_get_ref_for_node_olocked(proc, node, new_ref);
1753         }
1754         ret = binder_inc_ref_olocked(ref, strong, target_list);
1755         *rdata = ref->data;
1756         binder_proc_unlock(proc);
1757         if (new_ref && ref != new_ref)
1758                 /*
1759                  * Another thread created the ref first so
1760                  * free the one we allocated
1761                  */
1762                 kfree(new_ref);
1763         return ret;
1764 }
1765
1766 static void binder_pop_transaction_ilocked(struct binder_thread *target_thread,
1767                                            struct binder_transaction *t)
1768 {
1769         BUG_ON(!target_thread);
1770         assert_spin_locked(&target_thread->proc->inner_lock);
1771         BUG_ON(target_thread->transaction_stack != t);
1772         BUG_ON(target_thread->transaction_stack->from != target_thread);
1773         target_thread->transaction_stack =
1774                 target_thread->transaction_stack->from_parent;
1775         t->from = NULL;
1776 }
1777
1778 /**
1779  * binder_thread_dec_tmpref() - decrement thread->tmp_ref
1780  * @thread:     thread to decrement
1781  *
1782  * A thread needs to be kept alive while being used to create or
1783  * handle a transaction. binder_get_txn_from() is used to safely
1784  * extract t->from from a binder_transaction and keep the thread
1785  * indicated by t->from from being freed. When done with that
1786  * binder_thread, this function is called to decrement the
1787  * tmp_ref and free if appropriate (thread has been released
1788  * and no transaction being processed by the driver)
1789  */
1790 static void binder_thread_dec_tmpref(struct binder_thread *thread)
1791 {
1792         /*
1793          * atomic is used to protect the counter value while
1794          * it cannot reach zero or thread->is_dead is false
1795          */
1796         binder_inner_proc_lock(thread->proc);
1797         atomic_dec(&thread->tmp_ref);
1798         if (thread->is_dead && !atomic_read(&thread->tmp_ref)) {
1799                 binder_inner_proc_unlock(thread->proc);
1800                 binder_free_thread(thread);
1801                 return;
1802         }
1803         binder_inner_proc_unlock(thread->proc);
1804 }
1805
1806 /**
1807  * binder_proc_dec_tmpref() - decrement proc->tmp_ref
1808  * @proc:       proc to decrement
1809  *
1810  * A binder_proc needs to be kept alive while being used to create or
1811  * handle a transaction. proc->tmp_ref is incremented when
1812  * creating a new transaction or the binder_proc is currently in-use
1813  * by threads that are being released. When done with the binder_proc,
1814  * this function is called to decrement the counter and free the
1815  * proc if appropriate (proc has been released, all threads have
1816  * been released and not currenly in-use to process a transaction).
1817  */
1818 static void binder_proc_dec_tmpref(struct binder_proc *proc)
1819 {
1820         binder_inner_proc_lock(proc);
1821         proc->tmp_ref--;
1822         if (proc->is_dead && RB_EMPTY_ROOT(&proc->threads) &&
1823                         !proc->tmp_ref) {
1824                 binder_inner_proc_unlock(proc);
1825                 binder_free_proc(proc);
1826                 return;
1827         }
1828         binder_inner_proc_unlock(proc);
1829 }
1830
1831 /**
1832  * binder_get_txn_from() - safely extract the "from" thread in transaction
1833  * @t:  binder transaction for t->from
1834  *
1835  * Atomically return the "from" thread and increment the tmp_ref
1836  * count for the thread to ensure it stays alive until
1837  * binder_thread_dec_tmpref() is called.
1838  *
1839  * Return: the value of t->from
1840  */
1841 static struct binder_thread *binder_get_txn_from(
1842                 struct binder_transaction *t)
1843 {
1844         struct binder_thread *from;
1845
1846         spin_lock(&t->lock);
1847         from = t->from;
1848         if (from)
1849                 atomic_inc(&from->tmp_ref);
1850         spin_unlock(&t->lock);
1851         return from;
1852 }
1853
1854 /**
1855  * binder_get_txn_from_and_acq_inner() - get t->from and acquire inner lock
1856  * @t:  binder transaction for t->from
1857  *
1858  * Same as binder_get_txn_from() except it also acquires the proc->inner_lock
1859  * to guarantee that the thread cannot be released while operating on it.
1860  * The caller must call binder_inner_proc_unlock() to release the inner lock
1861  * as well as call binder_dec_thread_txn() to release the reference.
1862  *
1863  * Return: the value of t->from
1864  */
1865 static struct binder_thread *binder_get_txn_from_and_acq_inner(
1866                 struct binder_transaction *t)
1867 {
1868         struct binder_thread *from;
1869
1870         from = binder_get_txn_from(t);
1871         if (!from)
1872                 return NULL;
1873         binder_inner_proc_lock(from->proc);
1874         if (t->from) {
1875                 BUG_ON(from != t->from);
1876                 return from;
1877         }
1878         binder_inner_proc_unlock(from->proc);
1879         binder_thread_dec_tmpref(from);
1880         return NULL;
1881 }
1882
1883 static void binder_free_transaction(struct binder_transaction *t)
1884 {
1885         struct binder_proc *target_proc = t->to_proc;
1886
1887         if (target_proc) {
1888                 binder_inner_proc_lock(target_proc);
1889                 if (t->buffer)
1890                         t->buffer->transaction = NULL;
1891                 binder_inner_proc_unlock(target_proc);
1892         }
1893         /*
1894          * If the transaction has no target_proc, then
1895          * t->buffer->transaction has already been cleared.
1896          */
1897         kfree(t);
1898         binder_stats_deleted(BINDER_STAT_TRANSACTION);
1899 }
1900
1901 static void binder_send_failed_reply(struct binder_transaction *t,
1902                                      uint32_t error_code)
1903 {
1904         struct binder_thread *target_thread;
1905         struct binder_transaction *next;
1906
1907         BUG_ON(t->flags & TF_ONE_WAY);
1908         while (1) {
1909                 target_thread = binder_get_txn_from_and_acq_inner(t);
1910                 if (target_thread) {
1911                         binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
1912                                      "send failed reply for transaction %d to %d:%d\n",
1913                                       t->debug_id,
1914                                       target_thread->proc->pid,
1915                                       target_thread->pid);
1916
1917                         binder_pop_transaction_ilocked(target_thread, t);
1918                         if (target_thread->reply_error.cmd == BR_OK) {
1919                                 target_thread->reply_error.cmd = error_code;
1920                                 binder_enqueue_work_ilocked(
1921                                         &target_thread->reply_error.work,
1922                                         &target_thread->todo);
1923                                 wake_up_interruptible(&target_thread->wait);
1924                         } else {
1925                                 /*
1926                                  * Cannot get here for normal operation, but
1927                                  * we can if multiple synchronous transactions
1928                                  * are sent without blocking for responses.
1929                                  * Just ignore the 2nd error in this case.
1930                                  */
1931                                 pr_warn("Unexpected reply error: %u\n",
1932                                         target_thread->reply_error.cmd);
1933                         }
1934                         binder_inner_proc_unlock(target_thread->proc);
1935                         binder_thread_dec_tmpref(target_thread);
1936                         binder_free_transaction(t);
1937                         return;
1938                 }
1939                 next = t->from_parent;
1940
1941                 binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
1942                              "send failed reply for transaction %d, target dead\n",
1943                              t->debug_id);
1944
1945                 binder_free_transaction(t);
1946                 if (next == NULL) {
1947                         binder_debug(BINDER_DEBUG_DEAD_BINDER,
1948                                      "reply failed, no target thread at root\n");
1949                         return;
1950                 }
1951                 t = next;
1952                 binder_debug(BINDER_DEBUG_DEAD_BINDER,
1953                              "reply failed, no target thread -- retry %d\n",
1954                               t->debug_id);
1955         }
1956 }
1957
1958 /**
1959  * binder_cleanup_transaction() - cleans up undelivered transaction
1960  * @t:          transaction that needs to be cleaned up
1961  * @reason:     reason the transaction wasn't delivered
1962  * @error_code: error to return to caller (if synchronous call)
1963  */
1964 static void binder_cleanup_transaction(struct binder_transaction *t,
1965                                        const char *reason,
1966                                        uint32_t error_code)
1967 {
1968         if (t->buffer->target_node && !(t->flags & TF_ONE_WAY)) {
1969                 binder_send_failed_reply(t, error_code);
1970         } else {
1971                 binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
1972                         "undelivered transaction %d, %s\n",
1973                         t->debug_id, reason);
1974                 binder_free_transaction(t);
1975         }
1976 }
1977
1978 /**
1979  * binder_validate_object() - checks for a valid metadata object in a buffer.
1980  * @buffer:     binder_buffer that we're parsing.
1981  * @offset:     offset in the buffer at which to validate an object.
1982  *
1983  * Return:      If there's a valid metadata object at @offset in @buffer, the
1984  *              size of that object. Otherwise, it returns zero.
1985  */
1986 static size_t binder_validate_object(struct binder_buffer *buffer, u64 offset)
1987 {
1988         /* Check if we can read a header first */
1989         struct binder_object_header *hdr;
1990         size_t object_size = 0;
1991
1992         if (offset > buffer->data_size - sizeof(*hdr) ||
1993             buffer->data_size < sizeof(*hdr) ||
1994             !IS_ALIGNED(offset, sizeof(u32)))
1995                 return 0;
1996
1997         /* Ok, now see if we can read a complete object. */
1998         hdr = (struct binder_object_header *)(buffer->data + offset);
1999         switch (hdr->type) {
2000         case BINDER_TYPE_BINDER:
2001         case BINDER_TYPE_WEAK_BINDER:
2002         case BINDER_TYPE_HANDLE:
2003         case BINDER_TYPE_WEAK_HANDLE:
2004                 object_size = sizeof(struct flat_binder_object);
2005                 break;
2006         case BINDER_TYPE_FD:
2007                 object_size = sizeof(struct binder_fd_object);
2008                 break;
2009         case BINDER_TYPE_PTR:
2010                 object_size = sizeof(struct binder_buffer_object);
2011                 break;
2012         case BINDER_TYPE_FDA:
2013                 object_size = sizeof(struct binder_fd_array_object);
2014                 break;
2015         default:
2016                 return 0;
2017         }
2018         if (offset <= buffer->data_size - object_size &&
2019             buffer->data_size >= object_size)
2020                 return object_size;
2021         else
2022                 return 0;
2023 }
2024
2025 /**
2026  * binder_validate_ptr() - validates binder_buffer_object in a binder_buffer.
2027  * @b:          binder_buffer containing the object
2028  * @index:      index in offset array at which the binder_buffer_object is
2029  *              located
2030  * @start:      points to the start of the offset array
2031  * @num_valid:  the number of valid offsets in the offset array
2032  *
2033  * Return:      If @index is within the valid range of the offset array
2034  *              described by @start and @num_valid, and if there's a valid
2035  *              binder_buffer_object at the offset found in index @index
2036  *              of the offset array, that object is returned. Otherwise,
2037  *              %NULL is returned.
2038  *              Note that the offset found in index @index itself is not
2039  *              verified; this function assumes that @num_valid elements
2040  *              from @start were previously verified to have valid offsets.
2041  */
2042 static struct binder_buffer_object *binder_validate_ptr(struct binder_buffer *b,
2043                                                         binder_size_t index,
2044                                                         binder_size_t *start,
2045                                                         binder_size_t num_valid)
2046 {
2047         struct binder_buffer_object *buffer_obj;
2048         binder_size_t *offp;
2049
2050         if (index >= num_valid)
2051                 return NULL;
2052
2053         offp = start + index;
2054         buffer_obj = (struct binder_buffer_object *)(b->data + *offp);
2055         if (buffer_obj->hdr.type != BINDER_TYPE_PTR)
2056                 return NULL;
2057
2058         return buffer_obj;
2059 }
2060
2061 /**
2062  * binder_validate_fixup() - validates pointer/fd fixups happen in order.
2063  * @b:                  transaction buffer
2064  * @objects_start       start of objects buffer
2065  * @buffer:             binder_buffer_object in which to fix up
2066  * @offset:             start offset in @buffer to fix up
2067  * @last_obj:           last binder_buffer_object that we fixed up in
2068  * @last_min_offset:    minimum fixup offset in @last_obj
2069  *
2070  * Return:              %true if a fixup in buffer @buffer at offset @offset is
2071  *                      allowed.
2072  *
2073  * For safety reasons, we only allow fixups inside a buffer to happen
2074  * at increasing offsets; additionally, we only allow fixup on the last
2075  * buffer object that was verified, or one of its parents.
2076  *
2077  * Example of what is allowed:
2078  *
2079  * A
2080  *   B (parent = A, offset = 0)
2081  *   C (parent = A, offset = 16)
2082  *     D (parent = C, offset = 0)
2083  *   E (parent = A, offset = 32) // min_offset is 16 (C.parent_offset)
2084  *
2085  * Examples of what is not allowed:
2086  *
2087  * Decreasing offsets within the same parent:
2088  * A
2089  *   C (parent = A, offset = 16)
2090  *   B (parent = A, offset = 0) // decreasing offset within A
2091  *
2092  * Referring to a parent that wasn't the last object or any of its parents:
2093  * A
2094  *   B (parent = A, offset = 0)
2095  *   C (parent = A, offset = 0)
2096  *   C (parent = A, offset = 16)
2097  *     D (parent = B, offset = 0) // B is not A or any of A's parents
2098  */
2099 static bool binder_validate_fixup(struct binder_buffer *b,
2100                                   binder_size_t *objects_start,
2101                                   struct binder_buffer_object *buffer,
2102                                   binder_size_t fixup_offset,
2103                                   struct binder_buffer_object *last_obj,
2104                                   binder_size_t last_min_offset)
2105 {
2106         if (!last_obj) {
2107                 /* Nothing to fix up in */
2108                 return false;
2109         }
2110
2111         while (last_obj != buffer) {
2112                 /*
2113                  * Safe to retrieve the parent of last_obj, since it
2114                  * was already previously verified by the driver.
2115                  */
2116                 if ((last_obj->flags & BINDER_BUFFER_FLAG_HAS_PARENT) == 0)
2117                         return false;
2118                 last_min_offset = last_obj->parent_offset + sizeof(uintptr_t);
2119                 last_obj = (struct binder_buffer_object *)
2120                         (b->data + *(objects_start + last_obj->parent));
2121         }
2122         return (fixup_offset >= last_min_offset);
2123 }
2124
2125 static void binder_transaction_buffer_release(struct binder_proc *proc,
2126                                               struct binder_buffer *buffer,
2127                                               binder_size_t *failed_at)
2128 {
2129         binder_size_t *offp, *off_start, *off_end;
2130         int debug_id = buffer->debug_id;
2131
2132         binder_debug(BINDER_DEBUG_TRANSACTION,
2133                      "%d buffer release %d, size %zd-%zd, failed at %pK\n",
2134                      proc->pid, buffer->debug_id,
2135                      buffer->data_size, buffer->offsets_size, failed_at);
2136
2137         if (buffer->target_node)
2138                 binder_dec_node(buffer->target_node, 1, 0);
2139
2140         off_start = (binder_size_t *)(buffer->data +
2141                                       ALIGN(buffer->data_size, sizeof(void *)));
2142         if (failed_at)
2143                 off_end = failed_at;
2144         else
2145                 off_end = (void *)off_start + buffer->offsets_size;
2146         for (offp = off_start; offp < off_end; offp++) {
2147                 struct binder_object_header *hdr;
2148                 size_t object_size = binder_validate_object(buffer, *offp);
2149
2150                 if (object_size == 0) {
2151                         pr_err("transaction release %d bad object at offset %lld, size %zd\n",
2152                                debug_id, (u64)*offp, buffer->data_size);
2153                         continue;
2154                 }
2155                 hdr = (struct binder_object_header *)(buffer->data + *offp);
2156                 switch (hdr->type) {
2157                 case BINDER_TYPE_BINDER:
2158                 case BINDER_TYPE_WEAK_BINDER: {
2159                         struct flat_binder_object *fp;
2160                         struct binder_node *node;
2161
2162                         fp = to_flat_binder_object(hdr);
2163                         node = binder_get_node(proc, fp->binder);
2164                         if (node == NULL) {
2165                                 pr_err("transaction release %d bad node %016llx\n",
2166                                        debug_id, (u64)fp->binder);
2167                                 break;
2168                         }
2169                         binder_debug(BINDER_DEBUG_TRANSACTION,
2170                                      "        node %d u%016llx\n",
2171                                      node->debug_id, (u64)node->ptr);
2172                         binder_dec_node(node, hdr->type == BINDER_TYPE_BINDER,
2173                                         0);
2174                         binder_put_node(node);
2175                 } break;
2176                 case BINDER_TYPE_HANDLE:
2177                 case BINDER_TYPE_WEAK_HANDLE: {
2178                         struct flat_binder_object *fp;
2179                         struct binder_ref_data rdata;
2180                         int ret;
2181
2182                         fp = to_flat_binder_object(hdr);
2183                         ret = binder_dec_ref_for_handle(proc, fp->handle,
2184                                 hdr->type == BINDER_TYPE_HANDLE, &rdata);
2185
2186                         if (ret) {
2187                                 pr_err("transaction release %d bad handle %d, ret = %d\n",
2188                                  debug_id, fp->handle, ret);
2189                                 break;
2190                         }
2191                         binder_debug(BINDER_DEBUG_TRANSACTION,
2192                                      "        ref %d desc %d\n",
2193                                      rdata.debug_id, rdata.desc);
2194                 } break;
2195
2196                 case BINDER_TYPE_FD: {
2197                         struct binder_fd_object *fp = to_binder_fd_object(hdr);
2198
2199                         binder_debug(BINDER_DEBUG_TRANSACTION,
2200                                      "        fd %d\n", fp->fd);
2201                         if (failed_at)
2202                                 task_close_fd(proc, fp->fd);
2203                 } break;
2204                 case BINDER_TYPE_PTR:
2205                         /*
2206                          * Nothing to do here, this will get cleaned up when the
2207                          * transaction buffer gets freed
2208                          */
2209                         break;
2210                 case BINDER_TYPE_FDA: {
2211                         struct binder_fd_array_object *fda;
2212                         struct binder_buffer_object *parent;
2213                         uintptr_t parent_buffer;
2214                         u32 *fd_array;
2215                         size_t fd_index;
2216                         binder_size_t fd_buf_size;
2217
2218                         fda = to_binder_fd_array_object(hdr);
2219                         parent = binder_validate_ptr(buffer, fda->parent,
2220                                                      off_start,
2221                                                      offp - off_start);
2222                         if (!parent) {
2223                                 pr_err("transaction release %d bad parent offset",
2224                                        debug_id);
2225                                 continue;
2226                         }
2227                         /*
2228                          * Since the parent was already fixed up, convert it
2229                          * back to kernel address space to access it
2230                          */
2231                         parent_buffer = parent->buffer -
2232                                 binder_alloc_get_user_buffer_offset(
2233                                                 &proc->alloc);
2234
2235                         fd_buf_size = sizeof(u32) * fda->num_fds;
2236                         if (fda->num_fds >= SIZE_MAX / sizeof(u32)) {
2237                                 pr_err("transaction release %d invalid number of fds (%lld)\n",
2238                                        debug_id, (u64)fda->num_fds);
2239                                 continue;
2240                         }
2241                         if (fd_buf_size > parent->length ||
2242                             fda->parent_offset > parent->length - fd_buf_size) {
2243                                 /* No space for all file descriptors here. */
2244                                 pr_err("transaction release %d not enough space for %lld fds in buffer\n",
2245                                        debug_id, (u64)fda->num_fds);
2246                                 continue;
2247                         }
2248                         fd_array = (u32 *)(parent_buffer + (uintptr_t)fda->parent_offset);
2249                         for (fd_index = 0; fd_index < fda->num_fds; fd_index++)
2250                                 task_close_fd(proc, fd_array[fd_index]);
2251                 } break;
2252                 default:
2253                         pr_err("transaction release %d bad object type %x\n",
2254                                 debug_id, hdr->type);
2255                         break;
2256                 }
2257         }
2258 }
2259
2260 static int binder_translate_binder(struct flat_binder_object *fp,
2261                                    struct binder_transaction *t,
2262                                    struct binder_thread *thread)
2263 {
2264         struct binder_node *node;
2265         struct binder_proc *proc = thread->proc;
2266         struct binder_proc *target_proc = t->to_proc;
2267         struct binder_ref_data rdata;
2268         int ret = 0;
2269
2270         node = binder_get_node(proc, fp->binder);
2271         if (!node) {
2272                 node = binder_new_node(proc, fp);
2273                 if (!node)
2274                         return -ENOMEM;
2275         }
2276         if (fp->cookie != node->cookie) {
2277                 binder_user_error("%d:%d sending u%016llx node %d, cookie mismatch %016llx != %016llx\n",
2278                                   proc->pid, thread->pid, (u64)fp->binder,
2279                                   node->debug_id, (u64)fp->cookie,
2280                                   (u64)node->cookie);
2281                 ret = -EINVAL;
2282                 goto done;
2283         }
2284         if (security_binder_transfer_binder(proc->tsk, target_proc->tsk)) {
2285                 ret = -EPERM;
2286                 goto done;
2287         }
2288
2289         ret = binder_inc_ref_for_node(target_proc, node,
2290                         fp->hdr.type == BINDER_TYPE_BINDER,
2291                         &thread->todo, &rdata);
2292         if (ret)
2293                 goto done;
2294
2295         if (fp->hdr.type == BINDER_TYPE_BINDER)
2296                 fp->hdr.type = BINDER_TYPE_HANDLE;
2297         else
2298                 fp->hdr.type = BINDER_TYPE_WEAK_HANDLE;
2299         fp->binder = 0;
2300         fp->handle = rdata.desc;
2301         fp->cookie = 0;
2302
2303         trace_binder_transaction_node_to_ref(t, node, &rdata);
2304         binder_debug(BINDER_DEBUG_TRANSACTION,
2305                      "        node %d u%016llx -> ref %d desc %d\n",
2306                      node->debug_id, (u64)node->ptr,
2307                      rdata.debug_id, rdata.desc);
2308 done:
2309         binder_put_node(node);
2310         return ret;
2311 }
2312
2313 static int binder_translate_handle(struct flat_binder_object *fp,
2314                                    struct binder_transaction *t,
2315                                    struct binder_thread *thread)
2316 {
2317         struct binder_proc *proc = thread->proc;
2318         struct binder_proc *target_proc = t->to_proc;
2319         struct binder_node *node;
2320         struct binder_ref_data src_rdata;
2321         int ret = 0;
2322
2323         node = binder_get_node_from_ref(proc, fp->handle,
2324                         fp->hdr.type == BINDER_TYPE_HANDLE, &src_rdata);
2325         if (!node) {
2326                 binder_user_error("%d:%d got transaction with invalid handle, %d\n",
2327                                   proc->pid, thread->pid, fp->handle);
2328                 return -EINVAL;
2329         }
2330         if (security_binder_transfer_binder(proc->tsk, target_proc->tsk)) {
2331                 ret = -EPERM;
2332                 goto done;
2333         }
2334
2335         binder_node_lock(node);
2336         if (node->proc == target_proc) {
2337                 if (fp->hdr.type == BINDER_TYPE_HANDLE)
2338                         fp->hdr.type = BINDER_TYPE_BINDER;
2339                 else
2340                         fp->hdr.type = BINDER_TYPE_WEAK_BINDER;
2341                 fp->binder = node->ptr;
2342                 fp->cookie = node->cookie;
2343                 if (node->proc)
2344                         binder_inner_proc_lock(node->proc);
2345                 binder_inc_node_nilocked(node,
2346                                          fp->hdr.type == BINDER_TYPE_BINDER,
2347                                          0, NULL);
2348                 if (node->proc)
2349                         binder_inner_proc_unlock(node->proc);
2350                 trace_binder_transaction_ref_to_node(t, node, &src_rdata);
2351                 binder_debug(BINDER_DEBUG_TRANSACTION,
2352                              "        ref %d desc %d -> node %d u%016llx\n",
2353                              src_rdata.debug_id, src_rdata.desc, node->debug_id,
2354                              (u64)node->ptr);
2355                 binder_node_unlock(node);
2356         } else {
2357                 struct binder_ref_data dest_rdata;
2358
2359                 binder_node_unlock(node);
2360                 ret = binder_inc_ref_for_node(target_proc, node,
2361                                 fp->hdr.type == BINDER_TYPE_HANDLE,
2362                                 NULL, &dest_rdata);
2363                 if (ret)
2364                         goto done;
2365
2366                 fp->binder = 0;
2367                 fp->handle = dest_rdata.desc;
2368                 fp->cookie = 0;
2369                 trace_binder_transaction_ref_to_ref(t, node, &src_rdata,
2370                                                     &dest_rdata);
2371                 binder_debug(BINDER_DEBUG_TRANSACTION,
2372                              "        ref %d desc %d -> ref %d desc %d (node %d)\n",
2373                              src_rdata.debug_id, src_rdata.desc,
2374                              dest_rdata.debug_id, dest_rdata.desc,
2375                              node->debug_id);
2376         }
2377 done:
2378         binder_put_node(node);
2379         return ret;
2380 }
2381
2382 static int binder_translate_fd(int fd,
2383                                struct binder_transaction *t,
2384                                struct binder_thread *thread,
2385                                struct binder_transaction *in_reply_to)
2386 {
2387         struct binder_proc *proc = thread->proc;
2388         struct binder_proc *target_proc = t->to_proc;
2389         int target_fd;
2390         struct file *file;
2391         int ret;
2392         bool target_allows_fd;
2393
2394         if (in_reply_to)
2395                 target_allows_fd = !!(in_reply_to->flags & TF_ACCEPT_FDS);
2396         else
2397                 target_allows_fd = t->buffer->target_node->accept_fds;
2398         if (!target_allows_fd) {
2399                 binder_user_error("%d:%d got %s with fd, %d, but target does not allow fds\n",
2400                                   proc->pid, thread->pid,
2401                                   in_reply_to ? "reply" : "transaction",
2402                                   fd);
2403                 ret = -EPERM;
2404                 goto err_fd_not_accepted;
2405         }
2406
2407         file = fget(fd);
2408         if (!file) {
2409                 binder_user_error("%d:%d got transaction with invalid fd, %d\n",
2410                                   proc->pid, thread->pid, fd);
2411                 ret = -EBADF;
2412                 goto err_fget;
2413         }
2414         ret = security_binder_transfer_file(proc->tsk, target_proc->tsk, file);
2415         if (ret < 0) {
2416                 ret = -EPERM;
2417                 goto err_security;
2418         }
2419
2420         target_fd = task_get_unused_fd_flags(target_proc, O_CLOEXEC);
2421         if (target_fd < 0) {
2422                 ret = -ENOMEM;
2423                 goto err_get_unused_fd;
2424         }
2425         task_fd_install(target_proc, target_fd, file);
2426         trace_binder_transaction_fd(t, fd, target_fd);
2427         binder_debug(BINDER_DEBUG_TRANSACTION, "        fd %d -> %d\n",
2428                      fd, target_fd);
2429
2430         return target_fd;
2431
2432 err_get_unused_fd:
2433 err_security:
2434         fput(file);
2435 err_fget:
2436 err_fd_not_accepted:
2437         return ret;
2438 }
2439
2440 static int binder_translate_fd_array(struct binder_fd_array_object *fda,
2441                                      struct binder_buffer_object *parent,
2442                                      struct binder_transaction *t,
2443                                      struct binder_thread *thread,
2444                                      struct binder_transaction *in_reply_to)
2445 {
2446         binder_size_t fdi, fd_buf_size, num_installed_fds;
2447         int target_fd;
2448         uintptr_t parent_buffer;
2449         u32 *fd_array;
2450         struct binder_proc *proc = thread->proc;
2451         struct binder_proc *target_proc = t->to_proc;
2452
2453         fd_buf_size = sizeof(u32) * fda->num_fds;
2454         if (fda->num_fds >= SIZE_MAX / sizeof(u32)) {
2455                 binder_user_error("%d:%d got transaction with invalid number of fds (%lld)\n",
2456                                   proc->pid, thread->pid, (u64)fda->num_fds);
2457                 return -EINVAL;
2458         }
2459         if (fd_buf_size > parent->length ||
2460             fda->parent_offset > parent->length - fd_buf_size) {
2461                 /* No space for all file descriptors here. */
2462                 binder_user_error("%d:%d not enough space to store %lld fds in buffer\n",
2463                                   proc->pid, thread->pid, (u64)fda->num_fds);
2464                 return -EINVAL;
2465         }
2466         /*
2467          * Since the parent was already fixed up, convert it
2468          * back to the kernel address space to access it
2469          */
2470         parent_buffer = parent->buffer -
2471                 binder_alloc_get_user_buffer_offset(&target_proc->alloc);
2472         fd_array = (u32 *)(parent_buffer + (uintptr_t)fda->parent_offset);
2473         if (!IS_ALIGNED((unsigned long)fd_array, sizeof(u32))) {
2474                 binder_user_error("%d:%d parent offset not aligned correctly.\n",
2475                                   proc->pid, thread->pid);
2476                 return -EINVAL;
2477         }
2478         for (fdi = 0; fdi < fda->num_fds; fdi++) {
2479                 target_fd = binder_translate_fd(fd_array[fdi], t, thread,
2480                                                 in_reply_to);
2481                 if (target_fd < 0)
2482                         goto err_translate_fd_failed;
2483                 fd_array[fdi] = target_fd;
2484         }
2485         return 0;
2486
2487 err_translate_fd_failed:
2488         /*
2489          * Failed to allocate fd or security error, free fds
2490          * installed so far.
2491          */
2492         num_installed_fds = fdi;
2493         for (fdi = 0; fdi < num_installed_fds; fdi++)
2494                 task_close_fd(target_proc, fd_array[fdi]);
2495         return target_fd;
2496 }
2497
2498 static int binder_fixup_parent(struct binder_transaction *t,
2499                                struct binder_thread *thread,
2500                                struct binder_buffer_object *bp,
2501                                binder_size_t *off_start,
2502                                binder_size_t num_valid,
2503                                struct binder_buffer_object *last_fixup_obj,
2504                                binder_size_t last_fixup_min_off)
2505 {
2506         struct binder_buffer_object *parent;
2507         u8 *parent_buffer;
2508         struct binder_buffer *b = t->buffer;
2509         struct binder_proc *proc = thread->proc;
2510         struct binder_proc *target_proc = t->to_proc;
2511
2512         if (!(bp->flags & BINDER_BUFFER_FLAG_HAS_PARENT))
2513                 return 0;
2514
2515         parent = binder_validate_ptr(b, bp->parent, off_start, num_valid);
2516         if (!parent) {
2517                 binder_user_error("%d:%d got transaction with invalid parent offset or type\n",
2518                                   proc->pid, thread->pid);
2519                 return -EINVAL;
2520         }
2521
2522         if (!binder_validate_fixup(b, off_start,
2523                                    parent, bp->parent_offset,
2524                                    last_fixup_obj,
2525                                    last_fixup_min_off)) {
2526                 binder_user_error("%d:%d got transaction with out-of-order buffer fixup\n",
2527                                   proc->pid, thread->pid);
2528                 return -EINVAL;
2529         }
2530
2531         if (parent->length < sizeof(binder_uintptr_t) ||
2532             bp->parent_offset > parent->length - sizeof(binder_uintptr_t)) {
2533                 /* No space for a pointer here! */
2534                 binder_user_error("%d:%d got transaction with invalid parent offset\n",
2535                                   proc->pid, thread->pid);
2536                 return -EINVAL;
2537         }
2538         parent_buffer = (u8 *)((uintptr_t)parent->buffer -
2539                         binder_alloc_get_user_buffer_offset(
2540                                 &target_proc->alloc));
2541         *(binder_uintptr_t *)(parent_buffer + bp->parent_offset) = bp->buffer;
2542
2543         return 0;
2544 }
2545
2546 /**
2547  * binder_proc_transaction() - sends a transaction to a process and wakes it up
2548  * @t:          transaction to send
2549  * @proc:       process to send the transaction to
2550  * @thread:     thread in @proc to send the transaction to (may be NULL)
2551  *
2552  * This function queues a transaction to the specified process. It will try
2553  * to find a thread in the target process to handle the transaction and
2554  * wake it up. If no thread is found, the work is queued to the proc
2555  * waitqueue.
2556  *
2557  * If the @thread parameter is not NULL, the transaction is always queued
2558  * to the waitlist of that specific thread.
2559  *
2560  * Return:      true if the transactions was successfully queued
2561  *              false if the target process or thread is dead
2562  */
2563 static bool binder_proc_transaction(struct binder_transaction *t,
2564                                     struct binder_proc *proc,
2565                                     struct binder_thread *thread)
2566 {
2567         struct list_head *target_list = NULL;
2568         struct binder_node *node = t->buffer->target_node;
2569         bool oneway = !!(t->flags & TF_ONE_WAY);
2570         bool wakeup = true;
2571
2572         BUG_ON(!node);
2573         binder_node_lock(node);
2574         if (oneway) {
2575                 BUG_ON(thread);
2576                 if (node->has_async_transaction) {
2577                         target_list = &node->async_todo;
2578                         wakeup = false;
2579                 } else {
2580                         node->has_async_transaction = 1;
2581                 }
2582         }
2583
2584         binder_inner_proc_lock(proc);
2585
2586         if (proc->is_dead || (thread && thread->is_dead)) {
2587                 binder_inner_proc_unlock(proc);
2588                 binder_node_unlock(node);
2589                 return false;
2590         }
2591
2592         if (!thread && !target_list)
2593                 thread = binder_select_thread_ilocked(proc);
2594
2595         if (thread)
2596                 target_list = &thread->todo;
2597         else if (!target_list)
2598                 target_list = &proc->todo;
2599         else
2600                 BUG_ON(target_list != &node->async_todo);
2601
2602         binder_enqueue_work_ilocked(&t->work, target_list);
2603
2604         if (wakeup)
2605                 binder_wakeup_thread_ilocked(proc, thread, !oneway /* sync */);
2606
2607         binder_inner_proc_unlock(proc);
2608         binder_node_unlock(node);
2609
2610         return true;
2611 }
2612
2613 /**
2614  * binder_get_node_refs_for_txn() - Get required refs on node for txn
2615  * @node:         struct binder_node for which to get refs
2616  * @proc:         returns @node->proc if valid
2617  * @error:        if no @proc then returns BR_DEAD_REPLY
2618  *
2619  * User-space normally keeps the node alive when creating a transaction
2620  * since it has a reference to the target. The local strong ref keeps it
2621  * alive if the sending process dies before the target process processes
2622  * the transaction. If the source process is malicious or has a reference
2623  * counting bug, relying on the local strong ref can fail.
2624  *
2625  * Since user-space can cause the local strong ref to go away, we also take
2626  * a tmpref on the node to ensure it survives while we are constructing
2627  * the transaction. We also need a tmpref on the proc while we are
2628  * constructing the transaction, so we take that here as well.
2629  *
2630  * Return: The target_node with refs taken or NULL if no @node->proc is NULL.
2631  * Also sets @proc if valid. If the @node->proc is NULL indicating that the
2632  * target proc has died, @error is set to BR_DEAD_REPLY
2633  */
2634 static struct binder_node *binder_get_node_refs_for_txn(
2635                 struct binder_node *node,
2636                 struct binder_proc **procp,
2637                 uint32_t *error)
2638 {
2639         struct binder_node *target_node = NULL;
2640
2641         binder_node_inner_lock(node);
2642         if (node->proc) {
2643                 target_node = node;
2644                 binder_inc_node_nilocked(node, 1, 0, NULL);
2645                 binder_inc_node_tmpref_ilocked(node);
2646                 node->proc->tmp_ref++;
2647                 *procp = node->proc;
2648         } else
2649                 *error = BR_DEAD_REPLY;
2650         binder_node_inner_unlock(node);
2651
2652         return target_node;
2653 }
2654
2655 static void binder_transaction(struct binder_proc *proc,
2656                                struct binder_thread *thread,
2657                                struct binder_transaction_data *tr, int reply,
2658                                binder_size_t extra_buffers_size)
2659 {
2660         int ret;
2661         struct binder_transaction *t;
2662         struct binder_work *tcomplete;
2663         binder_size_t *offp, *off_end, *off_start;
2664         binder_size_t off_min;
2665         u8 *sg_bufp, *sg_buf_end;
2666         struct binder_proc *target_proc = NULL;
2667         struct binder_thread *target_thread = NULL;
2668         struct binder_node *target_node = NULL;
2669         struct binder_transaction *in_reply_to = NULL;
2670         struct binder_transaction_log_entry *e;
2671         uint32_t return_error = 0;
2672         uint32_t return_error_param = 0;
2673         uint32_t return_error_line = 0;
2674         struct binder_buffer_object *last_fixup_obj = NULL;
2675         binder_size_t last_fixup_min_off = 0;
2676         struct binder_context *context = proc->context;
2677         int t_debug_id = atomic_inc_return(&binder_last_id);
2678
2679         e = binder_transaction_log_add(&binder_transaction_log);
2680         e->debug_id = t_debug_id;
2681         e->call_type = reply ? 2 : !!(tr->flags & TF_ONE_WAY);
2682         e->from_proc = proc->pid;
2683         e->from_thread = thread->pid;
2684         e->target_handle = tr->target.handle;
2685         e->data_size = tr->data_size;
2686         e->offsets_size = tr->offsets_size;
2687         e->context_name = proc->context->name;
2688
2689         if (reply) {
2690                 binder_inner_proc_lock(proc);
2691                 in_reply_to = thread->transaction_stack;
2692                 if (in_reply_to == NULL) {
2693                         binder_inner_proc_unlock(proc);
2694                         binder_user_error("%d:%d got reply transaction with no transaction stack\n",
2695                                           proc->pid, thread->pid);
2696                         return_error = BR_FAILED_REPLY;
2697                         return_error_param = -EPROTO;
2698                         return_error_line = __LINE__;
2699                         goto err_empty_call_stack;
2700                 }
2701                 if (in_reply_to->to_thread != thread) {
2702                         spin_lock(&in_reply_to->lock);
2703                         binder_user_error("%d:%d got reply transaction with bad transaction stack, transaction %d has target %d:%d\n",
2704                                 proc->pid, thread->pid, in_reply_to->debug_id,
2705                                 in_reply_to->to_proc ?
2706                                 in_reply_to->to_proc->pid : 0,
2707                                 in_reply_to->to_thread ?
2708                                 in_reply_to->to_thread->pid : 0);
2709                         spin_unlock(&in_reply_to->lock);
2710                         binder_inner_proc_unlock(proc);
2711                         return_error = BR_FAILED_REPLY;
2712                         return_error_param = -EPROTO;
2713                         return_error_line = __LINE__;
2714                         in_reply_to = NULL;
2715                         goto err_bad_call_stack;
2716                 }
2717                 thread->transaction_stack = in_reply_to->to_parent;
2718                 binder_inner_proc_unlock(proc);
2719                 binder_set_nice(in_reply_to->saved_priority);
2720                 target_thread = binder_get_txn_from_and_acq_inner(in_reply_to);
2721                 if (target_thread == NULL) {
2722                         return_error = BR_DEAD_REPLY;
2723                         return_error_line = __LINE__;
2724                         goto err_dead_binder;
2725                 }
2726                 if (target_thread->transaction_stack != in_reply_to) {
2727                         binder_user_error("%d:%d got reply transaction with bad target transaction stack %d, expected %d\n",
2728                                 proc->pid, thread->pid,
2729                                 target_thread->transaction_stack ?
2730                                 target_thread->transaction_stack->debug_id : 0,
2731                                 in_reply_to->debug_id);
2732                         binder_inner_proc_unlock(target_thread->proc);
2733                         return_error = BR_FAILED_REPLY;
2734                         return_error_param = -EPROTO;
2735                         return_error_line = __LINE__;
2736                         in_reply_to = NULL;
2737                         target_thread = NULL;
2738                         goto err_dead_binder;
2739                 }
2740                 target_proc = target_thread->proc;
2741                 target_proc->tmp_ref++;
2742                 binder_inner_proc_unlock(target_thread->proc);
2743         } else {
2744                 if (tr->target.handle) {
2745                         struct binder_ref *ref;
2746
2747                         /*
2748                          * There must already be a strong ref
2749                          * on this node. If so, do a strong
2750                          * increment on the node to ensure it
2751                          * stays alive until the transaction is
2752                          * done.
2753                          */
2754                         binder_proc_lock(proc);
2755                         ref = binder_get_ref_olocked(proc, tr->target.handle,
2756                                                      true);
2757                         if (ref) {
2758                                 target_node = binder_get_node_refs_for_txn(
2759                                                 ref->node, &target_proc,
2760                                                 &return_error);
2761                         } else {
2762                                 binder_user_error("%d:%d got transaction to invalid handle\n",
2763                                                   proc->pid, thread->pid);
2764                                 return_error = BR_FAILED_REPLY;
2765                         }
2766                         binder_proc_unlock(proc);
2767                 } else {
2768                         mutex_lock(&context->context_mgr_node_lock);
2769                         target_node = context->binder_context_mgr_node;
2770                         if (target_node)
2771                                 target_node = binder_get_node_refs_for_txn(
2772                                                 target_node, &target_proc,
2773                                                 &return_error);
2774                         else
2775                                 return_error = BR_DEAD_REPLY;
2776                         mutex_unlock(&context->context_mgr_node_lock);
2777                         if (target_node && target_proc->pid == proc->pid) {
2778                                 binder_user_error("%d:%d got transaction to context manager from process owning it\n",
2779                                                   proc->pid, thread->pid);
2780                                 return_error = BR_FAILED_REPLY;
2781                                 return_error_param = -EINVAL;
2782                                 return_error_line = __LINE__;
2783                                 goto err_invalid_target_handle;
2784                         }
2785                 }
2786                 if (!target_node) {
2787                         /*
2788                          * return_error is set above
2789                          */
2790                         return_error_param = -EINVAL;
2791                         return_error_line = __LINE__;
2792                         goto err_dead_binder;
2793                 }
2794                 e->to_node = target_node->debug_id;
2795                 if (WARN_ON(proc == target_proc)) {
2796                         return_error = BR_FAILED_REPLY;
2797                         return_error_param = -EINVAL;
2798                         return_error_line = __LINE__;
2799                         goto err_invalid_target_handle;
2800                 }
2801                 if (security_binder_transaction(proc->tsk,
2802                                                 target_proc->tsk) < 0) {
2803                         return_error = BR_FAILED_REPLY;
2804                         return_error_param = -EPERM;
2805                         return_error_line = __LINE__;
2806                         goto err_invalid_target_handle;
2807                 }
2808                 binder_inner_proc_lock(proc);
2809                 if (!(tr->flags & TF_ONE_WAY) && thread->transaction_stack) {
2810                         struct binder_transaction *tmp;
2811
2812                         tmp = thread->transaction_stack;
2813                         if (tmp->to_thread != thread) {
2814                                 spin_lock(&tmp->lock);
2815                                 binder_user_error("%d:%d got new transaction with bad transaction stack, transaction %d has target %d:%d\n",
2816                                         proc->pid, thread->pid, tmp->debug_id,
2817                                         tmp->to_proc ? tmp->to_proc->pid : 0,
2818                                         tmp->to_thread ?
2819                                         tmp->to_thread->pid : 0);
2820                                 spin_unlock(&tmp->lock);
2821                                 binder_inner_proc_unlock(proc);
2822                                 return_error = BR_FAILED_REPLY;
2823                                 return_error_param = -EPROTO;
2824                                 return_error_line = __LINE__;
2825                                 goto err_bad_call_stack;
2826                         }
2827                         while (tmp) {
2828                                 struct binder_thread *from;
2829
2830                                 spin_lock(&tmp->lock);
2831                                 from = tmp->from;
2832                                 if (from && from->proc == target_proc) {
2833                                         atomic_inc(&from->tmp_ref);
2834                                         target_thread = from;
2835                                         spin_unlock(&tmp->lock);
2836                                         break;
2837                                 }
2838                                 spin_unlock(&tmp->lock);
2839                                 tmp = tmp->from_parent;
2840                         }
2841                 }
2842                 binder_inner_proc_unlock(proc);
2843         }
2844         if (target_thread)
2845                 e->to_thread = target_thread->pid;
2846         e->to_proc = target_proc->pid;
2847
2848         /* TODO: reuse incoming transaction for reply */
2849         t = kzalloc(sizeof(*t), GFP_KERNEL);
2850         if (t == NULL) {
2851                 return_error = BR_FAILED_REPLY;
2852                 return_error_param = -ENOMEM;
2853                 return_error_line = __LINE__;
2854                 goto err_alloc_t_failed;
2855         }
2856         binder_stats_created(BINDER_STAT_TRANSACTION);
2857         spin_lock_init(&t->lock);
2858
2859         tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);
2860         if (tcomplete == NULL) {
2861                 return_error = BR_FAILED_REPLY;
2862                 return_error_param = -ENOMEM;
2863                 return_error_line = __LINE__;
2864                 goto err_alloc_tcomplete_failed;
2865         }
2866         binder_stats_created(BINDER_STAT_TRANSACTION_COMPLETE);
2867
2868         t->debug_id = t_debug_id;
2869
2870         if (reply)
2871                 binder_debug(BINDER_DEBUG_TRANSACTION,
2872                              "%d:%d BC_REPLY %d -> %d:%d, data %016llx-%016llx size %lld-%lld-%lld\n",
2873                              proc->pid, thread->pid, t->debug_id,
2874                              target_proc->pid, target_thread->pid,
2875                              (u64)tr->data.ptr.buffer,
2876                              (u64)tr->data.ptr.offsets,
2877                              (u64)tr->data_size, (u64)tr->offsets_size,
2878                              (u64)extra_buffers_size);
2879         else
2880                 binder_debug(BINDER_DEBUG_TRANSACTION,
2881                              "%d:%d BC_TRANSACTION %d -> %d - node %d, data %016llx-%016llx size %lld-%lld-%lld\n",
2882                              proc->pid, thread->pid, t->debug_id,
2883                              target_proc->pid, target_node->debug_id,
2884                              (u64)tr->data.ptr.buffer,
2885                              (u64)tr->data.ptr.offsets,
2886                              (u64)tr->data_size, (u64)tr->offsets_size,
2887                              (u64)extra_buffers_size);
2888
2889         if (!reply && !(tr->flags & TF_ONE_WAY))
2890                 t->from = thread;
2891         else
2892                 t->from = NULL;
2893         t->sender_euid = task_euid(proc->tsk);
2894         t->to_proc = target_proc;
2895         t->to_thread = target_thread;
2896         t->code = tr->code;
2897         t->flags = tr->flags;
2898         t->priority = task_nice(current);
2899
2900         trace_binder_transaction(reply, t, target_node);
2901
2902         t->buffer = binder_alloc_new_buf(&target_proc->alloc, tr->data_size,
2903                 tr->offsets_size, extra_buffers_size,
2904                 !reply && (t->flags & TF_ONE_WAY));
2905         if (IS_ERR(t->buffer)) {
2906                 /*
2907                  * -ESRCH indicates VMA cleared. The target is dying.
2908                  */
2909                 return_error_param = PTR_ERR(t->buffer);
2910                 return_error = return_error_param == -ESRCH ?
2911                         BR_DEAD_REPLY : BR_FAILED_REPLY;
2912                 return_error_line = __LINE__;
2913                 t->buffer = NULL;
2914                 goto err_binder_alloc_buf_failed;
2915         }
2916         t->buffer->debug_id = t->debug_id;
2917         t->buffer->transaction = t;
2918         t->buffer->target_node = target_node;
2919         trace_binder_transaction_alloc_buf(t->buffer);
2920         off_start = (binder_size_t *)(t->buffer->data +
2921                                       ALIGN(tr->data_size, sizeof(void *)));
2922         offp = off_start;
2923
2924         if (copy_from_user(t->buffer->data, (const void __user *)(uintptr_t)
2925                            tr->data.ptr.buffer, tr->data_size)) {
2926                 binder_user_error("%d:%d got transaction with invalid data ptr\n",
2927                                 proc->pid, thread->pid);
2928                 return_error = BR_FAILED_REPLY;
2929                 return_error_param = -EFAULT;
2930                 return_error_line = __LINE__;
2931                 goto err_copy_data_failed;
2932         }
2933         if (copy_from_user(offp, (const void __user *)(uintptr_t)
2934                            tr->data.ptr.offsets, tr->offsets_size)) {
2935                 binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
2936                                 proc->pid, thread->pid);
2937                 return_error = BR_FAILED_REPLY;
2938                 return_error_param = -EFAULT;
2939                 return_error_line = __LINE__;
2940                 goto err_copy_data_failed;
2941         }
2942         if (!IS_ALIGNED(tr->offsets_size, sizeof(binder_size_t))) {
2943                 binder_user_error("%d:%d got transaction with invalid offsets size, %lld\n",
2944                                 proc->pid, thread->pid, (u64)tr->offsets_size);
2945                 return_error = BR_FAILED_REPLY;
2946                 return_error_param = -EINVAL;
2947                 return_error_line = __LINE__;
2948                 goto err_bad_offset;
2949         }
2950         if (!IS_ALIGNED(extra_buffers_size, sizeof(u64))) {
2951                 binder_user_error("%d:%d got transaction with unaligned buffers size, %lld\n",
2952                                   proc->pid, thread->pid,
2953                                   (u64)extra_buffers_size);
2954                 return_error = BR_FAILED_REPLY;
2955                 return_error_param = -EINVAL;
2956                 return_error_line = __LINE__;
2957                 goto err_bad_offset;
2958         }
2959         off_end = (void *)off_start + tr->offsets_size;
2960         sg_bufp = (u8 *)(PTR_ALIGN(off_end, sizeof(void *)));
2961         sg_buf_end = sg_bufp + extra_buffers_size;
2962         off_min = 0;
2963         for (; offp < off_end; offp++) {
2964                 struct binder_object_header *hdr;
2965                 size_t object_size = binder_validate_object(t->buffer, *offp);
2966
2967                 if (object_size == 0 || *offp < off_min) {
2968                         binder_user_error("%d:%d got transaction with invalid offset (%lld, min %lld max %lld) or object.\n",
2969                                           proc->pid, thread->pid, (u64)*offp,
2970                                           (u64)off_min,
2971                                           (u64)t->buffer->data_size);
2972                         return_error = BR_FAILED_REPLY;
2973                         return_error_param = -EINVAL;
2974                         return_error_line = __LINE__;
2975                         goto err_bad_offset;
2976                 }
2977
2978                 hdr = (struct binder_object_header *)(t->buffer->data + *offp);
2979                 off_min = *offp + object_size;
2980                 switch (hdr->type) {
2981                 case BINDER_TYPE_BINDER:
2982                 case BINDER_TYPE_WEAK_BINDER: {
2983                         struct flat_binder_object *fp;
2984
2985                         fp = to_flat_binder_object(hdr);
2986                         ret = binder_translate_binder(fp, t, thread);
2987                         if (ret < 0) {
2988                                 return_error = BR_FAILED_REPLY;
2989                                 return_error_param = ret;
2990                                 return_error_line = __LINE__;
2991                                 goto err_translate_failed;
2992                         }
2993                 } break;
2994                 case BINDER_TYPE_HANDLE:
2995                 case BINDER_TYPE_WEAK_HANDLE: {
2996                         struct flat_binder_object *fp;
2997
2998                         fp = to_flat_binder_object(hdr);
2999                         ret = binder_translate_handle(fp, t, thread);
3000                         if (ret < 0) {
3001                                 return_error = BR_FAILED_REPLY;
3002                                 return_error_param = ret;
3003                                 return_error_line = __LINE__;
3004                                 goto err_translate_failed;
3005                         }
3006                 } break;
3007
3008                 case BINDER_TYPE_FD: {
3009                         struct binder_fd_object *fp = to_binder_fd_object(hdr);
3010                         int target_fd = binder_translate_fd(fp->fd, t, thread,
3011                                                             in_reply_to);
3012
3013                         if (target_fd < 0) {
3014                                 return_error = BR_FAILED_REPLY;
3015                                 return_error_param = target_fd;
3016                                 return_error_line = __LINE__;
3017                                 goto err_translate_failed;
3018                         }
3019                         fp->pad_binder = 0;
3020                         fp->fd = target_fd;
3021                 } break;
3022                 case BINDER_TYPE_FDA: {
3023                         struct binder_fd_array_object *fda =
3024                                 to_binder_fd_array_object(hdr);
3025                         struct binder_buffer_object *parent =
3026                                 binder_validate_ptr(t->buffer, fda->parent,
3027                                                     off_start,
3028                                                     offp - off_start);
3029                         if (!parent) {
3030                                 binder_user_error("%d:%d got transaction with invalid parent offset or type\n",
3031                                                   proc->pid, thread->pid);
3032                                 return_error = BR_FAILED_REPLY;
3033                                 return_error_param = -EINVAL;
3034                                 return_error_line = __LINE__;
3035                                 goto err_bad_parent;
3036                         }
3037                         if (!binder_validate_fixup(t->buffer, off_start,
3038                                                    parent, fda->parent_offset,
3039                                                    last_fixup_obj,
3040                                                    last_fixup_min_off)) {
3041                                 binder_user_error("%d:%d got transaction with out-of-order buffer fixup\n",
3042                                                   proc->pid, thread->pid);
3043                                 return_error = BR_FAILED_REPLY;
3044                                 return_error_param = -EINVAL;
3045                                 return_error_line = __LINE__;
3046                                 goto err_bad_parent;
3047                         }
3048                         ret = binder_translate_fd_array(fda, parent, t, thread,
3049                                                         in_reply_to);
3050                         if (ret < 0) {
3051                                 return_error = BR_FAILED_REPLY;
3052                                 return_error_param = ret;
3053                                 return_error_line = __LINE__;
3054                                 goto err_translate_failed;
3055                         }
3056                         last_fixup_obj = parent;
3057                         last_fixup_min_off =
3058                                 fda->parent_offset + sizeof(u32) * fda->num_fds;
3059                 } break;
3060                 case BINDER_TYPE_PTR: {
3061                         struct binder_buffer_object *bp =
3062                                 to_binder_buffer_object(hdr);
3063                         size_t buf_left = sg_buf_end - sg_bufp;
3064
3065                         if (bp->length > buf_left) {
3066                                 binder_user_error("%d:%d got transaction with too large buffer\n",
3067                                                   proc->pid, thread->pid);
3068                                 return_error = BR_FAILED_REPLY;
3069                                 return_error_param = -EINVAL;
3070                                 return_error_line = __LINE__;
3071                                 goto err_bad_offset;
3072                         }
3073                         if (copy_from_user(sg_bufp,
3074                                            (const void __user *)(uintptr_t)
3075                                            bp->buffer, bp->length)) {
3076                                 binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
3077                                                   proc->pid, thread->pid);
3078                                 return_error_param = -EFAULT;
3079                                 return_error = BR_FAILED_REPLY;
3080                                 return_error_line = __LINE__;
3081                                 goto err_copy_data_failed;
3082                         }
3083                         /* Fixup buffer pointer to target proc address space */
3084                         bp->buffer = (uintptr_t)sg_bufp +
3085                                 binder_alloc_get_user_buffer_offset(
3086                                                 &target_proc->alloc);
3087                         sg_bufp += ALIGN(bp->length, sizeof(u64));
3088
3089                         ret = binder_fixup_parent(t, thread, bp, off_start,
3090                                                   offp - off_start,
3091                                                   last_fixup_obj,
3092                                                   last_fixup_min_off);
3093                         if (ret < 0) {
3094                                 return_error = BR_FAILED_REPLY;
3095                                 return_error_param = ret;
3096                                 return_error_line = __LINE__;
3097                                 goto err_translate_failed;
3098                         }
3099                         last_fixup_obj = bp;
3100                         last_fixup_min_off = 0;
3101                 } break;
3102                 default:
3103                         binder_user_error("%d:%d got transaction with invalid object type, %x\n",
3104                                 proc->pid, thread->pid, hdr->type);
3105                         return_error = BR_FAILED_REPLY;
3106                         return_error_param = -EINVAL;
3107                         return_error_line = __LINE__;
3108                         goto err_bad_object_type;
3109                 }
3110         }
3111         tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;
3112         binder_enqueue_work(proc, tcomplete, &thread->todo);
3113         t->work.type = BINDER_WORK_TRANSACTION;
3114
3115         if (reply) {
3116                 binder_inner_proc_lock(target_proc);
3117                 if (target_thread->is_dead) {
3118                         binder_inner_proc_unlock(target_proc);
3119                         goto err_dead_proc_or_thread;
3120                 }
3121                 BUG_ON(t->buffer->async_transaction != 0);
3122                 binder_pop_transaction_ilocked(target_thread, in_reply_to);
3123                 binder_enqueue_work_ilocked(&t->work, &target_thread->todo);
3124                 binder_inner_proc_unlock(target_proc);
3125                 wake_up_interruptible_sync(&target_thread->wait);
3126                 binder_free_transaction(in_reply_to);
3127         } else if (!(t->flags & TF_ONE_WAY)) {
3128                 BUG_ON(t->buffer->async_transaction != 0);
3129                 binder_inner_proc_lock(proc);
3130                 t->need_reply = 1;
3131                 t->from_parent = thread->transaction_stack;
3132                 thread->transaction_stack = t;
3133                 binder_inner_proc_unlock(proc);
3134                 if (!binder_proc_transaction(t, target_proc, target_thread)) {
3135                         binder_inner_proc_lock(proc);
3136                         binder_pop_transaction_ilocked(thread, t);
3137                         binder_inner_proc_unlock(proc);
3138                         goto err_dead_proc_or_thread;
3139                 }
3140         } else {
3141                 BUG_ON(target_node == NULL);
3142                 BUG_ON(t->buffer->async_transaction != 1);
3143                 if (!binder_proc_transaction(t, target_proc, NULL))
3144                         goto err_dead_proc_or_thread;
3145         }
3146         if (target_thread)
3147                 binder_thread_dec_tmpref(target_thread);
3148         binder_proc_dec_tmpref(target_proc);
3149         if (target_node)
3150                 binder_dec_node_tmpref(target_node);
3151         /*
3152          * write barrier to synchronize with initialization
3153          * of log entry
3154          */
3155         smp_wmb();
3156         WRITE_ONCE(e->debug_id_done, t_debug_id);
3157         return;
3158
3159 err_dead_proc_or_thread:
3160         return_error = BR_DEAD_REPLY;
3161         return_error_line = __LINE__;
3162         binder_dequeue_work(proc, tcomplete);
3163 err_translate_failed:
3164 err_bad_object_type:
3165 err_bad_offset:
3166 err_bad_parent:
3167 err_copy_data_failed:
3168         trace_binder_transaction_failed_buffer_release(t->buffer);
3169         binder_transaction_buffer_release(target_proc, t->buffer, offp);
3170         if (target_node)
3171                 binder_dec_node_tmpref(target_node);
3172         target_node = NULL;
3173         t->buffer->transaction = NULL;
3174         binder_alloc_free_buf(&target_proc->alloc, t->buffer);
3175 err_binder_alloc_buf_failed:
3176         kfree(tcomplete);
3177         binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
3178 err_alloc_tcomplete_failed:
3179         kfree(t);
3180         binder_stats_deleted(BINDER_STAT_TRANSACTION);
3181 err_alloc_t_failed:
3182 err_bad_call_stack:
3183 err_empty_call_stack:
3184 err_dead_binder:
3185 err_invalid_target_handle:
3186         if (target_thread)
3187                 binder_thread_dec_tmpref(target_thread);
3188         if (target_proc)
3189                 binder_proc_dec_tmpref(target_proc);
3190         if (target_node) {
3191                 binder_dec_node(target_node, 1, 0);
3192                 binder_dec_node_tmpref(target_node);
3193         }
3194
3195         binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
3196                      "%d:%d transaction failed %d/%d, size %lld-%lld line %d\n",
3197                      proc->pid, thread->pid, return_error, return_error_param,
3198                      (u64)tr->data_size, (u64)tr->offsets_size,
3199                      return_error_line);
3200
3201         {
3202                 struct binder_transaction_log_entry *fe;
3203
3204                 e->return_error = return_error;
3205                 e->return_error_param = return_error_param;
3206                 e->return_error_line = return_error_line;
3207                 fe = binder_transaction_log_add(&binder_transaction_log_failed);
3208                 *fe = *e;
3209                 /*
3210                  * write barrier to synchronize with initialization
3211                  * of log entry
3212                  */
3213                 smp_wmb();
3214                 WRITE_ONCE(e->debug_id_done, t_debug_id);
3215                 WRITE_ONCE(fe->debug_id_done, t_debug_id);
3216         }
3217
3218         BUG_ON(thread->return_error.cmd != BR_OK);
3219         if (in_reply_to) {
3220                 thread->return_error.cmd = BR_TRANSACTION_COMPLETE;
3221                 binder_enqueue_work(thread->proc,
3222                                     &thread->return_error.work,
3223                                     &thread->todo);
3224                 binder_send_failed_reply(in_reply_to, return_error);
3225         } else {
3226                 thread->return_error.cmd = return_error;
3227                 binder_enqueue_work(thread->proc,
3228                                     &thread->return_error.work,
3229                                     &thread->todo);
3230         }
3231 }
3232
3233 static int binder_thread_write(struct binder_proc *proc,
3234                         struct binder_thread *thread,
3235                         binder_uintptr_t binder_buffer, size_t size,
3236                         binder_size_t *consumed)
3237 {
3238         uint32_t cmd;
3239         struct binder_context *context = proc->context;
3240         void __user *buffer = (void __user *)(uintptr_t)binder_buffer;
3241         void __user *ptr = buffer + *consumed;
3242         void __user *end = buffer + size;
3243
3244         while (ptr < end && thread->return_error.cmd == BR_OK) {
3245                 int ret;
3246
3247                 if (get_user(cmd, (uint32_t __user *)ptr))
3248                         return -EFAULT;
3249                 ptr += sizeof(uint32_t);
3250                 trace_binder_command(cmd);
3251                 if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {
3252                         atomic_inc(&binder_stats.bc[_IOC_NR(cmd)]);
3253                         atomic_inc(&proc->stats.bc[_IOC_NR(cmd)]);
3254                         atomic_inc(&thread->stats.bc[_IOC_NR(cmd)]);
3255                 }
3256                 switch (cmd) {
3257                 case BC_INCREFS:
3258                 case BC_ACQUIRE:
3259                 case BC_RELEASE:
3260                 case BC_DECREFS: {
3261                         uint32_t target;
3262                         const char *debug_string;
3263                         bool strong = cmd == BC_ACQUIRE || cmd == BC_RELEASE;
3264                         bool increment = cmd == BC_INCREFS || cmd == BC_ACQUIRE;
3265                         struct binder_ref_data rdata;
3266
3267                         if (get_user(target, (uint32_t __user *)ptr))
3268                                 return -EFAULT;
3269
3270                         ptr += sizeof(uint32_t);
3271                         ret = -1;
3272                         if (increment && !target) {
3273                                 struct binder_node *ctx_mgr_node;
3274                                 mutex_lock(&context->context_mgr_node_lock);
3275                                 ctx_mgr_node = context->binder_context_mgr_node;
3276                                 if (ctx_mgr_node) {
3277                                         if (ctx_mgr_node->proc == proc) {
3278                                                 binder_user_error("%d:%d context manager tried to acquire desc 0\n",
3279                                                                   proc->pid, thread->pid);
3280                                                 mutex_unlock(&context->context_mgr_node_lock);
3281                                                 return -EINVAL;
3282                                         }
3283                                         ret = binder_inc_ref_for_node(
3284                                                         proc, ctx_mgr_node,
3285                                                         strong, NULL, &rdata);
3286                                 }
3287                                 mutex_unlock(&context->context_mgr_node_lock);
3288                         }
3289                         if (ret)
3290                                 ret = binder_update_ref_for_handle(
3291                                                 proc, target, increment, strong,
3292                                                 &rdata);
3293                         if (!ret && rdata.desc != target) {
3294                                 binder_user_error("%d:%d tried to acquire reference to desc %d, got %d instead\n",
3295                                         proc->pid, thread->pid,
3296                                         target, rdata.desc);
3297                         }
3298                         switch (cmd) {
3299                         case BC_INCREFS:
3300                                 debug_string = "IncRefs";
3301                                 break;
3302                         case BC_ACQUIRE:
3303                                 debug_string = "Acquire";
3304                                 break;
3305                         case BC_RELEASE:
3306                                 debug_string = "Release";
3307                                 break;
3308                         case BC_DECREFS:
3309                         default:
3310                                 debug_string = "DecRefs";
3311                                 break;
3312                         }
3313                         if (ret) {
3314                                 binder_user_error("%d:%d %s %d refcount change on invalid ref %d ret %d\n",
3315                                         proc->pid, thread->pid, debug_string,
3316                                         strong, target, ret);
3317                                 break;
3318                         }
3319                         binder_debug(BINDER_DEBUG_USER_REFS,
3320                                      "%d:%d %s ref %d desc %d s %d w %d\n",
3321                                      proc->pid, thread->pid, debug_string,
3322                                      rdata.debug_id, rdata.desc, rdata.strong,
3323                                      rdata.weak);
3324                         break;
3325                 }
3326                 case BC_INCREFS_DONE:
3327                 case BC_ACQUIRE_DONE: {
3328                         binder_uintptr_t node_ptr;
3329                         binder_uintptr_t cookie;
3330                         struct binder_node *node;
3331                         bool free_node;
3332
3333                         if (get_user(node_ptr, (binder_uintptr_t __user *)ptr))
3334                                 return -EFAULT;
3335                         ptr += sizeof(binder_uintptr_t);
3336                         if (get_user(cookie, (binder_uintptr_t __user *)ptr))
3337                                 return -EFAULT;
3338                         ptr += sizeof(binder_uintptr_t);
3339                         node = binder_get_node(proc, node_ptr);
3340                         if (node == NULL) {
3341                                 binder_user_error("%d:%d %s u%016llx no match\n",
3342                                         proc->pid, thread->pid,
3343                                         cmd == BC_INCREFS_DONE ?
3344                                         "BC_INCREFS_DONE" :
3345                                         "BC_ACQUIRE_DONE",
3346                                         (u64)node_ptr);
3347                                 break;
3348                         }
3349                         if (cookie != node->cookie) {
3350                                 binder_user_error("%d:%d %s u%016llx node %d cookie mismatch %016llx != %016llx\n",
3351                                         proc->pid, thread->pid,
3352                                         cmd == BC_INCREFS_DONE ?
3353                                         "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE",
3354                                         (u64)node_ptr, node->debug_id,
3355                                         (u64)cookie, (u64)node->cookie);
3356                                 binder_put_node(node);
3357                                 break;
3358                         }
3359                         binder_node_inner_lock(node);
3360                         if (cmd == BC_ACQUIRE_DONE) {
3361                                 if (node->pending_strong_ref == 0) {
3362                                         binder_user_error("%d:%d BC_ACQUIRE_DONE node %d has no pending acquire request\n",
3363                                                 proc->pid, thread->pid,
3364                                                 node->debug_id);
3365                                         binder_node_inner_unlock(node);
3366                                         binder_put_node(node);
3367                                         break;
3368                                 }
3369                                 node->pending_strong_ref = 0;
3370                         } else {
3371                                 if (node->pending_weak_ref == 0) {
3372                                         binder_user_error("%d:%d BC_INCREFS_DONE node %d has no pending increfs request\n",
3373                                                 proc->pid, thread->pid,
3374                                                 node->debug_id);
3375                                         binder_node_inner_unlock(node);
3376                                         binder_put_node(node);
3377                                         break;
3378                                 }
3379                                 node->pending_weak_ref = 0;
3380                         }
3381                         free_node = binder_dec_node_nilocked(node,
3382                                         cmd == BC_ACQUIRE_DONE, 0);
3383                         WARN_ON(free_node);
3384                         binder_debug(BINDER_DEBUG_USER_REFS,
3385                                      "%d:%d %s node %d ls %d lw %d tr %d\n",
3386                                      proc->pid, thread->pid,
3387                                      cmd == BC_INCREFS_DONE ? "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE",
3388                                      node->debug_id, node->local_strong_refs,
3389                                      node->local_weak_refs, node->tmp_refs);
3390                         binder_node_inner_unlock(node);
3391                         binder_put_node(node);
3392                         break;
3393                 }
3394                 case BC_ATTEMPT_ACQUIRE:
3395                         pr_err("BC_ATTEMPT_ACQUIRE not supported\n");
3396                         return -EINVAL;
3397                 case BC_ACQUIRE_RESULT:
3398                         pr_err("BC_ACQUIRE_RESULT not supported\n");
3399                         return -EINVAL;
3400
3401                 case BC_FREE_BUFFER: {
3402                         binder_uintptr_t data_ptr;
3403                         struct binder_buffer *buffer;
3404
3405                         if (get_user(data_ptr, (binder_uintptr_t __user *)ptr))
3406                                 return -EFAULT;
3407                         ptr += sizeof(binder_uintptr_t);
3408
3409                         buffer = binder_alloc_prepare_to_free(&proc->alloc,
3410                                                               data_ptr);
3411                         if (IS_ERR_OR_NULL(buffer)) {
3412                                 if (PTR_ERR(buffer) == -EPERM) {
3413                                         binder_user_error(
3414                                                 "%d:%d BC_FREE_BUFFER u%016llx matched unreturned or currently freeing buffer\n",
3415                                                 proc->pid, thread->pid,
3416                                                 (u64)data_ptr);
3417                                 } else {
3418                                         binder_user_error(
3419                                                 "%d:%d BC_FREE_BUFFER u%016llx no match\n",
3420                                                 proc->pid, thread->pid,
3421                                                 (u64)data_ptr);
3422                                 }
3423                                 break;
3424                         }
3425                         binder_debug(BINDER_DEBUG_FREE_BUFFER,
3426                                      "%d:%d BC_FREE_BUFFER u%016llx found buffer %d for %s transaction\n",
3427                                      proc->pid, thread->pid, (u64)data_ptr,
3428                                      buffer->debug_id,
3429                                      buffer->transaction ? "active" : "finished");
3430
3431                         binder_inner_proc_lock(proc);
3432                         if (buffer->transaction) {
3433                                 buffer->transaction->buffer = NULL;
3434                                 buffer->transaction = NULL;
3435                         }
3436                         binder_inner_proc_unlock(proc);
3437                         if (buffer->async_transaction && buffer->target_node) {
3438                                 struct binder_node *buf_node;
3439                                 struct binder_work *w;
3440
3441                                 buf_node = buffer->target_node;
3442                                 binder_node_inner_lock(buf_node);
3443                                 BUG_ON(!buf_node->has_async_transaction);
3444                                 BUG_ON(buf_node->proc != proc);
3445                                 w = binder_dequeue_work_head_ilocked(
3446                                                 &buf_node->async_todo);
3447                                 if (!w) {
3448                                         buf_node->has_async_transaction = 0;
3449                                 } else {
3450                                         binder_enqueue_work_ilocked(
3451                                                         w, &proc->todo);
3452                                         binder_wakeup_proc_ilocked(proc);
3453                                 }
3454                                 binder_node_inner_unlock(buf_node);
3455                         }
3456                         trace_binder_transaction_buffer_release(buffer);
3457                         binder_transaction_buffer_release(proc, buffer, NULL);
3458                         binder_alloc_free_buf(&proc->alloc, buffer);
3459                         break;
3460                 }
3461
3462                 case BC_TRANSACTION_SG:
3463                 case BC_REPLY_SG: {
3464                         struct binder_transaction_data_sg tr;
3465
3466                         if (copy_from_user(&tr, ptr, sizeof(tr)))
3467                                 return -EFAULT;
3468                         ptr += sizeof(tr);
3469                         binder_transaction(proc, thread, &tr.transaction_data,
3470                                            cmd == BC_REPLY_SG, tr.buffers_size);
3471                         break;
3472                 }
3473                 case BC_TRANSACTION:
3474                 case BC_REPLY: {
3475                         struct binder_transaction_data tr;
3476
3477                         if (copy_from_user(&tr, ptr, sizeof(tr)))
3478                                 return -EFAULT;
3479                         ptr += sizeof(tr);
3480                         binder_transaction(proc, thread, &tr,
3481                                            cmd == BC_REPLY, 0);
3482                         break;
3483                 }
3484
3485                 case BC_REGISTER_LOOPER:
3486                         binder_debug(BINDER_DEBUG_THREADS,
3487                                      "%d:%d BC_REGISTER_LOOPER\n",
3488                                      proc->pid, thread->pid);
3489                         binder_inner_proc_lock(proc);
3490                         if (thread->looper & BINDER_LOOPER_STATE_ENTERED) {
3491                                 thread->looper |= BINDER_LOOPER_STATE_INVALID;
3492                                 binder_user_error("%d:%d ERROR: BC_REGISTER_LOOPER called after BC_ENTER_LOOPER\n",
3493                                         proc->pid, thread->pid);
3494                         } else if (proc->requested_threads == 0) {
3495                                 thread->looper |= BINDER_LOOPER_STATE_INVALID;
3496                                 binder_user_error("%d:%d ERROR: BC_REGISTER_LOOPER called without request\n",
3497                                         proc->pid, thread->pid);
3498                         } else {
3499                                 proc->requested_threads--;
3500                                 proc->requested_threads_started++;
3501                         }
3502                         thread->looper |= BINDER_LOOPER_STATE_REGISTERED;
3503                         binder_inner_proc_unlock(proc);
3504                         break;
3505                 case BC_ENTER_LOOPER:
3506                         binder_debug(BINDER_DEBUG_THREADS,
3507                                      "%d:%d BC_ENTER_LOOPER\n",
3508                                      proc->pid, thread->pid);
3509                         if (thread->looper & BINDER_LOOPER_STATE_REGISTERED) {
3510                                 thread->looper |= BINDER_LOOPER_STATE_INVALID;
3511                                 binder_user_error("%d:%d ERROR: BC_ENTER_LOOPER called after BC_REGISTER_LOOPER\n",
3512                                         proc->pid, thread->pid);
3513                         }
3514                         thread->looper |= BINDER_LOOPER_STATE_ENTERED;
3515                         break;
3516                 case BC_EXIT_LOOPER:
3517                         binder_debug(BINDER_DEBUG_THREADS,
3518                                      "%d:%d BC_EXIT_LOOPER\n",
3519                                      proc->pid, thread->pid);
3520                         thread->looper |= BINDER_LOOPER_STATE_EXITED;
3521                         break;
3522
3523                 case BC_REQUEST_DEATH_NOTIFICATION:
3524                 case BC_CLEAR_DEATH_NOTIFICATION: {
3525                         uint32_t target;
3526                         binder_uintptr_t cookie;
3527                         struct binder_ref *ref;
3528                         struct binder_ref_death *death = NULL;
3529
3530                         if (get_user(target, (uint32_t __user *)ptr))
3531                                 return -EFAULT;
3532                         ptr += sizeof(uint32_t);
3533                         if (get_user(cookie, (binder_uintptr_t __user *)ptr))
3534                                 return -EFAULT;
3535                         ptr += sizeof(binder_uintptr_t);
3536                         if (cmd == BC_REQUEST_DEATH_NOTIFICATION) {
3537                                 /*
3538                                  * Allocate memory for death notification
3539                                  * before taking lock
3540                                  */
3541                                 death = kzalloc(sizeof(*death), GFP_KERNEL);
3542                                 if (death == NULL) {
3543                                         WARN_ON(thread->return_error.cmd !=
3544                                                 BR_OK);
3545                                         thread->return_error.cmd = BR_ERROR;
3546                                         binder_enqueue_work(
3547                                                 thread->proc,
3548                                                 &thread->return_error.work,
3549                                                 &thread->todo);
3550                                         binder_debug(
3551                                                 BINDER_DEBUG_FAILED_TRANSACTION,
3552                                                 "%d:%d BC_REQUEST_DEATH_NOTIFICATION failed\n",
3553                                                 proc->pid, thread->pid);
3554                                         break;
3555                                 }
3556                         }
3557                         binder_proc_lock(proc);
3558                         ref = binder_get_ref_olocked(proc, target, false);
3559                         if (ref == NULL) {
3560                                 binder_user_error("%d:%d %s invalid ref %d\n",
3561                                         proc->pid, thread->pid,
3562                                         cmd == BC_REQUEST_DEATH_NOTIFICATION ?
3563                                         "BC_REQUEST_DEATH_NOTIFICATION" :
3564                                         "BC_CLEAR_DEATH_NOTIFICATION",
3565                                         target);
3566                                 binder_proc_unlock(proc);
3567                                 kfree(death);
3568                                 break;
3569                         }
3570
3571                         binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION,
3572                                      "%d:%d %s %016llx ref %d desc %d s %d w %d for node %d\n",
3573                                      proc->pid, thread->pid,
3574                                      cmd == BC_REQUEST_DEATH_NOTIFICATION ?
3575                                      "BC_REQUEST_DEATH_NOTIFICATION" :
3576                                      "BC_CLEAR_DEATH_NOTIFICATION",
3577                                      (u64)cookie, ref->data.debug_id,
3578                                      ref->data.desc, ref->data.strong,
3579                                      ref->data.weak, ref->node->debug_id);
3580
3581                         binder_node_lock(ref->node);
3582                         if (cmd == BC_REQUEST_DEATH_NOTIFICATION) {
3583                                 if (ref->death) {
3584                                         binder_user_error("%d:%d BC_REQUEST_DEATH_NOTIFICATION death notification already set\n",
3585                                                 proc->pid, thread->pid);
3586                                         binder_node_unlock(ref->node);
3587                                         binder_proc_unlock(proc);
3588                                         kfree(death);
3589                                         break;
3590                                 }
3591                                 binder_stats_created(BINDER_STAT_DEATH);
3592                                 INIT_LIST_HEAD(&death->work.entry);
3593                                 death->cookie = cookie;
3594                                 ref->death = death;
3595                                 if (ref->node->proc == NULL) {
3596                                         ref->death->work.type = BINDER_WORK_DEAD_BINDER;
3597
3598                                         binder_inner_proc_lock(proc);
3599                                         binder_enqueue_work_ilocked(
3600                                                 &ref->death->work, &proc->todo);
3601                                         binder_wakeup_proc_ilocked(proc);
3602                                         binder_inner_proc_unlock(proc);
3603                                 }
3604                         } else {
3605                                 if (ref->death == NULL) {
3606                                         binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification not active\n",
3607                                                 proc->pid, thread->pid);
3608                                         binder_node_unlock(ref->node);
3609                                         binder_proc_unlock(proc);
3610                                         break;
3611                                 }
3612                                 death = ref->death;
3613                                 if (death->cookie != cookie) {
3614                                         binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification cookie mismatch %016llx != %016llx\n",
3615                                                 proc->pid, thread->pid,
3616                                                 (u64)death->cookie,
3617                                                 (u64)cookie);
3618                                         binder_node_unlock(ref->node);
3619                                         binder_proc_unlock(proc);
3620                                         break;
3621                                 }
3622                                 ref->death = NULL;
3623                                 binder_inner_proc_lock(proc);
3624                                 if (list_empty(&death->work.entry)) {
3625                                         death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION;
3626                                         if (thread->looper &
3627                                             (BINDER_LOOPER_STATE_REGISTERED |
3628                                              BINDER_LOOPER_STATE_ENTERED))
3629                                                 binder_enqueue_work_ilocked(
3630                                                                 &death->work,
3631                                                                 &thread->todo);
3632                                         else {
3633                                                 binder_enqueue_work_ilocked(
3634                                                                 &death->work,
3635                                                                 &proc->todo);
3636                                                 binder_wakeup_proc_ilocked(
3637                                                                 proc);
3638                                         }
3639                                 } else {
3640                                         BUG_ON(death->work.type != BINDER_WORK_DEAD_BINDER);
3641                                         death->work.type = BINDER_WORK_DEAD_BINDER_AND_CLEAR;
3642                                 }
3643                                 binder_inner_proc_unlock(proc);
3644                         }
3645                         binder_node_unlock(ref->node);
3646                         binder_proc_unlock(proc);
3647                 } break;
3648                 case BC_DEAD_BINDER_DONE: {
3649                         struct binder_work *w;
3650                         binder_uintptr_t cookie;
3651                         struct binder_ref_death *death = NULL;
3652
3653                         if (get_user(cookie, (binder_uintptr_t __user *)ptr))
3654                                 return -EFAULT;
3655
3656                         ptr += sizeof(cookie);
3657                         binder_inner_proc_lock(proc);
3658                         list_for_each_entry(w, &proc->delivered_death,
3659                                             entry) {
3660                                 struct binder_ref_death *tmp_death =
3661                                         container_of(w,
3662                                                      struct binder_ref_death,
3663                                                      work);
3664
3665                                 if (tmp_death->cookie == cookie) {
3666                                         death = tmp_death;
3667                                         break;
3668                                 }
3669                         }
3670                         binder_debug(BINDER_DEBUG_DEAD_BINDER,
3671                                      "%d:%d BC_DEAD_BINDER_DONE %016llx found %pK\n",
3672                                      proc->pid, thread->pid, (u64)cookie,
3673                                      death);
3674                         if (death == NULL) {
3675                                 binder_user_error("%d:%d BC_DEAD_BINDER_DONE %016llx not found\n",
3676                                         proc->pid, thread->pid, (u64)cookie);
3677                                 binder_inner_proc_unlock(proc);
3678                                 break;
3679                         }
3680                         binder_dequeue_work_ilocked(&death->work);
3681                         if (death->work.type == BINDER_WORK_DEAD_BINDER_AND_CLEAR) {
3682                                 death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION;
3683                                 if (thread->looper &
3684                                         (BINDER_LOOPER_STATE_REGISTERED |
3685                                          BINDER_LOOPER_STATE_ENTERED))
3686                                         binder_enqueue_work_ilocked(
3687                                                 &death->work, &thread->todo);
3688                                 else {
3689                                         binder_enqueue_work_ilocked(
3690                                                         &death->work,
3691                                                         &proc->todo);
3692                                         binder_wakeup_proc_ilocked(proc);
3693                                 }
3694                         }
3695                         binder_inner_proc_unlock(proc);
3696                 } break;
3697
3698                 default:
3699                         pr_err("%d:%d unknown command %d\n",
3700                                proc->pid, thread->pid, cmd);
3701                         return -EINVAL;
3702                 }
3703                 *consumed = ptr - buffer;
3704         }
3705         return 0;
3706 }
3707
3708 static void binder_stat_br(struct binder_proc *proc,
3709                            struct binder_thread *thread, uint32_t cmd)
3710 {
3711         trace_binder_return(cmd);
3712         if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.br)) {
3713                 atomic_inc(&binder_stats.br[_IOC_NR(cmd)]);
3714                 atomic_inc(&proc->stats.br[_IOC_NR(cmd)]);
3715                 atomic_inc(&thread->stats.br[_IOC_NR(cmd)]);
3716         }
3717 }
3718
3719 static int binder_put_node_cmd(struct binder_proc *proc,
3720                                struct binder_thread *thread,
3721                                void __user **ptrp,
3722                                binder_uintptr_t node_ptr,
3723                                binder_uintptr_t node_cookie,
3724                                int node_debug_id,
3725                                uint32_t cmd, const char *cmd_name)
3726 {
3727         void __user *ptr = *ptrp;
3728
3729         if (put_user(cmd, (uint32_t __user *)ptr))
3730                 return -EFAULT;
3731         ptr += sizeof(uint32_t);
3732
3733         if (put_user(node_ptr, (binder_uintptr_t __user *)ptr))
3734                 return -EFAULT;
3735         ptr += sizeof(binder_uintptr_t);
3736
3737         if (put_user(node_cookie, (binder_uintptr_t __user *)ptr))
3738                 return -EFAULT;
3739         ptr += sizeof(binder_uintptr_t);
3740
3741         binder_stat_br(proc, thread, cmd);
3742         binder_debug(BINDER_DEBUG_USER_REFS, "%d:%d %s %d u%016llx c%016llx\n",
3743                      proc->pid, thread->pid, cmd_name, node_debug_id,
3744                      (u64)node_ptr, (u64)node_cookie);
3745
3746         *ptrp = ptr;
3747         return 0;
3748 }
3749
3750 static int binder_wait_for_work(struct binder_thread *thread,
3751                                 bool do_proc_work)
3752 {
3753         DEFINE_WAIT(wait);
3754         struct binder_proc *proc = thread->proc;
3755         int ret = 0;
3756
3757         freezer_do_not_count();
3758         binder_inner_proc_lock(proc);
3759         for (;;) {
3760                 prepare_to_wait(&thread->wait, &wait, TASK_INTERRUPTIBLE);
3761                 if (binder_has_work_ilocked(thread, do_proc_work))
3762                         break;
3763                 if (do_proc_work)
3764                         list_add(&thread->waiting_thread_node,
3765                                  &proc->waiting_threads);
3766                 binder_inner_proc_unlock(proc);
3767                 schedule();
3768                 binder_inner_proc_lock(proc);
3769                 list_del_init(&thread->waiting_thread_node);
3770                 if (signal_pending(current)) {
3771                         ret = -ERESTARTSYS;
3772                         break;
3773                 }
3774         }
3775         finish_wait(&thread->wait, &wait);
3776         binder_inner_proc_unlock(proc);
3777         freezer_count();
3778
3779         return ret;
3780 }
3781
3782 static int binder_thread_read(struct binder_proc *proc,
3783                               struct binder_thread *thread,
3784                               binder_uintptr_t binder_buffer, size_t size,
3785                               binder_size_t *consumed, int non_block)
3786 {
3787         void __user *buffer = (void __user *)(uintptr_t)binder_buffer;
3788         void __user *ptr = buffer + *consumed;
3789         void __user *end = buffer + size;
3790
3791         int ret = 0;
3792         int wait_for_proc_work;
3793
3794         if (*consumed == 0) {
3795                 if (put_user(BR_NOOP, (uint32_t __user *)ptr))
3796                         return -EFAULT;
3797                 ptr += sizeof(uint32_t);
3798         }
3799
3800 retry:
3801         binder_inner_proc_lock(proc);
3802         wait_for_proc_work = binder_available_for_proc_work_ilocked(thread);
3803         binder_inner_proc_unlock(proc);
3804
3805         thread->looper |= BINDER_LOOPER_STATE_WAITING;
3806
3807         trace_binder_wait_for_work(wait_for_proc_work,
3808                                    !!thread->transaction_stack,
3809                                    !binder_worklist_empty(proc, &thread->todo));
3810         if (wait_for_proc_work) {
3811                 if (!(thread->looper & (BINDER_LOOPER_STATE_REGISTERED |
3812                                         BINDER_LOOPER_STATE_ENTERED))) {
3813                         binder_user_error("%d:%d ERROR: Thread waiting for process work before calling BC_REGISTER_LOOPER or BC_ENTER_LOOPER (state %x)\n",
3814                                 proc->pid, thread->pid, thread->looper);
3815                         wait_event_interruptible(binder_user_error_wait,
3816                                                  binder_stop_on_user_error < 2);
3817                 }
3818                 binder_set_nice(proc->default_priority);
3819         }
3820
3821         if (non_block) {
3822                 if (!binder_has_work(thread, wait_for_proc_work))
3823                         ret = -EAGAIN;
3824         } else {
3825                 ret = binder_wait_for_work(thread, wait_for_proc_work);
3826         }
3827
3828         thread->looper &= ~BINDER_LOOPER_STATE_WAITING;
3829
3830         if (ret)
3831                 return ret;
3832
3833         while (1) {
3834                 uint32_t cmd;
3835                 struct binder_transaction_data tr;
3836                 struct binder_work *w = NULL;
3837                 struct list_head *list = NULL;
3838                 struct binder_transaction *t = NULL;
3839                 struct binder_thread *t_from;
3840
3841                 binder_inner_proc_lock(proc);
3842                 if (!binder_worklist_empty_ilocked(&thread->todo))
3843                         list = &thread->todo;
3844                 else if (!binder_worklist_empty_ilocked(&proc->todo) &&
3845                            wait_for_proc_work)
3846                         list = &proc->todo;
3847                 else {
3848                         binder_inner_proc_unlock(proc);
3849
3850                         /* no data added */
3851                         if (ptr - buffer == 4 && !thread->looper_need_return)
3852                                 goto retry;
3853                         break;
3854                 }
3855
3856                 if (end - ptr < sizeof(tr) + 4) {
3857                         binder_inner_proc_unlock(proc);
3858                         break;
3859                 }
3860                 w = binder_dequeue_work_head_ilocked(list);
3861
3862                 switch (w->type) {
3863                 case BINDER_WORK_TRANSACTION: {
3864                         binder_inner_proc_unlock(proc);
3865                         t = container_of(w, struct binder_transaction, work);
3866                 } break;
3867                 case BINDER_WORK_RETURN_ERROR: {
3868                         struct binder_error *e = container_of(
3869                                         w, struct binder_error, work);
3870
3871                         WARN_ON(e->cmd == BR_OK);
3872                         binder_inner_proc_unlock(proc);
3873                         if (put_user(e->cmd, (uint32_t __user *)ptr))
3874                                 return -EFAULT;
3875                         e->cmd = BR_OK;
3876                         ptr += sizeof(uint32_t);
3877
3878                         binder_stat_br(proc, thread, e->cmd);
3879                 } break;
3880                 case BINDER_WORK_TRANSACTION_COMPLETE: {
3881                         binder_inner_proc_unlock(proc);
3882                         cmd = BR_TRANSACTION_COMPLETE;
3883                         kfree(w);
3884                         binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
3885                         if (put_user(cmd, (uint32_t __user *)ptr))
3886                                 return -EFAULT;
3887                         ptr += sizeof(uint32_t);
3888
3889                         binder_stat_br(proc, thread, cmd);
3890                         binder_debug(BINDER_DEBUG_TRANSACTION_COMPLETE,
3891                                      "%d:%d BR_TRANSACTION_COMPLETE\n",
3892                                      proc->pid, thread->pid);
3893                 } break;
3894                 case BINDER_WORK_NODE: {
3895                         struct binder_node *node = container_of(w, struct binder_node, work);
3896                         int strong, weak;
3897                         binder_uintptr_t node_ptr = node->ptr;
3898                         binder_uintptr_t node_cookie = node->cookie;
3899                         int node_debug_id = node->debug_id;
3900                         int has_weak_ref;
3901                         int has_strong_ref;
3902                         void __user *orig_ptr = ptr;
3903
3904                         BUG_ON(proc != node->proc);
3905                         strong = node->internal_strong_refs ||
3906                                         node->local_strong_refs;
3907                         weak = !hlist_empty(&node->refs) ||
3908                                         node->local_weak_refs ||
3909                                         node->tmp_refs || strong;
3910                         has_strong_ref = node->has_strong_ref;
3911                         has_weak_ref = node->has_weak_ref;
3912
3913                         if (weak && !has_weak_ref) {
3914                                 node->has_weak_ref = 1;
3915                                 node->pending_weak_ref = 1;
3916                                 node->local_weak_refs++;
3917                         }
3918                         if (strong && !has_strong_ref) {
3919                                 node->has_strong_ref = 1;
3920                                 node->pending_strong_ref = 1;
3921                                 node->local_strong_refs++;
3922                         }
3923                         if (!strong && has_strong_ref)
3924                                 node->has_strong_ref = 0;
3925                         if (!weak && has_weak_ref)
3926                                 node->has_weak_ref = 0;
3927                         if (!weak && !strong) {
3928                                 binder_debug(BINDER_DEBUG_INTERNAL_REFS,
3929                                              "%d:%d node %d u%016llx c%016llx deleted\n",
3930                                              proc->pid, thread->pid,
3931                                              node_debug_id,
3932                                              (u64)node_ptr,
3933                                              (u64)node_cookie);
3934                                 rb_erase(&node->rb_node, &proc->nodes);
3935                                 binder_inner_proc_unlock(proc);
3936                                 binder_node_lock(node);
3937                                 /*
3938                                  * Acquire the node lock before freeing the
3939                                  * node to serialize with other threads that
3940                                  * may have been holding the node lock while
3941                                  * decrementing this node (avoids race where
3942                                  * this thread frees while the other thread
3943                                  * is unlocking the node after the final
3944                                  * decrement)
3945                                  */
3946                                 binder_node_unlock(node);
3947                                 binder_free_node(node);
3948                         } else
3949                                 binder_inner_proc_unlock(proc);
3950
3951                         if (weak && !has_weak_ref)
3952                                 ret = binder_put_node_cmd(
3953                                                 proc, thread, &ptr, node_ptr,
3954                                                 node_cookie, node_debug_id,
3955                                                 BR_INCREFS, "BR_INCREFS");
3956                         if (!ret && strong && !has_strong_ref)
3957                                 ret = binder_put_node_cmd(
3958                                                 proc, thread, &ptr, node_ptr,
3959                                                 node_cookie, node_debug_id,
3960                                                 BR_ACQUIRE, "BR_ACQUIRE");
3961                         if (!ret && !strong && has_strong_ref)
3962                                 ret = binder_put_node_cmd(
3963                                                 proc, thread, &ptr, node_ptr,
3964                                                 node_cookie, node_debug_id,
3965                                                 BR_RELEASE, "BR_RELEASE");
3966                         if (!ret && !weak && has_weak_ref)
3967                                 ret = binder_put_node_cmd(
3968                                                 proc, thread, &ptr, node_ptr,
3969                                                 node_cookie, node_debug_id,
3970                                                 BR_DECREFS, "BR_DECREFS");
3971                         if (orig_ptr == ptr)
3972                                 binder_debug(BINDER_DEBUG_INTERNAL_REFS,
3973                                              "%d:%d node %d u%016llx c%016llx state unchanged\n",
3974                                              proc->pid, thread->pid,
3975                                              node_debug_id,
3976                                              (u64)node_ptr,
3977                                              (u64)node_cookie);
3978                         if (ret)
3979                                 return ret;
3980                 } break;
3981                 case BINDER_WORK_DEAD_BINDER:
3982                 case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
3983                 case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: {
3984                         struct binder_ref_death *death;
3985                         uint32_t cmd;
3986                         binder_uintptr_t cookie;
3987
3988                         death = container_of(w, struct binder_ref_death, work);
3989                         if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION)
3990                                 cmd = BR_CLEAR_DEATH_NOTIFICATION_DONE;
3991                         else
3992                                 cmd = BR_DEAD_BINDER;
3993                         cookie = death->cookie;
3994
3995                         binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION,
3996                                      "%d:%d %s %016llx\n",
3997                                       proc->pid, thread->pid,
3998                                       cmd == BR_DEAD_BINDER ?
3999                                       "BR_DEAD_BINDER" :
4000                                       "BR_CLEAR_DEATH_NOTIFICATION_DONE",
4001                                       (u64)cookie);
4002                         if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION) {
4003                                 binder_inner_proc_unlock(proc);
4004                                 kfree(death);
4005                                 binder_stats_deleted(BINDER_STAT_DEATH);
4006                         } else {
4007                                 binder_enqueue_work_ilocked(
4008                                                 w, &proc->delivered_death);
4009                                 binder_inner_proc_unlock(proc);
4010                         }
4011                         if (put_user(cmd, (uint32_t __user *)ptr))
4012                                 return -EFAULT;
4013                         ptr += sizeof(uint32_t);
4014                         if (put_user(cookie,
4015                                      (binder_uintptr_t __user *)ptr))
4016                                 return -EFAULT;
4017                         ptr += sizeof(binder_uintptr_t);
4018                         binder_stat_br(proc, thread, cmd);
4019                         if (cmd == BR_DEAD_BINDER)
4020                                 goto done; /* DEAD_BINDER notifications can cause transactions */
4021                 } break;
4022                 }
4023
4024                 if (!t)
4025                         continue;
4026
4027                 BUG_ON(t->buffer == NULL);
4028                 if (t->buffer->target_node) {
4029                         struct binder_node *target_node = t->buffer->target_node;
4030
4031                         tr.target.ptr = target_node->ptr;
4032                         tr.cookie =  target_node->cookie;
4033                         t->saved_priority = task_nice(current);
4034                         if (t->priority < target_node->min_priority &&
4035                             !(t->flags & TF_ONE_WAY))
4036                                 binder_set_nice(t->priority);
4037                         else if (!(t->flags & TF_ONE_WAY) ||
4038                                  t->saved_priority > target_node->min_priority)
4039                                 binder_set_nice(target_node->min_priority);
4040                         cmd = BR_TRANSACTION;
4041                 } else {
4042                         tr.target.ptr = 0;
4043                         tr.cookie = 0;
4044                         cmd = BR_REPLY;
4045                 }
4046                 tr.code = t->code;
4047                 tr.flags = t->flags;
4048                 tr.sender_euid = from_kuid(current_user_ns(), t->sender_euid);
4049
4050                 t_from = binder_get_txn_from(t);
4051                 if (t_from) {
4052                         struct task_struct *sender = t_from->proc->tsk;
4053
4054                         tr.sender_pid = task_tgid_nr_ns(sender,
4055                                                         task_active_pid_ns(current));
4056                 } else {
4057                         tr.sender_pid = 0;
4058                 }
4059
4060                 tr.data_size = t->buffer->data_size;
4061                 tr.offsets_size = t->buffer->offsets_size;
4062                 tr.data.ptr.buffer = (binder_uintptr_t)
4063                         ((uintptr_t)t->buffer->data +
4064                         binder_alloc_get_user_buffer_offset(&proc->alloc));
4065                 tr.data.ptr.offsets = tr.data.ptr.buffer +
4066                                         ALIGN(t->buffer->data_size,
4067                                             sizeof(void *));
4068
4069                 if (put_user(cmd, (uint32_t __user *)ptr)) {
4070                         if (t_from)
4071                                 binder_thread_dec_tmpref(t_from);
4072
4073                         binder_cleanup_transaction(t, "put_user failed",
4074                                                    BR_FAILED_REPLY);
4075
4076                         return -EFAULT;
4077                 }
4078                 ptr += sizeof(uint32_t);
4079                 if (copy_to_user(ptr, &tr, sizeof(tr))) {
4080                         if (t_from)
4081                                 binder_thread_dec_tmpref(t_from);
4082
4083                         binder_cleanup_transaction(t, "copy_to_user failed",
4084                                                    BR_FAILED_REPLY);
4085
4086                         return -EFAULT;
4087                 }
4088                 ptr += sizeof(tr);
4089
4090                 trace_binder_transaction_received(t);
4091                 binder_stat_br(proc, thread, cmd);
4092                 binder_debug(BINDER_DEBUG_TRANSACTION,
4093                              "%d:%d %s %d %d:%d, cmd %d size %zd-%zd ptr %016llx-%016llx\n",
4094                              proc->pid, thread->pid,
4095                              (cmd == BR_TRANSACTION) ? "BR_TRANSACTION" :
4096                              "BR_REPLY",
4097                              t->debug_id, t_from ? t_from->proc->pid : 0,
4098                              t_from ? t_from->pid : 0, cmd,
4099                              t->buffer->data_size, t->buffer->offsets_size,
4100                              (u64)tr.data.ptr.buffer, (u64)tr.data.ptr.offsets);
4101
4102                 if (t_from)
4103                         binder_thread_dec_tmpref(t_from);
4104                 t->buffer->allow_user_free = 1;
4105                 if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {
4106                         binder_inner_proc_lock(thread->proc);
4107                         t->to_parent = thread->transaction_stack;
4108                         t->to_thread = thread;
4109                         thread->transaction_stack = t;
4110                         binder_inner_proc_unlock(thread->proc);
4111                 } else {
4112                         binder_free_transaction(t);
4113                 }
4114                 break;
4115         }
4116
4117 done:
4118
4119         *consumed = ptr - buffer;
4120         binder_inner_proc_lock(proc);
4121         if (proc->requested_threads == 0 &&
4122             list_empty(&thread->proc->waiting_threads) &&
4123             proc->requested_threads_started < proc->max_threads &&
4124             (thread->looper & (BINDER_LOOPER_STATE_REGISTERED |
4125              BINDER_LOOPER_STATE_ENTERED)) /* the user-space code fails to */
4126              /*spawn a new thread if we leave this out */) {
4127                 proc->requested_threads++;
4128                 binder_inner_proc_unlock(proc);
4129                 binder_debug(BINDER_DEBUG_THREADS,
4130                              "%d:%d BR_SPAWN_LOOPER\n",
4131                              proc->pid, thread->pid);
4132                 if (put_user(BR_SPAWN_LOOPER, (uint32_t __user *)buffer))
4133                         return -EFAULT;
4134                 binder_stat_br(proc, thread, BR_SPAWN_LOOPER);
4135         } else
4136                 binder_inner_proc_unlock(proc);
4137         return 0;
4138 }
4139
4140 static void binder_release_work(struct binder_proc *proc,
4141                                 struct list_head *list)
4142 {
4143         struct binder_work *w;
4144         enum binder_work_type wtype;
4145
4146         while (1) {
4147                 binder_inner_proc_lock(proc);
4148                 w = binder_dequeue_work_head_ilocked(list);
4149                 wtype = w ? w->type : 0;
4150                 binder_inner_proc_unlock(proc);
4151                 if (!w)
4152                         return;
4153
4154                 switch (wtype) {
4155                 case BINDER_WORK_TRANSACTION: {
4156                         struct binder_transaction *t;
4157
4158                         t = container_of(w, struct binder_transaction, work);
4159
4160                         binder_cleanup_transaction(t, "process died.",
4161                                                    BR_DEAD_REPLY);
4162                 } break;
4163                 case BINDER_WORK_RETURN_ERROR: {
4164                         struct binder_error *e = container_of(
4165                                         w, struct binder_error, work);
4166
4167                         binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
4168                                 "undelivered TRANSACTION_ERROR: %u\n",
4169                                 e->cmd);
4170                 } break;
4171                 case BINDER_WORK_TRANSACTION_COMPLETE: {
4172                         binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
4173                                 "undelivered TRANSACTION_COMPLETE\n");
4174                         kfree(w);
4175                         binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
4176                 } break;
4177                 case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
4178                 case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: {
4179                         struct binder_ref_death *death;
4180
4181                         death = container_of(w, struct binder_ref_death, work);
4182                         binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
4183                                 "undelivered death notification, %016llx\n",
4184                                 (u64)death->cookie);
4185                         kfree(death);
4186                         binder_stats_deleted(BINDER_STAT_DEATH);
4187                 } break;
4188                 case BINDER_WORK_NODE:
4189                         break;
4190                 default:
4191                         pr_err("unexpected work type, %d, not freed\n",
4192                                wtype);
4193                         break;
4194                 }
4195         }
4196
4197 }
4198
4199 static struct binder_thread *binder_get_thread_ilocked(
4200                 struct binder_proc *proc, struct binder_thread *new_thread)
4201 {
4202         struct binder_thread *thread = NULL;
4203         struct rb_node *parent = NULL;
4204         struct rb_node **p = &proc->threads.rb_node;
4205
4206         while (*p) {
4207                 parent = *p;
4208                 thread = rb_entry(parent, struct binder_thread, rb_node);
4209
4210                 if (current->pid < thread->pid)
4211                         p = &(*p)->rb_left;
4212                 else if (current->pid > thread->pid)
4213                         p = &(*p)->rb_right;
4214                 else
4215                         return thread;
4216         }
4217         if (!new_thread)
4218                 return NULL;
4219         thread = new_thread;
4220         binder_stats_created(BINDER_STAT_THREAD);
4221         thread->proc = proc;
4222         thread->pid = current->pid;
4223         atomic_set(&thread->tmp_ref, 0);
4224         init_waitqueue_head(&thread->wait);
4225         INIT_LIST_HEAD(&thread->todo);
4226         rb_link_node(&thread->rb_node, parent, p);
4227         rb_insert_color(&thread->rb_node, &proc->threads);
4228         thread->looper_need_return = true;
4229         thread->return_error.work.type = BINDER_WORK_RETURN_ERROR;
4230         thread->return_error.cmd = BR_OK;
4231         thread->reply_error.work.type = BINDER_WORK_RETURN_ERROR;
4232         thread->reply_error.cmd = BR_OK;
4233         INIT_LIST_HEAD(&new_thread->waiting_thread_node);
4234         return thread;
4235 }
4236
4237 static struct binder_thread *binder_get_thread(struct binder_proc *proc)
4238 {
4239         struct binder_thread *thread;
4240         struct binder_thread *new_thread;
4241
4242         binder_inner_proc_lock(proc);
4243         thread = binder_get_thread_ilocked(proc, NULL);
4244         binder_inner_proc_unlock(proc);
4245         if (!thread) {
4246                 new_thread = kzalloc(sizeof(*thread), GFP_KERNEL);
4247                 if (new_thread == NULL)
4248                         return NULL;
4249                 binder_inner_proc_lock(proc);
4250                 thread = binder_get_thread_ilocked(proc, new_thread);
4251                 binder_inner_proc_unlock(proc);
4252                 if (thread != new_thread)
4253                         kfree(new_thread);
4254         }
4255         return thread;
4256 }
4257
4258 static void binder_free_proc(struct binder_proc *proc)
4259 {
4260         BUG_ON(!list_empty(&proc->todo));
4261         BUG_ON(!list_empty(&proc->delivered_death));
4262         binder_alloc_deferred_release(&proc->alloc);
4263         put_task_struct(proc->tsk);
4264         binder_stats_deleted(BINDER_STAT_PROC);
4265         kfree(proc);
4266 }
4267
4268 static void binder_free_thread(struct binder_thread *thread)
4269 {
4270         BUG_ON(!list_empty(&thread->todo));
4271         binder_stats_deleted(BINDER_STAT_THREAD);
4272         binder_proc_dec_tmpref(thread->proc);
4273         kfree(thread);
4274 }
4275
4276 static int binder_thread_release(struct binder_proc *proc,
4277                                  struct binder_thread *thread)
4278 {
4279         struct binder_transaction *t;
4280         struct binder_transaction *send_reply = NULL;
4281         int active_transactions = 0;
4282         struct binder_transaction *last_t = NULL;
4283
4284         binder_inner_proc_lock(thread->proc);
4285         /*
4286          * take a ref on the proc so it survives
4287          * after we remove this thread from proc->threads.
4288          * The corresponding dec is when we actually
4289          * free the thread in binder_free_thread()
4290          */
4291         proc->tmp_ref++;
4292         /*
4293          * take a ref on this thread to ensure it
4294          * survives while we are releasing it
4295          */
4296         atomic_inc(&thread->tmp_ref);
4297         rb_erase(&thread->rb_node, &proc->threads);
4298         t = thread->transaction_stack;
4299         if (t) {
4300                 spin_lock(&t->lock);
4301                 if (t->to_thread == thread)
4302                         send_reply = t;
4303         }
4304         thread->is_dead = true;
4305
4306         while (t) {
4307                 last_t = t;
4308                 active_transactions++;
4309                 binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
4310                              "release %d:%d transaction %d %s, still active\n",
4311                               proc->pid, thread->pid,
4312                              t->debug_id,
4313                              (t->to_thread == thread) ? "in" : "out");
4314
4315                 if (t->to_thread == thread) {
4316                         t->to_proc = NULL;
4317                         t->to_thread = NULL;
4318                         if (t->buffer) {
4319                                 t->buffer->transaction = NULL;
4320                                 t->buffer = NULL;
4321                         }
4322                         t = t->to_parent;
4323                 } else if (t->from == thread) {
4324                         t->from = NULL;
4325                         t = t->from_parent;
4326                 } else
4327                         BUG();
4328                 spin_unlock(&last_t->lock);
4329                 if (t)
4330                         spin_lock(&t->lock);
4331         }
4332
4333         /*
4334          * If this thread used poll, make sure we remove the waitqueue
4335          * from any epoll data structures holding it with POLLFREE.
4336          * waitqueue_active() is safe to use here because we're holding
4337          * the inner lock.
4338          */
4339         if ((thread->looper & BINDER_LOOPER_STATE_POLL) &&
4340             waitqueue_active(&thread->wait)) {
4341                 wake_up_poll(&thread->wait, POLLHUP | POLLFREE);
4342         }
4343
4344         binder_inner_proc_unlock(thread->proc);
4345
4346         /*
4347          * This is needed to avoid races between wake_up_poll() above and
4348          * and ep_remove_waitqueue() called for other reasons (eg the epoll file
4349          * descriptor being closed); ep_remove_waitqueue() holds an RCU read
4350          * lock, so we can be sure it's done after calling synchronize_rcu().
4351          */
4352         if (thread->looper & BINDER_LOOPER_STATE_POLL)
4353                 synchronize_rcu();
4354
4355         if (send_reply)
4356                 binder_send_failed_reply(send_reply, BR_DEAD_REPLY);
4357         binder_release_work(proc, &thread->todo);
4358         binder_thread_dec_tmpref(thread);
4359         return active_transactions;
4360 }
4361
4362 static unsigned int binder_poll(struct file *filp,
4363                                 struct poll_table_struct *wait)
4364 {
4365         struct binder_proc *proc = filp->private_data;
4366         struct binder_thread *thread = NULL;
4367         bool wait_for_proc_work;
4368
4369         thread = binder_get_thread(proc);
4370         if (!thread)
4371                 return POLLERR;
4372
4373         binder_inner_proc_lock(thread->proc);
4374         thread->looper |= BINDER_LOOPER_STATE_POLL;
4375         wait_for_proc_work = binder_available_for_proc_work_ilocked(thread);
4376
4377         binder_inner_proc_unlock(thread->proc);
4378
4379         poll_wait(filp, &thread->wait, wait);
4380
4381         if (binder_has_work(thread, wait_for_proc_work))
4382                 return POLLIN;
4383
4384         return 0;
4385 }
4386
4387 static int binder_ioctl_write_read(struct file *filp,
4388                                 unsigned int cmd, unsigned long arg,
4389                                 struct binder_thread *thread)
4390 {
4391         int ret = 0;
4392         struct binder_proc *proc = filp->private_data;
4393         unsigned int size = _IOC_SIZE(cmd);
4394         void __user *ubuf = (void __user *)arg;
4395         struct binder_write_read bwr;
4396
4397         if (size != sizeof(struct binder_write_read)) {
4398                 ret = -EINVAL;
4399                 goto out;
4400         }
4401         if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {
4402                 ret = -EFAULT;
4403                 goto out;
4404         }
4405         binder_debug(BINDER_DEBUG_READ_WRITE,
4406                      "%d:%d write %lld at %016llx, read %lld at %016llx\n",
4407                      proc->pid, thread->pid,
4408                      (u64)bwr.write_size, (u64)bwr.write_buffer,
4409                      (u64)bwr.read_size, (u64)bwr.read_buffer);
4410
4411         if (bwr.write_size > 0) {
4412                 ret = binder_thread_write(proc, thread,
4413                                           bwr.write_buffer,
4414                                           bwr.write_size,
4415                                           &bwr.write_consumed);
4416                 trace_binder_write_done(ret);
4417                 if (ret < 0) {
4418                         bwr.read_consumed = 0;
4419                         if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
4420                                 ret = -EFAULT;
4421                         goto out;
4422                 }
4423         }
4424         if (bwr.read_size > 0) {
4425                 ret = binder_thread_read(proc, thread, bwr.read_buffer,
4426                                          bwr.read_size,
4427                                          &bwr.read_consumed,
4428                                          filp->f_flags & O_NONBLOCK);
4429                 trace_binder_read_done(ret);
4430                 binder_inner_proc_lock(proc);
4431                 if (!binder_worklist_empty_ilocked(&proc->todo))
4432                         binder_wakeup_proc_ilocked(proc);
4433                 binder_inner_proc_unlock(proc);
4434                 if (ret < 0) {
4435                         if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
4436                                 ret = -EFAULT;
4437                         goto out;
4438                 }
4439         }
4440         binder_debug(BINDER_DEBUG_READ_WRITE,
4441                      "%d:%d wrote %lld of %lld, read return %lld of %lld\n",
4442                      proc->pid, thread->pid,
4443                      (u64)bwr.write_consumed, (u64)bwr.write_size,
4444                      (u64)bwr.read_consumed, (u64)bwr.read_size);
4445         if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
4446                 ret = -EFAULT;
4447                 goto out;
4448         }
4449 out:
4450         return ret;
4451 }
4452
4453 static int binder_ioctl_set_ctx_mgr(struct file *filp)
4454 {
4455         int ret = 0;
4456         struct binder_proc *proc = filp->private_data;
4457         struct binder_context *context = proc->context;
4458         struct binder_node *new_node;
4459         kuid_t curr_euid = current_euid();
4460
4461         mutex_lock(&context->context_mgr_node_lock);
4462         if (context->binder_context_mgr_node) {
4463                 pr_err("BINDER_SET_CONTEXT_MGR already set\n");
4464                 ret = -EBUSY;
4465                 goto out;
4466         }
4467         ret = security_binder_set_context_mgr(proc->tsk);
4468         if (ret < 0)
4469                 goto out;
4470         if (uid_valid(context->binder_context_mgr_uid)) {
4471                 if (!uid_eq(context->binder_context_mgr_uid, curr_euid)) {
4472                         pr_err("BINDER_SET_CONTEXT_MGR bad uid %d != %d\n",
4473                                from_kuid(&init_user_ns, curr_euid),
4474                                from_kuid(&init_user_ns,
4475                                          context->binder_context_mgr_uid));
4476                         ret = -EPERM;
4477                         goto out;
4478                 }
4479         } else {
4480                 context->binder_context_mgr_uid = curr_euid;
4481         }
4482         new_node = binder_new_node(proc, NULL);
4483         if (!new_node) {
4484                 ret = -ENOMEM;
4485                 goto out;
4486         }
4487         binder_node_lock(new_node);
4488         new_node->local_weak_refs++;
4489         new_node->local_strong_refs++;
4490         new_node->has_strong_ref = 1;
4491         new_node->has_weak_ref = 1;
4492         context->binder_context_mgr_node = new_node;
4493         binder_node_unlock(new_node);
4494         binder_put_node(new_node);
4495 out:
4496         mutex_unlock(&context->context_mgr_node_lock);
4497         return ret;
4498 }
4499
4500 static int binder_ioctl_get_node_debug_info(struct binder_proc *proc,
4501                                 struct binder_node_debug_info *info)
4502 {
4503         struct rb_node *n;
4504         binder_uintptr_t ptr = info->ptr;
4505
4506         memset(info, 0, sizeof(*info));
4507
4508         binder_inner_proc_lock(proc);
4509         for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n)) {
4510                 struct binder_node *node = rb_entry(n, struct binder_node,
4511                                                     rb_node);
4512                 if (node->ptr > ptr) {
4513                         info->ptr = node->ptr;
4514                         info->cookie = node->cookie;
4515                         info->has_strong_ref = node->has_strong_ref;
4516                         info->has_weak_ref = node->has_weak_ref;
4517                         break;
4518                 }
4519         }
4520         binder_inner_proc_unlock(proc);
4521
4522         return 0;
4523 }
4524
4525 static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
4526 {
4527         int ret;
4528         struct binder_proc *proc = filp->private_data;
4529         struct binder_thread *thread;
4530         unsigned int size = _IOC_SIZE(cmd);
4531         void __user *ubuf = (void __user *)arg;
4532
4533         /*pr_info("binder_ioctl: %d:%d %x %lx\n",
4534                         proc->pid, current->pid, cmd, arg);*/
4535
4536         binder_selftest_alloc(&proc->alloc);
4537
4538         trace_binder_ioctl(cmd, arg);
4539
4540         ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
4541         if (ret)
4542                 goto err_unlocked;
4543
4544         thread = binder_get_thread(proc);
4545         if (thread == NULL) {
4546                 ret = -ENOMEM;
4547                 goto err;
4548         }
4549
4550         switch (cmd) {
4551         case BINDER_WRITE_READ:
4552                 ret = binder_ioctl_write_read(filp, cmd, arg, thread);
4553                 if (ret)
4554                         goto err;
4555                 break;
4556         case BINDER_SET_MAX_THREADS: {
4557                 int max_threads;
4558
4559                 if (copy_from_user(&max_threads, ubuf,
4560                                    sizeof(max_threads))) {
4561                         ret = -EINVAL;
4562                         goto err;
4563                 }
4564                 binder_inner_proc_lock(proc);
4565                 proc->max_threads = max_threads;
4566                 binder_inner_proc_unlock(proc);
4567                 break;
4568         }
4569         case BINDER_SET_CONTEXT_MGR:
4570                 ret = binder_ioctl_set_ctx_mgr(filp);
4571                 if (ret)
4572                         goto err;
4573                 break;
4574         case BINDER_THREAD_EXIT:
4575                 binder_debug(BINDER_DEBUG_THREADS, "%d:%d exit\n",
4576                              proc->pid, thread->pid);
4577                 binder_thread_release(proc, thread);
4578                 thread = NULL;
4579                 break;
4580         case BINDER_VERSION: {
4581                 struct binder_version __user *ver = ubuf;
4582
4583                 if (size != sizeof(struct binder_version)) {
4584                         ret = -EINVAL;
4585                         goto err;
4586                 }
4587                 if (put_user(BINDER_CURRENT_PROTOCOL_VERSION,
4588                              &ver->protocol_version)) {
4589                         ret = -EINVAL;
4590                         goto err;
4591                 }
4592                 break;
4593         }
4594         case BINDER_GET_NODE_DEBUG_INFO: {
4595                 struct binder_node_debug_info info;
4596
4597                 if (copy_from_user(&info, ubuf, sizeof(info))) {
4598                         ret = -EFAULT;
4599                         goto err;
4600                 }
4601
4602                 ret = binder_ioctl_get_node_debug_info(proc, &info);
4603                 if (ret < 0)
4604                         goto err;
4605
4606                 if (copy_to_user(ubuf, &info, sizeof(info))) {
4607                         ret = -EFAULT;
4608                         goto err;
4609                 }
4610                 break;
4611         }
4612         default:
4613                 ret = -EINVAL;
4614                 goto err;
4615         }
4616         ret = 0;
4617 err:
4618         if (thread)
4619                 thread->looper_need_return = false;
4620         wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
4621         if (ret && ret != -ERESTARTSYS)
4622                 pr_info("%d:%d ioctl %x %lx returned %d\n", proc->pid, current->pid, cmd, arg, ret);
4623 err_unlocked:
4624         trace_binder_ioctl_done(ret);
4625         return ret;
4626 }
4627
4628 static void binder_vma_open(struct vm_area_struct *vma)
4629 {
4630         struct binder_proc *proc = vma->vm_private_data;
4631
4632         binder_debug(BINDER_DEBUG_OPEN_CLOSE,
4633                      "%d open vm area %lx-%lx (%ld K) vma %lx pagep %lx\n",
4634                      proc->pid, vma->vm_start, vma->vm_end,
4635                      (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
4636                      (unsigned long)pgprot_val(vma->vm_page_prot));
4637 }
4638
4639 static void binder_vma_close(struct vm_area_struct *vma)
4640 {
4641         struct binder_proc *proc = vma->vm_private_data;
4642
4643         binder_debug(BINDER_DEBUG_OPEN_CLOSE,
4644                      "%d close vm area %lx-%lx (%ld K) vma %lx pagep %lx\n",
4645                      proc->pid, vma->vm_start, vma->vm_end,
4646                      (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
4647                      (unsigned long)pgprot_val(vma->vm_page_prot));
4648         binder_alloc_vma_close(&proc->alloc);
4649         binder_defer_work(proc, BINDER_DEFERRED_PUT_FILES);
4650 }
4651
4652 static int binder_vm_fault(struct vm_fault *vmf)
4653 {
4654         return VM_FAULT_SIGBUS;
4655 }
4656
4657 static const struct vm_operations_struct binder_vm_ops = {
4658         .open = binder_vma_open,
4659         .close = binder_vma_close,
4660         .fault = binder_vm_fault,
4661 };
4662
4663 static int binder_mmap(struct file *filp, struct vm_area_struct *vma)
4664 {
4665         int ret;
4666         struct binder_proc *proc = filp->private_data;
4667         const char *failure_string;
4668
4669         if (proc->tsk != current->group_leader)
4670                 return -EINVAL;
4671
4672         if ((vma->vm_end - vma->vm_start) > SZ_4M)
4673                 vma->vm_end = vma->vm_start + SZ_4M;
4674
4675         binder_debug(BINDER_DEBUG_OPEN_CLOSE,
4676                      "%s: %d %lx-%lx (%ld K) vma %lx pagep %lx\n",
4677                      __func__, proc->pid, vma->vm_start, vma->vm_end,
4678                      (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
4679                      (unsigned long)pgprot_val(vma->vm_page_prot));
4680
4681         if (vma->vm_flags & FORBIDDEN_MMAP_FLAGS) {
4682                 ret = -EPERM;
4683                 failure_string = "bad vm_flags";
4684                 goto err_bad_arg;
4685         }
4686         vma->vm_flags = (vma->vm_flags | VM_DONTCOPY) & ~VM_MAYWRITE;
4687         vma->vm_ops = &binder_vm_ops;
4688         vma->vm_private_data = proc;
4689
4690         ret = binder_alloc_mmap_handler(&proc->alloc, vma);
4691         if (ret)
4692                 return ret;
4693         mutex_lock(&proc->files_lock);
4694         proc->files = get_files_struct(current);
4695         mutex_unlock(&proc->files_lock);
4696         return 0;
4697
4698 err_bad_arg:
4699         pr_err("binder_mmap: %d %lx-%lx %s failed %d\n",
4700                proc->pid, vma->vm_start, vma->vm_end, failure_string, ret);
4701         return ret;
4702 }
4703
4704 static int binder_open(struct inode *nodp, struct file *filp)
4705 {
4706         struct binder_proc *proc;
4707         struct binder_device *binder_dev;
4708
4709         binder_debug(BINDER_DEBUG_OPEN_CLOSE, "binder_open: %d:%d\n",
4710                      current->group_leader->pid, current->pid);
4711
4712         proc = kzalloc(sizeof(*proc), GFP_KERNEL);
4713         if (proc == NULL)
4714                 return -ENOMEM;
4715         spin_lock_init(&proc->inner_lock);
4716         spin_lock_init(&proc->outer_lock);
4717         get_task_struct(current->group_leader);
4718         proc->tsk = current->group_leader;
4719         mutex_init(&proc->files_lock);
4720         INIT_LIST_HEAD(&proc->todo);
4721         proc->default_priority = task_nice(current);
4722         binder_dev = container_of(filp->private_data, struct binder_device,
4723                                   miscdev);
4724         proc->context = &binder_dev->context;
4725         binder_alloc_init(&proc->alloc);
4726
4727         binder_stats_created(BINDER_STAT_PROC);
4728         proc->pid = current->group_leader->pid;
4729         INIT_LIST_HEAD(&proc->delivered_death);
4730         INIT_LIST_HEAD(&proc->waiting_threads);
4731         filp->private_data = proc;
4732
4733         mutex_lock(&binder_procs_lock);
4734         hlist_add_head(&proc->proc_node, &binder_procs);
4735         mutex_unlock(&binder_procs_lock);
4736
4737         if (binder_debugfs_dir_entry_proc) {
4738                 char strbuf[11];
4739
4740                 snprintf(strbuf, sizeof(strbuf), "%u", proc->pid);
4741                 /*
4742                  * proc debug entries are shared between contexts, so
4743                  * this will fail if the process tries to open the driver
4744                  * again with a different context. The priting code will
4745                  * anyway print all contexts that a given PID has, so this
4746                  * is not a problem.
4747                  */
4748                 proc->debugfs_entry = debugfs_create_file(strbuf, S_IRUGO,
4749                         binder_debugfs_dir_entry_proc,
4750                         (void *)(unsigned long)proc->pid,
4751                         &binder_proc_fops);
4752         }
4753
4754         return 0;
4755 }
4756
4757 static int binder_flush(struct file *filp, fl_owner_t id)
4758 {
4759         struct binder_proc *proc = filp->private_data;
4760
4761         binder_defer_work(proc, BINDER_DEFERRED_FLUSH);
4762
4763         return 0;
4764 }
4765
4766 static void binder_deferred_flush(struct binder_proc *proc)
4767 {
4768         struct rb_node *n;
4769         int wake_count = 0;
4770
4771         binder_inner_proc_lock(proc);
4772         for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n)) {
4773                 struct binder_thread *thread = rb_entry(n, struct binder_thread, rb_node);
4774
4775                 thread->looper_need_return = true;
4776                 if (thread->looper & BINDER_LOOPER_STATE_WAITING) {
4777                         wake_up_interruptible(&thread->wait);
4778                         wake_count++;
4779                 }
4780         }
4781         binder_inner_proc_unlock(proc);
4782
4783         binder_debug(BINDER_DEBUG_OPEN_CLOSE,
4784                      "binder_flush: %d woke %d threads\n", proc->pid,
4785                      wake_count);
4786 }
4787
4788 static int binder_release(struct inode *nodp, struct file *filp)
4789 {
4790         struct binder_proc *proc = filp->private_data;
4791
4792         debugfs_remove(proc->debugfs_entry);
4793         binder_defer_work(proc, BINDER_DEFERRED_RELEASE);
4794
4795         return 0;
4796 }
4797
4798 static int binder_node_release(struct binder_node *node, int refs)
4799 {
4800         struct binder_ref *ref;
4801         int death = 0;
4802         struct binder_proc *proc = node->proc;
4803
4804         binder_release_work(proc, &node->async_todo);
4805
4806         binder_node_lock(node);
4807         binder_inner_proc_lock(proc);
4808         binder_dequeue_work_ilocked(&node->work);
4809         /*
4810          * The caller must have taken a temporary ref on the node,
4811          */
4812         BUG_ON(!node->tmp_refs);
4813         if (hlist_empty(&node->refs) && node->tmp_refs == 1) {
4814                 binder_inner_proc_unlock(proc);
4815                 binder_node_unlock(node);
4816                 binder_free_node(node);
4817
4818                 return refs;
4819         }
4820
4821         node->proc = NULL;
4822         node->local_strong_refs = 0;
4823         node->local_weak_refs = 0;
4824         binder_inner_proc_unlock(proc);
4825
4826         spin_lock(&binder_dead_nodes_lock);
4827         hlist_add_head(&node->dead_node, &binder_dead_nodes);
4828         spin_unlock(&binder_dead_nodes_lock);
4829
4830         hlist_for_each_entry(ref, &node->refs, node_entry) {
4831                 refs++;
4832                 /*
4833                  * Need the node lock to synchronize
4834                  * with new notification requests and the
4835                  * inner lock to synchronize with queued
4836                  * death notifications.
4837                  */
4838                 binder_inner_proc_lock(ref->proc);
4839                 if (!ref->death) {
4840                         binder_inner_proc_unlock(ref->proc);
4841                         continue;
4842                 }
4843
4844                 death++;
4845
4846                 BUG_ON(!list_empty(&ref->death->work.entry));
4847                 ref->death->work.type = BINDER_WORK_DEAD_BINDER;
4848                 binder_enqueue_work_ilocked(&ref->death->work,
4849                                             &ref->proc->todo);
4850                 binder_wakeup_proc_ilocked(ref->proc);
4851                 binder_inner_proc_unlock(ref->proc);
4852         }
4853
4854         binder_debug(BINDER_DEBUG_DEAD_BINDER,
4855                      "node %d now dead, refs %d, death %d\n",
4856                      node->debug_id, refs, death);
4857         binder_node_unlock(node);
4858         binder_put_node(node);
4859
4860         return refs;
4861 }
4862
4863 static void binder_deferred_release(struct binder_proc *proc)
4864 {
4865         struct binder_context *context = proc->context;
4866         struct rb_node *n;
4867         int threads, nodes, incoming_refs, outgoing_refs, active_transactions;
4868
4869         BUG_ON(proc->files);
4870
4871         mutex_lock(&binder_procs_lock);
4872         hlist_del(&proc->proc_node);
4873         mutex_unlock(&binder_procs_lock);
4874
4875         mutex_lock(&context->context_mgr_node_lock);
4876         if (context->binder_context_mgr_node &&
4877             context->binder_context_mgr_node->proc == proc) {
4878                 binder_debug(BINDER_DEBUG_DEAD_BINDER,
4879                              "%s: %d context_mgr_node gone\n",
4880                              __func__, proc->pid);
4881                 context->binder_context_mgr_node = NULL;
4882         }
4883         mutex_unlock(&context->context_mgr_node_lock);
4884         binder_inner_proc_lock(proc);
4885         /*
4886          * Make sure proc stays alive after we
4887          * remove all the threads
4888          */
4889         proc->tmp_ref++;
4890
4891         proc->is_dead = true;
4892         threads = 0;
4893         active_transactions = 0;
4894         while ((n = rb_first(&proc->threads))) {
4895                 struct binder_thread *thread;
4896
4897                 thread = rb_entry(n, struct binder_thread, rb_node);
4898                 binder_inner_proc_unlock(proc);
4899                 threads++;
4900                 active_transactions += binder_thread_release(proc, thread);
4901                 binder_inner_proc_lock(proc);
4902         }
4903
4904         nodes = 0;
4905         incoming_refs = 0;
4906         while ((n = rb_first(&proc->nodes))) {
4907                 struct binder_node *node;
4908
4909                 node = rb_entry(n, struct binder_node, rb_node);
4910                 nodes++;
4911                 /*
4912                  * take a temporary ref on the node before
4913                  * calling binder_node_release() which will either
4914                  * kfree() the node or call binder_put_node()
4915                  */
4916                 binder_inc_node_tmpref_ilocked(node);
4917                 rb_erase(&node->rb_node, &proc->nodes);
4918                 binder_inner_proc_unlock(proc);
4919                 incoming_refs = binder_node_release(node, incoming_refs);
4920                 binder_inner_proc_lock(proc);
4921         }
4922         binder_inner_proc_unlock(proc);
4923
4924         outgoing_refs = 0;
4925         binder_proc_lock(proc);
4926         while ((n = rb_first(&proc->refs_by_desc))) {
4927                 struct binder_ref *ref;
4928
4929                 ref = rb_entry(n, struct binder_ref, rb_node_desc);
4930                 outgoing_refs++;
4931                 binder_cleanup_ref_olocked(ref);
4932                 binder_proc_unlock(proc);
4933                 binder_free_ref(ref);
4934                 binder_proc_lock(proc);
4935         }
4936         binder_proc_unlock(proc);
4937
4938         binder_release_work(proc, &proc->todo);
4939         binder_release_work(proc, &proc->delivered_death);
4940
4941         binder_debug(BINDER_DEBUG_OPEN_CLOSE,
4942                      "%s: %d threads %d, nodes %d (ref %d), refs %d, active transactions %d\n",
4943                      __func__, proc->pid, threads, nodes, incoming_refs,
4944                      outgoing_refs, active_transactions);
4945
4946         binder_proc_dec_tmpref(proc);
4947 }
4948
4949 static void binder_deferred_func(struct work_struct *work)
4950 {
4951         struct binder_proc *proc;
4952         struct files_struct *files;
4953
4954         int defer;
4955
4956         do {
4957                 mutex_lock(&binder_deferred_lock);
4958                 if (!hlist_empty(&binder_deferred_list)) {
4959                         proc = hlist_entry(binder_deferred_list.first,
4960                                         struct binder_proc, deferred_work_node);
4961                         hlist_del_init(&proc->deferred_work_node);
4962                         defer = proc->deferred_work;
4963                         proc->deferred_work = 0;
4964                 } else {
4965                         proc = NULL;
4966                         defer = 0;
4967                 }
4968                 mutex_unlock(&binder_deferred_lock);
4969
4970                 files = NULL;
4971                 if (defer & BINDER_DEFERRED_PUT_FILES) {
4972                         mutex_lock(&proc->files_lock);
4973                         files = proc->files;
4974                         if (files)
4975                                 proc->files = NULL;
4976                         mutex_unlock(&proc->files_lock);
4977                 }
4978
4979                 if (defer & BINDER_DEFERRED_FLUSH)
4980                         binder_deferred_flush(proc);
4981
4982                 if (defer & BINDER_DEFERRED_RELEASE)
4983                         binder_deferred_release(proc); /* frees proc */
4984
4985                 if (files)
4986                         put_files_struct(files);
4987         } while (proc);
4988 }
4989 static DECLARE_WORK(binder_deferred_work, binder_deferred_func);
4990
4991 static void
4992 binder_defer_work(struct binder_proc *proc, enum binder_deferred_state defer)
4993 {
4994         mutex_lock(&binder_deferred_lock);
4995         proc->deferred_work |= defer;
4996         if (hlist_unhashed(&proc->deferred_work_node)) {
4997                 hlist_add_head(&proc->deferred_work_node,
4998                                 &binder_deferred_list);
4999                 schedule_work(&binder_deferred_work);
5000         }
5001         mutex_unlock(&binder_deferred_lock);
5002 }
5003
5004 static void print_binder_transaction_ilocked(struct seq_file *m,
5005                                              struct binder_proc *proc,
5006                                              const char *prefix,
5007                                              struct binder_transaction *t)
5008 {
5009         struct binder_proc *to_proc;
5010         struct binder_buffer *buffer = t->buffer;
5011
5012         spin_lock(&t->lock);
5013         to_proc = t->to_proc;
5014         seq_printf(m,
5015                    "%s %d: %pK from %d:%d to %d:%d code %x flags %x pri %ld r%d",
5016                    prefix, t->debug_id, t,
5017                    t->from ? t->from->proc->pid : 0,
5018                    t->from ? t->from->pid : 0,
5019                    to_proc ? to_proc->pid : 0,
5020                    t->to_thread ? t->to_thread->pid : 0,
5021                    t->code, t->flags, t->priority, t->need_reply);
5022         spin_unlock(&t->lock);
5023
5024         if (proc != to_proc) {
5025                 /*
5026                  * Can only safely deref buffer if we are holding the
5027                  * correct proc inner lock for this node
5028                  */
5029                 seq_puts(m, "\n");
5030                 return;
5031         }
5032
5033         if (buffer == NULL) {
5034                 seq_puts(m, " buffer free\n");
5035                 return;
5036         }
5037         if (buffer->target_node)
5038                 seq_printf(m, " node %d", buffer->target_node->debug_id);
5039         seq_printf(m, " size %zd:%zd data %pK\n",
5040                    buffer->data_size, buffer->offsets_size,
5041                    buffer->data);
5042 }
5043
5044 static void print_binder_work_ilocked(struct seq_file *m,
5045                                      struct binder_proc *proc,
5046                                      const char *prefix,
5047                                      const char *transaction_prefix,
5048                                      struct binder_work *w)
5049 {
5050         struct binder_node *node;
5051         struct binder_transaction *t;
5052
5053         switch (w->type) {
5054         case BINDER_WORK_TRANSACTION:
5055                 t = container_of(w, struct binder_transaction, work);
5056                 print_binder_transaction_ilocked(
5057                                 m, proc, transaction_prefix, t);
5058                 break;
5059         case BINDER_WORK_RETURN_ERROR: {
5060                 struct binder_error *e = container_of(
5061                                 w, struct binder_error, work);
5062
5063                 seq_printf(m, "%stransaction error: %u\n",
5064                            prefix, e->cmd);
5065         } break;
5066         case BINDER_WORK_TRANSACTION_COMPLETE:
5067                 seq_printf(m, "%stransaction complete\n", prefix);
5068                 break;
5069         case BINDER_WORK_NODE:
5070                 node = container_of(w, struct binder_node, work);
5071                 seq_printf(m, "%snode work %d: u%016llx c%016llx\n",
5072                            prefix, node->debug_id,
5073                            (u64)node->ptr, (u64)node->cookie);
5074                 break;
5075         case BINDER_WORK_DEAD_BINDER:
5076                 seq_printf(m, "%shas dead binder\n", prefix);
5077                 break;
5078         case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
5079                 seq_printf(m, "%shas cleared dead binder\n", prefix);
5080                 break;
5081         case BINDER_WORK_CLEAR_DEATH_NOTIFICATION:
5082                 seq_printf(m, "%shas cleared death notification\n", prefix);
5083                 break;
5084         default:
5085                 seq_printf(m, "%sunknown work: type %d\n", prefix, w->type);
5086                 break;
5087         }
5088 }
5089
5090 static void print_binder_thread_ilocked(struct seq_file *m,
5091                                         struct binder_thread *thread,
5092                                         int print_always)
5093 {
5094         struct binder_transaction *t;
5095         struct binder_work *w;
5096         size_t start_pos = m->count;
5097         size_t header_pos;
5098
5099         seq_printf(m, "  thread %d: l %02x need_return %d tr %d\n",
5100                         thread->pid, thread->looper,
5101                         thread->looper_need_return,
5102                         atomic_read(&thread->tmp_ref));
5103         header_pos = m->count;
5104         t = thread->transaction_stack;
5105         while (t) {
5106                 if (t->from == thread) {
5107                         print_binder_transaction_ilocked(m, thread->proc,
5108                                         "    outgoing transaction", t);
5109                         t = t->from_parent;
5110                 } else if (t->to_thread == thread) {
5111                         print_binder_transaction_ilocked(m, thread->proc,
5112                                                  "    incoming transaction", t);
5113                         t = t->to_parent;
5114                 } else {
5115                         print_binder_transaction_ilocked(m, thread->proc,
5116                                         "    bad transaction", t);
5117                         t = NULL;
5118                 }
5119         }
5120         list_for_each_entry(w, &thread->todo, entry) {
5121                 print_binder_work_ilocked(m, thread->proc, "    ",
5122                                           "    pending transaction", w);
5123         }
5124         if (!print_always && m->count == header_pos)
5125                 m->count = start_pos;
5126 }
5127
5128 static void print_binder_node_nilocked(struct seq_file *m,
5129                                        struct binder_node *node)
5130 {
5131         struct binder_ref *ref;
5132         struct binder_work *w;
5133         int count;
5134
5135         count = 0;
5136         hlist_for_each_entry(ref, &node->refs, node_entry)
5137                 count++;
5138
5139         seq_printf(m, "  node %d: u%016llx c%016llx hs %d hw %d ls %d lw %d is %d iw %d tr %d",
5140                    node->debug_id, (u64)node->ptr, (u64)node->cookie,
5141                    node->has_strong_ref, node->has_weak_ref,
5142                    node->local_strong_refs, node->local_weak_refs,
5143                    node->internal_strong_refs, count, node->tmp_refs);
5144         if (count) {
5145                 seq_puts(m, " proc");
5146                 hlist_for_each_entry(ref, &node->refs, node_entry)
5147                         seq_printf(m, " %d", ref->proc->pid);
5148         }
5149         seq_puts(m, "\n");
5150         if (node->proc) {
5151                 list_for_each_entry(w, &node->async_todo, entry)
5152                         print_binder_work_ilocked(m, node->proc, "    ",
5153                                           "    pending async transaction", w);
5154         }
5155 }
5156
5157 static void print_binder_ref_olocked(struct seq_file *m,
5158                                      struct binder_ref *ref)
5159 {
5160         binder_node_lock(ref->node);
5161         seq_printf(m, "  ref %d: desc %d %snode %d s %d w %d d %pK\n",
5162                    ref->data.debug_id, ref->data.desc,
5163                    ref->node->proc ? "" : "dead ",
5164                    ref->node->debug_id, ref->data.strong,
5165                    ref->data.weak, ref->death);
5166         binder_node_unlock(ref->node);
5167 }
5168
5169 static void print_binder_proc(struct seq_file *m,
5170                               struct binder_proc *proc, int print_all)
5171 {
5172         struct binder_work *w;
5173         struct rb_node *n;
5174         size_t start_pos = m->count;
5175         size_t header_pos;
5176         struct binder_node *last_node = NULL;
5177
5178         seq_printf(m, "proc %d\n", proc->pid);
5179         seq_printf(m, "context %s\n", proc->context->name);
5180         header_pos = m->count;
5181
5182         binder_inner_proc_lock(proc);
5183         for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n))
5184                 print_binder_thread_ilocked(m, rb_entry(n, struct binder_thread,
5185                                                 rb_node), print_all);
5186
5187         for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n)) {
5188                 struct binder_node *node = rb_entry(n, struct binder_node,
5189                                                     rb_node);
5190                 /*
5191                  * take a temporary reference on the node so it
5192                  * survives and isn't removed from the tree
5193                  * while we print it.
5194                  */
5195                 binder_inc_node_tmpref_ilocked(node);
5196                 /* Need to drop inner lock to take node lock */
5197                 binder_inner_proc_unlock(proc);
5198                 if (last_node)
5199                         binder_put_node(last_node);
5200                 binder_node_inner_lock(node);
5201                 print_binder_node_nilocked(m, node);
5202                 binder_node_inner_unlock(node);
5203                 last_node = node;
5204                 binder_inner_proc_lock(proc);
5205         }
5206         binder_inner_proc_unlock(proc);
5207         if (last_node)
5208                 binder_put_node(last_node);
5209
5210         if (print_all) {
5211                 binder_proc_lock(proc);
5212                 for (n = rb_first(&proc->refs_by_desc);
5213                      n != NULL;
5214                      n = rb_next(n))
5215                         print_binder_ref_olocked(m, rb_entry(n,
5216                                                             struct binder_ref,
5217                                                             rb_node_desc));
5218                 binder_proc_unlock(proc);
5219         }
5220         binder_alloc_print_allocated(m, &proc->alloc);
5221         binder_inner_proc_lock(proc);
5222         list_for_each_entry(w, &proc->todo, entry)
5223                 print_binder_work_ilocked(m, proc, "  ",
5224                                           "  pending transaction", w);
5225         list_for_each_entry(w, &proc->delivered_death, entry) {
5226                 seq_puts(m, "  has delivered dead binder\n");
5227                 break;
5228         }
5229         binder_inner_proc_unlock(proc);
5230         if (!print_all && m->count == header_pos)
5231                 m->count = start_pos;
5232 }
5233
5234 static const char * const binder_return_strings[] = {
5235         "BR_ERROR",
5236         "BR_OK",
5237         "BR_TRANSACTION",
5238         "BR_REPLY",
5239         "BR_ACQUIRE_RESULT",
5240         "BR_DEAD_REPLY",
5241         "BR_TRANSACTION_COMPLETE",
5242         "BR_INCREFS",
5243         "BR_ACQUIRE",
5244         "BR_RELEASE",
5245         "BR_DECREFS",
5246         "BR_ATTEMPT_ACQUIRE",
5247         "BR_NOOP",
5248         "BR_SPAWN_LOOPER",
5249         "BR_FINISHED",
5250         "BR_DEAD_BINDER",
5251         "BR_CLEAR_DEATH_NOTIFICATION_DONE",
5252         "BR_FAILED_REPLY"
5253 };
5254
5255 static const char * const binder_command_strings[] = {
5256         "BC_TRANSACTION",
5257         "BC_REPLY",
5258         "BC_ACQUIRE_RESULT",
5259         "BC_FREE_BUFFER",
5260         "BC_INCREFS",
5261         "BC_ACQUIRE",
5262         "BC_RELEASE",
5263         "BC_DECREFS",
5264         "BC_INCREFS_DONE",
5265         "BC_ACQUIRE_DONE",
5266         "BC_ATTEMPT_ACQUIRE",
5267         "BC_REGISTER_LOOPER",
5268         "BC_ENTER_LOOPER",
5269         "BC_EXIT_LOOPER",
5270         "BC_REQUEST_DEATH_NOTIFICATION",
5271         "BC_CLEAR_DEATH_NOTIFICATION",
5272         "BC_DEAD_BINDER_DONE",
5273         "BC_TRANSACTION_SG",
5274         "BC_REPLY_SG",
5275 };
5276
5277 static const char * const binder_objstat_strings[] = {
5278         "proc",
5279         "thread",
5280         "node",
5281         "ref",
5282         "death",
5283         "transaction",
5284         "transaction_complete"
5285 };
5286
5287 static void print_binder_stats(struct seq_file *m, const char *prefix,
5288                                struct binder_stats *stats)
5289 {
5290         int i;
5291
5292         BUILD_BUG_ON(ARRAY_SIZE(stats->bc) !=
5293                      ARRAY_SIZE(binder_command_strings));
5294         for (i = 0; i < ARRAY_SIZE(stats->bc); i++) {
5295                 int temp = atomic_read(&stats->bc[i]);
5296
5297                 if (temp)
5298                         seq_printf(m, "%s%s: %d\n", prefix,
5299                                    binder_command_strings[i], temp);
5300         }
5301
5302         BUILD_BUG_ON(ARRAY_SIZE(stats->br) !=
5303                      ARRAY_SIZE(binder_return_strings));
5304         for (i = 0; i < ARRAY_SIZE(stats->br); i++) {
5305                 int temp = atomic_read(&stats->br[i]);
5306
5307                 if (temp)
5308                         seq_printf(m, "%s%s: %d\n", prefix,
5309                                    binder_return_strings[i], temp);
5310         }
5311
5312         BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) !=
5313                      ARRAY_SIZE(binder_objstat_strings));
5314         BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) !=
5315                      ARRAY_SIZE(stats->obj_deleted));
5316         for (i = 0; i < ARRAY_SIZE(stats->obj_created); i++) {
5317                 int created = atomic_read(&stats->obj_created[i]);
5318                 int deleted = atomic_read(&stats->obj_deleted[i]);
5319
5320                 if (created || deleted)
5321                         seq_printf(m, "%s%s: active %d total %d\n",
5322                                 prefix,
5323                                 binder_objstat_strings[i],
5324                                 created - deleted,
5325                                 created);
5326         }
5327 }
5328
5329 static void print_binder_proc_stats(struct seq_file *m,
5330                                     struct binder_proc *proc)
5331 {
5332         struct binder_work *w;
5333         struct binder_thread *thread;
5334         struct rb_node *n;
5335         int count, strong, weak, ready_threads;
5336         size_t free_async_space =
5337                 binder_alloc_get_free_async_space(&proc->alloc);
5338
5339         seq_printf(m, "proc %d\n", proc->pid);
5340         seq_printf(m, "context %s\n", proc->context->name);
5341         count = 0;
5342         ready_threads = 0;
5343         binder_inner_proc_lock(proc);
5344         for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n))
5345                 count++;
5346
5347         list_for_each_entry(thread, &proc->waiting_threads, waiting_thread_node)
5348                 ready_threads++;
5349
5350         seq_printf(m, "  threads: %d\n", count);
5351         seq_printf(m, "  requested threads: %d+%d/%d\n"
5352                         "  ready threads %d\n"
5353                         "  free async space %zd\n", proc->requested_threads,
5354                         proc->requested_threads_started, proc->max_threads,
5355                         ready_threads,
5356                         free_async_space);
5357         count = 0;
5358         for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n))
5359                 count++;
5360         binder_inner_proc_unlock(proc);
5361         seq_printf(m, "  nodes: %d\n", count);
5362         count = 0;
5363         strong = 0;
5364         weak = 0;
5365         binder_proc_lock(proc);
5366         for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {
5367                 struct binder_ref *ref = rb_entry(n, struct binder_ref,
5368                                                   rb_node_desc);
5369                 count++;
5370                 strong += ref->data.strong;
5371                 weak += ref->data.weak;
5372         }
5373         binder_proc_unlock(proc);
5374         seq_printf(m, "  refs: %d s %d w %d\n", count, strong, weak);
5375
5376         count = binder_alloc_get_allocated_count(&proc->alloc);
5377         seq_printf(m, "  buffers: %d\n", count);
5378
5379         binder_alloc_print_pages(m, &proc->alloc);
5380
5381         count = 0;
5382         binder_inner_proc_lock(proc);
5383         list_for_each_entry(w, &proc->todo, entry) {
5384                 if (w->type == BINDER_WORK_TRANSACTION)
5385                         count++;
5386         }
5387         binder_inner_proc_unlock(proc);
5388         seq_printf(m, "  pending transactions: %d\n", count);
5389
5390         print_binder_stats(m, "  ", &proc->stats);
5391 }
5392
5393
5394 static int binder_state_show(struct seq_file *m, void *unused)
5395 {
5396         struct binder_proc *proc;
5397         struct binder_node *node;
5398         struct binder_node *last_node = NULL;
5399
5400         seq_puts(m, "binder state:\n");
5401
5402         spin_lock(&binder_dead_nodes_lock);
5403         if (!hlist_empty(&binder_dead_nodes))
5404                 seq_puts(m, "dead nodes:\n");
5405         hlist_for_each_entry(node, &binder_dead_nodes, dead_node) {
5406                 /*
5407                  * take a temporary reference on the node so it
5408                  * survives and isn't removed from the list
5409                  * while we print it.
5410                  */
5411                 node->tmp_refs++;
5412                 spin_unlock(&binder_dead_nodes_lock);
5413                 if (last_node)
5414                         binder_put_node(last_node);
5415                 binder_node_lock(node);
5416                 print_binder_node_nilocked(m, node);
5417                 binder_node_unlock(node);
5418                 last_node = node;
5419                 spin_lock(&binder_dead_nodes_lock);
5420         }
5421         spin_unlock(&binder_dead_nodes_lock);
5422         if (last_node)
5423                 binder_put_node(last_node);
5424
5425         mutex_lock(&binder_procs_lock);
5426         hlist_for_each_entry(proc, &binder_procs, proc_node)
5427                 print_binder_proc(m, proc, 1);
5428         mutex_unlock(&binder_procs_lock);
5429
5430         return 0;
5431 }
5432
5433 static int binder_stats_show(struct seq_file *m, void *unused)
5434 {
5435         struct binder_proc *proc;
5436
5437         seq_puts(m, "binder stats:\n");
5438
5439         print_binder_stats(m, "", &binder_stats);
5440
5441         mutex_lock(&binder_procs_lock);
5442         hlist_for_each_entry(proc, &binder_procs, proc_node)
5443                 print_binder_proc_stats(m, proc);
5444         mutex_unlock(&binder_procs_lock);
5445
5446         return 0;
5447 }
5448
5449 static int binder_transactions_show(struct seq_file *m, void *unused)
5450 {
5451         struct binder_proc *proc;
5452
5453         seq_puts(m, "binder transactions:\n");
5454         mutex_lock(&binder_procs_lock);
5455         hlist_for_each_entry(proc, &binder_procs, proc_node)
5456                 print_binder_proc(m, proc, 0);
5457         mutex_unlock(&binder_procs_lock);
5458
5459         return 0;
5460 }
5461
5462 static int binder_proc_show(struct seq_file *m, void *unused)
5463 {
5464         struct binder_proc *itr;
5465         int pid = (unsigned long)m->private;
5466
5467         mutex_lock(&binder_procs_lock);
5468         hlist_for_each_entry(itr, &binder_procs, proc_node) {
5469                 if (itr->pid == pid) {
5470                         seq_puts(m, "binder proc state:\n");
5471                         print_binder_proc(m, itr, 1);
5472                 }
5473         }
5474         mutex_unlock(&binder_procs_lock);
5475
5476         return 0;
5477 }
5478
5479 static void print_binder_transaction_log_entry(struct seq_file *m,
5480                                         struct binder_transaction_log_entry *e)
5481 {
5482         int debug_id = READ_ONCE(e->debug_id_done);
5483         /*
5484          * read barrier to guarantee debug_id_done read before
5485          * we print the log values
5486          */
5487         smp_rmb();
5488         seq_printf(m,
5489                    "%d: %s from %d:%d to %d:%d context %s node %d handle %d size %d:%d ret %d/%d l=%d",
5490                    e->debug_id, (e->call_type == 2) ? "reply" :
5491                    ((e->call_type == 1) ? "async" : "call "), e->from_proc,
5492                    e->from_thread, e->to_proc, e->to_thread, e->context_name,
5493                    e->to_node, e->target_handle, e->data_size, e->offsets_size,
5494                    e->return_error, e->return_error_param,
5495                    e->return_error_line);
5496         /*
5497          * read-barrier to guarantee read of debug_id_done after
5498          * done printing the fields of the entry
5499          */
5500         smp_rmb();
5501         seq_printf(m, debug_id && debug_id == READ_ONCE(e->debug_id_done) ?
5502                         "\n" : " (incomplete)\n");
5503 }
5504
5505 static int binder_transaction_log_show(struct seq_file *m, void *unused)
5506 {
5507         struct binder_transaction_log *log = m->private;
5508         unsigned int log_cur = atomic_read(&log->cur);
5509         unsigned int count;
5510         unsigned int cur;
5511         int i;
5512
5513         count = log_cur + 1;
5514         cur = count < ARRAY_SIZE(log->entry) && !log->full ?
5515                 0 : count % ARRAY_SIZE(log->entry);
5516         if (count > ARRAY_SIZE(log->entry) || log->full)
5517                 count = ARRAY_SIZE(log->entry);
5518         for (i = 0; i < count; i++) {
5519                 unsigned int index = cur++ % ARRAY_SIZE(log->entry);
5520
5521                 print_binder_transaction_log_entry(m, &log->entry[index]);
5522         }
5523         return 0;
5524 }
5525
5526 static const struct file_operations binder_fops = {
5527         .owner = THIS_MODULE,
5528         .poll = binder_poll,
5529         .unlocked_ioctl = binder_ioctl,
5530         .compat_ioctl = binder_ioctl,
5531         .mmap = binder_mmap,
5532         .open = binder_open,
5533         .flush = binder_flush,
5534         .release = binder_release,
5535 };
5536
5537 BINDER_DEBUG_ENTRY(state);
5538 BINDER_DEBUG_ENTRY(stats);
5539 BINDER_DEBUG_ENTRY(transactions);
5540 BINDER_DEBUG_ENTRY(transaction_log);
5541
5542 static int __init init_binder_device(const char *name)
5543 {
5544         int ret;
5545         struct binder_device *binder_device;
5546
5547         binder_device = kzalloc(sizeof(*binder_device), GFP_KERNEL);
5548         if (!binder_device)
5549                 return -ENOMEM;
5550
5551         binder_device->miscdev.fops = &binder_fops;
5552         binder_device->miscdev.minor = MISC_DYNAMIC_MINOR;
5553         binder_device->miscdev.name = name;
5554
5555         binder_device->context.binder_context_mgr_uid = INVALID_UID;
5556         binder_device->context.name = name;
5557         mutex_init(&binder_device->context.context_mgr_node_lock);
5558
5559         ret = misc_register(&binder_device->miscdev);
5560         if (ret < 0) {
5561                 kfree(binder_device);
5562                 return ret;
5563         }
5564
5565         hlist_add_head(&binder_device->hlist, &binder_devices);
5566
5567         return ret;
5568 }
5569
5570 static int __init binder_init(void)
5571 {
5572         int ret;
5573         char *device_name, *device_names, *device_tmp;
5574         struct binder_device *device;
5575         struct hlist_node *tmp;
5576
5577         binder_alloc_shrinker_init();
5578
5579         atomic_set(&binder_transaction_log.cur, ~0U);
5580         atomic_set(&binder_transaction_log_failed.cur, ~0U);
5581
5582         binder_debugfs_dir_entry_root = debugfs_create_dir("binder", NULL);
5583         if (binder_debugfs_dir_entry_root)
5584                 binder_debugfs_dir_entry_proc = debugfs_create_dir("proc",
5585                                                  binder_debugfs_dir_entry_root);
5586
5587         if (binder_debugfs_dir_entry_root) {
5588                 debugfs_create_file("state",
5589                                     S_IRUGO,
5590                                     binder_debugfs_dir_entry_root,
5591                                     NULL,
5592                                     &binder_state_fops);
5593                 debugfs_create_file("stats",
5594                                     S_IRUGO,
5595                                     binder_debugfs_dir_entry_root,
5596                                     NULL,
5597                                     &binder_stats_fops);
5598                 debugfs_create_file("transactions",
5599                                     S_IRUGO,
5600                                     binder_debugfs_dir_entry_root,
5601                                     NULL,
5602                                     &binder_transactions_fops);
5603                 debugfs_create_file("transaction_log",
5604                                     S_IRUGO,
5605                                     binder_debugfs_dir_entry_root,
5606                                     &binder_transaction_log,
5607                                     &binder_transaction_log_fops);
5608                 debugfs_create_file("failed_transaction_log",
5609                                     S_IRUGO,
5610                                     binder_debugfs_dir_entry_root,
5611                                     &binder_transaction_log_failed,
5612                                     &binder_transaction_log_fops);
5613         }
5614
5615         /*
5616          * Copy the module_parameter string, because we don't want to
5617          * tokenize it in-place.
5618          */
5619         device_names = kzalloc(strlen(binder_devices_param) + 1, GFP_KERNEL);
5620         if (!device_names) {
5621                 ret = -ENOMEM;
5622                 goto err_alloc_device_names_failed;
5623         }
5624         strcpy(device_names, binder_devices_param);
5625
5626         device_tmp = device_names;
5627         while ((device_name = strsep(&device_tmp, ","))) {
5628                 ret = init_binder_device(device_name);
5629                 if (ret)
5630                         goto err_init_binder_device_failed;
5631         }
5632
5633         return ret;
5634
5635 err_init_binder_device_failed:
5636         hlist_for_each_entry_safe(device, tmp, &binder_devices, hlist) {
5637                 misc_deregister(&device->miscdev);
5638                 hlist_del(&device->hlist);
5639                 kfree(device);
5640         }
5641
5642         kfree(device_names);
5643
5644 err_alloc_device_names_failed:
5645         debugfs_remove_recursive(binder_debugfs_dir_entry_root);
5646
5647         return ret;
5648 }
5649
5650 device_initcall(binder_init);
5651
5652 #define CREATE_TRACE_POINTS
5653 #include "binder_trace.h"
5654
5655 MODULE_LICENSE("GPL v2");