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