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