OSDN Git Service

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