27b596f14463a397073d4541474fdaf1075e4c49
[linux-2.6-microblaze.git] / kernel / events / uprobes.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * User-space Probes (UProbes)
4  *
5  * Copyright (C) IBM Corporation, 2008-2012
6  * Authors:
7  *      Srikar Dronamraju
8  *      Jim Keniston
9  * Copyright (C) 2011-2012 Red Hat, Inc., Peter Zijlstra
10  */
11
12 #include <linux/kernel.h>
13 #include <linux/highmem.h>
14 #include <linux/pagemap.h>      /* read_mapping_page */
15 #include <linux/slab.h>
16 #include <linux/sched.h>
17 #include <linux/sched/mm.h>
18 #include <linux/sched/coredump.h>
19 #include <linux/export.h>
20 #include <linux/rmap.h>         /* anon_vma_prepare */
21 #include <linux/mmu_notifier.h> /* set_pte_at_notify */
22 #include <linux/swap.h>         /* try_to_free_swap */
23 #include <linux/ptrace.h>       /* user_enable_single_step */
24 #include <linux/kdebug.h>       /* notifier mechanism */
25 #include "../../mm/internal.h"  /* munlock_vma_page */
26 #include <linux/percpu-rwsem.h>
27 #include <linux/task_work.h>
28 #include <linux/shmem_fs.h>
29
30 #include <linux/uprobes.h>
31
32 #define UINSNS_PER_PAGE                 (PAGE_SIZE/UPROBE_XOL_SLOT_BYTES)
33 #define MAX_UPROBE_XOL_SLOTS            UINSNS_PER_PAGE
34
35 static struct rb_root uprobes_tree = RB_ROOT;
36 /*
37  * allows us to skip the uprobe_mmap if there are no uprobe events active
38  * at this time.  Probably a fine grained per inode count is better?
39  */
40 #define no_uprobe_events()      RB_EMPTY_ROOT(&uprobes_tree)
41
42 static DEFINE_SPINLOCK(uprobes_treelock);       /* serialize rbtree access */
43
44 #define UPROBES_HASH_SZ 13
45 /* serialize uprobe->pending_list */
46 static struct mutex uprobes_mmap_mutex[UPROBES_HASH_SZ];
47 #define uprobes_mmap_hash(v)    (&uprobes_mmap_mutex[((unsigned long)(v)) % UPROBES_HASH_SZ])
48
49 DEFINE_STATIC_PERCPU_RWSEM(dup_mmap_sem);
50
51 /* Have a copy of original instruction */
52 #define UPROBE_COPY_INSN        0
53
54 struct uprobe {
55         struct rb_node          rb_node;        /* node in the rb tree */
56         refcount_t              ref;
57         struct rw_semaphore     register_rwsem;
58         struct rw_semaphore     consumer_rwsem;
59         struct list_head        pending_list;
60         struct uprobe_consumer  *consumers;
61         struct inode            *inode;         /* Also hold a ref to inode */
62         loff_t                  offset;
63         loff_t                  ref_ctr_offset;
64         unsigned long           flags;
65
66         /*
67          * The generic code assumes that it has two members of unknown type
68          * owned by the arch-specific code:
69          *
70          *      insn -  copy_insn() saves the original instruction here for
71          *              arch_uprobe_analyze_insn().
72          *
73          *      ixol -  potentially modified instruction to execute out of
74          *              line, copied to xol_area by xol_get_insn_slot().
75          */
76         struct arch_uprobe      arch;
77 };
78
79 struct delayed_uprobe {
80         struct list_head list;
81         struct uprobe *uprobe;
82         struct mm_struct *mm;
83 };
84
85 static DEFINE_MUTEX(delayed_uprobe_lock);
86 static LIST_HEAD(delayed_uprobe_list);
87
88 /*
89  * Execute out of line area: anonymous executable mapping installed
90  * by the probed task to execute the copy of the original instruction
91  * mangled by set_swbp().
92  *
93  * On a breakpoint hit, thread contests for a slot.  It frees the
94  * slot after singlestep. Currently a fixed number of slots are
95  * allocated.
96  */
97 struct xol_area {
98         wait_queue_head_t               wq;             /* if all slots are busy */
99         atomic_t                        slot_count;     /* number of in-use slots */
100         unsigned long                   *bitmap;        /* 0 = free slot */
101
102         struct vm_special_mapping       xol_mapping;
103         struct page                     *pages[2];
104         /*
105          * We keep the vma's vm_start rather than a pointer to the vma
106          * itself.  The probed process or a naughty kernel module could make
107          * the vma go away, and we must handle that reasonably gracefully.
108          */
109         unsigned long                   vaddr;          /* Page(s) of instruction slots */
110 };
111
112 /*
113  * valid_vma: Verify if the specified vma is an executable vma
114  * Relax restrictions while unregistering: vm_flags might have
115  * changed after breakpoint was inserted.
116  *      - is_register: indicates if we are in register context.
117  *      - Return 1 if the specified virtual address is in an
118  *        executable vma.
119  */
120 static bool valid_vma(struct vm_area_struct *vma, bool is_register)
121 {
122         vm_flags_t flags = VM_HUGETLB | VM_MAYEXEC | VM_MAYSHARE;
123
124         if (is_register)
125                 flags |= VM_WRITE;
126
127         return vma->vm_file && (vma->vm_flags & flags) == VM_MAYEXEC;
128 }
129
130 static unsigned long offset_to_vaddr(struct vm_area_struct *vma, loff_t offset)
131 {
132         return vma->vm_start + offset - ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
133 }
134
135 static loff_t vaddr_to_offset(struct vm_area_struct *vma, unsigned long vaddr)
136 {
137         return ((loff_t)vma->vm_pgoff << PAGE_SHIFT) + (vaddr - vma->vm_start);
138 }
139
140 /**
141  * __replace_page - replace page in vma by new page.
142  * based on replace_page in mm/ksm.c
143  *
144  * @vma:      vma that holds the pte pointing to page
145  * @addr:     address the old @page is mapped at
146  * @old_page: the page we are replacing by new_page
147  * @new_page: the modified page we replace page by
148  *
149  * If @new_page is NULL, only unmap @old_page.
150  *
151  * Returns 0 on success, negative error code otherwise.
152  */
153 static int __replace_page(struct vm_area_struct *vma, unsigned long addr,
154                                 struct page *old_page, struct page *new_page)
155 {
156         struct mm_struct *mm = vma->vm_mm;
157         struct page_vma_mapped_walk pvmw = {
158                 .page = compound_head(old_page),
159                 .vma = vma,
160                 .address = addr,
161         };
162         int err;
163         struct mmu_notifier_range range;
164         struct mem_cgroup *memcg;
165
166         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, addr,
167                                 addr + PAGE_SIZE);
168
169         if (new_page) {
170                 err = mem_cgroup_try_charge(new_page, vma->vm_mm, GFP_KERNEL,
171                                             &memcg, false);
172                 if (err)
173                         return err;
174         }
175
176         /* For try_to_free_swap() and munlock_vma_page() below */
177         lock_page(old_page);
178
179         mmu_notifier_invalidate_range_start(&range);
180         err = -EAGAIN;
181         if (!page_vma_mapped_walk(&pvmw)) {
182                 if (new_page)
183                         mem_cgroup_cancel_charge(new_page, memcg, false);
184                 goto unlock;
185         }
186         VM_BUG_ON_PAGE(addr != pvmw.address, old_page);
187
188         if (new_page) {
189                 get_page(new_page);
190                 page_add_new_anon_rmap(new_page, vma, addr, false);
191                 mem_cgroup_commit_charge(new_page, memcg, false, false);
192                 lru_cache_add_active_or_unevictable(new_page, vma);
193         } else
194                 /* no new page, just dec_mm_counter for old_page */
195                 dec_mm_counter(mm, MM_ANONPAGES);
196
197         if (!PageAnon(old_page)) {
198                 dec_mm_counter(mm, mm_counter_file(old_page));
199                 inc_mm_counter(mm, MM_ANONPAGES);
200         }
201
202         flush_cache_page(vma, addr, pte_pfn(*pvmw.pte));
203         ptep_clear_flush_notify(vma, addr, pvmw.pte);
204         if (new_page)
205                 set_pte_at_notify(mm, addr, pvmw.pte,
206                                   mk_pte(new_page, vma->vm_page_prot));
207
208         page_remove_rmap(old_page, false);
209         if (!page_mapped(old_page))
210                 try_to_free_swap(old_page);
211         page_vma_mapped_walk_done(&pvmw);
212
213         if (vma->vm_flags & VM_LOCKED)
214                 munlock_vma_page(old_page);
215         put_page(old_page);
216
217         err = 0;
218  unlock:
219         mmu_notifier_invalidate_range_end(&range);
220         unlock_page(old_page);
221         return err;
222 }
223
224 /**
225  * is_swbp_insn - check if instruction is breakpoint instruction.
226  * @insn: instruction to be checked.
227  * Default implementation of is_swbp_insn
228  * Returns true if @insn is a breakpoint instruction.
229  */
230 bool __weak is_swbp_insn(uprobe_opcode_t *insn)
231 {
232         return *insn == UPROBE_SWBP_INSN;
233 }
234
235 /**
236  * is_trap_insn - check if instruction is breakpoint instruction.
237  * @insn: instruction to be checked.
238  * Default implementation of is_trap_insn
239  * Returns true if @insn is a breakpoint instruction.
240  *
241  * This function is needed for the case where an architecture has multiple
242  * trap instructions (like powerpc).
243  */
244 bool __weak is_trap_insn(uprobe_opcode_t *insn)
245 {
246         return is_swbp_insn(insn);
247 }
248
249 static void copy_from_page(struct page *page, unsigned long vaddr, void *dst, int len)
250 {
251         void *kaddr = kmap_atomic(page);
252         memcpy(dst, kaddr + (vaddr & ~PAGE_MASK), len);
253         kunmap_atomic(kaddr);
254 }
255
256 static void copy_to_page(struct page *page, unsigned long vaddr, const void *src, int len)
257 {
258         void *kaddr = kmap_atomic(page);
259         memcpy(kaddr + (vaddr & ~PAGE_MASK), src, len);
260         kunmap_atomic(kaddr);
261 }
262
263 static int verify_opcode(struct page *page, unsigned long vaddr, uprobe_opcode_t *new_opcode)
264 {
265         uprobe_opcode_t old_opcode;
266         bool is_swbp;
267
268         /*
269          * Note: We only check if the old_opcode is UPROBE_SWBP_INSN here.
270          * We do not check if it is any other 'trap variant' which could
271          * be conditional trap instruction such as the one powerpc supports.
272          *
273          * The logic is that we do not care if the underlying instruction
274          * is a trap variant; uprobes always wins over any other (gdb)
275          * breakpoint.
276          */
277         copy_from_page(page, vaddr, &old_opcode, UPROBE_SWBP_INSN_SIZE);
278         is_swbp = is_swbp_insn(&old_opcode);
279
280         if (is_swbp_insn(new_opcode)) {
281                 if (is_swbp)            /* register: already installed? */
282                         return 0;
283         } else {
284                 if (!is_swbp)           /* unregister: was it changed by us? */
285                         return 0;
286         }
287
288         return 1;
289 }
290
291 static struct delayed_uprobe *
292 delayed_uprobe_check(struct uprobe *uprobe, struct mm_struct *mm)
293 {
294         struct delayed_uprobe *du;
295
296         list_for_each_entry(du, &delayed_uprobe_list, list)
297                 if (du->uprobe == uprobe && du->mm == mm)
298                         return du;
299         return NULL;
300 }
301
302 static int delayed_uprobe_add(struct uprobe *uprobe, struct mm_struct *mm)
303 {
304         struct delayed_uprobe *du;
305
306         if (delayed_uprobe_check(uprobe, mm))
307                 return 0;
308
309         du  = kzalloc(sizeof(*du), GFP_KERNEL);
310         if (!du)
311                 return -ENOMEM;
312
313         du->uprobe = uprobe;
314         du->mm = mm;
315         list_add(&du->list, &delayed_uprobe_list);
316         return 0;
317 }
318
319 static void delayed_uprobe_delete(struct delayed_uprobe *du)
320 {
321         if (WARN_ON(!du))
322                 return;
323         list_del(&du->list);
324         kfree(du);
325 }
326
327 static void delayed_uprobe_remove(struct uprobe *uprobe, struct mm_struct *mm)
328 {
329         struct list_head *pos, *q;
330         struct delayed_uprobe *du;
331
332         if (!uprobe && !mm)
333                 return;
334
335         list_for_each_safe(pos, q, &delayed_uprobe_list) {
336                 du = list_entry(pos, struct delayed_uprobe, list);
337
338                 if (uprobe && du->uprobe != uprobe)
339                         continue;
340                 if (mm && du->mm != mm)
341                         continue;
342
343                 delayed_uprobe_delete(du);
344         }
345 }
346
347 static bool valid_ref_ctr_vma(struct uprobe *uprobe,
348                               struct vm_area_struct *vma)
349 {
350         unsigned long vaddr = offset_to_vaddr(vma, uprobe->ref_ctr_offset);
351
352         return uprobe->ref_ctr_offset &&
353                 vma->vm_file &&
354                 file_inode(vma->vm_file) == uprobe->inode &&
355                 (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
356                 vma->vm_start <= vaddr &&
357                 vma->vm_end > vaddr;
358 }
359
360 static struct vm_area_struct *
361 find_ref_ctr_vma(struct uprobe *uprobe, struct mm_struct *mm)
362 {
363         struct vm_area_struct *tmp;
364
365         for (tmp = mm->mmap; tmp; tmp = tmp->vm_next)
366                 if (valid_ref_ctr_vma(uprobe, tmp))
367                         return tmp;
368
369         return NULL;
370 }
371
372 static int
373 __update_ref_ctr(struct mm_struct *mm, unsigned long vaddr, short d)
374 {
375         void *kaddr;
376         struct page *page;
377         struct vm_area_struct *vma;
378         int ret;
379         short *ptr;
380
381         if (!vaddr || !d)
382                 return -EINVAL;
383
384         ret = get_user_pages_remote(NULL, mm, vaddr, 1,
385                         FOLL_WRITE, &page, &vma, NULL);
386         if (unlikely(ret <= 0)) {
387                 /*
388                  * We are asking for 1 page. If get_user_pages_remote() fails,
389                  * it may return 0, in that case we have to return error.
390                  */
391                 return ret == 0 ? -EBUSY : ret;
392         }
393
394         kaddr = kmap_atomic(page);
395         ptr = kaddr + (vaddr & ~PAGE_MASK);
396
397         if (unlikely(*ptr + d < 0)) {
398                 pr_warn("ref_ctr going negative. vaddr: 0x%lx, "
399                         "curr val: %d, delta: %d\n", vaddr, *ptr, d);
400                 ret = -EINVAL;
401                 goto out;
402         }
403
404         *ptr += d;
405         ret = 0;
406 out:
407         kunmap_atomic(kaddr);
408         put_page(page);
409         return ret;
410 }
411
412 static void update_ref_ctr_warn(struct uprobe *uprobe,
413                                 struct mm_struct *mm, short d)
414 {
415         pr_warn("ref_ctr %s failed for inode: 0x%lx offset: "
416                 "0x%llx ref_ctr_offset: 0x%llx of mm: 0x%pK\n",
417                 d > 0 ? "increment" : "decrement", uprobe->inode->i_ino,
418                 (unsigned long long) uprobe->offset,
419                 (unsigned long long) uprobe->ref_ctr_offset, mm);
420 }
421
422 static int update_ref_ctr(struct uprobe *uprobe, struct mm_struct *mm,
423                           short d)
424 {
425         struct vm_area_struct *rc_vma;
426         unsigned long rc_vaddr;
427         int ret = 0;
428
429         rc_vma = find_ref_ctr_vma(uprobe, mm);
430
431         if (rc_vma) {
432                 rc_vaddr = offset_to_vaddr(rc_vma, uprobe->ref_ctr_offset);
433                 ret = __update_ref_ctr(mm, rc_vaddr, d);
434                 if (ret)
435                         update_ref_ctr_warn(uprobe, mm, d);
436
437                 if (d > 0)
438                         return ret;
439         }
440
441         mutex_lock(&delayed_uprobe_lock);
442         if (d > 0)
443                 ret = delayed_uprobe_add(uprobe, mm);
444         else
445                 delayed_uprobe_remove(uprobe, mm);
446         mutex_unlock(&delayed_uprobe_lock);
447
448         return ret;
449 }
450
451 /*
452  * NOTE:
453  * Expect the breakpoint instruction to be the smallest size instruction for
454  * the architecture. If an arch has variable length instruction and the
455  * breakpoint instruction is not of the smallest length instruction
456  * supported by that architecture then we need to modify is_trap_at_addr and
457  * uprobe_write_opcode accordingly. This would never be a problem for archs
458  * that have fixed length instructions.
459  *
460  * uprobe_write_opcode - write the opcode at a given virtual address.
461  * @mm: the probed process address space.
462  * @vaddr: the virtual address to store the opcode.
463  * @opcode: opcode to be written at @vaddr.
464  *
465  * Called with mm->mmap_sem held for write.
466  * Return 0 (success) or a negative errno.
467  */
468 int uprobe_write_opcode(struct arch_uprobe *auprobe, struct mm_struct *mm,
469                         unsigned long vaddr, uprobe_opcode_t opcode)
470 {
471         struct uprobe *uprobe;
472         struct page *old_page, *new_page;
473         struct vm_area_struct *vma;
474         int ret, is_register, ref_ctr_updated = 0;
475
476         is_register = is_swbp_insn(&opcode);
477         uprobe = container_of(auprobe, struct uprobe, arch);
478
479 retry:
480         /* Read the page with vaddr into memory */
481         ret = get_user_pages_remote(NULL, mm, vaddr, 1,
482                         FOLL_FORCE | FOLL_SPLIT_PMD, &old_page, &vma, NULL);
483         if (ret <= 0)
484                 return ret;
485
486         ret = verify_opcode(old_page, vaddr, &opcode);
487         if (ret <= 0)
488                 goto put_old;
489
490         /* We are going to replace instruction, update ref_ctr. */
491         if (!ref_ctr_updated && uprobe->ref_ctr_offset) {
492                 ret = update_ref_ctr(uprobe, mm, is_register ? 1 : -1);
493                 if (ret)
494                         goto put_old;
495
496                 ref_ctr_updated = 1;
497         }
498
499         ret = 0;
500         if (!is_register && !PageAnon(old_page))
501                 goto put_old;
502
503         ret = anon_vma_prepare(vma);
504         if (ret)
505                 goto put_old;
506
507         ret = -ENOMEM;
508         new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vaddr);
509         if (!new_page)
510                 goto put_old;
511
512         __SetPageUptodate(new_page);
513         copy_highpage(new_page, old_page);
514         copy_to_page(new_page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE);
515
516         if (!is_register) {
517                 struct page *orig_page;
518                 pgoff_t index;
519
520                 VM_BUG_ON_PAGE(!PageAnon(old_page), old_page);
521
522                 index = vaddr_to_offset(vma, vaddr & PAGE_MASK) >> PAGE_SHIFT;
523                 orig_page = find_get_page(vma->vm_file->f_inode->i_mapping,
524                                           index);
525
526                 if (orig_page) {
527                         if (PageUptodate(orig_page) &&
528                             pages_identical(new_page, orig_page)) {
529                                 /* let go new_page */
530                                 put_page(new_page);
531                                 new_page = NULL;
532                         }
533                         put_page(orig_page);
534                 }
535         }
536
537         ret = __replace_page(vma, vaddr, old_page, new_page);
538         if (new_page)
539                 put_page(new_page);
540 put_old:
541         put_page(old_page);
542
543         if (unlikely(ret == -EAGAIN))
544                 goto retry;
545
546         /* Revert back reference counter if instruction update failed. */
547         if (ret && is_register && ref_ctr_updated)
548                 update_ref_ctr(uprobe, mm, -1);
549
550         return ret;
551 }
552
553 /**
554  * set_swbp - store breakpoint at a given address.
555  * @auprobe: arch specific probepoint information.
556  * @mm: the probed process address space.
557  * @vaddr: the virtual address to insert the opcode.
558  *
559  * For mm @mm, store the breakpoint instruction at @vaddr.
560  * Return 0 (success) or a negative errno.
561  */
562 int __weak set_swbp(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr)
563 {
564         return uprobe_write_opcode(auprobe, mm, vaddr, UPROBE_SWBP_INSN);
565 }
566
567 /**
568  * set_orig_insn - Restore the original instruction.
569  * @mm: the probed process address space.
570  * @auprobe: arch specific probepoint information.
571  * @vaddr: the virtual address to insert the opcode.
572  *
573  * For mm @mm, restore the original opcode (opcode) at @vaddr.
574  * Return 0 (success) or a negative errno.
575  */
576 int __weak
577 set_orig_insn(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr)
578 {
579         return uprobe_write_opcode(auprobe, mm, vaddr,
580                         *(uprobe_opcode_t *)&auprobe->insn);
581 }
582
583 static struct uprobe *get_uprobe(struct uprobe *uprobe)
584 {
585         refcount_inc(&uprobe->ref);
586         return uprobe;
587 }
588
589 static void put_uprobe(struct uprobe *uprobe)
590 {
591         if (refcount_dec_and_test(&uprobe->ref)) {
592                 /*
593                  * If application munmap(exec_vma) before uprobe_unregister()
594                  * gets called, we don't get a chance to remove uprobe from
595                  * delayed_uprobe_list from remove_breakpoint(). Do it here.
596                  */
597                 mutex_lock(&delayed_uprobe_lock);
598                 delayed_uprobe_remove(uprobe, NULL);
599                 mutex_unlock(&delayed_uprobe_lock);
600                 kfree(uprobe);
601         }
602 }
603
604 static int match_uprobe(struct uprobe *l, struct uprobe *r)
605 {
606         if (l->inode < r->inode)
607                 return -1;
608
609         if (l->inode > r->inode)
610                 return 1;
611
612         if (l->offset < r->offset)
613                 return -1;
614
615         if (l->offset > r->offset)
616                 return 1;
617
618         return 0;
619 }
620
621 static struct uprobe *__find_uprobe(struct inode *inode, loff_t offset)
622 {
623         struct uprobe u = { .inode = inode, .offset = offset };
624         struct rb_node *n = uprobes_tree.rb_node;
625         struct uprobe *uprobe;
626         int match;
627
628         while (n) {
629                 uprobe = rb_entry(n, struct uprobe, rb_node);
630                 match = match_uprobe(&u, uprobe);
631                 if (!match)
632                         return get_uprobe(uprobe);
633
634                 if (match < 0)
635                         n = n->rb_left;
636                 else
637                         n = n->rb_right;
638         }
639         return NULL;
640 }
641
642 /*
643  * Find a uprobe corresponding to a given inode:offset
644  * Acquires uprobes_treelock
645  */
646 static struct uprobe *find_uprobe(struct inode *inode, loff_t offset)
647 {
648         struct uprobe *uprobe;
649
650         spin_lock(&uprobes_treelock);
651         uprobe = __find_uprobe(inode, offset);
652         spin_unlock(&uprobes_treelock);
653
654         return uprobe;
655 }
656
657 static struct uprobe *__insert_uprobe(struct uprobe *uprobe)
658 {
659         struct rb_node **p = &uprobes_tree.rb_node;
660         struct rb_node *parent = NULL;
661         struct uprobe *u;
662         int match;
663
664         while (*p) {
665                 parent = *p;
666                 u = rb_entry(parent, struct uprobe, rb_node);
667                 match = match_uprobe(uprobe, u);
668                 if (!match)
669                         return get_uprobe(u);
670
671                 if (match < 0)
672                         p = &parent->rb_left;
673                 else
674                         p = &parent->rb_right;
675
676         }
677
678         u = NULL;
679         rb_link_node(&uprobe->rb_node, parent, p);
680         rb_insert_color(&uprobe->rb_node, &uprobes_tree);
681         /* get access + creation ref */
682         refcount_set(&uprobe->ref, 2);
683
684         return u;
685 }
686
687 /*
688  * Acquire uprobes_treelock.
689  * Matching uprobe already exists in rbtree;
690  *      increment (access refcount) and return the matching uprobe.
691  *
692  * No matching uprobe; insert the uprobe in rb_tree;
693  *      get a double refcount (access + creation) and return NULL.
694  */
695 static struct uprobe *insert_uprobe(struct uprobe *uprobe)
696 {
697         struct uprobe *u;
698
699         spin_lock(&uprobes_treelock);
700         u = __insert_uprobe(uprobe);
701         spin_unlock(&uprobes_treelock);
702
703         return u;
704 }
705
706 static void
707 ref_ctr_mismatch_warn(struct uprobe *cur_uprobe, struct uprobe *uprobe)
708 {
709         pr_warn("ref_ctr_offset mismatch. inode: 0x%lx offset: 0x%llx "
710                 "ref_ctr_offset(old): 0x%llx ref_ctr_offset(new): 0x%llx\n",
711                 uprobe->inode->i_ino, (unsigned long long) uprobe->offset,
712                 (unsigned long long) cur_uprobe->ref_ctr_offset,
713                 (unsigned long long) uprobe->ref_ctr_offset);
714 }
715
716 static struct uprobe *alloc_uprobe(struct inode *inode, loff_t offset,
717                                    loff_t ref_ctr_offset)
718 {
719         struct uprobe *uprobe, *cur_uprobe;
720
721         uprobe = kzalloc(sizeof(struct uprobe), GFP_KERNEL);
722         if (!uprobe)
723                 return NULL;
724
725         uprobe->inode = inode;
726         uprobe->offset = offset;
727         uprobe->ref_ctr_offset = ref_ctr_offset;
728         init_rwsem(&uprobe->register_rwsem);
729         init_rwsem(&uprobe->consumer_rwsem);
730
731         /* add to uprobes_tree, sorted on inode:offset */
732         cur_uprobe = insert_uprobe(uprobe);
733         /* a uprobe exists for this inode:offset combination */
734         if (cur_uprobe) {
735                 if (cur_uprobe->ref_ctr_offset != uprobe->ref_ctr_offset) {
736                         ref_ctr_mismatch_warn(cur_uprobe, uprobe);
737                         put_uprobe(cur_uprobe);
738                         kfree(uprobe);
739                         return ERR_PTR(-EINVAL);
740                 }
741                 kfree(uprobe);
742                 uprobe = cur_uprobe;
743         }
744
745         return uprobe;
746 }
747
748 static void consumer_add(struct uprobe *uprobe, struct uprobe_consumer *uc)
749 {
750         down_write(&uprobe->consumer_rwsem);
751         uc->next = uprobe->consumers;
752         uprobe->consumers = uc;
753         up_write(&uprobe->consumer_rwsem);
754 }
755
756 /*
757  * For uprobe @uprobe, delete the consumer @uc.
758  * Return true if the @uc is deleted successfully
759  * or return false.
760  */
761 static bool consumer_del(struct uprobe *uprobe, struct uprobe_consumer *uc)
762 {
763         struct uprobe_consumer **con;
764         bool ret = false;
765
766         down_write(&uprobe->consumer_rwsem);
767         for (con = &uprobe->consumers; *con; con = &(*con)->next) {
768                 if (*con == uc) {
769                         *con = uc->next;
770                         ret = true;
771                         break;
772                 }
773         }
774         up_write(&uprobe->consumer_rwsem);
775
776         return ret;
777 }
778
779 static int __copy_insn(struct address_space *mapping, struct file *filp,
780                         void *insn, int nbytes, loff_t offset)
781 {
782         struct page *page;
783         /*
784          * Ensure that the page that has the original instruction is populated
785          * and in page-cache. If ->readpage == NULL it must be shmem_mapping(),
786          * see uprobe_register().
787          */
788         if (mapping->a_ops->readpage)
789                 page = read_mapping_page(mapping, offset >> PAGE_SHIFT, filp);
790         else
791                 page = shmem_read_mapping_page(mapping, offset >> PAGE_SHIFT);
792         if (IS_ERR(page))
793                 return PTR_ERR(page);
794
795         copy_from_page(page, offset, insn, nbytes);
796         put_page(page);
797
798         return 0;
799 }
800
801 static int copy_insn(struct uprobe *uprobe, struct file *filp)
802 {
803         struct address_space *mapping = uprobe->inode->i_mapping;
804         loff_t offs = uprobe->offset;
805         void *insn = &uprobe->arch.insn;
806         int size = sizeof(uprobe->arch.insn);
807         int len, err = -EIO;
808
809         /* Copy only available bytes, -EIO if nothing was read */
810         do {
811                 if (offs >= i_size_read(uprobe->inode))
812                         break;
813
814                 len = min_t(int, size, PAGE_SIZE - (offs & ~PAGE_MASK));
815                 err = __copy_insn(mapping, filp, insn, len, offs);
816                 if (err)
817                         break;
818
819                 insn += len;
820                 offs += len;
821                 size -= len;
822         } while (size);
823
824         return err;
825 }
826
827 static int prepare_uprobe(struct uprobe *uprobe, struct file *file,
828                                 struct mm_struct *mm, unsigned long vaddr)
829 {
830         int ret = 0;
831
832         if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
833                 return ret;
834
835         /* TODO: move this into _register, until then we abuse this sem. */
836         down_write(&uprobe->consumer_rwsem);
837         if (test_bit(UPROBE_COPY_INSN, &uprobe->flags))
838                 goto out;
839
840         ret = copy_insn(uprobe, file);
841         if (ret)
842                 goto out;
843
844         ret = -ENOTSUPP;
845         if (is_trap_insn((uprobe_opcode_t *)&uprobe->arch.insn))
846                 goto out;
847
848         ret = arch_uprobe_analyze_insn(&uprobe->arch, mm, vaddr);
849         if (ret)
850                 goto out;
851
852         /* uprobe_write_opcode() assumes we don't cross page boundary */
853         BUG_ON((uprobe->offset & ~PAGE_MASK) +
854                         UPROBE_SWBP_INSN_SIZE > PAGE_SIZE);
855
856         smp_wmb(); /* pairs with the smp_rmb() in handle_swbp() */
857         set_bit(UPROBE_COPY_INSN, &uprobe->flags);
858
859  out:
860         up_write(&uprobe->consumer_rwsem);
861
862         return ret;
863 }
864
865 static inline bool consumer_filter(struct uprobe_consumer *uc,
866                                    enum uprobe_filter_ctx ctx, struct mm_struct *mm)
867 {
868         return !uc->filter || uc->filter(uc, ctx, mm);
869 }
870
871 static bool filter_chain(struct uprobe *uprobe,
872                          enum uprobe_filter_ctx ctx, struct mm_struct *mm)
873 {
874         struct uprobe_consumer *uc;
875         bool ret = false;
876
877         down_read(&uprobe->consumer_rwsem);
878         for (uc = uprobe->consumers; uc; uc = uc->next) {
879                 ret = consumer_filter(uc, ctx, mm);
880                 if (ret)
881                         break;
882         }
883         up_read(&uprobe->consumer_rwsem);
884
885         return ret;
886 }
887
888 static int
889 install_breakpoint(struct uprobe *uprobe, struct mm_struct *mm,
890                         struct vm_area_struct *vma, unsigned long vaddr)
891 {
892         bool first_uprobe;
893         int ret;
894
895         ret = prepare_uprobe(uprobe, vma->vm_file, mm, vaddr);
896         if (ret)
897                 return ret;
898
899         /*
900          * set MMF_HAS_UPROBES in advance for uprobe_pre_sstep_notifier(),
901          * the task can hit this breakpoint right after __replace_page().
902          */
903         first_uprobe = !test_bit(MMF_HAS_UPROBES, &mm->flags);
904         if (first_uprobe)
905                 set_bit(MMF_HAS_UPROBES, &mm->flags);
906
907         ret = set_swbp(&uprobe->arch, mm, vaddr);
908         if (!ret)
909                 clear_bit(MMF_RECALC_UPROBES, &mm->flags);
910         else if (first_uprobe)
911                 clear_bit(MMF_HAS_UPROBES, &mm->flags);
912
913         return ret;
914 }
915
916 static int
917 remove_breakpoint(struct uprobe *uprobe, struct mm_struct *mm, unsigned long vaddr)
918 {
919         set_bit(MMF_RECALC_UPROBES, &mm->flags);
920         return set_orig_insn(&uprobe->arch, mm, vaddr);
921 }
922
923 static inline bool uprobe_is_active(struct uprobe *uprobe)
924 {
925         return !RB_EMPTY_NODE(&uprobe->rb_node);
926 }
927 /*
928  * There could be threads that have already hit the breakpoint. They
929  * will recheck the current insn and restart if find_uprobe() fails.
930  * See find_active_uprobe().
931  */
932 static void delete_uprobe(struct uprobe *uprobe)
933 {
934         if (WARN_ON(!uprobe_is_active(uprobe)))
935                 return;
936
937         spin_lock(&uprobes_treelock);
938         rb_erase(&uprobe->rb_node, &uprobes_tree);
939         spin_unlock(&uprobes_treelock);
940         RB_CLEAR_NODE(&uprobe->rb_node); /* for uprobe_is_active() */
941         put_uprobe(uprobe);
942 }
943
944 struct map_info {
945         struct map_info *next;
946         struct mm_struct *mm;
947         unsigned long vaddr;
948 };
949
950 static inline struct map_info *free_map_info(struct map_info *info)
951 {
952         struct map_info *next = info->next;
953         kfree(info);
954         return next;
955 }
956
957 static struct map_info *
958 build_map_info(struct address_space *mapping, loff_t offset, bool is_register)
959 {
960         unsigned long pgoff = offset >> PAGE_SHIFT;
961         struct vm_area_struct *vma;
962         struct map_info *curr = NULL;
963         struct map_info *prev = NULL;
964         struct map_info *info;
965         int more = 0;
966
967  again:
968         i_mmap_lock_read(mapping);
969         vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
970                 if (!valid_vma(vma, is_register))
971                         continue;
972
973                 if (!prev && !more) {
974                         /*
975                          * Needs GFP_NOWAIT to avoid i_mmap_rwsem recursion through
976                          * reclaim. This is optimistic, no harm done if it fails.
977                          */
978                         prev = kmalloc(sizeof(struct map_info),
979                                         GFP_NOWAIT | __GFP_NOMEMALLOC | __GFP_NOWARN);
980                         if (prev)
981                                 prev->next = NULL;
982                 }
983                 if (!prev) {
984                         more++;
985                         continue;
986                 }
987
988                 if (!mmget_not_zero(vma->vm_mm))
989                         continue;
990
991                 info = prev;
992                 prev = prev->next;
993                 info->next = curr;
994                 curr = info;
995
996                 info->mm = vma->vm_mm;
997                 info->vaddr = offset_to_vaddr(vma, offset);
998         }
999         i_mmap_unlock_read(mapping);
1000
1001         if (!more)
1002                 goto out;
1003
1004         prev = curr;
1005         while (curr) {
1006                 mmput(curr->mm);
1007                 curr = curr->next;
1008         }
1009
1010         do {
1011                 info = kmalloc(sizeof(struct map_info), GFP_KERNEL);
1012                 if (!info) {
1013                         curr = ERR_PTR(-ENOMEM);
1014                         goto out;
1015                 }
1016                 info->next = prev;
1017                 prev = info;
1018         } while (--more);
1019
1020         goto again;
1021  out:
1022         while (prev)
1023                 prev = free_map_info(prev);
1024         return curr;
1025 }
1026
1027 static int
1028 register_for_each_vma(struct uprobe *uprobe, struct uprobe_consumer *new)
1029 {
1030         bool is_register = !!new;
1031         struct map_info *info;
1032         int err = 0;
1033
1034         percpu_down_write(&dup_mmap_sem);
1035         info = build_map_info(uprobe->inode->i_mapping,
1036                                         uprobe->offset, is_register);
1037         if (IS_ERR(info)) {
1038                 err = PTR_ERR(info);
1039                 goto out;
1040         }
1041
1042         while (info) {
1043                 struct mm_struct *mm = info->mm;
1044                 struct vm_area_struct *vma;
1045
1046                 if (err && is_register)
1047                         goto free;
1048
1049                 down_write(&mm->mmap_sem);
1050                 vma = find_vma(mm, info->vaddr);
1051                 if (!vma || !valid_vma(vma, is_register) ||
1052                     file_inode(vma->vm_file) != uprobe->inode)
1053                         goto unlock;
1054
1055                 if (vma->vm_start > info->vaddr ||
1056                     vaddr_to_offset(vma, info->vaddr) != uprobe->offset)
1057                         goto unlock;
1058
1059                 if (is_register) {
1060                         /* consult only the "caller", new consumer. */
1061                         if (consumer_filter(new,
1062                                         UPROBE_FILTER_REGISTER, mm))
1063                                 err = install_breakpoint(uprobe, mm, vma, info->vaddr);
1064                 } else if (test_bit(MMF_HAS_UPROBES, &mm->flags)) {
1065                         if (!filter_chain(uprobe,
1066                                         UPROBE_FILTER_UNREGISTER, mm))
1067                                 err |= remove_breakpoint(uprobe, mm, info->vaddr);
1068                 }
1069
1070  unlock:
1071                 up_write(&mm->mmap_sem);
1072  free:
1073                 mmput(mm);
1074                 info = free_map_info(info);
1075         }
1076  out:
1077         percpu_up_write(&dup_mmap_sem);
1078         return err;
1079 }
1080
1081 static void
1082 __uprobe_unregister(struct uprobe *uprobe, struct uprobe_consumer *uc)
1083 {
1084         int err;
1085
1086         if (WARN_ON(!consumer_del(uprobe, uc)))
1087                 return;
1088
1089         err = register_for_each_vma(uprobe, NULL);
1090         /* TODO : cant unregister? schedule a worker thread */
1091         if (!uprobe->consumers && !err)
1092                 delete_uprobe(uprobe);
1093 }
1094
1095 /*
1096  * uprobe_unregister - unregister an already registered probe.
1097  * @inode: the file in which the probe has to be removed.
1098  * @offset: offset from the start of the file.
1099  * @uc: identify which probe if multiple probes are colocated.
1100  */
1101 void uprobe_unregister(struct inode *inode, loff_t offset, struct uprobe_consumer *uc)
1102 {
1103         struct uprobe *uprobe;
1104
1105         uprobe = find_uprobe(inode, offset);
1106         if (WARN_ON(!uprobe))
1107                 return;
1108
1109         down_write(&uprobe->register_rwsem);
1110         __uprobe_unregister(uprobe, uc);
1111         up_write(&uprobe->register_rwsem);
1112         put_uprobe(uprobe);
1113 }
1114 EXPORT_SYMBOL_GPL(uprobe_unregister);
1115
1116 /*
1117  * __uprobe_register - register a probe
1118  * @inode: the file in which the probe has to be placed.
1119  * @offset: offset from the start of the file.
1120  * @uc: information on howto handle the probe..
1121  *
1122  * Apart from the access refcount, __uprobe_register() takes a creation
1123  * refcount (thro alloc_uprobe) if and only if this @uprobe is getting
1124  * inserted into the rbtree (i.e first consumer for a @inode:@offset
1125  * tuple).  Creation refcount stops uprobe_unregister from freeing the
1126  * @uprobe even before the register operation is complete. Creation
1127  * refcount is released when the last @uc for the @uprobe
1128  * unregisters. Caller of __uprobe_register() is required to keep @inode
1129  * (and the containing mount) referenced.
1130  *
1131  * Return errno if it cannot successully install probes
1132  * else return 0 (success)
1133  */
1134 static int __uprobe_register(struct inode *inode, loff_t offset,
1135                              loff_t ref_ctr_offset, struct uprobe_consumer *uc)
1136 {
1137         struct uprobe *uprobe;
1138         int ret;
1139
1140         /* Uprobe must have at least one set consumer */
1141         if (!uc->handler && !uc->ret_handler)
1142                 return -EINVAL;
1143
1144         /* copy_insn() uses read_mapping_page() or shmem_read_mapping_page() */
1145         if (!inode->i_mapping->a_ops->readpage && !shmem_mapping(inode->i_mapping))
1146                 return -EIO;
1147         /* Racy, just to catch the obvious mistakes */
1148         if (offset > i_size_read(inode))
1149                 return -EINVAL;
1150
1151  retry:
1152         uprobe = alloc_uprobe(inode, offset, ref_ctr_offset);
1153         if (!uprobe)
1154                 return -ENOMEM;
1155         if (IS_ERR(uprobe))
1156                 return PTR_ERR(uprobe);
1157
1158         /*
1159          * We can race with uprobe_unregister()->delete_uprobe().
1160          * Check uprobe_is_active() and retry if it is false.
1161          */
1162         down_write(&uprobe->register_rwsem);
1163         ret = -EAGAIN;
1164         if (likely(uprobe_is_active(uprobe))) {
1165                 consumer_add(uprobe, uc);
1166                 ret = register_for_each_vma(uprobe, uc);
1167                 if (ret)
1168                         __uprobe_unregister(uprobe, uc);
1169         }
1170         up_write(&uprobe->register_rwsem);
1171         put_uprobe(uprobe);
1172
1173         if (unlikely(ret == -EAGAIN))
1174                 goto retry;
1175         return ret;
1176 }
1177
1178 int uprobe_register(struct inode *inode, loff_t offset,
1179                     struct uprobe_consumer *uc)
1180 {
1181         return __uprobe_register(inode, offset, 0, uc);
1182 }
1183 EXPORT_SYMBOL_GPL(uprobe_register);
1184
1185 int uprobe_register_refctr(struct inode *inode, loff_t offset,
1186                            loff_t ref_ctr_offset, struct uprobe_consumer *uc)
1187 {
1188         return __uprobe_register(inode, offset, ref_ctr_offset, uc);
1189 }
1190 EXPORT_SYMBOL_GPL(uprobe_register_refctr);
1191
1192 /*
1193  * uprobe_apply - unregister an already registered probe.
1194  * @inode: the file in which the probe has to be removed.
1195  * @offset: offset from the start of the file.
1196  * @uc: consumer which wants to add more or remove some breakpoints
1197  * @add: add or remove the breakpoints
1198  */
1199 int uprobe_apply(struct inode *inode, loff_t offset,
1200                         struct uprobe_consumer *uc, bool add)
1201 {
1202         struct uprobe *uprobe;
1203         struct uprobe_consumer *con;
1204         int ret = -ENOENT;
1205
1206         uprobe = find_uprobe(inode, offset);
1207         if (WARN_ON(!uprobe))
1208                 return ret;
1209
1210         down_write(&uprobe->register_rwsem);
1211         for (con = uprobe->consumers; con && con != uc ; con = con->next)
1212                 ;
1213         if (con)
1214                 ret = register_for_each_vma(uprobe, add ? uc : NULL);
1215         up_write(&uprobe->register_rwsem);
1216         put_uprobe(uprobe);
1217
1218         return ret;
1219 }
1220
1221 static int unapply_uprobe(struct uprobe *uprobe, struct mm_struct *mm)
1222 {
1223         struct vm_area_struct *vma;
1224         int err = 0;
1225
1226         down_read(&mm->mmap_sem);
1227         for (vma = mm->mmap; vma; vma = vma->vm_next) {
1228                 unsigned long vaddr;
1229                 loff_t offset;
1230
1231                 if (!valid_vma(vma, false) ||
1232                     file_inode(vma->vm_file) != uprobe->inode)
1233                         continue;
1234
1235                 offset = (loff_t)vma->vm_pgoff << PAGE_SHIFT;
1236                 if (uprobe->offset <  offset ||
1237                     uprobe->offset >= offset + vma->vm_end - vma->vm_start)
1238                         continue;
1239
1240                 vaddr = offset_to_vaddr(vma, uprobe->offset);
1241                 err |= remove_breakpoint(uprobe, mm, vaddr);
1242         }
1243         up_read(&mm->mmap_sem);
1244
1245         return err;
1246 }
1247
1248 static struct rb_node *
1249 find_node_in_range(struct inode *inode, loff_t min, loff_t max)
1250 {
1251         struct rb_node *n = uprobes_tree.rb_node;
1252
1253         while (n) {
1254                 struct uprobe *u = rb_entry(n, struct uprobe, rb_node);
1255
1256                 if (inode < u->inode) {
1257                         n = n->rb_left;
1258                 } else if (inode > u->inode) {
1259                         n = n->rb_right;
1260                 } else {
1261                         if (max < u->offset)
1262                                 n = n->rb_left;
1263                         else if (min > u->offset)
1264                                 n = n->rb_right;
1265                         else
1266                                 break;
1267                 }
1268         }
1269
1270         return n;
1271 }
1272
1273 /*
1274  * For a given range in vma, build a list of probes that need to be inserted.
1275  */
1276 static void build_probe_list(struct inode *inode,
1277                                 struct vm_area_struct *vma,
1278                                 unsigned long start, unsigned long end,
1279                                 struct list_head *head)
1280 {
1281         loff_t min, max;
1282         struct rb_node *n, *t;
1283         struct uprobe *u;
1284
1285         INIT_LIST_HEAD(head);
1286         min = vaddr_to_offset(vma, start);
1287         max = min + (end - start) - 1;
1288
1289         spin_lock(&uprobes_treelock);
1290         n = find_node_in_range(inode, min, max);
1291         if (n) {
1292                 for (t = n; t; t = rb_prev(t)) {
1293                         u = rb_entry(t, struct uprobe, rb_node);
1294                         if (u->inode != inode || u->offset < min)
1295                                 break;
1296                         list_add(&u->pending_list, head);
1297                         get_uprobe(u);
1298                 }
1299                 for (t = n; (t = rb_next(t)); ) {
1300                         u = rb_entry(t, struct uprobe, rb_node);
1301                         if (u->inode != inode || u->offset > max)
1302                                 break;
1303                         list_add(&u->pending_list, head);
1304                         get_uprobe(u);
1305                 }
1306         }
1307         spin_unlock(&uprobes_treelock);
1308 }
1309
1310 /* @vma contains reference counter, not the probed instruction. */
1311 static int delayed_ref_ctr_inc(struct vm_area_struct *vma)
1312 {
1313         struct list_head *pos, *q;
1314         struct delayed_uprobe *du;
1315         unsigned long vaddr;
1316         int ret = 0, err = 0;
1317
1318         mutex_lock(&delayed_uprobe_lock);
1319         list_for_each_safe(pos, q, &delayed_uprobe_list) {
1320                 du = list_entry(pos, struct delayed_uprobe, list);
1321
1322                 if (du->mm != vma->vm_mm ||
1323                     !valid_ref_ctr_vma(du->uprobe, vma))
1324                         continue;
1325
1326                 vaddr = offset_to_vaddr(vma, du->uprobe->ref_ctr_offset);
1327                 ret = __update_ref_ctr(vma->vm_mm, vaddr, 1);
1328                 if (ret) {
1329                         update_ref_ctr_warn(du->uprobe, vma->vm_mm, 1);
1330                         if (!err)
1331                                 err = ret;
1332                 }
1333                 delayed_uprobe_delete(du);
1334         }
1335         mutex_unlock(&delayed_uprobe_lock);
1336         return err;
1337 }
1338
1339 /*
1340  * Called from mmap_region/vma_adjust with mm->mmap_sem acquired.
1341  *
1342  * Currently we ignore all errors and always return 0, the callers
1343  * can't handle the failure anyway.
1344  */
1345 int uprobe_mmap(struct vm_area_struct *vma)
1346 {
1347         struct list_head tmp_list;
1348         struct uprobe *uprobe, *u;
1349         struct inode *inode;
1350
1351         if (no_uprobe_events())
1352                 return 0;
1353
1354         if (vma->vm_file &&
1355             (vma->vm_flags & (VM_WRITE|VM_SHARED)) == VM_WRITE &&
1356             test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags))
1357                 delayed_ref_ctr_inc(vma);
1358
1359         if (!valid_vma(vma, true))
1360                 return 0;
1361
1362         inode = file_inode(vma->vm_file);
1363         if (!inode)
1364                 return 0;
1365
1366         mutex_lock(uprobes_mmap_hash(inode));
1367         build_probe_list(inode, vma, vma->vm_start, vma->vm_end, &tmp_list);
1368         /*
1369          * We can race with uprobe_unregister(), this uprobe can be already
1370          * removed. But in this case filter_chain() must return false, all
1371          * consumers have gone away.
1372          */
1373         list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) {
1374                 if (!fatal_signal_pending(current) &&
1375                     filter_chain(uprobe, UPROBE_FILTER_MMAP, vma->vm_mm)) {
1376                         unsigned long vaddr = offset_to_vaddr(vma, uprobe->offset);
1377                         install_breakpoint(uprobe, vma->vm_mm, vma, vaddr);
1378                 }
1379                 put_uprobe(uprobe);
1380         }
1381         mutex_unlock(uprobes_mmap_hash(inode));
1382
1383         return 0;
1384 }
1385
1386 static bool
1387 vma_has_uprobes(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1388 {
1389         loff_t min, max;
1390         struct inode *inode;
1391         struct rb_node *n;
1392
1393         inode = file_inode(vma->vm_file);
1394
1395         min = vaddr_to_offset(vma, start);
1396         max = min + (end - start) - 1;
1397
1398         spin_lock(&uprobes_treelock);
1399         n = find_node_in_range(inode, min, max);
1400         spin_unlock(&uprobes_treelock);
1401
1402         return !!n;
1403 }
1404
1405 /*
1406  * Called in context of a munmap of a vma.
1407  */
1408 void uprobe_munmap(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1409 {
1410         if (no_uprobe_events() || !valid_vma(vma, false))
1411                 return;
1412
1413         if (!atomic_read(&vma->vm_mm->mm_users)) /* called by mmput() ? */
1414                 return;
1415
1416         if (!test_bit(MMF_HAS_UPROBES, &vma->vm_mm->flags) ||
1417              test_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags))
1418                 return;
1419
1420         if (vma_has_uprobes(vma, start, end))
1421                 set_bit(MMF_RECALC_UPROBES, &vma->vm_mm->flags);
1422 }
1423
1424 /* Slot allocation for XOL */
1425 static int xol_add_vma(struct mm_struct *mm, struct xol_area *area)
1426 {
1427         struct vm_area_struct *vma;
1428         int ret;
1429
1430         if (down_write_killable(&mm->mmap_sem))
1431                 return -EINTR;
1432
1433         if (mm->uprobes_state.xol_area) {
1434                 ret = -EALREADY;
1435                 goto fail;
1436         }
1437
1438         if (!area->vaddr) {
1439                 /* Try to map as high as possible, this is only a hint. */
1440                 area->vaddr = get_unmapped_area(NULL, TASK_SIZE - PAGE_SIZE,
1441                                                 PAGE_SIZE, 0, 0);
1442                 if (area->vaddr & ~PAGE_MASK) {
1443                         ret = area->vaddr;
1444                         goto fail;
1445                 }
1446         }
1447
1448         vma = _install_special_mapping(mm, area->vaddr, PAGE_SIZE,
1449                                 VM_EXEC|VM_MAYEXEC|VM_DONTCOPY|VM_IO,
1450                                 &area->xol_mapping);
1451         if (IS_ERR(vma)) {
1452                 ret = PTR_ERR(vma);
1453                 goto fail;
1454         }
1455
1456         ret = 0;
1457         /* pairs with get_xol_area() */
1458         smp_store_release(&mm->uprobes_state.xol_area, area); /* ^^^ */
1459  fail:
1460         up_write(&mm->mmap_sem);
1461
1462         return ret;
1463 }
1464
1465 static struct xol_area *__create_xol_area(unsigned long vaddr)
1466 {
1467         struct mm_struct *mm = current->mm;
1468         uprobe_opcode_t insn = UPROBE_SWBP_INSN;
1469         struct xol_area *area;
1470
1471         area = kmalloc(sizeof(*area), GFP_KERNEL);
1472         if (unlikely(!area))
1473                 goto out;
1474
1475         area->bitmap = kcalloc(BITS_TO_LONGS(UINSNS_PER_PAGE), sizeof(long),
1476                                GFP_KERNEL);
1477         if (!area->bitmap)
1478                 goto free_area;
1479
1480         area->xol_mapping.name = "[uprobes]";
1481         area->xol_mapping.fault = NULL;
1482         area->xol_mapping.pages = area->pages;
1483         area->pages[0] = alloc_page(GFP_HIGHUSER);
1484         if (!area->pages[0])
1485                 goto free_bitmap;
1486         area->pages[1] = NULL;
1487
1488         area->vaddr = vaddr;
1489         init_waitqueue_head(&area->wq);
1490         /* Reserve the 1st slot for get_trampoline_vaddr() */
1491         set_bit(0, area->bitmap);
1492         atomic_set(&area->slot_count, 1);
1493         arch_uprobe_copy_ixol(area->pages[0], 0, &insn, UPROBE_SWBP_INSN_SIZE);
1494
1495         if (!xol_add_vma(mm, area))
1496                 return area;
1497
1498         __free_page(area->pages[0]);
1499  free_bitmap:
1500         kfree(area->bitmap);
1501  free_area:
1502         kfree(area);
1503  out:
1504         return NULL;
1505 }
1506
1507 /*
1508  * get_xol_area - Allocate process's xol_area if necessary.
1509  * This area will be used for storing instructions for execution out of line.
1510  *
1511  * Returns the allocated area or NULL.
1512  */
1513 static struct xol_area *get_xol_area(void)
1514 {
1515         struct mm_struct *mm = current->mm;
1516         struct xol_area *area;
1517
1518         if (!mm->uprobes_state.xol_area)
1519                 __create_xol_area(0);
1520
1521         /* Pairs with xol_add_vma() smp_store_release() */
1522         area = READ_ONCE(mm->uprobes_state.xol_area); /* ^^^ */
1523         return area;
1524 }
1525
1526 /*
1527  * uprobe_clear_state - Free the area allocated for slots.
1528  */
1529 void uprobe_clear_state(struct mm_struct *mm)
1530 {
1531         struct xol_area *area = mm->uprobes_state.xol_area;
1532
1533         mutex_lock(&delayed_uprobe_lock);
1534         delayed_uprobe_remove(NULL, mm);
1535         mutex_unlock(&delayed_uprobe_lock);
1536
1537         if (!area)
1538                 return;
1539
1540         put_page(area->pages[0]);
1541         kfree(area->bitmap);
1542         kfree(area);
1543 }
1544
1545 void uprobe_start_dup_mmap(void)
1546 {
1547         percpu_down_read(&dup_mmap_sem);
1548 }
1549
1550 void uprobe_end_dup_mmap(void)
1551 {
1552         percpu_up_read(&dup_mmap_sem);
1553 }
1554
1555 void uprobe_dup_mmap(struct mm_struct *oldmm, struct mm_struct *newmm)
1556 {
1557         if (test_bit(MMF_HAS_UPROBES, &oldmm->flags)) {
1558                 set_bit(MMF_HAS_UPROBES, &newmm->flags);
1559                 /* unconditionally, dup_mmap() skips VM_DONTCOPY vmas */
1560                 set_bit(MMF_RECALC_UPROBES, &newmm->flags);
1561         }
1562 }
1563
1564 /*
1565  *  - search for a free slot.
1566  */
1567 static unsigned long xol_take_insn_slot(struct xol_area *area)
1568 {
1569         unsigned long slot_addr;
1570         int slot_nr;
1571
1572         do {
1573                 slot_nr = find_first_zero_bit(area->bitmap, UINSNS_PER_PAGE);
1574                 if (slot_nr < UINSNS_PER_PAGE) {
1575                         if (!test_and_set_bit(slot_nr, area->bitmap))
1576                                 break;
1577
1578                         slot_nr = UINSNS_PER_PAGE;
1579                         continue;
1580                 }
1581                 wait_event(area->wq, (atomic_read(&area->slot_count) < UINSNS_PER_PAGE));
1582         } while (slot_nr >= UINSNS_PER_PAGE);
1583
1584         slot_addr = area->vaddr + (slot_nr * UPROBE_XOL_SLOT_BYTES);
1585         atomic_inc(&area->slot_count);
1586
1587         return slot_addr;
1588 }
1589
1590 /*
1591  * xol_get_insn_slot - allocate a slot for xol.
1592  * Returns the allocated slot address or 0.
1593  */
1594 static unsigned long xol_get_insn_slot(struct uprobe *uprobe)
1595 {
1596         struct xol_area *area;
1597         unsigned long xol_vaddr;
1598
1599         area = get_xol_area();
1600         if (!area)
1601                 return 0;
1602
1603         xol_vaddr = xol_take_insn_slot(area);
1604         if (unlikely(!xol_vaddr))
1605                 return 0;
1606
1607         arch_uprobe_copy_ixol(area->pages[0], xol_vaddr,
1608                               &uprobe->arch.ixol, sizeof(uprobe->arch.ixol));
1609
1610         return xol_vaddr;
1611 }
1612
1613 /*
1614  * xol_free_insn_slot - If slot was earlier allocated by
1615  * @xol_get_insn_slot(), make the slot available for
1616  * subsequent requests.
1617  */
1618 static void xol_free_insn_slot(struct task_struct *tsk)
1619 {
1620         struct xol_area *area;
1621         unsigned long vma_end;
1622         unsigned long slot_addr;
1623
1624         if (!tsk->mm || !tsk->mm->uprobes_state.xol_area || !tsk->utask)
1625                 return;
1626
1627         slot_addr = tsk->utask->xol_vaddr;
1628         if (unlikely(!slot_addr))
1629                 return;
1630
1631         area = tsk->mm->uprobes_state.xol_area;
1632         vma_end = area->vaddr + PAGE_SIZE;
1633         if (area->vaddr <= slot_addr && slot_addr < vma_end) {
1634                 unsigned long offset;
1635                 int slot_nr;
1636
1637                 offset = slot_addr - area->vaddr;
1638                 slot_nr = offset / UPROBE_XOL_SLOT_BYTES;
1639                 if (slot_nr >= UINSNS_PER_PAGE)
1640                         return;
1641
1642                 clear_bit(slot_nr, area->bitmap);
1643                 atomic_dec(&area->slot_count);
1644                 smp_mb__after_atomic(); /* pairs with prepare_to_wait() */
1645                 if (waitqueue_active(&area->wq))
1646                         wake_up(&area->wq);
1647
1648                 tsk->utask->xol_vaddr = 0;
1649         }
1650 }
1651
1652 void __weak arch_uprobe_copy_ixol(struct page *page, unsigned long vaddr,
1653                                   void *src, unsigned long len)
1654 {
1655         /* Initialize the slot */
1656         copy_to_page(page, vaddr, src, len);
1657
1658         /*
1659          * We probably need flush_icache_user_range() but it needs vma.
1660          * This should work on most of architectures by default. If
1661          * architecture needs to do something different it can define
1662          * its own version of the function.
1663          */
1664         flush_dcache_page(page);
1665 }
1666
1667 /**
1668  * uprobe_get_swbp_addr - compute address of swbp given post-swbp regs
1669  * @regs: Reflects the saved state of the task after it has hit a breakpoint
1670  * instruction.
1671  * Return the address of the breakpoint instruction.
1672  */
1673 unsigned long __weak uprobe_get_swbp_addr(struct pt_regs *regs)
1674 {
1675         return instruction_pointer(regs) - UPROBE_SWBP_INSN_SIZE;
1676 }
1677
1678 unsigned long uprobe_get_trap_addr(struct pt_regs *regs)
1679 {
1680         struct uprobe_task *utask = current->utask;
1681
1682         if (unlikely(utask && utask->active_uprobe))
1683                 return utask->vaddr;
1684
1685         return instruction_pointer(regs);
1686 }
1687
1688 static struct return_instance *free_ret_instance(struct return_instance *ri)
1689 {
1690         struct return_instance *next = ri->next;
1691         put_uprobe(ri->uprobe);
1692         kfree(ri);
1693         return next;
1694 }
1695
1696 /*
1697  * Called with no locks held.
1698  * Called in context of an exiting or an exec-ing thread.
1699  */
1700 void uprobe_free_utask(struct task_struct *t)
1701 {
1702         struct uprobe_task *utask = t->utask;
1703         struct return_instance *ri;
1704
1705         if (!utask)
1706                 return;
1707
1708         if (utask->active_uprobe)
1709                 put_uprobe(utask->active_uprobe);
1710
1711         ri = utask->return_instances;
1712         while (ri)
1713                 ri = free_ret_instance(ri);
1714
1715         xol_free_insn_slot(t);
1716         kfree(utask);
1717         t->utask = NULL;
1718 }
1719
1720 /*
1721  * Allocate a uprobe_task object for the task if if necessary.
1722  * Called when the thread hits a breakpoint.
1723  *
1724  * Returns:
1725  * - pointer to new uprobe_task on success
1726  * - NULL otherwise
1727  */
1728 static struct uprobe_task *get_utask(void)
1729 {
1730         if (!current->utask)
1731                 current->utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL);
1732         return current->utask;
1733 }
1734
1735 static int dup_utask(struct task_struct *t, struct uprobe_task *o_utask)
1736 {
1737         struct uprobe_task *n_utask;
1738         struct return_instance **p, *o, *n;
1739
1740         n_utask = kzalloc(sizeof(struct uprobe_task), GFP_KERNEL);
1741         if (!n_utask)
1742                 return -ENOMEM;
1743         t->utask = n_utask;
1744
1745         p = &n_utask->return_instances;
1746         for (o = o_utask->return_instances; o; o = o->next) {
1747                 n = kmalloc(sizeof(struct return_instance), GFP_KERNEL);
1748                 if (!n)
1749                         return -ENOMEM;
1750
1751                 *n = *o;
1752                 get_uprobe(n->uprobe);
1753                 n->next = NULL;
1754
1755                 *p = n;
1756                 p = &n->next;
1757                 n_utask->depth++;
1758         }
1759
1760         return 0;
1761 }
1762
1763 static void uprobe_warn(struct task_struct *t, const char *msg)
1764 {
1765         pr_warn("uprobe: %s:%d failed to %s\n",
1766                         current->comm, current->pid, msg);
1767 }
1768
1769 static void dup_xol_work(struct callback_head *work)
1770 {
1771         if (current->flags & PF_EXITING)
1772                 return;
1773
1774         if (!__create_xol_area(current->utask->dup_xol_addr) &&
1775                         !fatal_signal_pending(current))
1776                 uprobe_warn(current, "dup xol area");
1777 }
1778
1779 /*
1780  * Called in context of a new clone/fork from copy_process.
1781  */
1782 void uprobe_copy_process(struct task_struct *t, unsigned long flags)
1783 {
1784         struct uprobe_task *utask = current->utask;
1785         struct mm_struct *mm = current->mm;
1786         struct xol_area *area;
1787
1788         t->utask = NULL;
1789
1790         if (!utask || !utask->return_instances)
1791                 return;
1792
1793         if (mm == t->mm && !(flags & CLONE_VFORK))
1794                 return;
1795
1796         if (dup_utask(t, utask))
1797                 return uprobe_warn(t, "dup ret instances");
1798
1799         /* The task can fork() after dup_xol_work() fails */
1800         area = mm->uprobes_state.xol_area;
1801         if (!area)
1802                 return uprobe_warn(t, "dup xol area");
1803
1804         if (mm == t->mm)
1805                 return;
1806
1807         t->utask->dup_xol_addr = area->vaddr;
1808         init_task_work(&t->utask->dup_xol_work, dup_xol_work);
1809         task_work_add(t, &t->utask->dup_xol_work, true);
1810 }
1811
1812 /*
1813  * Current area->vaddr notion assume the trampoline address is always
1814  * equal area->vaddr.
1815  *
1816  * Returns -1 in case the xol_area is not allocated.
1817  */
1818 static unsigned long get_trampoline_vaddr(void)
1819 {
1820         struct xol_area *area;
1821         unsigned long trampoline_vaddr = -1;
1822
1823         /* Pairs with xol_add_vma() smp_store_release() */
1824         area = READ_ONCE(current->mm->uprobes_state.xol_area); /* ^^^ */
1825         if (area)
1826                 trampoline_vaddr = area->vaddr;
1827
1828         return trampoline_vaddr;
1829 }
1830
1831 static void cleanup_return_instances(struct uprobe_task *utask, bool chained,
1832                                         struct pt_regs *regs)
1833 {
1834         struct return_instance *ri = utask->return_instances;
1835         enum rp_check ctx = chained ? RP_CHECK_CHAIN_CALL : RP_CHECK_CALL;
1836
1837         while (ri && !arch_uretprobe_is_alive(ri, ctx, regs)) {
1838                 ri = free_ret_instance(ri);
1839                 utask->depth--;
1840         }
1841         utask->return_instances = ri;
1842 }
1843
1844 static void prepare_uretprobe(struct uprobe *uprobe, struct pt_regs *regs)
1845 {
1846         struct return_instance *ri;
1847         struct uprobe_task *utask;
1848         unsigned long orig_ret_vaddr, trampoline_vaddr;
1849         bool chained;
1850
1851         if (!get_xol_area())
1852                 return;
1853
1854         utask = get_utask();
1855         if (!utask)
1856                 return;
1857
1858         if (utask->depth >= MAX_URETPROBE_DEPTH) {
1859                 printk_ratelimited(KERN_INFO "uprobe: omit uretprobe due to"
1860                                 " nestedness limit pid/tgid=%d/%d\n",
1861                                 current->pid, current->tgid);
1862                 return;
1863         }
1864
1865         ri = kmalloc(sizeof(struct return_instance), GFP_KERNEL);
1866         if (!ri)
1867                 return;
1868
1869         trampoline_vaddr = get_trampoline_vaddr();
1870         orig_ret_vaddr = arch_uretprobe_hijack_return_addr(trampoline_vaddr, regs);
1871         if (orig_ret_vaddr == -1)
1872                 goto fail;
1873
1874         /* drop the entries invalidated by longjmp() */
1875         chained = (orig_ret_vaddr == trampoline_vaddr);
1876         cleanup_return_instances(utask, chained, regs);
1877
1878         /*
1879          * We don't want to keep trampoline address in stack, rather keep the
1880          * original return address of first caller thru all the consequent
1881          * instances. This also makes breakpoint unwrapping easier.
1882          */
1883         if (chained) {
1884                 if (!utask->return_instances) {
1885                         /*
1886                          * This situation is not possible. Likely we have an
1887                          * attack from user-space.
1888                          */
1889                         uprobe_warn(current, "handle tail call");
1890                         goto fail;
1891                 }
1892                 orig_ret_vaddr = utask->return_instances->orig_ret_vaddr;
1893         }
1894
1895         ri->uprobe = get_uprobe(uprobe);
1896         ri->func = instruction_pointer(regs);
1897         ri->stack = user_stack_pointer(regs);
1898         ri->orig_ret_vaddr = orig_ret_vaddr;
1899         ri->chained = chained;
1900
1901         utask->depth++;
1902         ri->next = utask->return_instances;
1903         utask->return_instances = ri;
1904
1905         return;
1906  fail:
1907         kfree(ri);
1908 }
1909
1910 /* Prepare to single-step probed instruction out of line. */
1911 static int
1912 pre_ssout(struct uprobe *uprobe, struct pt_regs *regs, unsigned long bp_vaddr)
1913 {
1914         struct uprobe_task *utask;
1915         unsigned long xol_vaddr;
1916         int err;
1917
1918         utask = get_utask();
1919         if (!utask)
1920                 return -ENOMEM;
1921
1922         xol_vaddr = xol_get_insn_slot(uprobe);
1923         if (!xol_vaddr)
1924                 return -ENOMEM;
1925
1926         utask->xol_vaddr = xol_vaddr;
1927         utask->vaddr = bp_vaddr;
1928
1929         err = arch_uprobe_pre_xol(&uprobe->arch, regs);
1930         if (unlikely(err)) {
1931                 xol_free_insn_slot(current);
1932                 return err;
1933         }
1934
1935         utask->active_uprobe = uprobe;
1936         utask->state = UTASK_SSTEP;
1937         return 0;
1938 }
1939
1940 /*
1941  * If we are singlestepping, then ensure this thread is not connected to
1942  * non-fatal signals until completion of singlestep.  When xol insn itself
1943  * triggers the signal,  restart the original insn even if the task is
1944  * already SIGKILL'ed (since coredump should report the correct ip).  This
1945  * is even more important if the task has a handler for SIGSEGV/etc, The
1946  * _same_ instruction should be repeated again after return from the signal
1947  * handler, and SSTEP can never finish in this case.
1948  */
1949 bool uprobe_deny_signal(void)
1950 {
1951         struct task_struct *t = current;
1952         struct uprobe_task *utask = t->utask;
1953
1954         if (likely(!utask || !utask->active_uprobe))
1955                 return false;
1956
1957         WARN_ON_ONCE(utask->state != UTASK_SSTEP);
1958
1959         if (signal_pending(t)) {
1960                 spin_lock_irq(&t->sighand->siglock);
1961                 clear_tsk_thread_flag(t, TIF_SIGPENDING);
1962                 spin_unlock_irq(&t->sighand->siglock);
1963
1964                 if (__fatal_signal_pending(t) || arch_uprobe_xol_was_trapped(t)) {
1965                         utask->state = UTASK_SSTEP_TRAPPED;
1966                         set_tsk_thread_flag(t, TIF_UPROBE);
1967                 }
1968         }
1969
1970         return true;
1971 }
1972
1973 static void mmf_recalc_uprobes(struct mm_struct *mm)
1974 {
1975         struct vm_area_struct *vma;
1976
1977         for (vma = mm->mmap; vma; vma = vma->vm_next) {
1978                 if (!valid_vma(vma, false))
1979                         continue;
1980                 /*
1981                  * This is not strictly accurate, we can race with
1982                  * uprobe_unregister() and see the already removed
1983                  * uprobe if delete_uprobe() was not yet called.
1984                  * Or this uprobe can be filtered out.
1985                  */
1986                 if (vma_has_uprobes(vma, vma->vm_start, vma->vm_end))
1987                         return;
1988         }
1989
1990         clear_bit(MMF_HAS_UPROBES, &mm->flags);
1991 }
1992
1993 static int is_trap_at_addr(struct mm_struct *mm, unsigned long vaddr)
1994 {
1995         struct page *page;
1996         uprobe_opcode_t opcode;
1997         int result;
1998
1999         pagefault_disable();
2000         result = __get_user(opcode, (uprobe_opcode_t __user *)vaddr);
2001         pagefault_enable();
2002
2003         if (likely(result == 0))
2004                 goto out;
2005
2006         /*
2007          * The NULL 'tsk' here ensures that any faults that occur here
2008          * will not be accounted to the task.  'mm' *is* current->mm,
2009          * but we treat this as a 'remote' access since it is
2010          * essentially a kernel access to the memory.
2011          */
2012         result = get_user_pages_remote(NULL, mm, vaddr, 1, FOLL_FORCE, &page,
2013                         NULL, NULL);
2014         if (result < 0)
2015                 return result;
2016
2017         copy_from_page(page, vaddr, &opcode, UPROBE_SWBP_INSN_SIZE);
2018         put_page(page);
2019  out:
2020         /* This needs to return true for any variant of the trap insn */
2021         return is_trap_insn(&opcode);
2022 }
2023
2024 static struct uprobe *find_active_uprobe(unsigned long bp_vaddr, int *is_swbp)
2025 {
2026         struct mm_struct *mm = current->mm;
2027         struct uprobe *uprobe = NULL;
2028         struct vm_area_struct *vma;
2029
2030         down_read(&mm->mmap_sem);
2031         vma = find_vma(mm, bp_vaddr);
2032         if (vma && vma->vm_start <= bp_vaddr) {
2033                 if (valid_vma(vma, false)) {
2034                         struct inode *inode = file_inode(vma->vm_file);
2035                         loff_t offset = vaddr_to_offset(vma, bp_vaddr);
2036
2037                         uprobe = find_uprobe(inode, offset);
2038                 }
2039
2040                 if (!uprobe)
2041                         *is_swbp = is_trap_at_addr(mm, bp_vaddr);
2042         } else {
2043                 *is_swbp = -EFAULT;
2044         }
2045
2046         if (!uprobe && test_and_clear_bit(MMF_RECALC_UPROBES, &mm->flags))
2047                 mmf_recalc_uprobes(mm);
2048         up_read(&mm->mmap_sem);
2049
2050         return uprobe;
2051 }
2052
2053 static void handler_chain(struct uprobe *uprobe, struct pt_regs *regs)
2054 {
2055         struct uprobe_consumer *uc;
2056         int remove = UPROBE_HANDLER_REMOVE;
2057         bool need_prep = false; /* prepare return uprobe, when needed */
2058
2059         down_read(&uprobe->register_rwsem);
2060         for (uc = uprobe->consumers; uc; uc = uc->next) {
2061                 int rc = 0;
2062
2063                 if (uc->handler) {
2064                         rc = uc->handler(uc, regs);
2065                         WARN(rc & ~UPROBE_HANDLER_MASK,
2066                                 "bad rc=0x%x from %ps()\n", rc, uc->handler);
2067                 }
2068
2069                 if (uc->ret_handler)
2070                         need_prep = true;
2071
2072                 remove &= rc;
2073         }
2074
2075         if (need_prep && !remove)
2076                 prepare_uretprobe(uprobe, regs); /* put bp at return */
2077
2078         if (remove && uprobe->consumers) {
2079                 WARN_ON(!uprobe_is_active(uprobe));
2080                 unapply_uprobe(uprobe, current->mm);
2081         }
2082         up_read(&uprobe->register_rwsem);
2083 }
2084
2085 static void
2086 handle_uretprobe_chain(struct return_instance *ri, struct pt_regs *regs)
2087 {
2088         struct uprobe *uprobe = ri->uprobe;
2089         struct uprobe_consumer *uc;
2090
2091         down_read(&uprobe->register_rwsem);
2092         for (uc = uprobe->consumers; uc; uc = uc->next) {
2093                 if (uc->ret_handler)
2094                         uc->ret_handler(uc, ri->func, regs);
2095         }
2096         up_read(&uprobe->register_rwsem);
2097 }
2098
2099 static struct return_instance *find_next_ret_chain(struct return_instance *ri)
2100 {
2101         bool chained;
2102
2103         do {
2104                 chained = ri->chained;
2105                 ri = ri->next;  /* can't be NULL if chained */
2106         } while (chained);
2107
2108         return ri;
2109 }
2110
2111 static void handle_trampoline(struct pt_regs *regs)
2112 {
2113         struct uprobe_task *utask;
2114         struct return_instance *ri, *next;
2115         bool valid;
2116
2117         utask = current->utask;
2118         if (!utask)
2119                 goto sigill;
2120
2121         ri = utask->return_instances;
2122         if (!ri)
2123                 goto sigill;
2124
2125         do {
2126                 /*
2127                  * We should throw out the frames invalidated by longjmp().
2128                  * If this chain is valid, then the next one should be alive
2129                  * or NULL; the latter case means that nobody but ri->func
2130                  * could hit this trampoline on return. TODO: sigaltstack().
2131                  */
2132                 next = find_next_ret_chain(ri);
2133                 valid = !next || arch_uretprobe_is_alive(next, RP_CHECK_RET, regs);
2134
2135                 instruction_pointer_set(regs, ri->orig_ret_vaddr);
2136                 do {
2137                         if (valid)
2138                                 handle_uretprobe_chain(ri, regs);
2139                         ri = free_ret_instance(ri);
2140                         utask->depth--;
2141                 } while (ri != next);
2142         } while (!valid);
2143
2144         utask->return_instances = ri;
2145         return;
2146
2147  sigill:
2148         uprobe_warn(current, "handle uretprobe, sending SIGILL.");
2149         force_sig(SIGILL);
2150
2151 }
2152
2153 bool __weak arch_uprobe_ignore(struct arch_uprobe *aup, struct pt_regs *regs)
2154 {
2155         return false;
2156 }
2157
2158 bool __weak arch_uretprobe_is_alive(struct return_instance *ret, enum rp_check ctx,
2159                                         struct pt_regs *regs)
2160 {
2161         return true;
2162 }
2163
2164 /*
2165  * Run handler and ask thread to singlestep.
2166  * Ensure all non-fatal signals cannot interrupt thread while it singlesteps.
2167  */
2168 static void handle_swbp(struct pt_regs *regs)
2169 {
2170         struct uprobe *uprobe;
2171         unsigned long bp_vaddr;
2172         int uninitialized_var(is_swbp);
2173
2174         bp_vaddr = uprobe_get_swbp_addr(regs);
2175         if (bp_vaddr == get_trampoline_vaddr())
2176                 return handle_trampoline(regs);
2177
2178         uprobe = find_active_uprobe(bp_vaddr, &is_swbp);
2179         if (!uprobe) {
2180                 if (is_swbp > 0) {
2181                         /* No matching uprobe; signal SIGTRAP. */
2182                         send_sig(SIGTRAP, current, 0);
2183                 } else {
2184                         /*
2185                          * Either we raced with uprobe_unregister() or we can't
2186                          * access this memory. The latter is only possible if
2187                          * another thread plays with our ->mm. In both cases
2188                          * we can simply restart. If this vma was unmapped we
2189                          * can pretend this insn was not executed yet and get
2190                          * the (correct) SIGSEGV after restart.
2191                          */
2192                         instruction_pointer_set(regs, bp_vaddr);
2193                 }
2194                 return;
2195         }
2196
2197         /* change it in advance for ->handler() and restart */
2198         instruction_pointer_set(regs, bp_vaddr);
2199
2200         /*
2201          * TODO: move copy_insn/etc into _register and remove this hack.
2202          * After we hit the bp, _unregister + _register can install the
2203          * new and not-yet-analyzed uprobe at the same address, restart.
2204          */
2205         if (unlikely(!test_bit(UPROBE_COPY_INSN, &uprobe->flags)))
2206                 goto out;
2207
2208         /*
2209          * Pairs with the smp_wmb() in prepare_uprobe().
2210          *
2211          * Guarantees that if we see the UPROBE_COPY_INSN bit set, then
2212          * we must also see the stores to &uprobe->arch performed by the
2213          * prepare_uprobe() call.
2214          */
2215         smp_rmb();
2216
2217         /* Tracing handlers use ->utask to communicate with fetch methods */
2218         if (!get_utask())
2219                 goto out;
2220
2221         if (arch_uprobe_ignore(&uprobe->arch, regs))
2222                 goto out;
2223
2224         handler_chain(uprobe, regs);
2225
2226         if (arch_uprobe_skip_sstep(&uprobe->arch, regs))
2227                 goto out;
2228
2229         if (!pre_ssout(uprobe, regs, bp_vaddr))
2230                 return;
2231
2232         /* arch_uprobe_skip_sstep() succeeded, or restart if can't singlestep */
2233 out:
2234         put_uprobe(uprobe);
2235 }
2236
2237 /*
2238  * Perform required fix-ups and disable singlestep.
2239  * Allow pending signals to take effect.
2240  */
2241 static void handle_singlestep(struct uprobe_task *utask, struct pt_regs *regs)
2242 {
2243         struct uprobe *uprobe;
2244         int err = 0;
2245
2246         uprobe = utask->active_uprobe;
2247         if (utask->state == UTASK_SSTEP_ACK)
2248                 err = arch_uprobe_post_xol(&uprobe->arch, regs);
2249         else if (utask->state == UTASK_SSTEP_TRAPPED)
2250                 arch_uprobe_abort_xol(&uprobe->arch, regs);
2251         else
2252                 WARN_ON_ONCE(1);
2253
2254         put_uprobe(uprobe);
2255         utask->active_uprobe = NULL;
2256         utask->state = UTASK_RUNNING;
2257         xol_free_insn_slot(current);
2258
2259         spin_lock_irq(&current->sighand->siglock);
2260         recalc_sigpending(); /* see uprobe_deny_signal() */
2261         spin_unlock_irq(&current->sighand->siglock);
2262
2263         if (unlikely(err)) {
2264                 uprobe_warn(current, "execute the probed insn, sending SIGILL.");
2265                 force_sig(SIGILL);
2266         }
2267 }
2268
2269 /*
2270  * On breakpoint hit, breakpoint notifier sets the TIF_UPROBE flag and
2271  * allows the thread to return from interrupt. After that handle_swbp()
2272  * sets utask->active_uprobe.
2273  *
2274  * On singlestep exception, singlestep notifier sets the TIF_UPROBE flag
2275  * and allows the thread to return from interrupt.
2276  *
2277  * While returning to userspace, thread notices the TIF_UPROBE flag and calls
2278  * uprobe_notify_resume().
2279  */
2280 void uprobe_notify_resume(struct pt_regs *regs)
2281 {
2282         struct uprobe_task *utask;
2283
2284         clear_thread_flag(TIF_UPROBE);
2285
2286         utask = current->utask;
2287         if (utask && utask->active_uprobe)
2288                 handle_singlestep(utask, regs);
2289         else
2290                 handle_swbp(regs);
2291 }
2292
2293 /*
2294  * uprobe_pre_sstep_notifier gets called from interrupt context as part of
2295  * notifier mechanism. Set TIF_UPROBE flag and indicate breakpoint hit.
2296  */
2297 int uprobe_pre_sstep_notifier(struct pt_regs *regs)
2298 {
2299         if (!current->mm)
2300                 return 0;
2301
2302         if (!test_bit(MMF_HAS_UPROBES, &current->mm->flags) &&
2303             (!current->utask || !current->utask->return_instances))
2304                 return 0;
2305
2306         set_thread_flag(TIF_UPROBE);
2307         return 1;
2308 }
2309
2310 /*
2311  * uprobe_post_sstep_notifier gets called in interrupt context as part of notifier
2312  * mechanism. Set TIF_UPROBE flag and indicate completion of singlestep.
2313  */
2314 int uprobe_post_sstep_notifier(struct pt_regs *regs)
2315 {
2316         struct uprobe_task *utask = current->utask;
2317
2318         if (!current->mm || !utask || !utask->active_uprobe)
2319                 /* task is currently not uprobed */
2320                 return 0;
2321
2322         utask->state = UTASK_SSTEP_ACK;
2323         set_thread_flag(TIF_UPROBE);
2324         return 1;
2325 }
2326
2327 static struct notifier_block uprobe_exception_nb = {
2328         .notifier_call          = arch_uprobe_exception_notify,
2329         .priority               = INT_MAX-1,    /* notified after kprobes, kgdb */
2330 };
2331
2332 void __init uprobes_init(void)
2333 {
2334         int i;
2335
2336         for (i = 0; i < UPROBES_HASH_SZ; i++)
2337                 mutex_init(&uprobes_mmap_mutex[i]);
2338
2339         BUG_ON(register_die_notifier(&uprobe_exception_nb));
2340 }