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