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