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