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