binder.c revision 56b468fc709b2b962cd91e6cd9f087c3cd095283
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#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19
20#include <asm/cacheflush.h>
21#include <linux/fdtable.h>
22#include <linux/file.h>
23#include <linux/fs.h>
24#include <linux/list.h>
25#include <linux/miscdevice.h>
26#include <linux/mm.h>
27#include <linux/module.h>
28#include <linux/mutex.h>
29#include <linux/nsproxy.h>
30#include <linux/poll.h>
31#include <linux/debugfs.h>
32#include <linux/rbtree.h>
33#include <linux/sched.h>
34#include <linux/seq_file.h>
35#include <linux/uaccess.h>
36#include <linux/vmalloc.h>
37#include <linux/slab.h>
38
39#include "binder.h"
40#include "binder_trace.h"
41
42static DEFINE_MUTEX(binder_main_lock);
43static DEFINE_MUTEX(binder_deferred_lock);
44static DEFINE_MUTEX(binder_mmap_lock);
45
46static HLIST_HEAD(binder_procs);
47static HLIST_HEAD(binder_deferred_list);
48static HLIST_HEAD(binder_dead_nodes);
49
50static struct dentry *binder_debugfs_dir_entry_root;
51static struct dentry *binder_debugfs_dir_entry_proc;
52static struct binder_node *binder_context_mgr_node;
53static kuid_t binder_context_mgr_uid = INVALID_UID;
54static int binder_last_id;
55static struct workqueue_struct *binder_deferred_workqueue;
56
57#define BINDER_DEBUG_ENTRY(name) \
58static int binder_##name##_open(struct inode *inode, struct file *file) \
59{ \
60	return single_open(file, binder_##name##_show, inode->i_private); \
61} \
62\
63static const struct file_operations binder_##name##_fops = { \
64	.owner = THIS_MODULE, \
65	.open = binder_##name##_open, \
66	.read = seq_read, \
67	.llseek = seq_lseek, \
68	.release = single_release, \
69}
70
71static int binder_proc_show(struct seq_file *m, void *unused);
72BINDER_DEBUG_ENTRY(proc);
73
74/* This is only defined in include/asm-arm/sizes.h */
75#ifndef SZ_1K
76#define SZ_1K                               0x400
77#endif
78
79#ifndef SZ_4M
80#define SZ_4M                               0x400000
81#endif
82
83#define FORBIDDEN_MMAP_FLAGS                (VM_WRITE)
84
85#define BINDER_SMALL_BUF_SIZE (PAGE_SIZE * 64)
86
87enum {
88	BINDER_DEBUG_USER_ERROR             = 1U << 0,
89	BINDER_DEBUG_FAILED_TRANSACTION     = 1U << 1,
90	BINDER_DEBUG_DEAD_TRANSACTION       = 1U << 2,
91	BINDER_DEBUG_OPEN_CLOSE             = 1U << 3,
92	BINDER_DEBUG_DEAD_BINDER            = 1U << 4,
93	BINDER_DEBUG_DEATH_NOTIFICATION     = 1U << 5,
94	BINDER_DEBUG_READ_WRITE             = 1U << 6,
95	BINDER_DEBUG_USER_REFS              = 1U << 7,
96	BINDER_DEBUG_THREADS                = 1U << 8,
97	BINDER_DEBUG_TRANSACTION            = 1U << 9,
98	BINDER_DEBUG_TRANSACTION_COMPLETE   = 1U << 10,
99	BINDER_DEBUG_FREE_BUFFER            = 1U << 11,
100	BINDER_DEBUG_INTERNAL_REFS          = 1U << 12,
101	BINDER_DEBUG_BUFFER_ALLOC           = 1U << 13,
102	BINDER_DEBUG_PRIORITY_CAP           = 1U << 14,
103	BINDER_DEBUG_BUFFER_ALLOC_ASYNC     = 1U << 15,
104};
105static uint32_t binder_debug_mask = BINDER_DEBUG_USER_ERROR |
106	BINDER_DEBUG_FAILED_TRANSACTION | BINDER_DEBUG_DEAD_TRANSACTION;
107module_param_named(debug_mask, binder_debug_mask, uint, S_IWUSR | S_IRUGO);
108
109static bool binder_debug_no_lock;
110module_param_named(proc_no_lock, binder_debug_no_lock, bool, S_IWUSR | S_IRUGO);
111
112static DECLARE_WAIT_QUEUE_HEAD(binder_user_error_wait);
113static int binder_stop_on_user_error;
114
115static int binder_set_stop_on_user_error(const char *val,
116					 struct kernel_param *kp)
117{
118	int ret;
119	ret = param_set_int(val, kp);
120	if (binder_stop_on_user_error < 2)
121		wake_up(&binder_user_error_wait);
122	return ret;
123}
124module_param_call(stop_on_user_error, binder_set_stop_on_user_error,
125	param_get_int, &binder_stop_on_user_error, S_IWUSR | S_IRUGO);
126
127#define binder_debug(mask, x...) \
128	do { \
129		if (binder_debug_mask & mask) \
130			pr_info(x); \
131	} while (0)
132
133#define binder_user_error(x...) \
134	do { \
135		if (binder_debug_mask & BINDER_DEBUG_USER_ERROR) \
136			pr_info(x); \
137		if (binder_stop_on_user_error) \
138			binder_stop_on_user_error = 2; \
139	} while (0)
140
141enum binder_stat_types {
142	BINDER_STAT_PROC,
143	BINDER_STAT_THREAD,
144	BINDER_STAT_NODE,
145	BINDER_STAT_REF,
146	BINDER_STAT_DEATH,
147	BINDER_STAT_TRANSACTION,
148	BINDER_STAT_TRANSACTION_COMPLETE,
149	BINDER_STAT_COUNT
150};
151
152struct binder_stats {
153	int br[_IOC_NR(BR_FAILED_REPLY) + 1];
154	int bc[_IOC_NR(BC_DEAD_BINDER_DONE) + 1];
155	int obj_created[BINDER_STAT_COUNT];
156	int obj_deleted[BINDER_STAT_COUNT];
157};
158
159static struct binder_stats binder_stats;
160
161static inline void binder_stats_deleted(enum binder_stat_types type)
162{
163	binder_stats.obj_deleted[type]++;
164}
165
166static inline void binder_stats_created(enum binder_stat_types type)
167{
168	binder_stats.obj_created[type]++;
169}
170
171struct binder_transaction_log_entry {
172	int debug_id;
173	int call_type;
174	int from_proc;
175	int from_thread;
176	int target_handle;
177	int to_proc;
178	int to_thread;
179	int to_node;
180	int data_size;
181	int offsets_size;
182};
183struct binder_transaction_log {
184	int next;
185	int full;
186	struct binder_transaction_log_entry entry[32];
187};
188static struct binder_transaction_log binder_transaction_log;
189static struct binder_transaction_log binder_transaction_log_failed;
190
191static struct binder_transaction_log_entry *binder_transaction_log_add(
192	struct binder_transaction_log *log)
193{
194	struct binder_transaction_log_entry *e;
195	e = &log->entry[log->next];
196	memset(e, 0, sizeof(*e));
197	log->next++;
198	if (log->next == ARRAY_SIZE(log->entry)) {
199		log->next = 0;
200		log->full = 1;
201	}
202	return e;
203}
204
205struct binder_work {
206	struct list_head entry;
207	enum {
208		BINDER_WORK_TRANSACTION = 1,
209		BINDER_WORK_TRANSACTION_COMPLETE,
210		BINDER_WORK_NODE,
211		BINDER_WORK_DEAD_BINDER,
212		BINDER_WORK_DEAD_BINDER_AND_CLEAR,
213		BINDER_WORK_CLEAR_DEATH_NOTIFICATION,
214	} type;
215};
216
217struct binder_node {
218	int debug_id;
219	struct binder_work work;
220	union {
221		struct rb_node rb_node;
222		struct hlist_node dead_node;
223	};
224	struct binder_proc *proc;
225	struct hlist_head refs;
226	int internal_strong_refs;
227	int local_weak_refs;
228	int local_strong_refs;
229	void __user *ptr;
230	void __user *cookie;
231	unsigned has_strong_ref:1;
232	unsigned pending_strong_ref:1;
233	unsigned has_weak_ref:1;
234	unsigned pending_weak_ref:1;
235	unsigned has_async_transaction:1;
236	unsigned accept_fds:1;
237	unsigned min_priority:8;
238	struct list_head async_todo;
239};
240
241struct binder_ref_death {
242	struct binder_work work;
243	void __user *cookie;
244};
245
246struct binder_ref {
247	/* Lookups needed: */
248	/*   node + proc => ref (transaction) */
249	/*   desc + proc => ref (transaction, inc/dec ref) */
250	/*   node => refs + procs (proc exit) */
251	int debug_id;
252	struct rb_node rb_node_desc;
253	struct rb_node rb_node_node;
254	struct hlist_node node_entry;
255	struct binder_proc *proc;
256	struct binder_node *node;
257	uint32_t desc;
258	int strong;
259	int weak;
260	struct binder_ref_death *death;
261};
262
263struct binder_buffer {
264	struct list_head entry; /* free and allocated entries by address */
265	struct rb_node rb_node; /* free entry by size or allocated entry */
266				/* by address */
267	unsigned free:1;
268	unsigned allow_user_free:1;
269	unsigned async_transaction:1;
270	unsigned debug_id:29;
271
272	struct binder_transaction *transaction;
273
274	struct binder_node *target_node;
275	size_t data_size;
276	size_t offsets_size;
277	uint8_t data[0];
278};
279
280enum binder_deferred_state {
281	BINDER_DEFERRED_PUT_FILES    = 0x01,
282	BINDER_DEFERRED_FLUSH        = 0x02,
283	BINDER_DEFERRED_RELEASE      = 0x04,
284};
285
286struct binder_proc {
287	struct hlist_node proc_node;
288	struct rb_root threads;
289	struct rb_root nodes;
290	struct rb_root refs_by_desc;
291	struct rb_root refs_by_node;
292	int pid;
293	struct vm_area_struct *vma;
294	struct mm_struct *vma_vm_mm;
295	struct task_struct *tsk;
296	struct files_struct *files;
297	struct hlist_node deferred_work_node;
298	int deferred_work;
299	void *buffer;
300	ptrdiff_t user_buffer_offset;
301
302	struct list_head buffers;
303	struct rb_root free_buffers;
304	struct rb_root allocated_buffers;
305	size_t free_async_space;
306
307	struct page **pages;
308	size_t buffer_size;
309	uint32_t buffer_free;
310	struct list_head todo;
311	wait_queue_head_t wait;
312	struct binder_stats stats;
313	struct list_head delivered_death;
314	int max_threads;
315	int requested_threads;
316	int requested_threads_started;
317	int ready_threads;
318	long default_priority;
319	struct dentry *debugfs_entry;
320};
321
322enum {
323	BINDER_LOOPER_STATE_REGISTERED  = 0x01,
324	BINDER_LOOPER_STATE_ENTERED     = 0x02,
325	BINDER_LOOPER_STATE_EXITED      = 0x04,
326	BINDER_LOOPER_STATE_INVALID     = 0x08,
327	BINDER_LOOPER_STATE_WAITING     = 0x10,
328	BINDER_LOOPER_STATE_NEED_RETURN = 0x20
329};
330
331struct binder_thread {
332	struct binder_proc *proc;
333	struct rb_node rb_node;
334	int pid;
335	int looper;
336	struct binder_transaction *transaction_stack;
337	struct list_head todo;
338	uint32_t return_error; /* Write failed, return error code in read buf */
339	uint32_t return_error2; /* Write failed, return error code in read */
340		/* buffer. Used when sending a reply to a dead process that */
341		/* we are also waiting on */
342	wait_queue_head_t wait;
343	struct binder_stats stats;
344};
345
346struct binder_transaction {
347	int debug_id;
348	struct binder_work work;
349	struct binder_thread *from;
350	struct binder_transaction *from_parent;
351	struct binder_proc *to_proc;
352	struct binder_thread *to_thread;
353	struct binder_transaction *to_parent;
354	unsigned need_reply:1;
355	/* unsigned is_dead:1; */	/* not used at the moment */
356
357	struct binder_buffer *buffer;
358	unsigned int	code;
359	unsigned int	flags;
360	long	priority;
361	long	saved_priority;
362	kuid_t	sender_euid;
363};
364
365static void
366binder_defer_work(struct binder_proc *proc, enum binder_deferred_state defer);
367
368static int task_get_unused_fd_flags(struct binder_proc *proc, int flags)
369{
370	struct files_struct *files = proc->files;
371	unsigned long rlim_cur;
372	unsigned long irqs;
373
374	if (files == NULL)
375		return -ESRCH;
376
377	if (!lock_task_sighand(proc->tsk, &irqs))
378		return -EMFILE;
379
380	rlim_cur = task_rlimit(proc->tsk, RLIMIT_NOFILE);
381	unlock_task_sighand(proc->tsk, &irqs);
382
383	return __alloc_fd(files, 0, rlim_cur, flags);
384}
385
386/*
387 * copied from fd_install
388 */
389static void task_fd_install(
390	struct binder_proc *proc, unsigned int fd, struct file *file)
391{
392	if (proc->files)
393		__fd_install(proc->files, fd, file);
394}
395
396/*
397 * copied from sys_close
398 */
399static long task_close_fd(struct binder_proc *proc, unsigned int fd)
400{
401	int retval;
402
403	if (proc->files == NULL)
404		return -ESRCH;
405
406	retval = __close_fd(proc->files, fd);
407	/* can't restart close syscall because file table entry was cleared */
408	if (unlikely(retval == -ERESTARTSYS ||
409		     retval == -ERESTARTNOINTR ||
410		     retval == -ERESTARTNOHAND ||
411		     retval == -ERESTART_RESTARTBLOCK))
412		retval = -EINTR;
413
414	return retval;
415}
416
417static inline void binder_lock(const char *tag)
418{
419	trace_binder_lock(tag);
420	mutex_lock(&binder_main_lock);
421	trace_binder_locked(tag);
422}
423
424static inline void binder_unlock(const char *tag)
425{
426	trace_binder_unlock(tag);
427	mutex_unlock(&binder_main_lock);
428}
429
430static void binder_set_nice(long nice)
431{
432	long min_nice;
433	if (can_nice(current, nice)) {
434		set_user_nice(current, nice);
435		return;
436	}
437	min_nice = 20 - current->signal->rlim[RLIMIT_NICE].rlim_cur;
438	binder_debug(BINDER_DEBUG_PRIORITY_CAP,
439		     "%d: nice value %ld not allowed use %ld instead\n",
440		      current->pid, nice, min_nice);
441	set_user_nice(current, min_nice);
442	if (min_nice < 20)
443		return;
444	binder_user_error("%d RLIMIT_NICE not set\n", current->pid);
445}
446
447static size_t binder_buffer_size(struct binder_proc *proc,
448				 struct binder_buffer *buffer)
449{
450	if (list_is_last(&buffer->entry, &proc->buffers))
451		return proc->buffer + proc->buffer_size - (void *)buffer->data;
452	else
453		return (size_t)list_entry(buffer->entry.next,
454			struct binder_buffer, entry) - (size_t)buffer->data;
455}
456
457static void binder_insert_free_buffer(struct binder_proc *proc,
458				      struct binder_buffer *new_buffer)
459{
460	struct rb_node **p = &proc->free_buffers.rb_node;
461	struct rb_node *parent = NULL;
462	struct binder_buffer *buffer;
463	size_t buffer_size;
464	size_t new_buffer_size;
465
466	BUG_ON(!new_buffer->free);
467
468	new_buffer_size = binder_buffer_size(proc, new_buffer);
469
470	binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
471		     "%d: add free buffer, size %zd, at %p\n",
472		      proc->pid, new_buffer_size, new_buffer);
473
474	while (*p) {
475		parent = *p;
476		buffer = rb_entry(parent, struct binder_buffer, rb_node);
477		BUG_ON(!buffer->free);
478
479		buffer_size = binder_buffer_size(proc, buffer);
480
481		if (new_buffer_size < buffer_size)
482			p = &parent->rb_left;
483		else
484			p = &parent->rb_right;
485	}
486	rb_link_node(&new_buffer->rb_node, parent, p);
487	rb_insert_color(&new_buffer->rb_node, &proc->free_buffers);
488}
489
490static void binder_insert_allocated_buffer(struct binder_proc *proc,
491					   struct binder_buffer *new_buffer)
492{
493	struct rb_node **p = &proc->allocated_buffers.rb_node;
494	struct rb_node *parent = NULL;
495	struct binder_buffer *buffer;
496
497	BUG_ON(new_buffer->free);
498
499	while (*p) {
500		parent = *p;
501		buffer = rb_entry(parent, struct binder_buffer, rb_node);
502		BUG_ON(buffer->free);
503
504		if (new_buffer < buffer)
505			p = &parent->rb_left;
506		else if (new_buffer > buffer)
507			p = &parent->rb_right;
508		else
509			BUG();
510	}
511	rb_link_node(&new_buffer->rb_node, parent, p);
512	rb_insert_color(&new_buffer->rb_node, &proc->allocated_buffers);
513}
514
515static struct binder_buffer *binder_buffer_lookup(struct binder_proc *proc,
516						  void __user *user_ptr)
517{
518	struct rb_node *n = proc->allocated_buffers.rb_node;
519	struct binder_buffer *buffer;
520	struct binder_buffer *kern_ptr;
521
522	kern_ptr = user_ptr - proc->user_buffer_offset
523		- offsetof(struct binder_buffer, data);
524
525	while (n) {
526		buffer = rb_entry(n, struct binder_buffer, rb_node);
527		BUG_ON(buffer->free);
528
529		if (kern_ptr < buffer)
530			n = n->rb_left;
531		else if (kern_ptr > buffer)
532			n = n->rb_right;
533		else
534			return buffer;
535	}
536	return NULL;
537}
538
539static int binder_update_page_range(struct binder_proc *proc, int allocate,
540				    void *start, void *end,
541				    struct vm_area_struct *vma)
542{
543	void *page_addr;
544	unsigned long user_page_addr;
545	struct vm_struct tmp_area;
546	struct page **page;
547	struct mm_struct *mm;
548
549	binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
550		     "%d: %s pages %p-%p\n", proc->pid,
551		     allocate ? "allocate" : "free", start, end);
552
553	if (end <= start)
554		return 0;
555
556	trace_binder_update_page_range(proc, allocate, start, end);
557
558	if (vma)
559		mm = NULL;
560	else
561		mm = get_task_mm(proc->tsk);
562
563	if (mm) {
564		down_write(&mm->mmap_sem);
565		vma = proc->vma;
566		if (vma && mm != proc->vma_vm_mm) {
567			pr_err("%d: vma mm and task mm mismatch\n",
568				proc->pid);
569			vma = NULL;
570		}
571	}
572
573	if (allocate == 0)
574		goto free_range;
575
576	if (vma == NULL) {
577		pr_err("%d: binder_alloc_buf failed to map pages in userspace, no vma\n",
578			proc->pid);
579		goto err_no_vma;
580	}
581
582	for (page_addr = start; page_addr < end; page_addr += PAGE_SIZE) {
583		int ret;
584		struct page **page_array_ptr;
585		page = &proc->pages[(page_addr - proc->buffer) / PAGE_SIZE];
586
587		BUG_ON(*page);
588		*page = alloc_page(GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO);
589		if (*page == NULL) {
590			pr_err("%d: binder_alloc_buf failed for page at %p\n",
591				proc->pid, page_addr);
592			goto err_alloc_page_failed;
593		}
594		tmp_area.addr = page_addr;
595		tmp_area.size = PAGE_SIZE + PAGE_SIZE /* guard page? */;
596		page_array_ptr = page;
597		ret = map_vm_area(&tmp_area, PAGE_KERNEL, &page_array_ptr);
598		if (ret) {
599			pr_err("%d: binder_alloc_buf failed to map page at %p in kernel\n",
600			       proc->pid, page_addr);
601			goto err_map_kernel_failed;
602		}
603		user_page_addr =
604			(uintptr_t)page_addr + proc->user_buffer_offset;
605		ret = vm_insert_page(vma, user_page_addr, page[0]);
606		if (ret) {
607			pr_err("%d: binder_alloc_buf failed to map page at %lx in userspace\n",
608			       proc->pid, user_page_addr);
609			goto err_vm_insert_page_failed;
610		}
611		/* vm_insert_page does not seem to increment the refcount */
612	}
613	if (mm) {
614		up_write(&mm->mmap_sem);
615		mmput(mm);
616	}
617	return 0;
618
619free_range:
620	for (page_addr = end - PAGE_SIZE; page_addr >= start;
621	     page_addr -= PAGE_SIZE) {
622		page = &proc->pages[(page_addr - proc->buffer) / PAGE_SIZE];
623		if (vma)
624			zap_page_range(vma, (uintptr_t)page_addr +
625				proc->user_buffer_offset, PAGE_SIZE, NULL);
626err_vm_insert_page_failed:
627		unmap_kernel_range((unsigned long)page_addr, PAGE_SIZE);
628err_map_kernel_failed:
629		__free_page(*page);
630		*page = NULL;
631err_alloc_page_failed:
632		;
633	}
634err_no_vma:
635	if (mm) {
636		up_write(&mm->mmap_sem);
637		mmput(mm);
638	}
639	return -ENOMEM;
640}
641
642static struct binder_buffer *binder_alloc_buf(struct binder_proc *proc,
643					      size_t data_size,
644					      size_t offsets_size, int is_async)
645{
646	struct rb_node *n = proc->free_buffers.rb_node;
647	struct binder_buffer *buffer;
648	size_t buffer_size;
649	struct rb_node *best_fit = NULL;
650	void *has_page_addr;
651	void *end_page_addr;
652	size_t size;
653
654	if (proc->vma == NULL) {
655		pr_err("%d: binder_alloc_buf, no vma\n",
656		       proc->pid);
657		return NULL;
658	}
659
660	size = ALIGN(data_size, sizeof(void *)) +
661		ALIGN(offsets_size, sizeof(void *));
662
663	if (size < data_size || size < offsets_size) {
664		binder_user_error("%d: got transaction with invalid size %zd-%zd\n",
665				proc->pid, data_size, offsets_size);
666		return NULL;
667	}
668
669	if (is_async &&
670	    proc->free_async_space < size + sizeof(struct binder_buffer)) {
671		binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
672			     "%d: binder_alloc_buf size %zd failed, no async space left\n",
673			      proc->pid, size);
674		return NULL;
675	}
676
677	while (n) {
678		buffer = rb_entry(n, struct binder_buffer, rb_node);
679		BUG_ON(!buffer->free);
680		buffer_size = binder_buffer_size(proc, buffer);
681
682		if (size < buffer_size) {
683			best_fit = n;
684			n = n->rb_left;
685		} else if (size > buffer_size)
686			n = n->rb_right;
687		else {
688			best_fit = n;
689			break;
690		}
691	}
692	if (best_fit == NULL) {
693		pr_err("%d: binder_alloc_buf size %zd failed, no address space\n",
694			proc->pid, size);
695		return NULL;
696	}
697	if (n == NULL) {
698		buffer = rb_entry(best_fit, struct binder_buffer, rb_node);
699		buffer_size = binder_buffer_size(proc, buffer);
700	}
701
702	binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
703		     "%d: binder_alloc_buf size %zd got buffer %p size %zd\n",
704		      proc->pid, size, buffer, buffer_size);
705
706	has_page_addr =
707		(void *)(((uintptr_t)buffer->data + buffer_size) & PAGE_MASK);
708	if (n == NULL) {
709		if (size + sizeof(struct binder_buffer) + 4 >= buffer_size)
710			buffer_size = size; /* no room for other buffers */
711		else
712			buffer_size = size + sizeof(struct binder_buffer);
713	}
714	end_page_addr =
715		(void *)PAGE_ALIGN((uintptr_t)buffer->data + buffer_size);
716	if (end_page_addr > has_page_addr)
717		end_page_addr = has_page_addr;
718	if (binder_update_page_range(proc, 1,
719	    (void *)PAGE_ALIGN((uintptr_t)buffer->data), end_page_addr, NULL))
720		return NULL;
721
722	rb_erase(best_fit, &proc->free_buffers);
723	buffer->free = 0;
724	binder_insert_allocated_buffer(proc, buffer);
725	if (buffer_size != size) {
726		struct binder_buffer *new_buffer = (void *)buffer->data + size;
727		list_add(&new_buffer->entry, &buffer->entry);
728		new_buffer->free = 1;
729		binder_insert_free_buffer(proc, new_buffer);
730	}
731	binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
732		     "%d: binder_alloc_buf size %zd got %p\n",
733		      proc->pid, size, buffer);
734	buffer->data_size = data_size;
735	buffer->offsets_size = offsets_size;
736	buffer->async_transaction = is_async;
737	if (is_async) {
738		proc->free_async_space -= size + sizeof(struct binder_buffer);
739		binder_debug(BINDER_DEBUG_BUFFER_ALLOC_ASYNC,
740			     "%d: binder_alloc_buf size %zd async free %zd\n",
741			      proc->pid, size, proc->free_async_space);
742	}
743
744	return buffer;
745}
746
747static void *buffer_start_page(struct binder_buffer *buffer)
748{
749	return (void *)((uintptr_t)buffer & PAGE_MASK);
750}
751
752static void *buffer_end_page(struct binder_buffer *buffer)
753{
754	return (void *)(((uintptr_t)(buffer + 1) - 1) & PAGE_MASK);
755}
756
757static void binder_delete_free_buffer(struct binder_proc *proc,
758				      struct binder_buffer *buffer)
759{
760	struct binder_buffer *prev, *next = NULL;
761	int free_page_end = 1;
762	int free_page_start = 1;
763
764	BUG_ON(proc->buffers.next == &buffer->entry);
765	prev = list_entry(buffer->entry.prev, struct binder_buffer, entry);
766	BUG_ON(!prev->free);
767	if (buffer_end_page(prev) == buffer_start_page(buffer)) {
768		free_page_start = 0;
769		if (buffer_end_page(prev) == buffer_end_page(buffer))
770			free_page_end = 0;
771		binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
772			     "%d: merge free, buffer %p share page with %p\n",
773			      proc->pid, buffer, prev);
774	}
775
776	if (!list_is_last(&buffer->entry, &proc->buffers)) {
777		next = list_entry(buffer->entry.next,
778				  struct binder_buffer, entry);
779		if (buffer_start_page(next) == buffer_end_page(buffer)) {
780			free_page_end = 0;
781			if (buffer_start_page(next) ==
782			    buffer_start_page(buffer))
783				free_page_start = 0;
784			binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
785				     "%d: merge free, buffer %p share page with %p\n",
786				      proc->pid, buffer, prev);
787		}
788	}
789	list_del(&buffer->entry);
790	if (free_page_start || free_page_end) {
791		binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
792			     "%d: merge free, buffer %p do not share page%s%s with with %p or %p\n",
793			     proc->pid, buffer, free_page_start ? "" : " end",
794			     free_page_end ? "" : " start", prev, next);
795		binder_update_page_range(proc, 0, free_page_start ?
796			buffer_start_page(buffer) : buffer_end_page(buffer),
797			(free_page_end ? buffer_end_page(buffer) :
798			buffer_start_page(buffer)) + PAGE_SIZE, NULL);
799	}
800}
801
802static void binder_free_buf(struct binder_proc *proc,
803			    struct binder_buffer *buffer)
804{
805	size_t size, buffer_size;
806
807	buffer_size = binder_buffer_size(proc, buffer);
808
809	size = ALIGN(buffer->data_size, sizeof(void *)) +
810		ALIGN(buffer->offsets_size, sizeof(void *));
811
812	binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
813		     "%d: binder_free_buf %p size %zd buffer_size %zd\n",
814		      proc->pid, buffer, size, buffer_size);
815
816	BUG_ON(buffer->free);
817	BUG_ON(size > buffer_size);
818	BUG_ON(buffer->transaction != NULL);
819	BUG_ON((void *)buffer < proc->buffer);
820	BUG_ON((void *)buffer > proc->buffer + proc->buffer_size);
821
822	if (buffer->async_transaction) {
823		proc->free_async_space += size + sizeof(struct binder_buffer);
824
825		binder_debug(BINDER_DEBUG_BUFFER_ALLOC_ASYNC,
826			     "%d: binder_free_buf size %zd async free %zd\n",
827			      proc->pid, size, proc->free_async_space);
828	}
829
830	binder_update_page_range(proc, 0,
831		(void *)PAGE_ALIGN((uintptr_t)buffer->data),
832		(void *)(((uintptr_t)buffer->data + buffer_size) & PAGE_MASK),
833		NULL);
834	rb_erase(&buffer->rb_node, &proc->allocated_buffers);
835	buffer->free = 1;
836	if (!list_is_last(&buffer->entry, &proc->buffers)) {
837		struct binder_buffer *next = list_entry(buffer->entry.next,
838						struct binder_buffer, entry);
839		if (next->free) {
840			rb_erase(&next->rb_node, &proc->free_buffers);
841			binder_delete_free_buffer(proc, next);
842		}
843	}
844	if (proc->buffers.next != &buffer->entry) {
845		struct binder_buffer *prev = list_entry(buffer->entry.prev,
846						struct binder_buffer, entry);
847		if (prev->free) {
848			binder_delete_free_buffer(proc, buffer);
849			rb_erase(&prev->rb_node, &proc->free_buffers);
850			buffer = prev;
851		}
852	}
853	binder_insert_free_buffer(proc, buffer);
854}
855
856static struct binder_node *binder_get_node(struct binder_proc *proc,
857					   void __user *ptr)
858{
859	struct rb_node *n = proc->nodes.rb_node;
860	struct binder_node *node;
861
862	while (n) {
863		node = rb_entry(n, struct binder_node, rb_node);
864
865		if (ptr < node->ptr)
866			n = n->rb_left;
867		else if (ptr > node->ptr)
868			n = n->rb_right;
869		else
870			return node;
871	}
872	return NULL;
873}
874
875static struct binder_node *binder_new_node(struct binder_proc *proc,
876					   void __user *ptr,
877					   void __user *cookie)
878{
879	struct rb_node **p = &proc->nodes.rb_node;
880	struct rb_node *parent = NULL;
881	struct binder_node *node;
882
883	while (*p) {
884		parent = *p;
885		node = rb_entry(parent, struct binder_node, rb_node);
886
887		if (ptr < node->ptr)
888			p = &(*p)->rb_left;
889		else if (ptr > node->ptr)
890			p = &(*p)->rb_right;
891		else
892			return NULL;
893	}
894
895	node = kzalloc(sizeof(*node), GFP_KERNEL);
896	if (node == NULL)
897		return NULL;
898	binder_stats_created(BINDER_STAT_NODE);
899	rb_link_node(&node->rb_node, parent, p);
900	rb_insert_color(&node->rb_node, &proc->nodes);
901	node->debug_id = ++binder_last_id;
902	node->proc = proc;
903	node->ptr = ptr;
904	node->cookie = cookie;
905	node->work.type = BINDER_WORK_NODE;
906	INIT_LIST_HEAD(&node->work.entry);
907	INIT_LIST_HEAD(&node->async_todo);
908	binder_debug(BINDER_DEBUG_INTERNAL_REFS,
909		     "%d:%d node %d u%p c%p created\n",
910		     proc->pid, current->pid, node->debug_id,
911		     node->ptr, node->cookie);
912	return node;
913}
914
915static int binder_inc_node(struct binder_node *node, int strong, int internal,
916			   struct list_head *target_list)
917{
918	if (strong) {
919		if (internal) {
920			if (target_list == NULL &&
921			    node->internal_strong_refs == 0 &&
922			    !(node == binder_context_mgr_node &&
923			    node->has_strong_ref)) {
924				pr_err("invalid inc strong node for %d\n",
925					node->debug_id);
926				return -EINVAL;
927			}
928			node->internal_strong_refs++;
929		} else
930			node->local_strong_refs++;
931		if (!node->has_strong_ref && target_list) {
932			list_del_init(&node->work.entry);
933			list_add_tail(&node->work.entry, target_list);
934		}
935	} else {
936		if (!internal)
937			node->local_weak_refs++;
938		if (!node->has_weak_ref && list_empty(&node->work.entry)) {
939			if (target_list == NULL) {
940				pr_err("invalid inc weak node for %d\n",
941					node->debug_id);
942				return -EINVAL;
943			}
944			list_add_tail(&node->work.entry, target_list);
945		}
946	}
947	return 0;
948}
949
950static int binder_dec_node(struct binder_node *node, int strong, int internal)
951{
952	if (strong) {
953		if (internal)
954			node->internal_strong_refs--;
955		else
956			node->local_strong_refs--;
957		if (node->local_strong_refs || node->internal_strong_refs)
958			return 0;
959	} else {
960		if (!internal)
961			node->local_weak_refs--;
962		if (node->local_weak_refs || !hlist_empty(&node->refs))
963			return 0;
964	}
965	if (node->proc && (node->has_strong_ref || node->has_weak_ref)) {
966		if (list_empty(&node->work.entry)) {
967			list_add_tail(&node->work.entry, &node->proc->todo);
968			wake_up_interruptible(&node->proc->wait);
969		}
970	} else {
971		if (hlist_empty(&node->refs) && !node->local_strong_refs &&
972		    !node->local_weak_refs) {
973			list_del_init(&node->work.entry);
974			if (node->proc) {
975				rb_erase(&node->rb_node, &node->proc->nodes);
976				binder_debug(BINDER_DEBUG_INTERNAL_REFS,
977					     "refless node %d deleted\n",
978					     node->debug_id);
979			} else {
980				hlist_del(&node->dead_node);
981				binder_debug(BINDER_DEBUG_INTERNAL_REFS,
982					     "dead node %d deleted\n",
983					     node->debug_id);
984			}
985			kfree(node);
986			binder_stats_deleted(BINDER_STAT_NODE);
987		}
988	}
989
990	return 0;
991}
992
993
994static struct binder_ref *binder_get_ref(struct binder_proc *proc,
995					 uint32_t desc)
996{
997	struct rb_node *n = proc->refs_by_desc.rb_node;
998	struct binder_ref *ref;
999
1000	while (n) {
1001		ref = rb_entry(n, struct binder_ref, rb_node_desc);
1002
1003		if (desc < ref->desc)
1004			n = n->rb_left;
1005		else if (desc > ref->desc)
1006			n = n->rb_right;
1007		else
1008			return ref;
1009	}
1010	return NULL;
1011}
1012
1013static struct binder_ref *binder_get_ref_for_node(struct binder_proc *proc,
1014						  struct binder_node *node)
1015{
1016	struct rb_node *n;
1017	struct rb_node **p = &proc->refs_by_node.rb_node;
1018	struct rb_node *parent = NULL;
1019	struct binder_ref *ref, *new_ref;
1020
1021	while (*p) {
1022		parent = *p;
1023		ref = rb_entry(parent, struct binder_ref, rb_node_node);
1024
1025		if (node < ref->node)
1026			p = &(*p)->rb_left;
1027		else if (node > ref->node)
1028			p = &(*p)->rb_right;
1029		else
1030			return ref;
1031	}
1032	new_ref = kzalloc(sizeof(*ref), GFP_KERNEL);
1033	if (new_ref == NULL)
1034		return NULL;
1035	binder_stats_created(BINDER_STAT_REF);
1036	new_ref->debug_id = ++binder_last_id;
1037	new_ref->proc = proc;
1038	new_ref->node = node;
1039	rb_link_node(&new_ref->rb_node_node, parent, p);
1040	rb_insert_color(&new_ref->rb_node_node, &proc->refs_by_node);
1041
1042	new_ref->desc = (node == binder_context_mgr_node) ? 0 : 1;
1043	for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {
1044		ref = rb_entry(n, struct binder_ref, rb_node_desc);
1045		if (ref->desc > new_ref->desc)
1046			break;
1047		new_ref->desc = ref->desc + 1;
1048	}
1049
1050	p = &proc->refs_by_desc.rb_node;
1051	while (*p) {
1052		parent = *p;
1053		ref = rb_entry(parent, struct binder_ref, rb_node_desc);
1054
1055		if (new_ref->desc < ref->desc)
1056			p = &(*p)->rb_left;
1057		else if (new_ref->desc > ref->desc)
1058			p = &(*p)->rb_right;
1059		else
1060			BUG();
1061	}
1062	rb_link_node(&new_ref->rb_node_desc, parent, p);
1063	rb_insert_color(&new_ref->rb_node_desc, &proc->refs_by_desc);
1064	if (node) {
1065		hlist_add_head(&new_ref->node_entry, &node->refs);
1066
1067		binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1068			     "%d new ref %d desc %d for node %d\n",
1069			      proc->pid, new_ref->debug_id, new_ref->desc,
1070			      node->debug_id);
1071	} else {
1072		binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1073			     "%d new ref %d desc %d for dead node\n",
1074			      proc->pid, new_ref->debug_id, new_ref->desc);
1075	}
1076	return new_ref;
1077}
1078
1079static void binder_delete_ref(struct binder_ref *ref)
1080{
1081	binder_debug(BINDER_DEBUG_INTERNAL_REFS,
1082		     "%d delete ref %d desc %d for node %d\n",
1083		      ref->proc->pid, ref->debug_id, ref->desc,
1084		      ref->node->debug_id);
1085
1086	rb_erase(&ref->rb_node_desc, &ref->proc->refs_by_desc);
1087	rb_erase(&ref->rb_node_node, &ref->proc->refs_by_node);
1088	if (ref->strong)
1089		binder_dec_node(ref->node, 1, 1);
1090	hlist_del(&ref->node_entry);
1091	binder_dec_node(ref->node, 0, 1);
1092	if (ref->death) {
1093		binder_debug(BINDER_DEBUG_DEAD_BINDER,
1094			     "%d delete ref %d desc %d has death notification\n",
1095			      ref->proc->pid, ref->debug_id, ref->desc);
1096		list_del(&ref->death->work.entry);
1097		kfree(ref->death);
1098		binder_stats_deleted(BINDER_STAT_DEATH);
1099	}
1100	kfree(ref);
1101	binder_stats_deleted(BINDER_STAT_REF);
1102}
1103
1104static int binder_inc_ref(struct binder_ref *ref, int strong,
1105			  struct list_head *target_list)
1106{
1107	int ret;
1108	if (strong) {
1109		if (ref->strong == 0) {
1110			ret = binder_inc_node(ref->node, 1, 1, target_list);
1111			if (ret)
1112				return ret;
1113		}
1114		ref->strong++;
1115	} else {
1116		if (ref->weak == 0) {
1117			ret = binder_inc_node(ref->node, 0, 1, target_list);
1118			if (ret)
1119				return ret;
1120		}
1121		ref->weak++;
1122	}
1123	return 0;
1124}
1125
1126
1127static int binder_dec_ref(struct binder_ref *ref, int strong)
1128{
1129	if (strong) {
1130		if (ref->strong == 0) {
1131			binder_user_error("%d invalid dec strong, ref %d desc %d s %d w %d\n",
1132					  ref->proc->pid, ref->debug_id,
1133					  ref->desc, ref->strong, ref->weak);
1134			return -EINVAL;
1135		}
1136		ref->strong--;
1137		if (ref->strong == 0) {
1138			int ret;
1139			ret = binder_dec_node(ref->node, strong, 1);
1140			if (ret)
1141				return ret;
1142		}
1143	} else {
1144		if (ref->weak == 0) {
1145			binder_user_error("%d invalid dec weak, ref %d desc %d s %d w %d\n",
1146					  ref->proc->pid, ref->debug_id,
1147					  ref->desc, ref->strong, ref->weak);
1148			return -EINVAL;
1149		}
1150		ref->weak--;
1151	}
1152	if (ref->strong == 0 && ref->weak == 0)
1153		binder_delete_ref(ref);
1154	return 0;
1155}
1156
1157static void binder_pop_transaction(struct binder_thread *target_thread,
1158				   struct binder_transaction *t)
1159{
1160	if (target_thread) {
1161		BUG_ON(target_thread->transaction_stack != t);
1162		BUG_ON(target_thread->transaction_stack->from != target_thread);
1163		target_thread->transaction_stack =
1164			target_thread->transaction_stack->from_parent;
1165		t->from = NULL;
1166	}
1167	t->need_reply = 0;
1168	if (t->buffer)
1169		t->buffer->transaction = NULL;
1170	kfree(t);
1171	binder_stats_deleted(BINDER_STAT_TRANSACTION);
1172}
1173
1174static void binder_send_failed_reply(struct binder_transaction *t,
1175				     uint32_t error_code)
1176{
1177	struct binder_thread *target_thread;
1178	BUG_ON(t->flags & TF_ONE_WAY);
1179	while (1) {
1180		target_thread = t->from;
1181		if (target_thread) {
1182			if (target_thread->return_error != BR_OK &&
1183			   target_thread->return_error2 == BR_OK) {
1184				target_thread->return_error2 =
1185					target_thread->return_error;
1186				target_thread->return_error = BR_OK;
1187			}
1188			if (target_thread->return_error == BR_OK) {
1189				binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
1190					     "send failed reply for transaction %d to %d:%d\n",
1191					      t->debug_id, target_thread->proc->pid,
1192					      target_thread->pid);
1193
1194				binder_pop_transaction(target_thread, t);
1195				target_thread->return_error = error_code;
1196				wake_up_interruptible(&target_thread->wait);
1197			} else {
1198				pr_err("reply failed, target thread, %d:%d, has error code %d already\n",
1199					target_thread->proc->pid,
1200					target_thread->pid,
1201					target_thread->return_error);
1202			}
1203			return;
1204		} else {
1205			struct binder_transaction *next = t->from_parent;
1206
1207			binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
1208				     "send failed reply for transaction %d, target dead\n",
1209				     t->debug_id);
1210
1211			binder_pop_transaction(target_thread, t);
1212			if (next == NULL) {
1213				binder_debug(BINDER_DEBUG_DEAD_BINDER,
1214					     "reply failed, no target thread at root\n");
1215				return;
1216			}
1217			t = next;
1218			binder_debug(BINDER_DEBUG_DEAD_BINDER,
1219				     "reply failed, no target thread -- retry %d\n",
1220				      t->debug_id);
1221		}
1222	}
1223}
1224
1225static void binder_transaction_buffer_release(struct binder_proc *proc,
1226					      struct binder_buffer *buffer,
1227					      size_t *failed_at)
1228{
1229	size_t *offp, *off_end;
1230	int debug_id = buffer->debug_id;
1231
1232	binder_debug(BINDER_DEBUG_TRANSACTION,
1233		     "%d buffer release %d, size %zd-%zd, failed at %p\n",
1234		     proc->pid, buffer->debug_id,
1235		     buffer->data_size, buffer->offsets_size, failed_at);
1236
1237	if (buffer->target_node)
1238		binder_dec_node(buffer->target_node, 1, 0);
1239
1240	offp = (size_t *)(buffer->data + ALIGN(buffer->data_size, sizeof(void *)));
1241	if (failed_at)
1242		off_end = failed_at;
1243	else
1244		off_end = (void *)offp + buffer->offsets_size;
1245	for (; offp < off_end; offp++) {
1246		struct flat_binder_object *fp;
1247		if (*offp > buffer->data_size - sizeof(*fp) ||
1248		    buffer->data_size < sizeof(*fp) ||
1249		    !IS_ALIGNED(*offp, sizeof(void *))) {
1250			pr_err("transaction release %d bad offset %zd, size %zd\n",
1251			 debug_id, *offp, buffer->data_size);
1252			continue;
1253		}
1254		fp = (struct flat_binder_object *)(buffer->data + *offp);
1255		switch (fp->type) {
1256		case BINDER_TYPE_BINDER:
1257		case BINDER_TYPE_WEAK_BINDER: {
1258			struct binder_node *node = binder_get_node(proc, fp->binder);
1259			if (node == NULL) {
1260				pr_err("transaction release %d bad node %p\n",
1261					debug_id, fp->binder);
1262				break;
1263			}
1264			binder_debug(BINDER_DEBUG_TRANSACTION,
1265				     "        node %d u%p\n",
1266				     node->debug_id, node->ptr);
1267			binder_dec_node(node, fp->type == BINDER_TYPE_BINDER, 0);
1268		} break;
1269		case BINDER_TYPE_HANDLE:
1270		case BINDER_TYPE_WEAK_HANDLE: {
1271			struct binder_ref *ref = binder_get_ref(proc, fp->handle);
1272			if (ref == NULL) {
1273				pr_err("transaction release %d bad handle %ld\n",
1274				 debug_id, fp->handle);
1275				break;
1276			}
1277			binder_debug(BINDER_DEBUG_TRANSACTION,
1278				     "        ref %d desc %d (node %d)\n",
1279				     ref->debug_id, ref->desc, ref->node->debug_id);
1280			binder_dec_ref(ref, fp->type == BINDER_TYPE_HANDLE);
1281		} break;
1282
1283		case BINDER_TYPE_FD:
1284			binder_debug(BINDER_DEBUG_TRANSACTION,
1285				     "        fd %ld\n", fp->handle);
1286			if (failed_at)
1287				task_close_fd(proc, fp->handle);
1288			break;
1289
1290		default:
1291			pr_err("transaction release %d bad object type %lx\n",
1292				debug_id, fp->type);
1293			break;
1294		}
1295	}
1296}
1297
1298static void binder_transaction(struct binder_proc *proc,
1299			       struct binder_thread *thread,
1300			       struct binder_transaction_data *tr, int reply)
1301{
1302	struct binder_transaction *t;
1303	struct binder_work *tcomplete;
1304	size_t *offp, *off_end;
1305	struct binder_proc *target_proc;
1306	struct binder_thread *target_thread = NULL;
1307	struct binder_node *target_node = NULL;
1308	struct list_head *target_list;
1309	wait_queue_head_t *target_wait;
1310	struct binder_transaction *in_reply_to = NULL;
1311	struct binder_transaction_log_entry *e;
1312	uint32_t return_error;
1313
1314	e = binder_transaction_log_add(&binder_transaction_log);
1315	e->call_type = reply ? 2 : !!(tr->flags & TF_ONE_WAY);
1316	e->from_proc = proc->pid;
1317	e->from_thread = thread->pid;
1318	e->target_handle = tr->target.handle;
1319	e->data_size = tr->data_size;
1320	e->offsets_size = tr->offsets_size;
1321
1322	if (reply) {
1323		in_reply_to = thread->transaction_stack;
1324		if (in_reply_to == NULL) {
1325			binder_user_error("%d:%d got reply transaction with no transaction stack\n",
1326					  proc->pid, thread->pid);
1327			return_error = BR_FAILED_REPLY;
1328			goto err_empty_call_stack;
1329		}
1330		binder_set_nice(in_reply_to->saved_priority);
1331		if (in_reply_to->to_thread != thread) {
1332			binder_user_error("%d:%d got reply transaction with bad transaction stack, transaction %d has target %d:%d\n",
1333				proc->pid, thread->pid, in_reply_to->debug_id,
1334				in_reply_to->to_proc ?
1335				in_reply_to->to_proc->pid : 0,
1336				in_reply_to->to_thread ?
1337				in_reply_to->to_thread->pid : 0);
1338			return_error = BR_FAILED_REPLY;
1339			in_reply_to = NULL;
1340			goto err_bad_call_stack;
1341		}
1342		thread->transaction_stack = in_reply_to->to_parent;
1343		target_thread = in_reply_to->from;
1344		if (target_thread == NULL) {
1345			return_error = BR_DEAD_REPLY;
1346			goto err_dead_binder;
1347		}
1348		if (target_thread->transaction_stack != in_reply_to) {
1349			binder_user_error("%d:%d got reply transaction with bad target transaction stack %d, expected %d\n",
1350				proc->pid, thread->pid,
1351				target_thread->transaction_stack ?
1352				target_thread->transaction_stack->debug_id : 0,
1353				in_reply_to->debug_id);
1354			return_error = BR_FAILED_REPLY;
1355			in_reply_to = NULL;
1356			target_thread = NULL;
1357			goto err_dead_binder;
1358		}
1359		target_proc = target_thread->proc;
1360	} else {
1361		if (tr->target.handle) {
1362			struct binder_ref *ref;
1363			ref = binder_get_ref(proc, tr->target.handle);
1364			if (ref == NULL) {
1365				binder_user_error("%d:%d got transaction to invalid handle\n",
1366					proc->pid, thread->pid);
1367				return_error = BR_FAILED_REPLY;
1368				goto err_invalid_target_handle;
1369			}
1370			target_node = ref->node;
1371		} else {
1372			target_node = binder_context_mgr_node;
1373			if (target_node == NULL) {
1374				return_error = BR_DEAD_REPLY;
1375				goto err_no_context_mgr_node;
1376			}
1377		}
1378		e->to_node = target_node->debug_id;
1379		target_proc = target_node->proc;
1380		if (target_proc == NULL) {
1381			return_error = BR_DEAD_REPLY;
1382			goto err_dead_binder;
1383		}
1384		if (!(tr->flags & TF_ONE_WAY) && thread->transaction_stack) {
1385			struct binder_transaction *tmp;
1386			tmp = thread->transaction_stack;
1387			if (tmp->to_thread != thread) {
1388				binder_user_error("%d:%d got new transaction with bad transaction stack, transaction %d has target %d:%d\n",
1389					proc->pid, thread->pid, tmp->debug_id,
1390					tmp->to_proc ? tmp->to_proc->pid : 0,
1391					tmp->to_thread ?
1392					tmp->to_thread->pid : 0);
1393				return_error = BR_FAILED_REPLY;
1394				goto err_bad_call_stack;
1395			}
1396			while (tmp) {
1397				if (tmp->from && tmp->from->proc == target_proc)
1398					target_thread = tmp->from;
1399				tmp = tmp->from_parent;
1400			}
1401		}
1402	}
1403	if (target_thread) {
1404		e->to_thread = target_thread->pid;
1405		target_list = &target_thread->todo;
1406		target_wait = &target_thread->wait;
1407	} else {
1408		target_list = &target_proc->todo;
1409		target_wait = &target_proc->wait;
1410	}
1411	e->to_proc = target_proc->pid;
1412
1413	/* TODO: reuse incoming transaction for reply */
1414	t = kzalloc(sizeof(*t), GFP_KERNEL);
1415	if (t == NULL) {
1416		return_error = BR_FAILED_REPLY;
1417		goto err_alloc_t_failed;
1418	}
1419	binder_stats_created(BINDER_STAT_TRANSACTION);
1420
1421	tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);
1422	if (tcomplete == NULL) {
1423		return_error = BR_FAILED_REPLY;
1424		goto err_alloc_tcomplete_failed;
1425	}
1426	binder_stats_created(BINDER_STAT_TRANSACTION_COMPLETE);
1427
1428	t->debug_id = ++binder_last_id;
1429	e->debug_id = t->debug_id;
1430
1431	if (reply)
1432		binder_debug(BINDER_DEBUG_TRANSACTION,
1433			     "%d:%d BC_REPLY %d -> %d:%d, data %p-%p size %zd-%zd\n",
1434			     proc->pid, thread->pid, t->debug_id,
1435			     target_proc->pid, target_thread->pid,
1436			     tr->data.ptr.buffer, tr->data.ptr.offsets,
1437			     tr->data_size, tr->offsets_size);
1438	else
1439		binder_debug(BINDER_DEBUG_TRANSACTION,
1440			     "%d:%d BC_TRANSACTION %d -> %d - node %d, data %p-%p size %zd-%zd\n",
1441			     proc->pid, thread->pid, t->debug_id,
1442			     target_proc->pid, target_node->debug_id,
1443			     tr->data.ptr.buffer, tr->data.ptr.offsets,
1444			     tr->data_size, tr->offsets_size);
1445
1446	if (!reply && !(tr->flags & TF_ONE_WAY))
1447		t->from = thread;
1448	else
1449		t->from = NULL;
1450	t->sender_euid = proc->tsk->cred->euid;
1451	t->to_proc = target_proc;
1452	t->to_thread = target_thread;
1453	t->code = tr->code;
1454	t->flags = tr->flags;
1455	t->priority = task_nice(current);
1456
1457	trace_binder_transaction(reply, t, target_node);
1458
1459	t->buffer = binder_alloc_buf(target_proc, tr->data_size,
1460		tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));
1461	if (t->buffer == NULL) {
1462		return_error = BR_FAILED_REPLY;
1463		goto err_binder_alloc_buf_failed;
1464	}
1465	t->buffer->allow_user_free = 0;
1466	t->buffer->debug_id = t->debug_id;
1467	t->buffer->transaction = t;
1468	t->buffer->target_node = target_node;
1469	trace_binder_transaction_alloc_buf(t->buffer);
1470	if (target_node)
1471		binder_inc_node(target_node, 1, 0, NULL);
1472
1473	offp = (size_t *)(t->buffer->data + ALIGN(tr->data_size, sizeof(void *)));
1474
1475	if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) {
1476		binder_user_error("%d:%d got transaction with invalid data ptr\n",
1477				proc->pid, thread->pid);
1478		return_error = BR_FAILED_REPLY;
1479		goto err_copy_data_failed;
1480	}
1481	if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {
1482		binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
1483				proc->pid, thread->pid);
1484		return_error = BR_FAILED_REPLY;
1485		goto err_copy_data_failed;
1486	}
1487	if (!IS_ALIGNED(tr->offsets_size, sizeof(size_t))) {
1488		binder_user_error("%d:%d got transaction with invalid offsets size, %zd\n",
1489				proc->pid, thread->pid, tr->offsets_size);
1490		return_error = BR_FAILED_REPLY;
1491		goto err_bad_offset;
1492	}
1493	off_end = (void *)offp + tr->offsets_size;
1494	for (; offp < off_end; offp++) {
1495		struct flat_binder_object *fp;
1496		if (*offp > t->buffer->data_size - sizeof(*fp) ||
1497		    t->buffer->data_size < sizeof(*fp) ||
1498		    !IS_ALIGNED(*offp, sizeof(void *))) {
1499			binder_user_error("%d:%d got transaction with invalid offset, %zd\n",
1500					proc->pid, thread->pid, *offp);
1501			return_error = BR_FAILED_REPLY;
1502			goto err_bad_offset;
1503		}
1504		fp = (struct flat_binder_object *)(t->buffer->data + *offp);
1505		switch (fp->type) {
1506		case BINDER_TYPE_BINDER:
1507		case BINDER_TYPE_WEAK_BINDER: {
1508			struct binder_ref *ref;
1509			struct binder_node *node = binder_get_node(proc, fp->binder);
1510			if (node == NULL) {
1511				node = binder_new_node(proc, fp->binder, fp->cookie);
1512				if (node == NULL) {
1513					return_error = BR_FAILED_REPLY;
1514					goto err_binder_new_node_failed;
1515				}
1516				node->min_priority = fp->flags & FLAT_BINDER_FLAG_PRIORITY_MASK;
1517				node->accept_fds = !!(fp->flags & FLAT_BINDER_FLAG_ACCEPTS_FDS);
1518			}
1519			if (fp->cookie != node->cookie) {
1520				binder_user_error("%d:%d sending u%p node %d, cookie mismatch %p != %p\n",
1521					proc->pid, thread->pid,
1522					fp->binder, node->debug_id,
1523					fp->cookie, node->cookie);
1524				goto err_binder_get_ref_for_node_failed;
1525			}
1526			ref = binder_get_ref_for_node(target_proc, node);
1527			if (ref == NULL) {
1528				return_error = BR_FAILED_REPLY;
1529				goto err_binder_get_ref_for_node_failed;
1530			}
1531			if (fp->type == BINDER_TYPE_BINDER)
1532				fp->type = BINDER_TYPE_HANDLE;
1533			else
1534				fp->type = BINDER_TYPE_WEAK_HANDLE;
1535			fp->handle = ref->desc;
1536			binder_inc_ref(ref, fp->type == BINDER_TYPE_HANDLE,
1537				       &thread->todo);
1538
1539			trace_binder_transaction_node_to_ref(t, node, ref);
1540			binder_debug(BINDER_DEBUG_TRANSACTION,
1541				     "        node %d u%p -> ref %d desc %d\n",
1542				     node->debug_id, node->ptr, ref->debug_id,
1543				     ref->desc);
1544		} break;
1545		case BINDER_TYPE_HANDLE:
1546		case BINDER_TYPE_WEAK_HANDLE: {
1547			struct binder_ref *ref = binder_get_ref(proc, fp->handle);
1548			if (ref == NULL) {
1549				binder_user_error("%d:%d got transaction with invalid handle, %ld\n",
1550						proc->pid,
1551						thread->pid, fp->handle);
1552				return_error = BR_FAILED_REPLY;
1553				goto err_binder_get_ref_failed;
1554			}
1555			if (ref->node->proc == target_proc) {
1556				if (fp->type == BINDER_TYPE_HANDLE)
1557					fp->type = BINDER_TYPE_BINDER;
1558				else
1559					fp->type = BINDER_TYPE_WEAK_BINDER;
1560				fp->binder = ref->node->ptr;
1561				fp->cookie = ref->node->cookie;
1562				binder_inc_node(ref->node, fp->type == BINDER_TYPE_BINDER, 0, NULL);
1563				trace_binder_transaction_ref_to_node(t, ref);
1564				binder_debug(BINDER_DEBUG_TRANSACTION,
1565					     "        ref %d desc %d -> node %d u%p\n",
1566					     ref->debug_id, ref->desc, ref->node->debug_id,
1567					     ref->node->ptr);
1568			} else {
1569				struct binder_ref *new_ref;
1570				new_ref = binder_get_ref_for_node(target_proc, ref->node);
1571				if (new_ref == NULL) {
1572					return_error = BR_FAILED_REPLY;
1573					goto err_binder_get_ref_for_node_failed;
1574				}
1575				fp->handle = new_ref->desc;
1576				binder_inc_ref(new_ref, fp->type == BINDER_TYPE_HANDLE, NULL);
1577				trace_binder_transaction_ref_to_ref(t, ref,
1578								    new_ref);
1579				binder_debug(BINDER_DEBUG_TRANSACTION,
1580					     "        ref %d desc %d -> ref %d desc %d (node %d)\n",
1581					     ref->debug_id, ref->desc, new_ref->debug_id,
1582					     new_ref->desc, ref->node->debug_id);
1583			}
1584		} break;
1585
1586		case BINDER_TYPE_FD: {
1587			int target_fd;
1588			struct file *file;
1589
1590			if (reply) {
1591				if (!(in_reply_to->flags & TF_ACCEPT_FDS)) {
1592					binder_user_error("%d:%d got reply with fd, %ld, but target does not allow fds\n",
1593						proc->pid, thread->pid, fp->handle);
1594					return_error = BR_FAILED_REPLY;
1595					goto err_fd_not_allowed;
1596				}
1597			} else if (!target_node->accept_fds) {
1598				binder_user_error("%d:%d got transaction with fd, %ld, but target does not allow fds\n",
1599					proc->pid, thread->pid, fp->handle);
1600				return_error = BR_FAILED_REPLY;
1601				goto err_fd_not_allowed;
1602			}
1603
1604			file = fget(fp->handle);
1605			if (file == NULL) {
1606				binder_user_error("%d:%d got transaction with invalid fd, %ld\n",
1607					proc->pid, thread->pid, fp->handle);
1608				return_error = BR_FAILED_REPLY;
1609				goto err_fget_failed;
1610			}
1611			target_fd = task_get_unused_fd_flags(target_proc, O_CLOEXEC);
1612			if (target_fd < 0) {
1613				fput(file);
1614				return_error = BR_FAILED_REPLY;
1615				goto err_get_unused_fd_failed;
1616			}
1617			task_fd_install(target_proc, target_fd, file);
1618			trace_binder_transaction_fd(t, fp->handle, target_fd);
1619			binder_debug(BINDER_DEBUG_TRANSACTION,
1620				     "        fd %ld -> %d\n", fp->handle, target_fd);
1621			/* TODO: fput? */
1622			fp->handle = target_fd;
1623		} break;
1624
1625		default:
1626			binder_user_error("%d:%d got transaction with invalid object type, %lx\n",
1627				proc->pid, thread->pid, fp->type);
1628			return_error = BR_FAILED_REPLY;
1629			goto err_bad_object_type;
1630		}
1631	}
1632	if (reply) {
1633		BUG_ON(t->buffer->async_transaction != 0);
1634		binder_pop_transaction(target_thread, in_reply_to);
1635	} else if (!(t->flags & TF_ONE_WAY)) {
1636		BUG_ON(t->buffer->async_transaction != 0);
1637		t->need_reply = 1;
1638		t->from_parent = thread->transaction_stack;
1639		thread->transaction_stack = t;
1640	} else {
1641		BUG_ON(target_node == NULL);
1642		BUG_ON(t->buffer->async_transaction != 1);
1643		if (target_node->has_async_transaction) {
1644			target_list = &target_node->async_todo;
1645			target_wait = NULL;
1646		} else
1647			target_node->has_async_transaction = 1;
1648	}
1649	t->work.type = BINDER_WORK_TRANSACTION;
1650	list_add_tail(&t->work.entry, target_list);
1651	tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;
1652	list_add_tail(&tcomplete->entry, &thread->todo);
1653	if (target_wait)
1654		wake_up_interruptible(target_wait);
1655	return;
1656
1657err_get_unused_fd_failed:
1658err_fget_failed:
1659err_fd_not_allowed:
1660err_binder_get_ref_for_node_failed:
1661err_binder_get_ref_failed:
1662err_binder_new_node_failed:
1663err_bad_object_type:
1664err_bad_offset:
1665err_copy_data_failed:
1666	trace_binder_transaction_failed_buffer_release(t->buffer);
1667	binder_transaction_buffer_release(target_proc, t->buffer, offp);
1668	t->buffer->transaction = NULL;
1669	binder_free_buf(target_proc, t->buffer);
1670err_binder_alloc_buf_failed:
1671	kfree(tcomplete);
1672	binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
1673err_alloc_tcomplete_failed:
1674	kfree(t);
1675	binder_stats_deleted(BINDER_STAT_TRANSACTION);
1676err_alloc_t_failed:
1677err_bad_call_stack:
1678err_empty_call_stack:
1679err_dead_binder:
1680err_invalid_target_handle:
1681err_no_context_mgr_node:
1682	binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
1683		     "%d:%d transaction failed %d, size %zd-%zd\n",
1684		     proc->pid, thread->pid, return_error,
1685		     tr->data_size, tr->offsets_size);
1686
1687	{
1688		struct binder_transaction_log_entry *fe;
1689		fe = binder_transaction_log_add(&binder_transaction_log_failed);
1690		*fe = *e;
1691	}
1692
1693	BUG_ON(thread->return_error != BR_OK);
1694	if (in_reply_to) {
1695		thread->return_error = BR_TRANSACTION_COMPLETE;
1696		binder_send_failed_reply(in_reply_to, return_error);
1697	} else
1698		thread->return_error = return_error;
1699}
1700
1701int binder_thread_write(struct binder_proc *proc, struct binder_thread *thread,
1702			void __user *buffer, int size, signed long *consumed)
1703{
1704	uint32_t cmd;
1705	void __user *ptr = buffer + *consumed;
1706	void __user *end = buffer + size;
1707
1708	while (ptr < end && thread->return_error == BR_OK) {
1709		if (get_user(cmd, (uint32_t __user *)ptr))
1710			return -EFAULT;
1711		ptr += sizeof(uint32_t);
1712		trace_binder_command(cmd);
1713		if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {
1714			binder_stats.bc[_IOC_NR(cmd)]++;
1715			proc->stats.bc[_IOC_NR(cmd)]++;
1716			thread->stats.bc[_IOC_NR(cmd)]++;
1717		}
1718		switch (cmd) {
1719		case BC_INCREFS:
1720		case BC_ACQUIRE:
1721		case BC_RELEASE:
1722		case BC_DECREFS: {
1723			uint32_t target;
1724			struct binder_ref *ref;
1725			const char *debug_string;
1726
1727			if (get_user(target, (uint32_t __user *)ptr))
1728				return -EFAULT;
1729			ptr += sizeof(uint32_t);
1730			if (target == 0 && binder_context_mgr_node &&
1731			    (cmd == BC_INCREFS || cmd == BC_ACQUIRE)) {
1732				ref = binder_get_ref_for_node(proc,
1733					       binder_context_mgr_node);
1734				if (ref->desc != target) {
1735					binder_user_error("%d:%d tried to acquire reference to desc 0, got %d instead\n",
1736						proc->pid, thread->pid,
1737						ref->desc);
1738				}
1739			} else
1740				ref = binder_get_ref(proc, target);
1741			if (ref == NULL) {
1742				binder_user_error("%d:%d refcount change on invalid ref %d\n",
1743					proc->pid, thread->pid, target);
1744				break;
1745			}
1746			switch (cmd) {
1747			case BC_INCREFS:
1748				debug_string = "IncRefs";
1749				binder_inc_ref(ref, 0, NULL);
1750				break;
1751			case BC_ACQUIRE:
1752				debug_string = "Acquire";
1753				binder_inc_ref(ref, 1, NULL);
1754				break;
1755			case BC_RELEASE:
1756				debug_string = "Release";
1757				binder_dec_ref(ref, 1);
1758				break;
1759			case BC_DECREFS:
1760			default:
1761				debug_string = "DecRefs";
1762				binder_dec_ref(ref, 0);
1763				break;
1764			}
1765			binder_debug(BINDER_DEBUG_USER_REFS,
1766				     "%d:%d %s ref %d desc %d s %d w %d for node %d\n",
1767				     proc->pid, thread->pid, debug_string, ref->debug_id,
1768				     ref->desc, ref->strong, ref->weak, ref->node->debug_id);
1769			break;
1770		}
1771		case BC_INCREFS_DONE:
1772		case BC_ACQUIRE_DONE: {
1773			void __user *node_ptr;
1774			void *cookie;
1775			struct binder_node *node;
1776
1777			if (get_user(node_ptr, (void * __user *)ptr))
1778				return -EFAULT;
1779			ptr += sizeof(void *);
1780			if (get_user(cookie, (void * __user *)ptr))
1781				return -EFAULT;
1782			ptr += sizeof(void *);
1783			node = binder_get_node(proc, node_ptr);
1784			if (node == NULL) {
1785				binder_user_error("%d:%d %s u%p no match\n",
1786					proc->pid, thread->pid,
1787					cmd == BC_INCREFS_DONE ?
1788					"BC_INCREFS_DONE" :
1789					"BC_ACQUIRE_DONE",
1790					node_ptr);
1791				break;
1792			}
1793			if (cookie != node->cookie) {
1794				binder_user_error("%d:%d %s u%p node %d cookie mismatch %p != %p\n",
1795					proc->pid, thread->pid,
1796					cmd == BC_INCREFS_DONE ?
1797					"BC_INCREFS_DONE" : "BC_ACQUIRE_DONE",
1798					node_ptr, node->debug_id,
1799					cookie, node->cookie);
1800				break;
1801			}
1802			if (cmd == BC_ACQUIRE_DONE) {
1803				if (node->pending_strong_ref == 0) {
1804					binder_user_error("%d:%d BC_ACQUIRE_DONE node %d has no pending acquire request\n",
1805						proc->pid, thread->pid,
1806						node->debug_id);
1807					break;
1808				}
1809				node->pending_strong_ref = 0;
1810			} else {
1811				if (node->pending_weak_ref == 0) {
1812					binder_user_error("%d:%d BC_INCREFS_DONE node %d has no pending increfs request\n",
1813						proc->pid, thread->pid,
1814						node->debug_id);
1815					break;
1816				}
1817				node->pending_weak_ref = 0;
1818			}
1819			binder_dec_node(node, cmd == BC_ACQUIRE_DONE, 0);
1820			binder_debug(BINDER_DEBUG_USER_REFS,
1821				     "%d:%d %s node %d ls %d lw %d\n",
1822				     proc->pid, thread->pid,
1823				     cmd == BC_INCREFS_DONE ? "BC_INCREFS_DONE" : "BC_ACQUIRE_DONE",
1824				     node->debug_id, node->local_strong_refs, node->local_weak_refs);
1825			break;
1826		}
1827		case BC_ATTEMPT_ACQUIRE:
1828			pr_err("BC_ATTEMPT_ACQUIRE not supported\n");
1829			return -EINVAL;
1830		case BC_ACQUIRE_RESULT:
1831			pr_err("BC_ACQUIRE_RESULT not supported\n");
1832			return -EINVAL;
1833
1834		case BC_FREE_BUFFER: {
1835			void __user *data_ptr;
1836			struct binder_buffer *buffer;
1837
1838			if (get_user(data_ptr, (void * __user *)ptr))
1839				return -EFAULT;
1840			ptr += sizeof(void *);
1841
1842			buffer = binder_buffer_lookup(proc, data_ptr);
1843			if (buffer == NULL) {
1844				binder_user_error("%d:%d BC_FREE_BUFFER u%p no match\n",
1845					proc->pid, thread->pid, data_ptr);
1846				break;
1847			}
1848			if (!buffer->allow_user_free) {
1849				binder_user_error("%d:%d BC_FREE_BUFFER u%p matched unreturned buffer\n",
1850					proc->pid, thread->pid, data_ptr);
1851				break;
1852			}
1853			binder_debug(BINDER_DEBUG_FREE_BUFFER,
1854				     "%d:%d BC_FREE_BUFFER u%p found buffer %d for %s transaction\n",
1855				     proc->pid, thread->pid, data_ptr, buffer->debug_id,
1856				     buffer->transaction ? "active" : "finished");
1857
1858			if (buffer->transaction) {
1859				buffer->transaction->buffer = NULL;
1860				buffer->transaction = NULL;
1861			}
1862			if (buffer->async_transaction && buffer->target_node) {
1863				BUG_ON(!buffer->target_node->has_async_transaction);
1864				if (list_empty(&buffer->target_node->async_todo))
1865					buffer->target_node->has_async_transaction = 0;
1866				else
1867					list_move_tail(buffer->target_node->async_todo.next, &thread->todo);
1868			}
1869			trace_binder_transaction_buffer_release(buffer);
1870			binder_transaction_buffer_release(proc, buffer, NULL);
1871			binder_free_buf(proc, buffer);
1872			break;
1873		}
1874
1875		case BC_TRANSACTION:
1876		case BC_REPLY: {
1877			struct binder_transaction_data tr;
1878
1879			if (copy_from_user(&tr, ptr, sizeof(tr)))
1880				return -EFAULT;
1881			ptr += sizeof(tr);
1882			binder_transaction(proc, thread, &tr, cmd == BC_REPLY);
1883			break;
1884		}
1885
1886		case BC_REGISTER_LOOPER:
1887			binder_debug(BINDER_DEBUG_THREADS,
1888				     "%d:%d BC_REGISTER_LOOPER\n",
1889				     proc->pid, thread->pid);
1890			if (thread->looper & BINDER_LOOPER_STATE_ENTERED) {
1891				thread->looper |= BINDER_LOOPER_STATE_INVALID;
1892				binder_user_error("%d:%d ERROR: BC_REGISTER_LOOPER called after BC_ENTER_LOOPER\n",
1893					proc->pid, thread->pid);
1894			} else if (proc->requested_threads == 0) {
1895				thread->looper |= BINDER_LOOPER_STATE_INVALID;
1896				binder_user_error("%d:%d ERROR: BC_REGISTER_LOOPER called without request\n",
1897					proc->pid, thread->pid);
1898			} else {
1899				proc->requested_threads--;
1900				proc->requested_threads_started++;
1901			}
1902			thread->looper |= BINDER_LOOPER_STATE_REGISTERED;
1903			break;
1904		case BC_ENTER_LOOPER:
1905			binder_debug(BINDER_DEBUG_THREADS,
1906				     "%d:%d BC_ENTER_LOOPER\n",
1907				     proc->pid, thread->pid);
1908			if (thread->looper & BINDER_LOOPER_STATE_REGISTERED) {
1909				thread->looper |= BINDER_LOOPER_STATE_INVALID;
1910				binder_user_error("%d:%d ERROR: BC_ENTER_LOOPER called after BC_REGISTER_LOOPER\n",
1911					proc->pid, thread->pid);
1912			}
1913			thread->looper |= BINDER_LOOPER_STATE_ENTERED;
1914			break;
1915		case BC_EXIT_LOOPER:
1916			binder_debug(BINDER_DEBUG_THREADS,
1917				     "%d:%d BC_EXIT_LOOPER\n",
1918				     proc->pid, thread->pid);
1919			thread->looper |= BINDER_LOOPER_STATE_EXITED;
1920			break;
1921
1922		case BC_REQUEST_DEATH_NOTIFICATION:
1923		case BC_CLEAR_DEATH_NOTIFICATION: {
1924			uint32_t target;
1925			void __user *cookie;
1926			struct binder_ref *ref;
1927			struct binder_ref_death *death;
1928
1929			if (get_user(target, (uint32_t __user *)ptr))
1930				return -EFAULT;
1931			ptr += sizeof(uint32_t);
1932			if (get_user(cookie, (void __user * __user *)ptr))
1933				return -EFAULT;
1934			ptr += sizeof(void *);
1935			ref = binder_get_ref(proc, target);
1936			if (ref == NULL) {
1937				binder_user_error("%d:%d %s invalid ref %d\n",
1938					proc->pid, thread->pid,
1939					cmd == BC_REQUEST_DEATH_NOTIFICATION ?
1940					"BC_REQUEST_DEATH_NOTIFICATION" :
1941					"BC_CLEAR_DEATH_NOTIFICATION",
1942					target);
1943				break;
1944			}
1945
1946			binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION,
1947				     "%d:%d %s %p ref %d desc %d s %d w %d for node %d\n",
1948				     proc->pid, thread->pid,
1949				     cmd == BC_REQUEST_DEATH_NOTIFICATION ?
1950				     "BC_REQUEST_DEATH_NOTIFICATION" :
1951				     "BC_CLEAR_DEATH_NOTIFICATION",
1952				     cookie, ref->debug_id, ref->desc,
1953				     ref->strong, ref->weak, ref->node->debug_id);
1954
1955			if (cmd == BC_REQUEST_DEATH_NOTIFICATION) {
1956				if (ref->death) {
1957					binder_user_error("%d:%d BC_REQUEST_DEATH_NOTIFICATION death notification already set\n",
1958						proc->pid, thread->pid);
1959					break;
1960				}
1961				death = kzalloc(sizeof(*death), GFP_KERNEL);
1962				if (death == NULL) {
1963					thread->return_error = BR_ERROR;
1964					binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
1965						     "%d:%d BC_REQUEST_DEATH_NOTIFICATION failed\n",
1966						     proc->pid, thread->pid);
1967					break;
1968				}
1969				binder_stats_created(BINDER_STAT_DEATH);
1970				INIT_LIST_HEAD(&death->work.entry);
1971				death->cookie = cookie;
1972				ref->death = death;
1973				if (ref->node->proc == NULL) {
1974					ref->death->work.type = BINDER_WORK_DEAD_BINDER;
1975					if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
1976						list_add_tail(&ref->death->work.entry, &thread->todo);
1977					} else {
1978						list_add_tail(&ref->death->work.entry, &proc->todo);
1979						wake_up_interruptible(&proc->wait);
1980					}
1981				}
1982			} else {
1983				if (ref->death == NULL) {
1984					binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification not active\n",
1985						proc->pid, thread->pid);
1986					break;
1987				}
1988				death = ref->death;
1989				if (death->cookie != cookie) {
1990					binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification cookie mismatch %p != %p\n",
1991						proc->pid, thread->pid,
1992						death->cookie, cookie);
1993					break;
1994				}
1995				ref->death = NULL;
1996				if (list_empty(&death->work.entry)) {
1997					death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION;
1998					if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
1999						list_add_tail(&death->work.entry, &thread->todo);
2000					} else {
2001						list_add_tail(&death->work.entry, &proc->todo);
2002						wake_up_interruptible(&proc->wait);
2003					}
2004				} else {
2005					BUG_ON(death->work.type != BINDER_WORK_DEAD_BINDER);
2006					death->work.type = BINDER_WORK_DEAD_BINDER_AND_CLEAR;
2007				}
2008			}
2009		} break;
2010		case BC_DEAD_BINDER_DONE: {
2011			struct binder_work *w;
2012			void __user *cookie;
2013			struct binder_ref_death *death = NULL;
2014			if (get_user(cookie, (void __user * __user *)ptr))
2015				return -EFAULT;
2016
2017			ptr += sizeof(void *);
2018			list_for_each_entry(w, &proc->delivered_death, entry) {
2019				struct binder_ref_death *tmp_death = container_of(w, struct binder_ref_death, work);
2020				if (tmp_death->cookie == cookie) {
2021					death = tmp_death;
2022					break;
2023				}
2024			}
2025			binder_debug(BINDER_DEBUG_DEAD_BINDER,
2026				     "%d:%d BC_DEAD_BINDER_DONE %p found %p\n",
2027				     proc->pid, thread->pid, cookie, death);
2028			if (death == NULL) {
2029				binder_user_error("%d:%d BC_DEAD_BINDER_DONE %p not found\n",
2030					proc->pid, thread->pid, cookie);
2031				break;
2032			}
2033
2034			list_del_init(&death->work.entry);
2035			if (death->work.type == BINDER_WORK_DEAD_BINDER_AND_CLEAR) {
2036				death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION;
2037				if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
2038					list_add_tail(&death->work.entry, &thread->todo);
2039				} else {
2040					list_add_tail(&death->work.entry, &proc->todo);
2041					wake_up_interruptible(&proc->wait);
2042				}
2043			}
2044		} break;
2045
2046		default:
2047			pr_err("%d:%d unknown command %d\n",
2048			       proc->pid, thread->pid, cmd);
2049			return -EINVAL;
2050		}
2051		*consumed = ptr - buffer;
2052	}
2053	return 0;
2054}
2055
2056void binder_stat_br(struct binder_proc *proc, struct binder_thread *thread,
2057		    uint32_t cmd)
2058{
2059	trace_binder_return(cmd);
2060	if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.br)) {
2061		binder_stats.br[_IOC_NR(cmd)]++;
2062		proc->stats.br[_IOC_NR(cmd)]++;
2063		thread->stats.br[_IOC_NR(cmd)]++;
2064	}
2065}
2066
2067static int binder_has_proc_work(struct binder_proc *proc,
2068				struct binder_thread *thread)
2069{
2070	return !list_empty(&proc->todo) ||
2071		(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN);
2072}
2073
2074static int binder_has_thread_work(struct binder_thread *thread)
2075{
2076	return !list_empty(&thread->todo) || thread->return_error != BR_OK ||
2077		(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN);
2078}
2079
2080static int binder_thread_read(struct binder_proc *proc,
2081			      struct binder_thread *thread,
2082			      void  __user *buffer, int size,
2083			      signed long *consumed, int non_block)
2084{
2085	void __user *ptr = buffer + *consumed;
2086	void __user *end = buffer + size;
2087
2088	int ret = 0;
2089	int wait_for_proc_work;
2090
2091	if (*consumed == 0) {
2092		if (put_user(BR_NOOP, (uint32_t __user *)ptr))
2093			return -EFAULT;
2094		ptr += sizeof(uint32_t);
2095	}
2096
2097retry:
2098	wait_for_proc_work = thread->transaction_stack == NULL &&
2099				list_empty(&thread->todo);
2100
2101	if (thread->return_error != BR_OK && ptr < end) {
2102		if (thread->return_error2 != BR_OK) {
2103			if (put_user(thread->return_error2, (uint32_t __user *)ptr))
2104				return -EFAULT;
2105			ptr += sizeof(uint32_t);
2106			binder_stat_br(proc, thread, thread->return_error2);
2107			if (ptr == end)
2108				goto done;
2109			thread->return_error2 = BR_OK;
2110		}
2111		if (put_user(thread->return_error, (uint32_t __user *)ptr))
2112			return -EFAULT;
2113		ptr += sizeof(uint32_t);
2114		binder_stat_br(proc, thread, thread->return_error);
2115		thread->return_error = BR_OK;
2116		goto done;
2117	}
2118
2119
2120	thread->looper |= BINDER_LOOPER_STATE_WAITING;
2121	if (wait_for_proc_work)
2122		proc->ready_threads++;
2123
2124	binder_unlock(__func__);
2125
2126	trace_binder_wait_for_work(wait_for_proc_work,
2127				   !!thread->transaction_stack,
2128				   !list_empty(&thread->todo));
2129	if (wait_for_proc_work) {
2130		if (!(thread->looper & (BINDER_LOOPER_STATE_REGISTERED |
2131					BINDER_LOOPER_STATE_ENTERED))) {
2132			binder_user_error("%d:%d ERROR: Thread waiting for process work before calling BC_REGISTER_LOOPER or BC_ENTER_LOOPER (state %x)\n",
2133				proc->pid, thread->pid, thread->looper);
2134			wait_event_interruptible(binder_user_error_wait,
2135						 binder_stop_on_user_error < 2);
2136		}
2137		binder_set_nice(proc->default_priority);
2138		if (non_block) {
2139			if (!binder_has_proc_work(proc, thread))
2140				ret = -EAGAIN;
2141		} else
2142			ret = wait_event_interruptible_exclusive(proc->wait, binder_has_proc_work(proc, thread));
2143	} else {
2144		if (non_block) {
2145			if (!binder_has_thread_work(thread))
2146				ret = -EAGAIN;
2147		} else
2148			ret = wait_event_interruptible(thread->wait, binder_has_thread_work(thread));
2149	}
2150
2151	binder_lock(__func__);
2152
2153	if (wait_for_proc_work)
2154		proc->ready_threads--;
2155	thread->looper &= ~BINDER_LOOPER_STATE_WAITING;
2156
2157	if (ret)
2158		return ret;
2159
2160	while (1) {
2161		uint32_t cmd;
2162		struct binder_transaction_data tr;
2163		struct binder_work *w;
2164		struct binder_transaction *t = NULL;
2165
2166		if (!list_empty(&thread->todo))
2167			w = list_first_entry(&thread->todo, struct binder_work, entry);
2168		else if (!list_empty(&proc->todo) && wait_for_proc_work)
2169			w = list_first_entry(&proc->todo, struct binder_work, entry);
2170		else {
2171			if (ptr - buffer == 4 && !(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN)) /* no data added */
2172				goto retry;
2173			break;
2174		}
2175
2176		if (end - ptr < sizeof(tr) + 4)
2177			break;
2178
2179		switch (w->type) {
2180		case BINDER_WORK_TRANSACTION: {
2181			t = container_of(w, struct binder_transaction, work);
2182		} break;
2183		case BINDER_WORK_TRANSACTION_COMPLETE: {
2184			cmd = BR_TRANSACTION_COMPLETE;
2185			if (put_user(cmd, (uint32_t __user *)ptr))
2186				return -EFAULT;
2187			ptr += sizeof(uint32_t);
2188
2189			binder_stat_br(proc, thread, cmd);
2190			binder_debug(BINDER_DEBUG_TRANSACTION_COMPLETE,
2191				     "%d:%d BR_TRANSACTION_COMPLETE\n",
2192				     proc->pid, thread->pid);
2193
2194			list_del(&w->entry);
2195			kfree(w);
2196			binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
2197		} break;
2198		case BINDER_WORK_NODE: {
2199			struct binder_node *node = container_of(w, struct binder_node, work);
2200			uint32_t cmd = BR_NOOP;
2201			const char *cmd_name;
2202			int strong = node->internal_strong_refs || node->local_strong_refs;
2203			int weak = !hlist_empty(&node->refs) || node->local_weak_refs || strong;
2204			if (weak && !node->has_weak_ref) {
2205				cmd = BR_INCREFS;
2206				cmd_name = "BR_INCREFS";
2207				node->has_weak_ref = 1;
2208				node->pending_weak_ref = 1;
2209				node->local_weak_refs++;
2210			} else if (strong && !node->has_strong_ref) {
2211				cmd = BR_ACQUIRE;
2212				cmd_name = "BR_ACQUIRE";
2213				node->has_strong_ref = 1;
2214				node->pending_strong_ref = 1;
2215				node->local_strong_refs++;
2216			} else if (!strong && node->has_strong_ref) {
2217				cmd = BR_RELEASE;
2218				cmd_name = "BR_RELEASE";
2219				node->has_strong_ref = 0;
2220			} else if (!weak && node->has_weak_ref) {
2221				cmd = BR_DECREFS;
2222				cmd_name = "BR_DECREFS";
2223				node->has_weak_ref = 0;
2224			}
2225			if (cmd != BR_NOOP) {
2226				if (put_user(cmd, (uint32_t __user *)ptr))
2227					return -EFAULT;
2228				ptr += sizeof(uint32_t);
2229				if (put_user(node->ptr, (void * __user *)ptr))
2230					return -EFAULT;
2231				ptr += sizeof(void *);
2232				if (put_user(node->cookie, (void * __user *)ptr))
2233					return -EFAULT;
2234				ptr += sizeof(void *);
2235
2236				binder_stat_br(proc, thread, cmd);
2237				binder_debug(BINDER_DEBUG_USER_REFS,
2238					     "%d:%d %s %d u%p c%p\n",
2239					     proc->pid, thread->pid, cmd_name, node->debug_id, node->ptr, node->cookie);
2240			} else {
2241				list_del_init(&w->entry);
2242				if (!weak && !strong) {
2243					binder_debug(BINDER_DEBUG_INTERNAL_REFS,
2244						     "%d:%d node %d u%p c%p deleted\n",
2245						     proc->pid, thread->pid, node->debug_id,
2246						     node->ptr, node->cookie);
2247					rb_erase(&node->rb_node, &proc->nodes);
2248					kfree(node);
2249					binder_stats_deleted(BINDER_STAT_NODE);
2250				} else {
2251					binder_debug(BINDER_DEBUG_INTERNAL_REFS,
2252						     "%d:%d node %d u%p c%p state unchanged\n",
2253						     proc->pid, thread->pid, node->debug_id, node->ptr,
2254						     node->cookie);
2255				}
2256			}
2257		} break;
2258		case BINDER_WORK_DEAD_BINDER:
2259		case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
2260		case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: {
2261			struct binder_ref_death *death;
2262			uint32_t cmd;
2263
2264			death = container_of(w, struct binder_ref_death, work);
2265			if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION)
2266				cmd = BR_CLEAR_DEATH_NOTIFICATION_DONE;
2267			else
2268				cmd = BR_DEAD_BINDER;
2269			if (put_user(cmd, (uint32_t __user *)ptr))
2270				return -EFAULT;
2271			ptr += sizeof(uint32_t);
2272			if (put_user(death->cookie, (void * __user *)ptr))
2273				return -EFAULT;
2274			ptr += sizeof(void *);
2275			binder_stat_br(proc, thread, cmd);
2276			binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION,
2277				     "%d:%d %s %p\n",
2278				      proc->pid, thread->pid,
2279				      cmd == BR_DEAD_BINDER ?
2280				      "BR_DEAD_BINDER" :
2281				      "BR_CLEAR_DEATH_NOTIFICATION_DONE",
2282				      death->cookie);
2283
2284			if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION) {
2285				list_del(&w->entry);
2286				kfree(death);
2287				binder_stats_deleted(BINDER_STAT_DEATH);
2288			} else
2289				list_move(&w->entry, &proc->delivered_death);
2290			if (cmd == BR_DEAD_BINDER)
2291				goto done; /* DEAD_BINDER notifications can cause transactions */
2292		} break;
2293		}
2294
2295		if (!t)
2296			continue;
2297
2298		BUG_ON(t->buffer == NULL);
2299		if (t->buffer->target_node) {
2300			struct binder_node *target_node = t->buffer->target_node;
2301			tr.target.ptr = target_node->ptr;
2302			tr.cookie =  target_node->cookie;
2303			t->saved_priority = task_nice(current);
2304			if (t->priority < target_node->min_priority &&
2305			    !(t->flags & TF_ONE_WAY))
2306				binder_set_nice(t->priority);
2307			else if (!(t->flags & TF_ONE_WAY) ||
2308				 t->saved_priority > target_node->min_priority)
2309				binder_set_nice(target_node->min_priority);
2310			cmd = BR_TRANSACTION;
2311		} else {
2312			tr.target.ptr = NULL;
2313			tr.cookie = NULL;
2314			cmd = BR_REPLY;
2315		}
2316		tr.code = t->code;
2317		tr.flags = t->flags;
2318		tr.sender_euid = from_kuid(current_user_ns(), t->sender_euid);
2319
2320		if (t->from) {
2321			struct task_struct *sender = t->from->proc->tsk;
2322			tr.sender_pid = task_tgid_nr_ns(sender,
2323							current->nsproxy->pid_ns);
2324		} else {
2325			tr.sender_pid = 0;
2326		}
2327
2328		tr.data_size = t->buffer->data_size;
2329		tr.offsets_size = t->buffer->offsets_size;
2330		tr.data.ptr.buffer = (void *)t->buffer->data +
2331					proc->user_buffer_offset;
2332		tr.data.ptr.offsets = tr.data.ptr.buffer +
2333					ALIGN(t->buffer->data_size,
2334					    sizeof(void *));
2335
2336		if (put_user(cmd, (uint32_t __user *)ptr))
2337			return -EFAULT;
2338		ptr += sizeof(uint32_t);
2339		if (copy_to_user(ptr, &tr, sizeof(tr)))
2340			return -EFAULT;
2341		ptr += sizeof(tr);
2342
2343		trace_binder_transaction_received(t);
2344		binder_stat_br(proc, thread, cmd);
2345		binder_debug(BINDER_DEBUG_TRANSACTION,
2346			     "%d:%d %s %d %d:%d, cmd %d size %zd-%zd ptr %p-%p\n",
2347			     proc->pid, thread->pid,
2348			     (cmd == BR_TRANSACTION) ? "BR_TRANSACTION" :
2349			     "BR_REPLY",
2350			     t->debug_id, t->from ? t->from->proc->pid : 0,
2351			     t->from ? t->from->pid : 0, cmd,
2352			     t->buffer->data_size, t->buffer->offsets_size,
2353			     tr.data.ptr.buffer, tr.data.ptr.offsets);
2354
2355		list_del(&t->work.entry);
2356		t->buffer->allow_user_free = 1;
2357		if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {
2358			t->to_parent = thread->transaction_stack;
2359			t->to_thread = thread;
2360			thread->transaction_stack = t;
2361		} else {
2362			t->buffer->transaction = NULL;
2363			kfree(t);
2364			binder_stats_deleted(BINDER_STAT_TRANSACTION);
2365		}
2366		break;
2367	}
2368
2369done:
2370
2371	*consumed = ptr - buffer;
2372	if (proc->requested_threads + proc->ready_threads == 0 &&
2373	    proc->requested_threads_started < proc->max_threads &&
2374	    (thread->looper & (BINDER_LOOPER_STATE_REGISTERED |
2375	     BINDER_LOOPER_STATE_ENTERED)) /* the user-space code fails to */
2376	     /*spawn a new thread if we leave this out */) {
2377		proc->requested_threads++;
2378		binder_debug(BINDER_DEBUG_THREADS,
2379			     "%d:%d BR_SPAWN_LOOPER\n",
2380			     proc->pid, thread->pid);
2381		if (put_user(BR_SPAWN_LOOPER, (uint32_t __user *)buffer))
2382			return -EFAULT;
2383		binder_stat_br(proc, thread, BR_SPAWN_LOOPER);
2384	}
2385	return 0;
2386}
2387
2388static void binder_release_work(struct list_head *list)
2389{
2390	struct binder_work *w;
2391	while (!list_empty(list)) {
2392		w = list_first_entry(list, struct binder_work, entry);
2393		list_del_init(&w->entry);
2394		switch (w->type) {
2395		case BINDER_WORK_TRANSACTION: {
2396			struct binder_transaction *t;
2397
2398			t = container_of(w, struct binder_transaction, work);
2399			if (t->buffer->target_node &&
2400			    !(t->flags & TF_ONE_WAY)) {
2401				binder_send_failed_reply(t, BR_DEAD_REPLY);
2402			} else {
2403				binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
2404					"undelivered transaction %d\n",
2405					t->debug_id);
2406				t->buffer->transaction = NULL;
2407				kfree(t);
2408				binder_stats_deleted(BINDER_STAT_TRANSACTION);
2409			}
2410		} break;
2411		case BINDER_WORK_TRANSACTION_COMPLETE: {
2412			binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
2413				"undelivered TRANSACTION_COMPLETE\n");
2414			kfree(w);
2415			binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);
2416		} break;
2417		case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
2418		case BINDER_WORK_CLEAR_DEATH_NOTIFICATION: {
2419			struct binder_ref_death *death;
2420
2421			death = container_of(w, struct binder_ref_death, work);
2422			binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
2423				"undelivered death notification, %p\n",
2424				death->cookie);
2425			kfree(death);
2426			binder_stats_deleted(BINDER_STAT_DEATH);
2427		} break;
2428		default:
2429			pr_err("unexpected work type, %d, not freed\n",
2430			       w->type);
2431			break;
2432		}
2433	}
2434
2435}
2436
2437static struct binder_thread *binder_get_thread(struct binder_proc *proc)
2438{
2439	struct binder_thread *thread = NULL;
2440	struct rb_node *parent = NULL;
2441	struct rb_node **p = &proc->threads.rb_node;
2442
2443	while (*p) {
2444		parent = *p;
2445		thread = rb_entry(parent, struct binder_thread, rb_node);
2446
2447		if (current->pid < thread->pid)
2448			p = &(*p)->rb_left;
2449		else if (current->pid > thread->pid)
2450			p = &(*p)->rb_right;
2451		else
2452			break;
2453	}
2454	if (*p == NULL) {
2455		thread = kzalloc(sizeof(*thread), GFP_KERNEL);
2456		if (thread == NULL)
2457			return NULL;
2458		binder_stats_created(BINDER_STAT_THREAD);
2459		thread->proc = proc;
2460		thread->pid = current->pid;
2461		init_waitqueue_head(&thread->wait);
2462		INIT_LIST_HEAD(&thread->todo);
2463		rb_link_node(&thread->rb_node, parent, p);
2464		rb_insert_color(&thread->rb_node, &proc->threads);
2465		thread->looper |= BINDER_LOOPER_STATE_NEED_RETURN;
2466		thread->return_error = BR_OK;
2467		thread->return_error2 = BR_OK;
2468	}
2469	return thread;
2470}
2471
2472static int binder_free_thread(struct binder_proc *proc,
2473			      struct binder_thread *thread)
2474{
2475	struct binder_transaction *t;
2476	struct binder_transaction *send_reply = NULL;
2477	int active_transactions = 0;
2478
2479	rb_erase(&thread->rb_node, &proc->threads);
2480	t = thread->transaction_stack;
2481	if (t && t->to_thread == thread)
2482		send_reply = t;
2483	while (t) {
2484		active_transactions++;
2485		binder_debug(BINDER_DEBUG_DEAD_TRANSACTION,
2486			     "release %d:%d transaction %d %s, still active\n",
2487			      proc->pid, thread->pid,
2488			     t->debug_id,
2489			     (t->to_thread == thread) ? "in" : "out");
2490
2491		if (t->to_thread == thread) {
2492			t->to_proc = NULL;
2493			t->to_thread = NULL;
2494			if (t->buffer) {
2495				t->buffer->transaction = NULL;
2496				t->buffer = NULL;
2497			}
2498			t = t->to_parent;
2499		} else if (t->from == thread) {
2500			t->from = NULL;
2501			t = t->from_parent;
2502		} else
2503			BUG();
2504	}
2505	if (send_reply)
2506		binder_send_failed_reply(send_reply, BR_DEAD_REPLY);
2507	binder_release_work(&thread->todo);
2508	kfree(thread);
2509	binder_stats_deleted(BINDER_STAT_THREAD);
2510	return active_transactions;
2511}
2512
2513static unsigned int binder_poll(struct file *filp,
2514				struct poll_table_struct *wait)
2515{
2516	struct binder_proc *proc = filp->private_data;
2517	struct binder_thread *thread = NULL;
2518	int wait_for_proc_work;
2519
2520	binder_lock(__func__);
2521
2522	thread = binder_get_thread(proc);
2523
2524	wait_for_proc_work = thread->transaction_stack == NULL &&
2525		list_empty(&thread->todo) && thread->return_error == BR_OK;
2526
2527	binder_unlock(__func__);
2528
2529	if (wait_for_proc_work) {
2530		if (binder_has_proc_work(proc, thread))
2531			return POLLIN;
2532		poll_wait(filp, &proc->wait, wait);
2533		if (binder_has_proc_work(proc, thread))
2534			return POLLIN;
2535	} else {
2536		if (binder_has_thread_work(thread))
2537			return POLLIN;
2538		poll_wait(filp, &thread->wait, wait);
2539		if (binder_has_thread_work(thread))
2540			return POLLIN;
2541	}
2542	return 0;
2543}
2544
2545static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
2546{
2547	int ret;
2548	struct binder_proc *proc = filp->private_data;
2549	struct binder_thread *thread;
2550	unsigned int size = _IOC_SIZE(cmd);
2551	void __user *ubuf = (void __user *)arg;
2552
2553	/*pr_info("binder_ioctl: %d:%d %x %lx\n", proc->pid, current->pid, cmd, arg);*/
2554
2555	trace_binder_ioctl(cmd, arg);
2556
2557	ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
2558	if (ret)
2559		goto err_unlocked;
2560
2561	binder_lock(__func__);
2562	thread = binder_get_thread(proc);
2563	if (thread == NULL) {
2564		ret = -ENOMEM;
2565		goto err;
2566	}
2567
2568	switch (cmd) {
2569	case BINDER_WRITE_READ: {
2570		struct binder_write_read bwr;
2571		if (size != sizeof(struct binder_write_read)) {
2572			ret = -EINVAL;
2573			goto err;
2574		}
2575		if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {
2576			ret = -EFAULT;
2577			goto err;
2578		}
2579		binder_debug(BINDER_DEBUG_READ_WRITE,
2580			     "%d:%d write %ld at %08lx, read %ld at %08lx\n",
2581			     proc->pid, thread->pid, bwr.write_size,
2582			     bwr.write_buffer, bwr.read_size, bwr.read_buffer);
2583
2584		if (bwr.write_size > 0) {
2585			ret = binder_thread_write(proc, thread, (void __user *)bwr.write_buffer, bwr.write_size, &bwr.write_consumed);
2586			trace_binder_write_done(ret);
2587			if (ret < 0) {
2588				bwr.read_consumed = 0;
2589				if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
2590					ret = -EFAULT;
2591				goto err;
2592			}
2593		}
2594		if (bwr.read_size > 0) {
2595			ret = binder_thread_read(proc, thread, (void __user *)bwr.read_buffer, bwr.read_size, &bwr.read_consumed, filp->f_flags & O_NONBLOCK);
2596			trace_binder_read_done(ret);
2597			if (!list_empty(&proc->todo))
2598				wake_up_interruptible(&proc->wait);
2599			if (ret < 0) {
2600				if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
2601					ret = -EFAULT;
2602				goto err;
2603			}
2604		}
2605		binder_debug(BINDER_DEBUG_READ_WRITE,
2606			     "%d:%d wrote %ld of %ld, read return %ld of %ld\n",
2607			     proc->pid, thread->pid, bwr.write_consumed, bwr.write_size,
2608			     bwr.read_consumed, bwr.read_size);
2609		if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
2610			ret = -EFAULT;
2611			goto err;
2612		}
2613		break;
2614	}
2615	case BINDER_SET_MAX_THREADS:
2616		if (copy_from_user(&proc->max_threads, ubuf, sizeof(proc->max_threads))) {
2617			ret = -EINVAL;
2618			goto err;
2619		}
2620		break;
2621	case BINDER_SET_CONTEXT_MGR:
2622		if (binder_context_mgr_node != NULL) {
2623			pr_err("BINDER_SET_CONTEXT_MGR already set\n");
2624			ret = -EBUSY;
2625			goto err;
2626		}
2627		if (uid_valid(binder_context_mgr_uid)) {
2628			if (!uid_eq(binder_context_mgr_uid, current->cred->euid)) {
2629				pr_err("BINDER_SET_CONTEXT_MGR bad uid %d != %d\n",
2630				       from_kuid(&init_user_ns, current->cred->euid),
2631				       from_kuid(&init_user_ns, binder_context_mgr_uid));
2632				ret = -EPERM;
2633				goto err;
2634			}
2635		} else
2636			binder_context_mgr_uid = current->cred->euid;
2637		binder_context_mgr_node = binder_new_node(proc, NULL, NULL);
2638		if (binder_context_mgr_node == NULL) {
2639			ret = -ENOMEM;
2640			goto err;
2641		}
2642		binder_context_mgr_node->local_weak_refs++;
2643		binder_context_mgr_node->local_strong_refs++;
2644		binder_context_mgr_node->has_strong_ref = 1;
2645		binder_context_mgr_node->has_weak_ref = 1;
2646		break;
2647	case BINDER_THREAD_EXIT:
2648		binder_debug(BINDER_DEBUG_THREADS, "%d:%d exit\n",
2649			     proc->pid, thread->pid);
2650		binder_free_thread(proc, thread);
2651		thread = NULL;
2652		break;
2653	case BINDER_VERSION:
2654		if (size != sizeof(struct binder_version)) {
2655			ret = -EINVAL;
2656			goto err;
2657		}
2658		if (put_user(BINDER_CURRENT_PROTOCOL_VERSION, &((struct binder_version *)ubuf)->protocol_version)) {
2659			ret = -EINVAL;
2660			goto err;
2661		}
2662		break;
2663	default:
2664		ret = -EINVAL;
2665		goto err;
2666	}
2667	ret = 0;
2668err:
2669	if (thread)
2670		thread->looper &= ~BINDER_LOOPER_STATE_NEED_RETURN;
2671	binder_unlock(__func__);
2672	wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
2673	if (ret && ret != -ERESTARTSYS)
2674		pr_info("%d:%d ioctl %x %lx returned %d\n", proc->pid, current->pid, cmd, arg, ret);
2675err_unlocked:
2676	trace_binder_ioctl_done(ret);
2677	return ret;
2678}
2679
2680static void binder_vma_open(struct vm_area_struct *vma)
2681{
2682	struct binder_proc *proc = vma->vm_private_data;
2683	binder_debug(BINDER_DEBUG_OPEN_CLOSE,
2684		     "%d open vm area %lx-%lx (%ld K) vma %lx pagep %lx\n",
2685		     proc->pid, vma->vm_start, vma->vm_end,
2686		     (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
2687		     (unsigned long)pgprot_val(vma->vm_page_prot));
2688}
2689
2690static void binder_vma_close(struct vm_area_struct *vma)
2691{
2692	struct binder_proc *proc = vma->vm_private_data;
2693	binder_debug(BINDER_DEBUG_OPEN_CLOSE,
2694		     "%d close vm area %lx-%lx (%ld K) vma %lx pagep %lx\n",
2695		     proc->pid, vma->vm_start, vma->vm_end,
2696		     (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
2697		     (unsigned long)pgprot_val(vma->vm_page_prot));
2698	proc->vma = NULL;
2699	proc->vma_vm_mm = NULL;
2700	binder_defer_work(proc, BINDER_DEFERRED_PUT_FILES);
2701}
2702
2703static struct vm_operations_struct binder_vm_ops = {
2704	.open = binder_vma_open,
2705	.close = binder_vma_close,
2706};
2707
2708static int binder_mmap(struct file *filp, struct vm_area_struct *vma)
2709{
2710	int ret;
2711	struct vm_struct *area;
2712	struct binder_proc *proc = filp->private_data;
2713	const char *failure_string;
2714	struct binder_buffer *buffer;
2715
2716	if (proc->tsk != current)
2717		return -EINVAL;
2718
2719	if ((vma->vm_end - vma->vm_start) > SZ_4M)
2720		vma->vm_end = vma->vm_start + SZ_4M;
2721
2722	binder_debug(BINDER_DEBUG_OPEN_CLOSE,
2723		     "binder_mmap: %d %lx-%lx (%ld K) vma %lx pagep %lx\n",
2724		     proc->pid, vma->vm_start, vma->vm_end,
2725		     (vma->vm_end - vma->vm_start) / SZ_1K, vma->vm_flags,
2726		     (unsigned long)pgprot_val(vma->vm_page_prot));
2727
2728	if (vma->vm_flags & FORBIDDEN_MMAP_FLAGS) {
2729		ret = -EPERM;
2730		failure_string = "bad vm_flags";
2731		goto err_bad_arg;
2732	}
2733	vma->vm_flags = (vma->vm_flags | VM_DONTCOPY) & ~VM_MAYWRITE;
2734
2735	mutex_lock(&binder_mmap_lock);
2736	if (proc->buffer) {
2737		ret = -EBUSY;
2738		failure_string = "already mapped";
2739		goto err_already_mapped;
2740	}
2741
2742	area = get_vm_area(vma->vm_end - vma->vm_start, VM_IOREMAP);
2743	if (area == NULL) {
2744		ret = -ENOMEM;
2745		failure_string = "get_vm_area";
2746		goto err_get_vm_area_failed;
2747	}
2748	proc->buffer = area->addr;
2749	proc->user_buffer_offset = vma->vm_start - (uintptr_t)proc->buffer;
2750	mutex_unlock(&binder_mmap_lock);
2751
2752#ifdef CONFIG_CPU_CACHE_VIPT
2753	if (cache_is_vipt_aliasing()) {
2754		while (CACHE_COLOUR((vma->vm_start ^ (uint32_t)proc->buffer))) {
2755			pr_info("binder_mmap: %d %lx-%lx maps %p bad alignment\n", proc->pid, vma->vm_start, vma->vm_end, proc->buffer);
2756			vma->vm_start += PAGE_SIZE;
2757		}
2758	}
2759#endif
2760	proc->pages = kzalloc(sizeof(proc->pages[0]) * ((vma->vm_end - vma->vm_start) / PAGE_SIZE), GFP_KERNEL);
2761	if (proc->pages == NULL) {
2762		ret = -ENOMEM;
2763		failure_string = "alloc page array";
2764		goto err_alloc_pages_failed;
2765	}
2766	proc->buffer_size = vma->vm_end - vma->vm_start;
2767
2768	vma->vm_ops = &binder_vm_ops;
2769	vma->vm_private_data = proc;
2770
2771	if (binder_update_page_range(proc, 1, proc->buffer, proc->buffer + PAGE_SIZE, vma)) {
2772		ret = -ENOMEM;
2773		failure_string = "alloc small buf";
2774		goto err_alloc_small_buf_failed;
2775	}
2776	buffer = proc->buffer;
2777	INIT_LIST_HEAD(&proc->buffers);
2778	list_add(&buffer->entry, &proc->buffers);
2779	buffer->free = 1;
2780	binder_insert_free_buffer(proc, buffer);
2781	proc->free_async_space = proc->buffer_size / 2;
2782	barrier();
2783	proc->files = get_files_struct(current);
2784	proc->vma = vma;
2785	proc->vma_vm_mm = vma->vm_mm;
2786
2787	/*pr_info("binder_mmap: %d %lx-%lx maps %p\n",
2788		 proc->pid, vma->vm_start, vma->vm_end, proc->buffer);*/
2789	return 0;
2790
2791err_alloc_small_buf_failed:
2792	kfree(proc->pages);
2793	proc->pages = NULL;
2794err_alloc_pages_failed:
2795	mutex_lock(&binder_mmap_lock);
2796	vfree(proc->buffer);
2797	proc->buffer = NULL;
2798err_get_vm_area_failed:
2799err_already_mapped:
2800	mutex_unlock(&binder_mmap_lock);
2801err_bad_arg:
2802	pr_err("binder_mmap: %d %lx-%lx %s failed %d\n",
2803	       proc->pid, vma->vm_start, vma->vm_end, failure_string, ret);
2804	return ret;
2805}
2806
2807static int binder_open(struct inode *nodp, struct file *filp)
2808{
2809	struct binder_proc *proc;
2810
2811	binder_debug(BINDER_DEBUG_OPEN_CLOSE, "binder_open: %d:%d\n",
2812		     current->group_leader->pid, current->pid);
2813
2814	proc = kzalloc(sizeof(*proc), GFP_KERNEL);
2815	if (proc == NULL)
2816		return -ENOMEM;
2817	get_task_struct(current);
2818	proc->tsk = current;
2819	INIT_LIST_HEAD(&proc->todo);
2820	init_waitqueue_head(&proc->wait);
2821	proc->default_priority = task_nice(current);
2822
2823	binder_lock(__func__);
2824
2825	binder_stats_created(BINDER_STAT_PROC);
2826	hlist_add_head(&proc->proc_node, &binder_procs);
2827	proc->pid = current->group_leader->pid;
2828	INIT_LIST_HEAD(&proc->delivered_death);
2829	filp->private_data = proc;
2830
2831	binder_unlock(__func__);
2832
2833	if (binder_debugfs_dir_entry_proc) {
2834		char strbuf[11];
2835		snprintf(strbuf, sizeof(strbuf), "%u", proc->pid);
2836		proc->debugfs_entry = debugfs_create_file(strbuf, S_IRUGO,
2837			binder_debugfs_dir_entry_proc, proc, &binder_proc_fops);
2838	}
2839
2840	return 0;
2841}
2842
2843static int binder_flush(struct file *filp, fl_owner_t id)
2844{
2845	struct binder_proc *proc = filp->private_data;
2846
2847	binder_defer_work(proc, BINDER_DEFERRED_FLUSH);
2848
2849	return 0;
2850}
2851
2852static void binder_deferred_flush(struct binder_proc *proc)
2853{
2854	struct rb_node *n;
2855	int wake_count = 0;
2856	for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n)) {
2857		struct binder_thread *thread = rb_entry(n, struct binder_thread, rb_node);
2858		thread->looper |= BINDER_LOOPER_STATE_NEED_RETURN;
2859		if (thread->looper & BINDER_LOOPER_STATE_WAITING) {
2860			wake_up_interruptible(&thread->wait);
2861			wake_count++;
2862		}
2863	}
2864	wake_up_interruptible_all(&proc->wait);
2865
2866	binder_debug(BINDER_DEBUG_OPEN_CLOSE,
2867		     "binder_flush: %d woke %d threads\n", proc->pid,
2868		     wake_count);
2869}
2870
2871static int binder_release(struct inode *nodp, struct file *filp)
2872{
2873	struct binder_proc *proc = filp->private_data;
2874	debugfs_remove(proc->debugfs_entry);
2875	binder_defer_work(proc, BINDER_DEFERRED_RELEASE);
2876
2877	return 0;
2878}
2879
2880static void binder_deferred_release(struct binder_proc *proc)
2881{
2882	struct hlist_node *pos;
2883	struct binder_transaction *t;
2884	struct rb_node *n;
2885	int threads, nodes, incoming_refs, outgoing_refs, buffers, active_transactions, page_count;
2886
2887	BUG_ON(proc->vma);
2888	BUG_ON(proc->files);
2889
2890	hlist_del(&proc->proc_node);
2891	if (binder_context_mgr_node && binder_context_mgr_node->proc == proc) {
2892		binder_debug(BINDER_DEBUG_DEAD_BINDER,
2893			     "binder_release: %d context_mgr_node gone\n",
2894			     proc->pid);
2895		binder_context_mgr_node = NULL;
2896	}
2897
2898	threads = 0;
2899	active_transactions = 0;
2900	while ((n = rb_first(&proc->threads))) {
2901		struct binder_thread *thread = rb_entry(n, struct binder_thread, rb_node);
2902		threads++;
2903		active_transactions += binder_free_thread(proc, thread);
2904	}
2905	nodes = 0;
2906	incoming_refs = 0;
2907	while ((n = rb_first(&proc->nodes))) {
2908		struct binder_node *node = rb_entry(n, struct binder_node, rb_node);
2909
2910		nodes++;
2911		rb_erase(&node->rb_node, &proc->nodes);
2912		list_del_init(&node->work.entry);
2913		binder_release_work(&node->async_todo);
2914		if (hlist_empty(&node->refs)) {
2915			kfree(node);
2916			binder_stats_deleted(BINDER_STAT_NODE);
2917		} else {
2918			struct binder_ref *ref;
2919			int death = 0;
2920
2921			node->proc = NULL;
2922			node->local_strong_refs = 0;
2923			node->local_weak_refs = 0;
2924			hlist_add_head(&node->dead_node, &binder_dead_nodes);
2925
2926			hlist_for_each_entry(ref, pos, &node->refs, node_entry) {
2927				incoming_refs++;
2928				if (ref->death) {
2929					death++;
2930					if (list_empty(&ref->death->work.entry)) {
2931						ref->death->work.type = BINDER_WORK_DEAD_BINDER;
2932						list_add_tail(&ref->death->work.entry, &ref->proc->todo);
2933						wake_up_interruptible(&ref->proc->wait);
2934					} else
2935						BUG();
2936				}
2937			}
2938			binder_debug(BINDER_DEBUG_DEAD_BINDER,
2939				     "node %d now dead, refs %d, death %d\n",
2940				      node->debug_id, incoming_refs, death);
2941		}
2942	}
2943	outgoing_refs = 0;
2944	while ((n = rb_first(&proc->refs_by_desc))) {
2945		struct binder_ref *ref = rb_entry(n, struct binder_ref,
2946						  rb_node_desc);
2947		outgoing_refs++;
2948		binder_delete_ref(ref);
2949	}
2950	binder_release_work(&proc->todo);
2951	binder_release_work(&proc->delivered_death);
2952	buffers = 0;
2953
2954	while ((n = rb_first(&proc->allocated_buffers))) {
2955		struct binder_buffer *buffer = rb_entry(n, struct binder_buffer,
2956							rb_node);
2957		t = buffer->transaction;
2958		if (t) {
2959			t->buffer = NULL;
2960			buffer->transaction = NULL;
2961			pr_err("release proc %d, transaction %d, not freed\n",
2962			       proc->pid, t->debug_id);
2963			/*BUG();*/
2964		}
2965		binder_free_buf(proc, buffer);
2966		buffers++;
2967	}
2968
2969	binder_stats_deleted(BINDER_STAT_PROC);
2970
2971	page_count = 0;
2972	if (proc->pages) {
2973		int i;
2974		for (i = 0; i < proc->buffer_size / PAGE_SIZE; i++) {
2975			if (proc->pages[i]) {
2976				void *page_addr = proc->buffer + i * PAGE_SIZE;
2977				binder_debug(BINDER_DEBUG_BUFFER_ALLOC,
2978					     "binder_release: %d: page %d at %p not freed\n",
2979					     proc->pid, i,
2980					     page_addr);
2981				unmap_kernel_range((unsigned long)page_addr,
2982					PAGE_SIZE);
2983				__free_page(proc->pages[i]);
2984				page_count++;
2985			}
2986		}
2987		kfree(proc->pages);
2988		vfree(proc->buffer);
2989	}
2990
2991	put_task_struct(proc->tsk);
2992
2993	binder_debug(BINDER_DEBUG_OPEN_CLOSE,
2994		     "binder_release: %d threads %d, nodes %d (ref %d), refs %d, active transactions %d, buffers %d, pages %d\n",
2995		     proc->pid, threads, nodes, incoming_refs, outgoing_refs,
2996		     active_transactions, buffers, page_count);
2997
2998	kfree(proc);
2999}
3000
3001static void binder_deferred_func(struct work_struct *work)
3002{
3003	struct binder_proc *proc;
3004	struct files_struct *files;
3005
3006	int defer;
3007	do {
3008		binder_lock(__func__);
3009		mutex_lock(&binder_deferred_lock);
3010		if (!hlist_empty(&binder_deferred_list)) {
3011			proc = hlist_entry(binder_deferred_list.first,
3012					struct binder_proc, deferred_work_node);
3013			hlist_del_init(&proc->deferred_work_node);
3014			defer = proc->deferred_work;
3015			proc->deferred_work = 0;
3016		} else {
3017			proc = NULL;
3018			defer = 0;
3019		}
3020		mutex_unlock(&binder_deferred_lock);
3021
3022		files = NULL;
3023		if (defer & BINDER_DEFERRED_PUT_FILES) {
3024			files = proc->files;
3025			if (files)
3026				proc->files = NULL;
3027		}
3028
3029		if (defer & BINDER_DEFERRED_FLUSH)
3030			binder_deferred_flush(proc);
3031
3032		if (defer & BINDER_DEFERRED_RELEASE)
3033			binder_deferred_release(proc); /* frees proc */
3034
3035		binder_unlock(__func__);
3036		if (files)
3037			put_files_struct(files);
3038	} while (proc);
3039}
3040static DECLARE_WORK(binder_deferred_work, binder_deferred_func);
3041
3042static void
3043binder_defer_work(struct binder_proc *proc, enum binder_deferred_state defer)
3044{
3045	mutex_lock(&binder_deferred_lock);
3046	proc->deferred_work |= defer;
3047	if (hlist_unhashed(&proc->deferred_work_node)) {
3048		hlist_add_head(&proc->deferred_work_node,
3049				&binder_deferred_list);
3050		queue_work(binder_deferred_workqueue, &binder_deferred_work);
3051	}
3052	mutex_unlock(&binder_deferred_lock);
3053}
3054
3055static void print_binder_transaction(struct seq_file *m, const char *prefix,
3056				     struct binder_transaction *t)
3057{
3058	seq_printf(m,
3059		   "%s %d: %p from %d:%d to %d:%d code %x flags %x pri %ld r%d",
3060		   prefix, t->debug_id, t,
3061		   t->from ? t->from->proc->pid : 0,
3062		   t->from ? t->from->pid : 0,
3063		   t->to_proc ? t->to_proc->pid : 0,
3064		   t->to_thread ? t->to_thread->pid : 0,
3065		   t->code, t->flags, t->priority, t->need_reply);
3066	if (t->buffer == NULL) {
3067		seq_puts(m, " buffer free\n");
3068		return;
3069	}
3070	if (t->buffer->target_node)
3071		seq_printf(m, " node %d",
3072			   t->buffer->target_node->debug_id);
3073	seq_printf(m, " size %zd:%zd data %p\n",
3074		   t->buffer->data_size, t->buffer->offsets_size,
3075		   t->buffer->data);
3076}
3077
3078static void print_binder_buffer(struct seq_file *m, const char *prefix,
3079				struct binder_buffer *buffer)
3080{
3081	seq_printf(m, "%s %d: %p size %zd:%zd %s\n",
3082		   prefix, buffer->debug_id, buffer->data,
3083		   buffer->data_size, buffer->offsets_size,
3084		   buffer->transaction ? "active" : "delivered");
3085}
3086
3087static void print_binder_work(struct seq_file *m, const char *prefix,
3088			      const char *transaction_prefix,
3089			      struct binder_work *w)
3090{
3091	struct binder_node *node;
3092	struct binder_transaction *t;
3093
3094	switch (w->type) {
3095	case BINDER_WORK_TRANSACTION:
3096		t = container_of(w, struct binder_transaction, work);
3097		print_binder_transaction(m, transaction_prefix, t);
3098		break;
3099	case BINDER_WORK_TRANSACTION_COMPLETE:
3100		seq_printf(m, "%stransaction complete\n", prefix);
3101		break;
3102	case BINDER_WORK_NODE:
3103		node = container_of(w, struct binder_node, work);
3104		seq_printf(m, "%snode work %d: u%p c%p\n",
3105			   prefix, node->debug_id, node->ptr, node->cookie);
3106		break;
3107	case BINDER_WORK_DEAD_BINDER:
3108		seq_printf(m, "%shas dead binder\n", prefix);
3109		break;
3110	case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
3111		seq_printf(m, "%shas cleared dead binder\n", prefix);
3112		break;
3113	case BINDER_WORK_CLEAR_DEATH_NOTIFICATION:
3114		seq_printf(m, "%shas cleared death notification\n", prefix);
3115		break;
3116	default:
3117		seq_printf(m, "%sunknown work: type %d\n", prefix, w->type);
3118		break;
3119	}
3120}
3121
3122static void print_binder_thread(struct seq_file *m,
3123				struct binder_thread *thread,
3124				int print_always)
3125{
3126	struct binder_transaction *t;
3127	struct binder_work *w;
3128	size_t start_pos = m->count;
3129	size_t header_pos;
3130
3131	seq_printf(m, "  thread %d: l %02x\n", thread->pid, thread->looper);
3132	header_pos = m->count;
3133	t = thread->transaction_stack;
3134	while (t) {
3135		if (t->from == thread) {
3136			print_binder_transaction(m,
3137						 "    outgoing transaction", t);
3138			t = t->from_parent;
3139		} else if (t->to_thread == thread) {
3140			print_binder_transaction(m,
3141						 "    incoming transaction", t);
3142			t = t->to_parent;
3143		} else {
3144			print_binder_transaction(m, "    bad transaction", t);
3145			t = NULL;
3146		}
3147	}
3148	list_for_each_entry(w, &thread->todo, entry) {
3149		print_binder_work(m, "    ", "    pending transaction", w);
3150	}
3151	if (!print_always && m->count == header_pos)
3152		m->count = start_pos;
3153}
3154
3155static void print_binder_node(struct seq_file *m, struct binder_node *node)
3156{
3157	struct binder_ref *ref;
3158	struct hlist_node *pos;
3159	struct binder_work *w;
3160	int count;
3161
3162	count = 0;
3163	hlist_for_each_entry(ref, pos, &node->refs, node_entry)
3164		count++;
3165
3166	seq_printf(m, "  node %d: u%p c%p hs %d hw %d ls %d lw %d is %d iw %d",
3167		   node->debug_id, node->ptr, node->cookie,
3168		   node->has_strong_ref, node->has_weak_ref,
3169		   node->local_strong_refs, node->local_weak_refs,
3170		   node->internal_strong_refs, count);
3171	if (count) {
3172		seq_puts(m, " proc");
3173		hlist_for_each_entry(ref, pos, &node->refs, node_entry)
3174			seq_printf(m, " %d", ref->proc->pid);
3175	}
3176	seq_puts(m, "\n");
3177	list_for_each_entry(w, &node->async_todo, entry)
3178		print_binder_work(m, "    ",
3179				  "    pending async transaction", w);
3180}
3181
3182static void print_binder_ref(struct seq_file *m, struct binder_ref *ref)
3183{
3184	seq_printf(m, "  ref %d: desc %d %snode %d s %d w %d d %p\n",
3185		   ref->debug_id, ref->desc, ref->node->proc ? "" : "dead ",
3186		   ref->node->debug_id, ref->strong, ref->weak, ref->death);
3187}
3188
3189static void print_binder_proc(struct seq_file *m,
3190			      struct binder_proc *proc, int print_all)
3191{
3192	struct binder_work *w;
3193	struct rb_node *n;
3194	size_t start_pos = m->count;
3195	size_t header_pos;
3196
3197	seq_printf(m, "proc %d\n", proc->pid);
3198	header_pos = m->count;
3199
3200	for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n))
3201		print_binder_thread(m, rb_entry(n, struct binder_thread,
3202						rb_node), print_all);
3203	for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n)) {
3204		struct binder_node *node = rb_entry(n, struct binder_node,
3205						    rb_node);
3206		if (print_all || node->has_async_transaction)
3207			print_binder_node(m, node);
3208	}
3209	if (print_all) {
3210		for (n = rb_first(&proc->refs_by_desc);
3211		     n != NULL;
3212		     n = rb_next(n))
3213			print_binder_ref(m, rb_entry(n, struct binder_ref,
3214						     rb_node_desc));
3215	}
3216	for (n = rb_first(&proc->allocated_buffers); n != NULL; n = rb_next(n))
3217		print_binder_buffer(m, "  buffer",
3218				    rb_entry(n, struct binder_buffer, rb_node));
3219	list_for_each_entry(w, &proc->todo, entry)
3220		print_binder_work(m, "  ", "  pending transaction", w);
3221	list_for_each_entry(w, &proc->delivered_death, entry) {
3222		seq_puts(m, "  has delivered dead binder\n");
3223		break;
3224	}
3225	if (!print_all && m->count == header_pos)
3226		m->count = start_pos;
3227}
3228
3229static const char *binder_return_strings[] = {
3230	"BR_ERROR",
3231	"BR_OK",
3232	"BR_TRANSACTION",
3233	"BR_REPLY",
3234	"BR_ACQUIRE_RESULT",
3235	"BR_DEAD_REPLY",
3236	"BR_TRANSACTION_COMPLETE",
3237	"BR_INCREFS",
3238	"BR_ACQUIRE",
3239	"BR_RELEASE",
3240	"BR_DECREFS",
3241	"BR_ATTEMPT_ACQUIRE",
3242	"BR_NOOP",
3243	"BR_SPAWN_LOOPER",
3244	"BR_FINISHED",
3245	"BR_DEAD_BINDER",
3246	"BR_CLEAR_DEATH_NOTIFICATION_DONE",
3247	"BR_FAILED_REPLY"
3248};
3249
3250static const char *binder_command_strings[] = {
3251	"BC_TRANSACTION",
3252	"BC_REPLY",
3253	"BC_ACQUIRE_RESULT",
3254	"BC_FREE_BUFFER",
3255	"BC_INCREFS",
3256	"BC_ACQUIRE",
3257	"BC_RELEASE",
3258	"BC_DECREFS",
3259	"BC_INCREFS_DONE",
3260	"BC_ACQUIRE_DONE",
3261	"BC_ATTEMPT_ACQUIRE",
3262	"BC_REGISTER_LOOPER",
3263	"BC_ENTER_LOOPER",
3264	"BC_EXIT_LOOPER",
3265	"BC_REQUEST_DEATH_NOTIFICATION",
3266	"BC_CLEAR_DEATH_NOTIFICATION",
3267	"BC_DEAD_BINDER_DONE"
3268};
3269
3270static const char *binder_objstat_strings[] = {
3271	"proc",
3272	"thread",
3273	"node",
3274	"ref",
3275	"death",
3276	"transaction",
3277	"transaction_complete"
3278};
3279
3280static void print_binder_stats(struct seq_file *m, const char *prefix,
3281			       struct binder_stats *stats)
3282{
3283	int i;
3284
3285	BUILD_BUG_ON(ARRAY_SIZE(stats->bc) !=
3286		     ARRAY_SIZE(binder_command_strings));
3287	for (i = 0; i < ARRAY_SIZE(stats->bc); i++) {
3288		if (stats->bc[i])
3289			seq_printf(m, "%s%s: %d\n", prefix,
3290				   binder_command_strings[i], stats->bc[i]);
3291	}
3292
3293	BUILD_BUG_ON(ARRAY_SIZE(stats->br) !=
3294		     ARRAY_SIZE(binder_return_strings));
3295	for (i = 0; i < ARRAY_SIZE(stats->br); i++) {
3296		if (stats->br[i])
3297			seq_printf(m, "%s%s: %d\n", prefix,
3298				   binder_return_strings[i], stats->br[i]);
3299	}
3300
3301	BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) !=
3302		     ARRAY_SIZE(binder_objstat_strings));
3303	BUILD_BUG_ON(ARRAY_SIZE(stats->obj_created) !=
3304		     ARRAY_SIZE(stats->obj_deleted));
3305	for (i = 0; i < ARRAY_SIZE(stats->obj_created); i++) {
3306		if (stats->obj_created[i] || stats->obj_deleted[i])
3307			seq_printf(m, "%s%s: active %d total %d\n", prefix,
3308				binder_objstat_strings[i],
3309				stats->obj_created[i] - stats->obj_deleted[i],
3310				stats->obj_created[i]);
3311	}
3312}
3313
3314static void print_binder_proc_stats(struct seq_file *m,
3315				    struct binder_proc *proc)
3316{
3317	struct binder_work *w;
3318	struct rb_node *n;
3319	int count, strong, weak;
3320
3321	seq_printf(m, "proc %d\n", proc->pid);
3322	count = 0;
3323	for (n = rb_first(&proc->threads); n != NULL; n = rb_next(n))
3324		count++;
3325	seq_printf(m, "  threads: %d\n", count);
3326	seq_printf(m, "  requested threads: %d+%d/%d\n"
3327			"  ready threads %d\n"
3328			"  free async space %zd\n", proc->requested_threads,
3329			proc->requested_threads_started, proc->max_threads,
3330			proc->ready_threads, proc->free_async_space);
3331	count = 0;
3332	for (n = rb_first(&proc->nodes); n != NULL; n = rb_next(n))
3333		count++;
3334	seq_printf(m, "  nodes: %d\n", count);
3335	count = 0;
3336	strong = 0;
3337	weak = 0;
3338	for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {
3339		struct binder_ref *ref = rb_entry(n, struct binder_ref,
3340						  rb_node_desc);
3341		count++;
3342		strong += ref->strong;
3343		weak += ref->weak;
3344	}
3345	seq_printf(m, "  refs: %d s %d w %d\n", count, strong, weak);
3346
3347	count = 0;
3348	for (n = rb_first(&proc->allocated_buffers); n != NULL; n = rb_next(n))
3349		count++;
3350	seq_printf(m, "  buffers: %d\n", count);
3351
3352	count = 0;
3353	list_for_each_entry(w, &proc->todo, entry) {
3354		switch (w->type) {
3355		case BINDER_WORK_TRANSACTION:
3356			count++;
3357			break;
3358		default:
3359			break;
3360		}
3361	}
3362	seq_printf(m, "  pending transactions: %d\n", count);
3363
3364	print_binder_stats(m, "  ", &proc->stats);
3365}
3366
3367
3368static int binder_state_show(struct seq_file *m, void *unused)
3369{
3370	struct binder_proc *proc;
3371	struct hlist_node *pos;
3372	struct binder_node *node;
3373	int do_lock = !binder_debug_no_lock;
3374
3375	if (do_lock)
3376		binder_lock(__func__);
3377
3378	seq_puts(m, "binder state:\n");
3379
3380	if (!hlist_empty(&binder_dead_nodes))
3381		seq_puts(m, "dead nodes:\n");
3382	hlist_for_each_entry(node, pos, &binder_dead_nodes, dead_node)
3383		print_binder_node(m, node);
3384
3385	hlist_for_each_entry(proc, pos, &binder_procs, proc_node)
3386		print_binder_proc(m, proc, 1);
3387	if (do_lock)
3388		binder_unlock(__func__);
3389	return 0;
3390}
3391
3392static int binder_stats_show(struct seq_file *m, void *unused)
3393{
3394	struct binder_proc *proc;
3395	struct hlist_node *pos;
3396	int do_lock = !binder_debug_no_lock;
3397
3398	if (do_lock)
3399		binder_lock(__func__);
3400
3401	seq_puts(m, "binder stats:\n");
3402
3403	print_binder_stats(m, "", &binder_stats);
3404
3405	hlist_for_each_entry(proc, pos, &binder_procs, proc_node)
3406		print_binder_proc_stats(m, proc);
3407	if (do_lock)
3408		binder_unlock(__func__);
3409	return 0;
3410}
3411
3412static int binder_transactions_show(struct seq_file *m, void *unused)
3413{
3414	struct binder_proc *proc;
3415	struct hlist_node *pos;
3416	int do_lock = !binder_debug_no_lock;
3417
3418	if (do_lock)
3419		binder_lock(__func__);
3420
3421	seq_puts(m, "binder transactions:\n");
3422	hlist_for_each_entry(proc, pos, &binder_procs, proc_node)
3423		print_binder_proc(m, proc, 0);
3424	if (do_lock)
3425		binder_unlock(__func__);
3426	return 0;
3427}
3428
3429static int binder_proc_show(struct seq_file *m, void *unused)
3430{
3431	struct binder_proc *proc = m->private;
3432	int do_lock = !binder_debug_no_lock;
3433
3434	if (do_lock)
3435		binder_lock(__func__);
3436	seq_puts(m, "binder proc state:\n");
3437	print_binder_proc(m, proc, 1);
3438	if (do_lock)
3439		binder_unlock(__func__);
3440	return 0;
3441}
3442
3443static void print_binder_transaction_log_entry(struct seq_file *m,
3444					struct binder_transaction_log_entry *e)
3445{
3446	seq_printf(m,
3447		   "%d: %s from %d:%d to %d:%d node %d handle %d size %d:%d\n",
3448		   e->debug_id, (e->call_type == 2) ? "reply" :
3449		   ((e->call_type == 1) ? "async" : "call "), e->from_proc,
3450		   e->from_thread, e->to_proc, e->to_thread, e->to_node,
3451		   e->target_handle, e->data_size, e->offsets_size);
3452}
3453
3454static int binder_transaction_log_show(struct seq_file *m, void *unused)
3455{
3456	struct binder_transaction_log *log = m->private;
3457	int i;
3458
3459	if (log->full) {
3460		for (i = log->next; i < ARRAY_SIZE(log->entry); i++)
3461			print_binder_transaction_log_entry(m, &log->entry[i]);
3462	}
3463	for (i = 0; i < log->next; i++)
3464		print_binder_transaction_log_entry(m, &log->entry[i]);
3465	return 0;
3466}
3467
3468static const struct file_operations binder_fops = {
3469	.owner = THIS_MODULE,
3470	.poll = binder_poll,
3471	.unlocked_ioctl = binder_ioctl,
3472	.mmap = binder_mmap,
3473	.open = binder_open,
3474	.flush = binder_flush,
3475	.release = binder_release,
3476};
3477
3478static struct miscdevice binder_miscdev = {
3479	.minor = MISC_DYNAMIC_MINOR,
3480	.name = "binder",
3481	.fops = &binder_fops
3482};
3483
3484BINDER_DEBUG_ENTRY(state);
3485BINDER_DEBUG_ENTRY(stats);
3486BINDER_DEBUG_ENTRY(transactions);
3487BINDER_DEBUG_ENTRY(transaction_log);
3488
3489static int __init binder_init(void)
3490{
3491	int ret;
3492
3493	binder_deferred_workqueue = create_singlethread_workqueue("binder");
3494	if (!binder_deferred_workqueue)
3495		return -ENOMEM;
3496
3497	binder_debugfs_dir_entry_root = debugfs_create_dir("binder", NULL);
3498	if (binder_debugfs_dir_entry_root)
3499		binder_debugfs_dir_entry_proc = debugfs_create_dir("proc",
3500						 binder_debugfs_dir_entry_root);
3501	ret = misc_register(&binder_miscdev);
3502	if (binder_debugfs_dir_entry_root) {
3503		debugfs_create_file("state",
3504				    S_IRUGO,
3505				    binder_debugfs_dir_entry_root,
3506				    NULL,
3507				    &binder_state_fops);
3508		debugfs_create_file("stats",
3509				    S_IRUGO,
3510				    binder_debugfs_dir_entry_root,
3511				    NULL,
3512				    &binder_stats_fops);
3513		debugfs_create_file("transactions",
3514				    S_IRUGO,
3515				    binder_debugfs_dir_entry_root,
3516				    NULL,
3517				    &binder_transactions_fops);
3518		debugfs_create_file("transaction_log",
3519				    S_IRUGO,
3520				    binder_debugfs_dir_entry_root,
3521				    &binder_transaction_log,
3522				    &binder_transaction_log_fops);
3523		debugfs_create_file("failed_transaction_log",
3524				    S_IRUGO,
3525				    binder_debugfs_dir_entry_root,
3526				    &binder_transaction_log_failed,
3527				    &binder_transaction_log_fops);
3528	}
3529	return ret;
3530}
3531
3532device_initcall(binder_init);
3533
3534#define CREATE_TRACE_POINTS
3535#include "binder_trace.h"
3536
3537MODULE_LICENSE("GPL v2");
3538