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