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