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