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