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