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