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