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