uprobes: Pass probed vaddr to arch_uprobe_analyze_insn()
[cascardo/linux.git] / kernel / events / uprobes.c
1 /*
2  * User-space Probes (UProbes)
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  *
18  * Copyright (C) IBM Corporation, 2008-2012
19  * Authors:
20  *      Srikar Dronamraju
21  *      Jim Keniston
22  * Copyright (C) 2011-2012 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
23  */
24
25 #include <linux/kernel.h>
26 #include <linux/highmem.h>
27 #include <linux/pagemap.h>      /* read_mapping_page */
28 #include <linux/slab.h>
29 #include <linux/sched.h>
30 #include <linux/rmap.h>         /* anon_vma_prepare */
31 #include <linux/mmu_notifier.h> /* set_pte_at_notify */
32 #include <linux/swap.h>         /* try_to_free_swap */
33 #include <linux/ptrace.h>       /* user_enable_single_step */
34 #include <linux/kdebug.h>       /* notifier mechanism */
35
36 #include <linux/uprobes.h>
37
38 #define UINSNS_PER_PAGE                 (PAGE_SIZE/UPROBE_XOL_SLOT_BYTES)
39 #define MAX_UPROBE_XOL_SLOTS            UINSNS_PER_PAGE
40
41 static struct rb_root uprobes_tree = RB_ROOT;
42
43 static DEFINE_SPINLOCK(uprobes_treelock);       /* serialize rbtree access */
44
45 #define UPROBES_HASH_SZ 13
46
47 /* serialize (un)register */
48 static struct mutex uprobes_mutex[UPROBES_HASH_SZ];
49
50 #define uprobes_hash(v)         (&uprobes_mutex[((unsigned long)(v)) % UPROBES_HASH_SZ])
51
52 /* serialize uprobe->pending_list */
53 static struct mutex uprobes_mmap_mutex[UPROBES_HASH_SZ];
54 #define uprobes_mmap_hash(v)    (&uprobes_mmap_mutex[((unsigned long)(v)) % UPROBES_HASH_SZ])
55
56 /*
57  * uprobe_events allows us to skip the uprobe_mmap if there are no uprobe
58  * events active at this time.  Probably a fine grained per inode count is
59  * better?
60  */
61 static atomic_t uprobe_events = ATOMIC_INIT(0);
62
63 /*
64  * Maintain a temporary per vma info that can be used to search if a vma
65  * has already been handled. This structure is introduced since extending
66  * vm_area_struct wasnt recommended.
67  */
68 struct vma_info {
69         struct list_head        probe_list;
70         struct mm_struct        *mm;
71         loff_t                  vaddr;
72 };
73
74 struct uprobe {
75         struct rb_node          rb_node;        /* node in the rb tree */
76         atomic_t                ref;
77         struct rw_semaphore     consumer_rwsem;
78         struct list_head        pending_list;
79         struct uprobe_consumer  *consumers;
80         struct inode            *inode;         /* Also hold a ref to inode */
81         loff_t                  offset;
82         int                     flags;
83         struct arch_uprobe      arch;
84 };
85
86 /*
87  * valid_vma: Verify if the specified vma is an executable vma
88  * Relax restrictions while unregistering: vm_flags might have
89  * changed after breakpoint was inserted.
90  *      - is_register: indicates if we are in register context.
91  *      - Return 1 if the specified virtual address is in an
92  *        executable vma.
93  */
94 static bool valid_vma(struct vm_area_struct *vma, bool is_register)
95 {
96         if (!vma->vm_file)
97                 return false;
98
99         if (!is_register)
100                 return true;
101
102         if ((vma->vm_flags & (VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)) == (VM_READ|VM_EXEC))
103                 return true;
104
105         return false;
106 }
107
108 static loff_t vma_address(struct vm_area_struct *vma, loff_t offset)
109 {
110         loff_t vaddr;
111
112         vaddr = vma->vm_start + offset;
113         vaddr -= vma->vm_pgoff << PAGE_SHIFT;
114
115         return vaddr;
116 }
117
118 /**
119  * __replace_page - replace page in vma by new page.
120  * based on replace_page in mm/ksm.c
121  *
122  * @vma:      vma that holds the pte pointing to page
123  * @page:     the cowed page we are replacing by kpage
124  * @kpage:    the modified page we replace page by
125  *
126  * Returns 0 on success, -EFAULT on failure.
127  */
128 static int __replace_page(struct vm_area_struct *vma, struct page *page, struct page *kpage)
129 {
130         struct mm_struct *mm = vma->vm_mm;
131         pgd_t *pgd;
132         pud_t *pud;
133         pmd_t *pmd;
134         pte_t *ptep;
135         spinlock_t *ptl;
136         unsigned long addr;
137         int err = -EFAULT;
138
139         addr = page_address_in_vma(page, vma);
140         if (addr == -EFAULT)
141                 goto out;
142
143         pgd = pgd_offset(mm, addr);
144         if (!pgd_present(*pgd))
145                 goto out;
146
147         pud = pud_offset(pgd, addr);
148         if (!pud_present(*pud))
149                 goto out;
150
151         pmd = pmd_offset(pud, addr);
152         if (!pmd_present(*pmd))
153                 goto out;
154
155         ptep = pte_offset_map_lock(mm, pmd, addr, &ptl);
156         if (!ptep)
157                 goto out;
158
159         get_page(kpage);
160         page_add_new_anon_rmap(kpage, vma, addr);
161
162         if (!PageAnon(page)) {
163                 dec_mm_counter(mm, MM_FILEPAGES);
164                 inc_mm_counter(mm, MM_ANONPAGES);
165         }
166
167         flush_cache_page(vma, addr, pte_pfn(*ptep));
168         ptep_clear_flush(vma, addr, ptep);
169         set_pte_at_notify(mm, addr, ptep, mk_pte(kpage, vma->vm_page_prot));
170
171         page_remove_rmap(page);
172         if (!page_mapped(page))
173                 try_to_free_swap(page);
174         put_page(page);
175         pte_unmap_unlock(ptep, ptl);
176         err = 0;
177
178 out:
179         return err;
180 }
181
182 /**
183  * is_swbp_insn - check if instruction is breakpoint instruction.
184  * @insn: instruction to be checked.
185  * Default implementation of is_swbp_insn
186  * Returns true if @insn is a breakpoint instruction.
187  */
188 bool __weak is_swbp_insn(uprobe_opcode_t *insn)
189 {
190         return *insn == UPROBE_SWBP_INSN;
191 }
192
193 /*
194  * NOTE:
195  * Expect the breakpoint instruction to be the smallest size instruction for
196  * the architecture. If an arch has variable length instruction and the
197  * breakpoint instruction is not of the smallest length instruction
198  * supported by that architecture then we need to modify read_opcode /
199  * write_opcode accordingly. This would never be a problem for archs that
200  * have fixed length instructions.
201  */
202
203 /*
204  * write_opcode - write the opcode at a given virtual address.
205  * @auprobe: arch breakpointing information.
206  * @mm: the probed process address space.
207  * @vaddr: the virtual address to store the opcode.
208  * @opcode: opcode to be written at @vaddr.
209  *
210  * Called with mm->mmap_sem held (for read and with a reference to
211  * mm).
212  *
213  * For mm @mm, write the opcode at @vaddr.
214  * Return 0 (success) or a negative errno.
215  */
216 static int write_opcode(struct arch_uprobe *auprobe, struct mm_struct *mm,
217                         unsigned long vaddr, uprobe_opcode_t opcode)
218 {
219         struct page *old_page, *new_page;
220         struct address_space *mapping;
221         void *vaddr_old, *vaddr_new;
222         struct vm_area_struct *vma;
223         struct uprobe *uprobe;
224         loff_t addr;
225         int ret;
226
227         /* Read the page with vaddr into memory */
228         ret = get_user_pages(NULL, mm, vaddr, 1, 0, 0, &old_page, &vma);
229         if (ret <= 0)
230                 return ret;
231
232         ret = -EINVAL;
233
234         /*
235          * We are interested in text pages only. Our pages of interest
236          * should be mapped for read and execute only. We desist from
237          * adding probes in write mapped pages since the breakpoints
238          * might end up in the file copy.
239          */
240         if (!valid_vma(vma, is_swbp_insn(&opcode)))
241                 goto put_out;
242
243         uprobe = container_of(auprobe, struct uprobe, arch);
244         mapping = uprobe->inode->i_mapping;
245         if (mapping != vma->vm_file->f_mapping)
246                 goto put_out;
247
248         addr = vma_address(vma, uprobe->offset);
249         if (vaddr != (unsigned long)addr)
250                 goto put_out;
251
252         ret = -ENOMEM;
253         new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vaddr);
254         if (!new_page)
255                 goto put_out;
256
257         __SetPageUptodate(new_page);
258
259         /*
260          * lock page will serialize against do_wp_page()'s
261          * PageAnon() handling
262          */
263         lock_page(old_page);
264         /* copy the page now that we've got it stable */
265         vaddr_old = kmap_atomic(old_page);
266         vaddr_new = kmap_atomic(new_page);
267
268         memcpy(vaddr_new, vaddr_old, PAGE_SIZE);
269
270         /* poke the new insn in, ASSUMES we don't cross page boundary */
271         vaddr &= ~PAGE_MASK;
272         BUG_ON(vaddr + UPROBE_SWBP_INSN_SIZE > PAGE_SIZE);
273         memcpy(vaddr_new + vaddr, &opcode, UPROBE_SWBP_INSN_SIZE);
274
275         kunmap_atomic(vaddr_new);
276         kunmap_atomic(vaddr_old);
277
278         ret = anon_vma_prepare(vma);
279         if (ret)
280                 goto unlock_out;
281
282         lock_page(new_page);
283         ret = __replace_page(vma, old_page, new_page);
284         unlock_page(new_page);
285
286 unlock_out:
287         unlock_page(old_page);
288         page_cache_release(new_page);
289
290 put_out:
291         put_page(old_page);
292
293         return ret;
294 }
295
296 /**
297  * read_opcode - read the opcode at a given virtual address.
298  * @mm: the probed process address space.
299  * @vaddr: the virtual address to read the opcode.
300  * @opcode: location to store the read opcode.
301  *
302  * Called with mm->mmap_sem held (for read and with a reference to
303  * mm.
304  *
305  * For mm @mm, read the opcode at @vaddr and store it in @opcode.
306  * Return 0 (success) or a negative errno.
307  */
308 static int read_opcode(struct mm_struct *mm, unsigned long vaddr, uprobe_opcode_t *opcode)
309 {
310         struct page *page;
311         void *vaddr_new;
312         int ret;
313
314         ret = get_user_pages(NULL, mm, vaddr, 1, 0, 1, &page, NULL);
315         if (ret <= 0)
316                 return ret;
317
318         lock_page(page);
319         vaddr_new = kmap_atomic(page);
320         vaddr &= ~PAGE_MASK;
321         memcpy(opcode, vaddr_new + vaddr, UPROBE_SWBP_INSN_SIZE);
322         kunmap_atomic(vaddr_new);
323         unlock_page(page);
324
325         put_page(page);
326
327         return 0;
328 }
329
330 static int is_swbp_at_addr(struct mm_struct *mm, unsigned long vaddr)
331 {
332         uprobe_opcode_t opcode;
333         int result;
334
335         if (current->mm == mm) {
336                 pagefault_disable();
337                 result = __copy_from_user_inatomic(&opcode, (void __user*)vaddr,
338                                                                 sizeof(opcode));
339                 pagefault_enable();
340
341                 if (likely(result == 0))
342                         goto out;
343         }
344
345         result = read_opcode(mm, vaddr, &opcode);
346         if (result)
347                 return result;
348 out:
349         if (is_swbp_insn(&opcode))
350                 return 1;
351
352         return 0;
353 }
354
355 /**
356  * set_swbp - store breakpoint at a given address.
357  * @auprobe: arch specific probepoint information.
358  * @mm: the probed process address space.
359  * @vaddr: the virtual address to insert the opcode.
360  *
361  * For mm @mm, store the breakpoint instruction at @vaddr.
362  * Return 0 (success) or a negative errno.
363  */
364 int __weak set_swbp(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr)
365 {
366         int result;
367
368         result = is_swbp_at_addr(mm, vaddr);
369         if (result == 1)
370                 return -EEXIST;
371
372         if (result)
373                 return result;
374
375         return write_opcode(auprobe, mm, vaddr, UPROBE_SWBP_INSN);
376 }
377
378 /**
379  * set_orig_insn - Restore the original instruction.
380  * @mm: the probed process address space.
381  * @auprobe: arch specific probepoint information.
382  * @vaddr: the virtual address to insert the opcode.
383  * @verify: if true, verify existance of breakpoint instruction.
384  *
385  * For mm @mm, restore the original opcode (opcode) at @vaddr.
386  * Return 0 (success) or a negative errno.
387  */
388 int __weak
389 set_orig_insn(struct arch_uprobe *auprobe, struct mm_struct *mm, unsigned long vaddr, bool verify)
390 {
391         if (verify) {
392                 int result;
393
394                 result = is_swbp_at_addr(mm, vaddr);
395                 if (!result)
396                         return -EINVAL;
397
398                 if (result != 1)
399                         return result;
400         }
401         return write_opcode(auprobe, mm, vaddr, *(uprobe_opcode_t *)auprobe->insn);
402 }
403
404 static int match_uprobe(struct uprobe *l, struct uprobe *r)
405 {
406         if (l->inode < r->inode)
407                 return -1;
408
409         if (l->inode > r->inode)
410                 return 1;
411
412         if (l->offset < r->offset)
413                 return -1;
414
415         if (l->offset > r->offset)
416                 return 1;
417
418         return 0;
419 }
420
421 static struct uprobe *__find_uprobe(struct inode *inode, loff_t offset)
422 {
423         struct uprobe u = { .inode = inode, .offset = offset };
424         struct rb_node *n = uprobes_tree.rb_node;
425         struct uprobe *uprobe;
426         int match;
427
428         while (n) {
429                 uprobe = rb_entry(n, struct uprobe, rb_node);
430                 match = match_uprobe(&u, uprobe);
431                 if (!match) {
432                         atomic_inc(&uprobe->ref);
433                         return uprobe;
434                 }
435
436                 if (match < 0)
437                         n = n->rb_left;
438                 else
439                         n = n->rb_right;
440         }
441         return NULL;
442 }
443
444 /*
445  * Find a uprobe corresponding to a given inode:offset
446  * Acquires uprobes_treelock
447  */
448 static struct uprobe *find_uprobe(struct inode *inode, loff_t offset)
449 {
450         struct uprobe *uprobe;
451         unsigned long flags;
452
453         spin_lock_irqsave(&uprobes_treelock, flags);
454         uprobe = __find_uprobe(inode, offset);
455         spin_unlock_irqrestore(&uprobes_treelock, flags);
456
457         return uprobe;
458 }
459
460 static struct uprobe *__insert_uprobe(struct uprobe *uprobe)
461 {
462         struct rb_node **p = &uprobes_tree.rb_node;
463         struct rb_node *parent = NULL;
464         struct uprobe *u;
465         int match;
466
467         while (*p) {
468                 parent = *p;
469                 u = rb_entry(parent, struct uprobe, rb_node);
470                 match = match_uprobe(uprobe, u);
471                 if (!match) {
472                         atomic_inc(&u->ref);
473                         return u;
474                 }
475
476                 if (match < 0)
477                         p = &parent->rb_left;
478                 else
479                         p = &parent->rb_right;
480
481         }
482
483         u = NULL;
484         rb_link_node(&uprobe->rb_node, parent, p);
485         rb_insert_color(&uprobe->rb_node, &uprobes_tree);
486         /* get access + creation ref */
487         atomic_set(&uprobe->ref, 2);
488
489         return u;
490 }
491
492 /*
493  * Acquire uprobes_treelock.
494  * Matching uprobe already exists in rbtree;
495  *      increment (access refcount) and return the matching uprobe.
496  *
497  * No matching uprobe; insert the uprobe in rb_tree;
498  *      get a double refcount (access + creation) and return NULL.
499  */
500 static struct uprobe *insert_uprobe(struct uprobe *uprobe)
501 {
502         unsigned long flags;
503         struct uprobe *u;
504
505         spin_lock_irqsave(&uprobes_treelock, flags);
506         u = __insert_uprobe(uprobe);
507         spin_unlock_irqrestore(&uprobes_treelock, flags);
508
509         /* For now assume that the instruction need not be single-stepped */
510         uprobe->flags |= UPROBE_SKIP_SSTEP;
511
512         return u;
513 }
514
515 static void put_uprobe(struct uprobe *uprobe)
516 {
517         if (atomic_dec_and_test(&uprobe->ref))
518                 kfree(uprobe);
519 }
520
521 static struct uprobe *alloc_uprobe(struct inode *inode, loff_t offset)
522 {
523         struct uprobe *uprobe, *cur_uprobe;
524
525         uprobe = kzalloc(sizeof(struct uprobe), GFP_KERNEL);
526         if (!uprobe)
527                 return NULL;
528
529         uprobe->inode = igrab(inode);
530         uprobe->offset = offset;
531         init_rwsem(&uprobe->consumer_rwsem);
532         INIT_LIST_HEAD(&uprobe->pending_list);
533
534         /* add to uprobes_tree, sorted on inode:offset */
535         cur_uprobe = insert_uprobe(uprobe);
536
537         /* a uprobe exists for this inode:offset combination */
538         if (cur_uprobe) {
539                 kfree(uprobe);
540                 uprobe = cur_uprobe;
541                 iput(inode);
542         } else {
543                 atomic_inc(&uprobe_events);
544         }
545
546         return uprobe;
547 }
548
549 static void handler_chain(struct uprobe *uprobe, struct pt_regs *regs)
550 {
551         struct uprobe_consumer *uc;
552
553         if (!(uprobe->flags & UPROBE_RUN_HANDLER))
554                 return;
555
556         down_read(&uprobe->consumer_rwsem);
557         for (uc = uprobe->consumers; uc; uc = uc->next) {
558                 if (!uc->filter || uc->filter(uc, current))
559                         uc->handler(uc, regs);
560         }
561         up_read(&uprobe->consumer_rwsem);
562 }
563
564 /* Returns the previous consumer */
565 static struct uprobe_consumer *
566 consumer_add(struct uprobe *uprobe, struct uprobe_consumer *uc)
567 {
568         down_write(&uprobe->consumer_rwsem);
569         uc->next = uprobe->consumers;
570         uprobe->consumers = uc;
571         up_write(&uprobe->consumer_rwsem);
572
573         return uc->next;
574 }
575
576 /*
577  * For uprobe @uprobe, delete the consumer @uc.
578  * Return true if the @uc is deleted successfully
579  * or return false.
580  */
581 static bool consumer_del(struct uprobe *uprobe, struct uprobe_consumer *uc)
582 {
583         struct uprobe_consumer **con;
584         bool ret = false;
585
586         down_write(&uprobe->consumer_rwsem);
587         for (con = &uprobe->consumers; *con; con = &(*con)->next) {
588                 if (*con == uc) {
589                         *con = uc->next;
590                         ret = true;
591                         break;
592                 }
593         }
594         up_write(&uprobe->consumer_rwsem);
595
596         return ret;
597 }
598
599 static int
600 __copy_insn(struct address_space *mapping, struct vm_area_struct *vma, char *insn,
601                         unsigned long nbytes, unsigned long offset)
602 {
603         struct file *filp = vma->vm_file;
604         struct page *page;
605         void *vaddr;
606         unsigned long off1;
607         unsigned long idx;
608
609         if (!filp)
610                 return -EINVAL;
611
612         idx = (unsigned long)(offset >> PAGE_CACHE_SHIFT);
613         off1 = offset &= ~PAGE_MASK;
614
615         /*
616          * Ensure that the page that has the original instruction is
617          * populated and in page-cache.
618          */
619         page = read_mapping_page(mapping, idx, filp);
620         if (IS_ERR(page))
621                 return PTR_ERR(page);
622
623         vaddr = kmap_atomic(page);
624         memcpy(insn, vaddr + off1, nbytes);
625         kunmap_atomic(vaddr);
626         page_cache_release(page);
627
628         return 0;
629 }
630
631 static int
632 copy_insn(struct uprobe *uprobe, struct vm_area_struct *vma, unsigned long addr)
633 {
634         struct address_space *mapping;
635         unsigned long nbytes;
636         int bytes;
637
638         addr &= ~PAGE_MASK;
639         nbytes = PAGE_SIZE - addr;
640         mapping = uprobe->inode->i_mapping;
641
642         /* Instruction at end of binary; copy only available bytes */
643         if (uprobe->offset + MAX_UINSN_BYTES > uprobe->inode->i_size)
644                 bytes = uprobe->inode->i_size - uprobe->offset;
645         else
646                 bytes = MAX_UINSN_BYTES;
647
648         /* Instruction at the page-boundary; copy bytes in second page */
649         if (nbytes < bytes) {
650                 if (__copy_insn(mapping, vma, uprobe->arch.insn + nbytes,
651                                 bytes - nbytes, uprobe->offset + nbytes))
652                         return -ENOMEM;
653
654                 bytes = nbytes;
655         }
656         return __copy_insn(mapping, vma, uprobe->arch.insn, bytes, uprobe->offset);
657 }
658
659 /*
660  * How mm->uprobes_state.count gets updated
661  * uprobe_mmap() increments the count if
662  *      - it successfully adds a breakpoint.
663  *      - it cannot add a breakpoint, but sees that there is a underlying
664  *        breakpoint (via a is_swbp_at_addr()).
665  *
666  * uprobe_munmap() decrements the count if
667  *      - it sees a underlying breakpoint, (via is_swbp_at_addr)
668  *        (Subsequent uprobe_unregister wouldnt find the breakpoint
669  *        unless a uprobe_mmap kicks in, since the old vma would be
670  *        dropped just after uprobe_munmap.)
671  *
672  * uprobe_register increments the count if:
673  *      - it successfully adds a breakpoint.
674  *
675  * uprobe_unregister decrements the count if:
676  *      - it sees a underlying breakpoint and removes successfully.
677  *        (via is_swbp_at_addr)
678  *        (Subsequent uprobe_munmap wouldnt find the breakpoint
679  *        since there is no underlying breakpoint after the
680  *        breakpoint removal.)
681  */
682 static int
683 install_breakpoint(struct uprobe *uprobe, struct mm_struct *mm,
684                         struct vm_area_struct *vma, loff_t vaddr)
685 {
686         unsigned long addr;
687         int ret;
688
689         /*
690          * If probe is being deleted, unregister thread could be done with
691          * the vma-rmap-walk through. Adding a probe now can be fatal since
692          * nobody will be able to cleanup. Also we could be from fork or
693          * mremap path, where the probe might have already been inserted.
694          * Hence behave as if probe already existed.
695          */
696         if (!uprobe->consumers)
697                 return -EEXIST;
698
699         addr = (unsigned long)vaddr;
700
701         if (!(uprobe->flags & UPROBE_COPY_INSN)) {
702                 ret = copy_insn(uprobe, vma, addr);
703                 if (ret)
704                         return ret;
705
706                 if (is_swbp_insn((uprobe_opcode_t *)uprobe->arch.insn))
707                         return -EEXIST;
708
709                 ret = arch_uprobe_analyze_insn(&uprobe->arch, mm, addr);
710                 if (ret)
711                         return ret;
712
713                 uprobe->flags |= UPROBE_COPY_INSN;
714         }
715
716         /*
717          * Ideally, should be updating the probe count after the breakpoint
718          * has been successfully inserted. However a thread could hit the
719          * breakpoint we just inserted even before the probe count is
720          * incremented. If this is the first breakpoint placed, breakpoint
721          * notifier might ignore uprobes and pass the trap to the thread.
722          * Hence increment before and decrement on failure.
723          */
724         atomic_inc(&mm->uprobes_state.count);
725         ret = set_swbp(&uprobe->arch, mm, addr);
726         if (ret)
727                 atomic_dec(&mm->uprobes_state.count);
728
729         return ret;
730 }
731
732 static void
733 remove_breakpoint(struct uprobe *uprobe, struct mm_struct *mm, loff_t vaddr)
734 {
735         if (!set_orig_insn(&uprobe->arch, mm, (unsigned long)vaddr, true))
736                 atomic_dec(&mm->uprobes_state.count);
737 }
738
739 /*
740  * There could be threads that have already hit the breakpoint. They
741  * will recheck the current insn and restart if find_uprobe() fails.
742  * See find_active_uprobe().
743  */
744 static void delete_uprobe(struct uprobe *uprobe)
745 {
746         unsigned long flags;
747
748         spin_lock_irqsave(&uprobes_treelock, flags);
749         rb_erase(&uprobe->rb_node, &uprobes_tree);
750         spin_unlock_irqrestore(&uprobes_treelock, flags);
751         iput(uprobe->inode);
752         put_uprobe(uprobe);
753         atomic_dec(&uprobe_events);
754 }
755
756 static struct vma_info *
757 __find_next_vma_info(struct address_space *mapping, struct list_head *head,
758                         struct vma_info *vi, loff_t offset, bool is_register)
759 {
760         struct prio_tree_iter iter;
761         struct vm_area_struct *vma;
762         struct vma_info *tmpvi;
763         unsigned long pgoff;
764         int existing_vma;
765         loff_t vaddr;
766
767         pgoff = offset >> PAGE_SHIFT;
768
769         vma_prio_tree_foreach(vma, &iter, &mapping->i_mmap, pgoff, pgoff) {
770                 if (!valid_vma(vma, is_register))
771                         continue;
772
773                 existing_vma = 0;
774                 vaddr = vma_address(vma, offset);
775
776                 list_for_each_entry(tmpvi, head, probe_list) {
777                         if (tmpvi->mm == vma->vm_mm && tmpvi->vaddr == vaddr) {
778                                 existing_vma = 1;
779                                 break;
780                         }
781                 }
782
783                 /*
784                  * Another vma needs a probe to be installed. However skip
785                  * installing the probe if the vma is about to be unlinked.
786                  */
787                 if (!existing_vma && atomic_inc_not_zero(&vma->vm_mm->mm_users)) {
788                         vi->mm = vma->vm_mm;
789                         vi->vaddr = vaddr;
790                         list_add(&vi->probe_list, head);
791
792                         return vi;
793                 }
794         }
795
796         return NULL;
797 }
798
799 /*
800  * Iterate in the rmap prio tree  and find a vma where a probe has not
801  * yet been inserted.
802  */
803 static struct vma_info *
804 find_next_vma_info(struct address_space *mapping, struct list_head *head,
805                 loff_t offset, bool is_register)
806 {
807         struct vma_info *vi, *retvi;
808
809         vi = kzalloc(sizeof(struct vma_info), GFP_KERNEL);
810         if (!vi)
811                 return ERR_PTR(-ENOMEM);
812
813         mutex_lock(&mapping->i_mmap_mutex);
814         retvi = __find_next_vma_info(mapping, head, vi, offset, is_register);
815         mutex_unlock(&mapping->i_mmap_mutex);
816
817         if (!retvi)
818                 kfree(vi);
819
820         return retvi;
821 }
822
823 static int register_for_each_vma(struct uprobe *uprobe, bool is_register)
824 {
825         struct list_head try_list;
826         struct vm_area_struct *vma;
827         struct address_space *mapping;
828         struct vma_info *vi, *tmpvi;
829         struct mm_struct *mm;
830         loff_t vaddr;
831         int ret;
832
833         mapping = uprobe->inode->i_mapping;
834         INIT_LIST_HEAD(&try_list);
835
836         ret = 0;
837
838         for (;;) {
839                 vi = find_next_vma_info(mapping, &try_list, uprobe->offset, is_register);
840                 if (!vi)
841                         break;
842
843                 if (IS_ERR(vi)) {
844                         ret = PTR_ERR(vi);
845                         break;
846                 }
847
848                 mm = vi->mm;
849                 down_write(&mm->mmap_sem);
850                 vma = find_vma(mm, (unsigned long)vi->vaddr);
851                 if (!vma || !valid_vma(vma, is_register)) {
852                         list_del(&vi->probe_list);
853                         kfree(vi);
854                         up_write(&mm->mmap_sem);
855                         mmput(mm);
856                         continue;
857                 }
858                 vaddr = vma_address(vma, uprobe->offset);
859                 if (vma->vm_file->f_mapping->host != uprobe->inode ||
860                                                 vaddr != vi->vaddr) {
861                         list_del(&vi->probe_list);
862                         kfree(vi);
863                         up_write(&mm->mmap_sem);
864                         mmput(mm);
865                         continue;
866                 }
867
868                 if (is_register)
869                         ret = install_breakpoint(uprobe, mm, vma, vi->vaddr);
870                 else
871                         remove_breakpoint(uprobe, mm, vi->vaddr);
872
873                 up_write(&mm->mmap_sem);
874                 mmput(mm);
875                 if (is_register) {
876                         if (ret && ret == -EEXIST)
877                                 ret = 0;
878                         if (ret)
879                                 break;
880                 }
881         }
882
883         list_for_each_entry_safe(vi, tmpvi, &try_list, probe_list) {
884                 list_del(&vi->probe_list);
885                 kfree(vi);
886         }
887
888         return ret;
889 }
890
891 static int __uprobe_register(struct uprobe *uprobe)
892 {
893         return register_for_each_vma(uprobe, true);
894 }
895
896 static void __uprobe_unregister(struct uprobe *uprobe)
897 {
898         if (!register_for_each_vma(uprobe, false))
899                 delete_uprobe(uprobe);
900
901         /* TODO : cant unregister? schedule a worker thread */
902 }
903
904 /*
905  * uprobe_register - register a probe
906  * @inode: the file in which the probe has to be placed.
907  * @offset: offset from the start of the file.
908  * @uc: information on howto handle the probe..
909  *
910  * Apart from the access refcount, uprobe_register() takes a creation
911  * refcount (thro alloc_uprobe) if and only if this @uprobe is getting
912  * inserted into the rbtree (i.e first consumer for a @inode:@offset
913  * tuple).  Creation refcount stops uprobe_unregister from freeing the
914  * @uprobe even before the register operation is complete. Creation
915  * refcount is released when the last @uc for the @uprobe
916  * unregisters.
917  *
918  * Return errno if it cannot successully install probes
919  * else return 0 (success)
920  */
921 int uprobe_register(struct inode *inode, loff_t offset, struct uprobe_consumer *uc)
922 {
923         struct uprobe *uprobe;
924         int ret;
925
926         if (!inode || !uc || uc->next)
927                 return -EINVAL;
928
929         if (offset > i_size_read(inode))
930                 return -EINVAL;
931
932         ret = 0;
933         mutex_lock(uprobes_hash(inode));
934         uprobe = alloc_uprobe(inode, offset);
935
936         if (uprobe && !consumer_add(uprobe, uc)) {
937                 ret = __uprobe_register(uprobe);
938                 if (ret) {
939                         uprobe->consumers = NULL;
940                         __uprobe_unregister(uprobe);
941                 } else {
942                         uprobe->flags |= UPROBE_RUN_HANDLER;
943                 }
944         }
945
946         mutex_unlock(uprobes_hash(inode));
947         put_uprobe(uprobe);
948
949         return ret;
950 }
951
952 /*
953  * uprobe_unregister - unregister a already registered probe.
954  * @inode: the file in which the probe has to be removed.
955  * @offset: offset from the start of the file.
956  * @uc: identify which probe if multiple probes are colocated.
957  */
958 void uprobe_unregister(struct inode *inode, loff_t offset, struct uprobe_consumer *uc)
959 {
960         struct uprobe *uprobe;
961
962         if (!inode || !uc)
963                 return;
964
965         uprobe = find_uprobe(inode, offset);
966         if (!uprobe)
967                 return;
968
969         mutex_lock(uprobes_hash(inode));
970
971         if (consumer_del(uprobe, uc)) {
972                 if (!uprobe->consumers) {
973                         __uprobe_unregister(uprobe);
974                         uprobe->flags &= ~UPROBE_RUN_HANDLER;
975                 }
976         }
977
978         mutex_unlock(uprobes_hash(inode));
979         if (uprobe)
980                 put_uprobe(uprobe);
981 }
982
983 /*
984  * Of all the nodes that correspond to the given inode, return the node
985  * with the least offset.
986  */
987 static struct rb_node *find_least_offset_node(struct inode *inode)
988 {
989         struct uprobe u = { .inode = inode, .offset = 0};
990         struct rb_node *n = uprobes_tree.rb_node;
991         struct rb_node *close_node = NULL;
992         struct uprobe *uprobe;
993         int match;
994
995         while (n) {
996                 uprobe = rb_entry(n, struct uprobe, rb_node);
997                 match = match_uprobe(&u, uprobe);
998
999                 if (uprobe->inode == inode)
1000                         close_node = n;
1001
1002                 if (!match)
1003                         return close_node;
1004
1005                 if (match < 0)
1006                         n = n->rb_left;
1007                 else
1008                         n = n->rb_right;
1009         }
1010
1011         return close_node;
1012 }
1013
1014 /*
1015  * For a given inode, build a list of probes that need to be inserted.
1016  */
1017 static void build_probe_list(struct inode *inode, struct list_head *head)
1018 {
1019         struct uprobe *uprobe;
1020         unsigned long flags;
1021         struct rb_node *n;
1022
1023         spin_lock_irqsave(&uprobes_treelock, flags);
1024
1025         n = find_least_offset_node(inode);
1026
1027         for (; n; n = rb_next(n)) {
1028                 uprobe = rb_entry(n, struct uprobe, rb_node);
1029                 if (uprobe->inode != inode)
1030                         break;
1031
1032                 list_add(&uprobe->pending_list, head);
1033                 atomic_inc(&uprobe->ref);
1034         }
1035
1036         spin_unlock_irqrestore(&uprobes_treelock, flags);
1037 }
1038
1039 /*
1040  * Called from mmap_region.
1041  * called with mm->mmap_sem acquired.
1042  *
1043  * Return -ve no if we fail to insert probes and we cannot
1044  * bail-out.
1045  * Return 0 otherwise. i.e:
1046  *
1047  *      - successful insertion of probes
1048  *      - (or) no possible probes to be inserted.
1049  *      - (or) insertion of probes failed but we can bail-out.
1050  */
1051 int uprobe_mmap(struct vm_area_struct *vma)
1052 {
1053         struct list_head tmp_list;
1054         struct uprobe *uprobe, *u;
1055         struct inode *inode;
1056         int ret, count;
1057
1058         if (!atomic_read(&uprobe_events) || !valid_vma(vma, true))
1059                 return 0;
1060
1061         inode = vma->vm_file->f_mapping->host;
1062         if (!inode)
1063                 return 0;
1064
1065         INIT_LIST_HEAD(&tmp_list);
1066         mutex_lock(uprobes_mmap_hash(inode));
1067         build_probe_list(inode, &tmp_list);
1068
1069         ret = 0;
1070         count = 0;
1071
1072         list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) {
1073                 loff_t vaddr;
1074
1075                 list_del(&uprobe->pending_list);
1076                 if (!ret) {
1077                         vaddr = vma_address(vma, uprobe->offset);
1078
1079                         if (vaddr < vma->vm_start || vaddr >= vma->vm_end) {
1080                                 put_uprobe(uprobe);
1081                                 continue;
1082                         }
1083
1084                         ret = install_breakpoint(uprobe, vma->vm_mm, vma, vaddr);
1085
1086                         /* Ignore double add: */
1087                         if (ret == -EEXIST) {
1088                                 ret = 0;
1089
1090                                 if (!is_swbp_at_addr(vma->vm_mm, vaddr))
1091                                         continue;
1092
1093                                 /*
1094                                  * Unable to insert a breakpoint, but
1095                                  * breakpoint lies underneath. Increment the
1096                                  * probe count.
1097                                  */
1098                                 atomic_inc(&vma->vm_mm->uprobes_state.count);
1099                         }
1100
1101                         if (!ret)
1102                                 count++;
1103                 }
1104                 put_uprobe(uprobe);
1105         }
1106
1107         mutex_unlock(uprobes_mmap_hash(inode));
1108
1109         if (ret)
1110                 atomic_sub(count, &vma->vm_mm->uprobes_state.count);
1111
1112         return ret;
1113 }
1114
1115 /*
1116  * Called in context of a munmap of a vma.
1117  */
1118 void uprobe_munmap(struct vm_area_struct *vma, unsigned long start, unsigned long end)
1119 {
1120         struct list_head tmp_list;
1121         struct uprobe *uprobe, *u;
1122         struct inode *inode;
1123
1124         if (!atomic_read(&uprobe_events) || !valid_vma(vma, false))
1125                 return;
1126
1127         if (!atomic_read(&vma->vm_mm->uprobes_state.count))
1128                 return;
1129
1130         inode = vma->vm_file->f_mapping->host;
1131         if (!inode)
1132                 return;
1133
1134         INIT_LIST_HEAD(&tmp_list);
1135         mutex_lock(uprobes_mmap_hash(inode));
1136         build_probe_list(inode, &tmp_list);
1137
1138         list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) {
1139                 loff_t vaddr;
1140
1141                 list_del(&uprobe->pending_list);
1142                 vaddr = vma_address(vma, uprobe->offset);
1143
1144                 if (vaddr >= start && vaddr < end) {
1145                         /*
1146                          * An unregister could have removed the probe before
1147                          * unmap. So check before we decrement the count.
1148                          */
1149                         if (is_swbp_at_addr(vma->vm_mm, vaddr) == 1)
1150                                 atomic_dec(&vma->vm_mm->uprobes_state.count);
1151                 }
1152                 put_uprobe(uprobe);
1153         }
1154         mutex_unlock(uprobes_mmap_hash(inode));
1155 }
1156
1157 /* Slot allocation for XOL */
1158 static int xol_add_vma(struct xol_area *area)
1159 {
1160         struct mm_struct *mm;
1161         int ret;
1162
1163         area->page = alloc_page(GFP_HIGHUSER);
1164         if (!area->page)
1165                 return -ENOMEM;
1166
1167         ret = -EALREADY;
1168         mm = current->mm;
1169
1170         down_write(&mm->mmap_sem);
1171         if (mm->uprobes_state.xol_area)
1172                 goto fail;
1173
1174         ret = -ENOMEM;
1175
1176         /* Try to map as high as possible, this is only a hint. */
1177         area->vaddr = get_unmapped_area(NULL, TASK_SIZE - PAGE_SIZE, PAGE_SIZE, 0, 0);
1178         if (area->vaddr & ~PAGE_MASK) {
1179                 ret = area->vaddr;
1180                 goto fail;
1181         }
1182
1183         ret = install_special_mapping(mm, area->vaddr, PAGE_SIZE,
1184                                 VM_EXEC|VM_MAYEXEC|VM_DONTCOPY|VM_IO, &area->page);
1185         if (ret)
1186                 goto fail;
1187
1188         smp_wmb();      /* pairs with get_xol_area() */
1189         mm->uprobes_state.xol_area = area;
1190         ret = 0;
1191
1192 fail:
1193         up_write(&mm->mmap_sem);
1194         if (ret)
1195                 __free_page(area->page);
1196
1197         return ret;
1198 }
1199
1200 static struct xol_area *get_xol_area(struct mm_struct *mm)
1201 {
1202         struct xol_area *area;
1203
1204         area = mm->uprobes_state.xol_area;
1205         smp_read_barrier_depends();     /* pairs with wmb in xol_add_vma() */
1206
1207         return area;
1208 }
1209
1210 /*
1211  * xol_alloc_area - Allocate process's xol_area.
1212  * This area will be used for storing instructions for execution out of
1213  * line.
1214  *
1215  * Returns the allocated area or NULL.
1216  */
1217 static struct xol_area *xol_alloc_area(void)
1218 {
1219         struct xol_area *area;
1220
1221         area = kzalloc(sizeof(*area), GFP_KERNEL);
1222         if (unlikely(!area))
1223                 return NULL;
1224
1225         area->bitmap = kzalloc(BITS_TO_LONGS(UINSNS_PER_PAGE) * sizeof(long), GFP_KERNEL);
1226
1227         if (!area->bitmap)
1228                 goto fail;
1229
1230         init_waitqueue_head(&area->wq);
1231         if (!xol_add_vma(area))
1232                 return area;
1233
1234 fail:
1235         kfree(area->bitmap);
1236         kfree(area);
1237
1238         return get_xol_area(current->mm);
1239 }
1240
1241 /*
1242  * uprobe_clear_state - Free the area allocated for slots.
1243  */
1244 void uprobe_clear_state(struct mm_struct *mm)
1245 {
1246         struct xol_area *area = mm->uprobes_state.xol_area;
1247
1248         if (!area)
1249                 return;
1250
1251         put_page(area->page);
1252         kfree(area->bitmap);
1253         kfree(area);
1254 }
1255
1256 /*
1257  * uprobe_reset_state - Free the area allocated for slots.
1258  */
1259 void uprobe_reset_state(struct mm_struct *mm)
1260 {
1261         mm->uprobes_state.xol_area = NULL;
1262         atomic_set(&mm->uprobes_state.count, 0);
1263 }
1264
1265 /*
1266  *  - search for a free slot.
1267  */
1268 static unsigned long xol_take_insn_slot(struct xol_area *area)
1269 {
1270         unsigned long slot_addr;
1271         int slot_nr;
1272
1273         do {
1274                 slot_nr = find_first_zero_bit(area->bitmap, UINSNS_PER_PAGE);
1275                 if (slot_nr < UINSNS_PER_PAGE) {
1276                         if (!test_and_set_bit(slot_nr, area->bitmap))
1277                                 break;
1278
1279                         slot_nr = UINSNS_PER_PAGE;
1280                         continue;
1281                 }
1282                 wait_event(area->wq, (atomic_read(&area->slot_count) < UINSNS_PER_PAGE));
1283         } while (slot_nr >= UINSNS_PER_PAGE);
1284
1285         slot_addr = area->vaddr + (slot_nr * UPROBE_XOL_SLOT_BYTES);
1286         atomic_inc(&area->slot_count);
1287
1288         return slot_addr;
1289 }
1290
1291 /*
1292  * xol_get_insn_slot - If was not allocated a slot, then
1293  * allocate a slot.
1294  * Returns the allocated slot address or 0.
1295  */
1296 static unsigned long xol_get_insn_slot(struct uprobe *uprobe, unsigned long slot_addr)
1297 {
1298         struct xol_area *area;
1299         unsigned long offset;
1300         void *vaddr;
1301
1302         area = get_xol_area(current->mm);
1303         if (!area) {
1304                 area = xol_alloc_area();
1305                 if (!area)
1306                         return 0;
1307         }
1308         current->utask->xol_vaddr = xol_take_insn_slot(area);
1309
1310         /*
1311          * Initialize the slot if xol_vaddr points to valid
1312          * instruction slot.
1313          */
1314         if (unlikely(!current->utask->xol_vaddr))
1315                 return 0;
1316
1317         current->utask->vaddr = slot_addr;
1318         offset = current->utask->xol_vaddr & ~PAGE_MASK;
1319         vaddr = kmap_atomic(area->page);
1320         memcpy(vaddr + offset, uprobe->arch.insn, MAX_UINSN_BYTES);
1321         kunmap_atomic(vaddr);
1322
1323         return current->utask->xol_vaddr;
1324 }
1325
1326 /*
1327  * xol_free_insn_slot - If slot was earlier allocated by
1328  * @xol_get_insn_slot(), make the slot available for
1329  * subsequent requests.
1330  */
1331 static void xol_free_insn_slot(struct task_struct *tsk)
1332 {
1333         struct xol_area *area;
1334         unsigned long vma_end;
1335         unsigned long slot_addr;
1336
1337         if (!tsk->mm || !tsk->mm->uprobes_state.xol_area || !tsk->utask)
1338                 return;
1339
1340         slot_addr = tsk->utask->xol_vaddr;
1341
1342         if (unlikely(!slot_addr || IS_ERR_VALUE(slot_addr)))
1343                 return;
1344
1345         area = tsk->mm->uprobes_state.xol_area;
1346         vma_end = area->vaddr + PAGE_SIZE;
1347         if (area->vaddr <= slot_addr && slot_addr < vma_end) {
1348                 unsigned long offset;
1349                 int slot_nr;
1350
1351                 offset = slot_addr - area->vaddr;
1352                 slot_nr = offset / UPROBE_XOL_SLOT_BYTES;
1353                 if (slot_nr >= UINSNS_PER_PAGE)
1354                         return;
1355
1356                 clear_bit(slot_nr, area->bitmap);
1357                 atomic_dec(&area->slot_count);
1358                 if (waitqueue_active(&area->wq))
1359                         wake_up(&area->wq);
1360
1361                 tsk->utask->xol_vaddr = 0;
1362         }
1363 }
1364
1365 /**
1366  * uprobe_get_swbp_addr - compute address of swbp given post-swbp regs
1367  * @regs: Reflects the saved state of the task after it has hit a breakpoint
1368  * instruction.
1369  * Return the address of the breakpoint instruction.
1370  */
1371 unsigned long __weak uprobe_get_swbp_addr(struct pt_regs *regs)
1372 {
1373         return instruction_pointer(regs) - UPROBE_SWBP_INSN_SIZE;
1374 }
1375
1376 /*
1377  * Called with no locks held.
1378  * Called in context of a exiting or a exec-ing thread.
1379  */
1380 void uprobe_free_utask(struct task_struct *t)
1381 {
1382         struct uprobe_task *utask = t->utask;
1383
1384         if (!utask)
1385                 return;
1386
1387         if (utask->active_uprobe)
1388                 put_uprobe(utask->active_uprobe);
1389
1390         xol_free_insn_slot(t);
1391         kfree(utask);
1392         t->utask = NULL;
1393 }
1394
1395 /*
1396  * Called in context of a new clone/fork from copy_process.
1397  */
1398 void uprobe_copy_process(struct task_struct *t)
1399 {
1400         t->utask = NULL;
1401 }
1402
1403 /*
1404  * Allocate a uprobe_task object for the task.
1405  * Called when the thread hits a breakpoint for the first time.
1406  *
1407  * Returns:
1408  * - pointer to new uprobe_task on success
1409  * - NULL otherwise
1410  */
1411 static struct uprobe_task *add_utask(void)
1412 {
1413         struct uprobe_task *utask;
1414
1415         utask = kzalloc(sizeof *utask, GFP_KERNEL);
1416         if (unlikely(!utask))
1417                 return NULL;
1418
1419         utask->active_uprobe = NULL;
1420         current->utask = utask;
1421         return utask;
1422 }
1423
1424 /* Prepare to single-step probed instruction out of line. */
1425 static int
1426 pre_ssout(struct uprobe *uprobe, struct pt_regs *regs, unsigned long vaddr)
1427 {
1428         if (xol_get_insn_slot(uprobe, vaddr) && !arch_uprobe_pre_xol(&uprobe->arch, regs))
1429                 return 0;
1430
1431         return -EFAULT;
1432 }
1433
1434 /*
1435  * If we are singlestepping, then ensure this thread is not connected to
1436  * non-fatal signals until completion of singlestep.  When xol insn itself
1437  * triggers the signal,  restart the original insn even if the task is
1438  * already SIGKILL'ed (since coredump should report the correct ip).  This
1439  * is even more important if the task has a handler for SIGSEGV/etc, The
1440  * _same_ instruction should be repeated again after return from the signal
1441  * handler, and SSTEP can never finish in this case.
1442  */
1443 bool uprobe_deny_signal(void)
1444 {
1445         struct task_struct *t = current;
1446         struct uprobe_task *utask = t->utask;
1447
1448         if (likely(!utask || !utask->active_uprobe))
1449                 return false;
1450
1451         WARN_ON_ONCE(utask->state != UTASK_SSTEP);
1452
1453         if (signal_pending(t)) {
1454                 spin_lock_irq(&t->sighand->siglock);
1455                 clear_tsk_thread_flag(t, TIF_SIGPENDING);
1456                 spin_unlock_irq(&t->sighand->siglock);
1457
1458                 if (__fatal_signal_pending(t) || arch_uprobe_xol_was_trapped(t)) {
1459                         utask->state = UTASK_SSTEP_TRAPPED;
1460                         set_tsk_thread_flag(t, TIF_UPROBE);
1461                         set_tsk_thread_flag(t, TIF_NOTIFY_RESUME);
1462                 }
1463         }
1464
1465         return true;
1466 }
1467
1468 /*
1469  * Avoid singlestepping the original instruction if the original instruction
1470  * is a NOP or can be emulated.
1471  */
1472 static bool can_skip_sstep(struct uprobe *uprobe, struct pt_regs *regs)
1473 {
1474         if (arch_uprobe_skip_sstep(&uprobe->arch, regs))
1475                 return true;
1476
1477         uprobe->flags &= ~UPROBE_SKIP_SSTEP;
1478         return false;
1479 }
1480
1481 static struct uprobe *find_active_uprobe(unsigned long bp_vaddr, int *is_swbp)
1482 {
1483         struct mm_struct *mm = current->mm;
1484         struct uprobe *uprobe = NULL;
1485         struct vm_area_struct *vma;
1486
1487         down_read(&mm->mmap_sem);
1488         vma = find_vma(mm, bp_vaddr);
1489         if (vma && vma->vm_start <= bp_vaddr) {
1490                 if (valid_vma(vma, false)) {
1491                         struct inode *inode;
1492                         loff_t offset;
1493
1494                         inode = vma->vm_file->f_mapping->host;
1495                         offset = bp_vaddr - vma->vm_start;
1496                         offset += (vma->vm_pgoff << PAGE_SHIFT);
1497                         uprobe = find_uprobe(inode, offset);
1498                 }
1499
1500                 if (!uprobe)
1501                         *is_swbp = is_swbp_at_addr(mm, bp_vaddr);
1502         } else {
1503                 *is_swbp = -EFAULT;
1504         }
1505         up_read(&mm->mmap_sem);
1506
1507         return uprobe;
1508 }
1509
1510 /*
1511  * Run handler and ask thread to singlestep.
1512  * Ensure all non-fatal signals cannot interrupt thread while it singlesteps.
1513  */
1514 static void handle_swbp(struct pt_regs *regs)
1515 {
1516         struct uprobe_task *utask;
1517         struct uprobe *uprobe;
1518         unsigned long bp_vaddr;
1519         int uninitialized_var(is_swbp);
1520
1521         bp_vaddr = uprobe_get_swbp_addr(regs);
1522         uprobe = find_active_uprobe(bp_vaddr, &is_swbp);
1523
1524         if (!uprobe) {
1525                 if (is_swbp > 0) {
1526                         /* No matching uprobe; signal SIGTRAP. */
1527                         send_sig(SIGTRAP, current, 0);
1528                 } else {
1529                         /*
1530                          * Either we raced with uprobe_unregister() or we can't
1531                          * access this memory. The latter is only possible if
1532                          * another thread plays with our ->mm. In both cases
1533                          * we can simply restart. If this vma was unmapped we
1534                          * can pretend this insn was not executed yet and get
1535                          * the (correct) SIGSEGV after restart.
1536                          */
1537                         instruction_pointer_set(regs, bp_vaddr);
1538                 }
1539                 return;
1540         }
1541
1542         utask = current->utask;
1543         if (!utask) {
1544                 utask = add_utask();
1545                 /* Cannot allocate; re-execute the instruction. */
1546                 if (!utask)
1547                         goto cleanup_ret;
1548         }
1549         utask->active_uprobe = uprobe;
1550         handler_chain(uprobe, regs);
1551         if (uprobe->flags & UPROBE_SKIP_SSTEP && can_skip_sstep(uprobe, regs))
1552                 goto cleanup_ret;
1553
1554         utask->state = UTASK_SSTEP;
1555         if (!pre_ssout(uprobe, regs, bp_vaddr)) {
1556                 user_enable_single_step(current);
1557                 return;
1558         }
1559
1560 cleanup_ret:
1561         if (utask) {
1562                 utask->active_uprobe = NULL;
1563                 utask->state = UTASK_RUNNING;
1564         }
1565         if (uprobe) {
1566                 if (!(uprobe->flags & UPROBE_SKIP_SSTEP))
1567
1568                         /*
1569                          * cannot singlestep; cannot skip instruction;
1570                          * re-execute the instruction.
1571                          */
1572                         instruction_pointer_set(regs, bp_vaddr);
1573
1574                 put_uprobe(uprobe);
1575         }
1576 }
1577
1578 /*
1579  * Perform required fix-ups and disable singlestep.
1580  * Allow pending signals to take effect.
1581  */
1582 static void handle_singlestep(struct uprobe_task *utask, struct pt_regs *regs)
1583 {
1584         struct uprobe *uprobe;
1585
1586         uprobe = utask->active_uprobe;
1587         if (utask->state == UTASK_SSTEP_ACK)
1588                 arch_uprobe_post_xol(&uprobe->arch, regs);
1589         else if (utask->state == UTASK_SSTEP_TRAPPED)
1590                 arch_uprobe_abort_xol(&uprobe->arch, regs);
1591         else
1592                 WARN_ON_ONCE(1);
1593
1594         put_uprobe(uprobe);
1595         utask->active_uprobe = NULL;
1596         utask->state = UTASK_RUNNING;
1597         user_disable_single_step(current);
1598         xol_free_insn_slot(current);
1599
1600         spin_lock_irq(&current->sighand->siglock);
1601         recalc_sigpending(); /* see uprobe_deny_signal() */
1602         spin_unlock_irq(&current->sighand->siglock);
1603 }
1604
1605 /*
1606  * On breakpoint hit, breakpoint notifier sets the TIF_UPROBE flag.  (and on
1607  * subsequent probe hits on the thread sets the state to UTASK_BP_HIT) and
1608  * allows the thread to return from interrupt.
1609  *
1610  * On singlestep exception, singlestep notifier sets the TIF_UPROBE flag and
1611  * also sets the state to UTASK_SSTEP_ACK and allows the thread to return from
1612  * interrupt.
1613  *
1614  * While returning to userspace, thread notices the TIF_UPROBE flag and calls
1615  * uprobe_notify_resume().
1616  */
1617 void uprobe_notify_resume(struct pt_regs *regs)
1618 {
1619         struct uprobe_task *utask;
1620
1621         utask = current->utask;
1622         if (!utask || utask->state == UTASK_BP_HIT)
1623                 handle_swbp(regs);
1624         else
1625                 handle_singlestep(utask, regs);
1626 }
1627
1628 /*
1629  * uprobe_pre_sstep_notifier gets called from interrupt context as part of
1630  * notifier mechanism. Set TIF_UPROBE flag and indicate breakpoint hit.
1631  */
1632 int uprobe_pre_sstep_notifier(struct pt_regs *regs)
1633 {
1634         struct uprobe_task *utask;
1635
1636         if (!current->mm || !atomic_read(&current->mm->uprobes_state.count))
1637                 /* task is currently not uprobed */
1638                 return 0;
1639
1640         utask = current->utask;
1641         if (utask)
1642                 utask->state = UTASK_BP_HIT;
1643
1644         set_thread_flag(TIF_UPROBE);
1645
1646         return 1;
1647 }
1648
1649 /*
1650  * uprobe_post_sstep_notifier gets called in interrupt context as part of notifier
1651  * mechanism. Set TIF_UPROBE flag and indicate completion of singlestep.
1652  */
1653 int uprobe_post_sstep_notifier(struct pt_regs *regs)
1654 {
1655         struct uprobe_task *utask = current->utask;
1656
1657         if (!current->mm || !utask || !utask->active_uprobe)
1658                 /* task is currently not uprobed */
1659                 return 0;
1660
1661         utask->state = UTASK_SSTEP_ACK;
1662         set_thread_flag(TIF_UPROBE);
1663         return 1;
1664 }
1665
1666 static struct notifier_block uprobe_exception_nb = {
1667         .notifier_call          = arch_uprobe_exception_notify,
1668         .priority               = INT_MAX-1,    /* notified after kprobes, kgdb */
1669 };
1670
1671 static int __init init_uprobes(void)
1672 {
1673         int i;
1674
1675         for (i = 0; i < UPROBES_HASH_SZ; i++) {
1676                 mutex_init(&uprobes_mutex[i]);
1677                 mutex_init(&uprobes_mmap_mutex[i]);
1678         }
1679
1680         return register_die_notifier(&uprobe_exception_nb);
1681 }
1682 module_init(init_uprobes);
1683
1684 static void __exit exit_uprobes(void)
1685 {
1686 }
1687 module_exit(exit_uprobes);