Skip to contentSkip to conversation

Uprobes patchset with perf probe support

PATCH In review Srikar Dronamraju 7 participants 34 messages Feb 2, 2012 – May 23, 2012

Subsystems (10)
lore
Share & tools
lore
#0 lore raw

v10 cover Uprobes patchset with perf probe support

This patchset implements Uprobes which enables you to dynamically probe any routine in a user space application and collect information non-disruptively.

This patchset resolves most of the comments on the previous posting
(https://lkml.org/lkml/2012/1/10/128) patchset applies on top of commit (62aa2b5 Linux 3.3-rc2)

uprobes git is hosted at git://github.com/srikard/linux.git
with branch inode_uprobes_v33rc2.

Uprobes Patches
This patchset implements inode based uprobes which are specified as <file>:<offset> where offset is the offset from start of the map.

When a uprobe is registered, Uprobes makes a copy of the probed instruction, replaces the first byte(s) of the probed instruction with a breakpoint instruction. (Uprobes uses background page replacement mechanism and ensures that the breakpoint affects only that process.)

When a CPU hits the breakpoint instruction, Uprobes gets notified of trap and finds the associated uprobe. It then executes the associated handler. Uprobes single-steps its copy of the probed instruction and resumes execution of the probed process at the instruction following the probepoint. Instruction copies to be single-stepped are stored in a per-mm "execution out of line (XOL) area". Currently XOL area is allocated as one page vma.

For previous postings: please refer: https://lkml.org/lkml/2011/11/18/149
https://lkml.org/lkml/2011/11/10/408 https://lkml.org/lkml/2011/9/20/123
https://lkml.org/lkml/2011/6/7/232 https://lkml.org/lkml/2011/4/1/176
http://lkml.org/lkml/2011/3/14/171/ http://lkml.org/lkml/2010/12/16/65
http://lkml.org/lkml/2010/8/25/165 http://lkml.org/lkml/2010/7/27/121
http://lkml.org/lkml/2010/7/12/67 http://lkml.org/lkml/2010/7/8/239
http://lkml.org/lkml/2010/6/29/299 http://lkml.org/lkml/2010/6/14/41
http://lkml.org/lkml/2010/3/20/107 and http://lkml.org/lkml/2010/5/18/307

This patchset is a rework based on suggestions from discussions on lkml in September, March and January 2010 (http://lkml.org/lkml/2010/1/11/92,
http://lkml.org/lkml/2010/1/27/19, http://lkml.org/lkml/2010/3/20/107
and http://lkml.org/lkml/2010/3/31/199 ). This implementation of uprobes doesnt depend on utrace.

Advantages of uprobes over conventional debugging include:

1. Non-disruptive.
Unlike current ptrace based mechanisms, uprobes tracing wouldnt involve signals, stopping threads and context switching between the tracer and tracee.

2. Much better handling of multithreaded programs because of XOL. Current ptrace based mechanisms use single stepping inline, i.e they copy back the original instruction on hitting a breakpoint. In such mechanisms tracers have to stop all the threads on a breakpoint hit or tracers will not be able to handle all hits to the location of interest. Uprobes uses execution out of line, where the instruction to be traced is analysed at the time of breakpoint insertion and a copy of instruction is stored at a different location. On breakpoint hit, uprobes jumps to that copied location and singlesteps the same instruction and does the necessary fixups post singlestepping.

3. Multiple tracers for an application.
Multiple uprobes based tracer could work in unison to trace an application. There could one tracer that could be interested in generic events for a particular set of process. While there could be another tracer that is just interested in one specific event of a particular process thats part of the previous set of process.

4. Corelating events from kernels and userspace.
Uprobes could be used with other tools like kprobes, tracepoints or as part of higher level tools like perf to give a consolidated set of events from kernel and userspace. In future we could look at a single backtrace showing application, library and kernel calls.

Changes from last patchset:
- Rebased to 62aa2b5 Linux 3.3-rc2
- Handled comments from Ingo Molnar, Masami Hiramatsu and Jiri Olsa.

Here is the list of TODO Items.

- worker thread if unregister_uprobe were to fail.
- Prefiltering (i.e filtering at the time of probe insertion)
- Return probes.
- Support for other architectures.
- Uprobes booster.
- replace macro W with bits in inat table.

Please refer "[PATCH v10 3.3-rc2 7/9] tracing: uprobes trace_event interface".

Please refer "[PATCH v10 3.3-rc2 9/9] perf: perf interface for uprobes".

Please do provide your valuable comments.

Thanks in advance.
Srikar

Srikar Dronamraju (9)
0: Uprobes patchset with perf probe support
1: uprobes: Install and remove breakpoints.
2: uprobes: handle breakpoint and signal step exception. 3: uprobes: slot allocation.
4: uprobes: counter to optimize probe hits.
5: tracing: modify is_delete, is_return from ints to bool. 6: tracing: Extract out common code for kprobes/uprobes traceevents. 7: tracing: uprobes trace_event interface
8: perf: rename target_module to target
9: perf: perf interface for uprobes

 Documentation/trace/uprobetracer.txt    |   93 ++
 arch/Kconfig                            |    3 +
 arch/x86/Kconfig                        |    5 +-
 arch/x86/include/asm/thread_info.h      |    2 +
 arch/x86/include/asm/uprobes.h          |   58 ++
 arch/x86/kernel/Makefile                |    1 +
 arch/x86/kernel/signal.c                |    6 +
 arch/x86/kernel/uprobes.c               |  664 +++++++++++++
 include/linux/mm_types.h                |    5 +
 include/linux/sched.h                   |    4 +
 include/linux/uprobes.h                 |  171 ++++
 kernel/Makefile                         |    1 +
 kernel/fork.c                           |   15 +
 kernel/signal.c                         |    3 +
 kernel/trace/Kconfig                    |   20 +
 kernel/trace/Makefile                   |    2 +
 kernel/trace/trace.h                    |    5 +
 kernel/trace/trace_kprobe.c             |  899 +-----------------
 kernel/trace/trace_probe.c              |  786 ++++++++++++++++
 kernel/trace/trace_probe.h              |  162 ++++
 kernel/trace/trace_uprobe.c             |  772 +++++++++++++++
 kernel/uprobes.c                        | 1546 +++++++++++++++++++++++++++++++
 mm/mmap.c                               |   33 +-
 tools/perf/Documentation/perf-probe.txt |   14 +
 tools/perf/builtin-probe.c              |   49 +-
 tools/perf/util/probe-event.c           |  429 +++++++--
 tools/perf/util/probe-event.h           |   12 +-
 tools/perf/util/symbol.c                |    8 +
 tools/perf/util/symbol.h                |    1 +
 29 files changed, 4780 insertions(+), 989 deletions(-)

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#1 lore raw

PATCH v10 1/9 uprobes: Install and remove breakpoints.

Uprobes are maintained in an rb-tree indexed by inode and offset (the offset here is from the start of the mapping). For a unique (inode, offset) tuple, there can be atmost one uprobe in the rb-tree.

Since the (inode, offset) tuple identifies a unique uprobe, more than one user may be interested in the same uprobe. Provides the ability to hook multiple 'consumers' for the same uprobe.

Each consumer defines a handler and a filter (optional). The 'handler' is run every time the uprobe is hit, if it matches the 'filter' criteria.

The first consumer of a uprobe causes the breakpoint to be inserted at the specified address and subsequent consumers are appended to this list. On subsequent probes, the consumer gets appended to the existing list of consumers. The breakpoint is removed when the last consumer unregisters. For all other unregisterations, the consumer is removed from the list of consumers.

Given a inode, we get a list of the mms that have mapped the inode. Do the actual registration if mm maps the page where a probe needs to be inserted/removed.

We use a temporary list to walk thro the vmas that map the inode.
- The number of maps that map the inode, is not known before we walk the rmap and keeps changing.
- extending vm_area_struct wasnt recommended.
- There can be more than one maps of the inode in the same mm.

Hook mmap to keep an eye on text vmas that are of interest to uprobes. When a vma of interest is mapped, insert the breakpoint at the right address.

Uprobe works by replacing the instruction at the address defined by (inode, offset) with the arch specific breakpoint instruction. Save a copy of the original instruction at the uprobed address.

This is needed for:
a. executing the instruction out-of-line (xol).
b. instruction analysis for any subsequent fixups.
c. restoring the instruction back when the uprobe is unregistered.

We insert or delete a breakpoint instruction, and this breakpoint instruction is assumed to be the smallest instruction available on the platform. For fixed size instruction platforms this is trivially true, for variable size instruction platforms the breakpoint instruction is typically the smallest (often a single byte).

Writing the instruction is done by COWing the page and changing the instruction during the copy, this even though most platforms allow atomic writes of the breakpoint instruction. This also mirrors the behaviour of a ptrace() memory write to a PRIVATE file map.

The core worker is derived from ksm's replace_page() logic.

In essence, similar to ksm:
a. allocate a new page and copy over contents of the page that has the
uprobed vaddr
b. modify the copy and insert the breakpoint at the required address c. switch the original page with the copy containing the breakpoint d. flush page tables.

replace_page is being replicated here because of some minor changes in the type of pages and also because Hugh Dickins had plans to improve replace_page for ksm specific work.

Instruction analysis on x86 is based on instruction decoder and determines if an instruction can be probed and determines the necessary fixups after singlestep. Instruction analysis is done at probe insertion time so that we avoid having to repeat the same analysis every time a probe is hit.

A lot of code here is due to the improvement/suggestions/inputs from Peter Zijlstra.

---

Changelog: (Since v9) : Use insn_offset_modrm as suggested by Masami Hiramatsu.

Changelog: (Since v7) : Handle comments from Peter Zijlstra
- Dont take reference to inode. (expect inode to register_uprobe to be sane).
- Use PTR_ERR to set the return value.
- No need to take reference to inode.
- use PTR_ERR to return error value.
- register and unregister_uprobe share code.

Changelog:(Since v5)
- Modified del_consumer as per comments from Peter.
- Drop reference to inode before dropping reference to uprobe.
- Use i_size_read(inode) instead of inode->i_size.
- Ensure uprobe->consumers is NULL, before __unregister_uprobe() is called.
- Includes errno.h as recommended by Stephen Rothwell to fix a build issue on sparc defconfig
- Remove restrictions while unregistering.
- Earlier code leaked inode references under some conditions while registering/unregistering.
- Continue the vma-rmap walk even if the intermediate vma doesnt meet the requirements.
- Validate the vma found by find_vma before inserting/removing the breakpoint
- Call del_consumer under mutex_lock.
- Use hash locks.
- Handle mremap.
- Introduce find_least_offset_node() instead of close match logic in find_uprobe
- Uprobes no more depends on MM_OWNER; No reference to task_structs while inserting/removing a probe.
- Uses read_mapping_page instead of grab_cache_page so that the pages have valid content.
- pass NULL to get_user_pages for the task parameter.
- call SetPageUptodate on the new page allocated in write_opcode.
- fix leaking a reference to the new page under certain conditions.
- Include Instruction Decoder if Uprobes gets defined.
- Remove const attributes for instruction prefix arrays.
- Uses mm_context to know if the application is 32 bit.

 arch/Kconfig                   |   11 
 arch/x86/Kconfig               |    5 
 arch/x86/include/asm/uprobes.h |   42 ++
 arch/x86/kernel/Makefile       |    1 
 arch/x86/kernel/uprobes.c      |  402 ++++++++++++++++
 include/linux/uprobes.h        |   98 ++++
 kernel/Makefile                |    1 
 kernel/uprobes.c               |  976 ++++++++++++++++++++++++++++++++++++++++
 mm/mmap.c                      |   23 +
 9 files changed, 1558 insertions(+), 1 deletions(-)
 create mode 100644 arch/x86/include/asm/uprobes.h
 create mode 100644 arch/x86/kernel/uprobes.c
 create mode 100644 include/linux/uprobes.h
 create mode 100644 kernel/uprobes.c
arch/Kconfig +11 -0
index 4f55c73..284f589 100644
@@ -65,6 +65,17 @@ config OPTPROBES
 	depends on KPROBES && HAVE_OPTPROBES
 	depends on !PREEMPT
 
+config UPROBES
+	bool "User-space probes (EXPERIMENTAL)"
+	depends on ARCH_SUPPORTS_UPROBES
+	default n
+	help
+	  Uprobes enables kernel subsystems to establish probepoints
+	  in user applications and execute handler functions when
+	  the probepoints are hit.
+
+	  If in doubt, say "N".
+
 config HAVE_EFFICIENT_UNALIGNED_ACCESS
 	bool
 	help
arch/x86/Kconfig +4 -1
index 5bed94e..481dbfc 100644
@@ -84,7 +84,7 @@ config X86
 	select GENERIC_IOMAP
 
 config INSTRUCTION_DECODER
-	def_bool (KPROBES || PERF_EVENTS)
+	def_bool (KPROBES || PERF_EVENTS || UPROBES)
 
 config OUTPUT_FORMAT
 	string
@@ -240,6 +240,9 @@ config ARCH_CPU_PROBE_RELEASE
 	def_bool y
 	depends on HOTPLUG_CPU
 
+config ARCH_SUPPORTS_UPROBES
+	def_bool y
+
 source "init/Kconfig"
 source "kernel/Kconfig.freezer"
 
arch/x86/include/asm/uprobes.h new file +42 -0

42 lines not on this page · raw message

arch/x86/kernel/Makefile +1 -0
index 5369059..8c8c365 100644
@@ -100,6 +100,7 @@ obj-$(CONFIG_X86_CHECK_BIOS_CORRUPTION) += check.o
 
 obj-$(CONFIG_SWIOTLB)			+= pci-swiotlb.o
 obj-$(CONFIG_OF)			+= devicetree.o
+obj-$(CONFIG_UPROBES)			+= uprobes.o
 
 ###
 # 64 bit specific files
arch/x86/kernel/uprobes.c new file +402 -0

402 lines not on this page · raw message

include/linux/uprobes.h new file +98 -0

98 lines not on this page · raw message

kernel/Makefile +1 -0
index 2d9de86..8609dd3 100644
@@ -107,6 +107,7 @@ obj-$(CONFIG_USER_RETURN_NOTIFIER) += user-return-notifier.o
 obj-$(CONFIG_PADATA) += padata.o
 obj-$(CONFIG_CRASH_DUMP) += crash_dump.o
 obj-$(CONFIG_JUMP_LABEL) += jump_label.o
+obj-$(CONFIG_UPROBES) += uprobes.o
 
 $(obj)/configs.o: $(obj)/config_data.h
 
kernel/uprobes.c new file +976 -0

976 lines not on this page · raw message

mm/mmap.c +23 -0
index 3f758c7..1aed183 100644
@@ -30,6 +30,7 @@
 #include <linux/perf_event.h>
 #include <linux/audit.h>
 #include <linux/khugepaged.h>
+#include <linux/uprobes.h>
 
 #include <asm/uaccess.h>
 #include <asm/cacheflush.h>
@@ -616,6 +617,13 @@ again:			remove_next = 1 + (end > next->vm_end);
 	if (mapping)
 		mutex_unlock(&mapping->i_mmap_mutex);
 
+	if (root) {
+		mmap_uprobe(vma);
+
+		if (adjust_next)
+			mmap_uprobe(next);
+	}
+
 	if (remove_next) {
 		if (file) {
 			fput(file);
@@ -637,6 +645,8 @@ again:			remove_next = 1 + (end > next->vm_end);
 			goto again;
 		}
 	}
+	if (insert && file)
+		mmap_uprobe(insert);
 
 	validate_mm(mm);
 
@@ -1329,6 +1339,11 @@ unsigned long mmap_region(struct file *file, unsigned long addr,
 			mm->locked_vm += (len >> PAGE_SHIFT);
 	} else if ((flags & MAP_POPULATE) && !(flags & MAP_NONBLOCK))
 		make_pages_present(addr, addr + len);
+
+	if (file && mmap_uprobe(vma))
+		/* matching probes but cannot insert */
+		goto unmap_and_free_vma;
+
 	return addr;
 
 unmap_and_free_vma:
@@ -2285,6 +2300,10 @@ int insert_vm_struct(struct mm_struct * mm, struct vm_area_struct * vma)
 	if ((vma->vm_flags & VM_ACCOUNT) &&
 	     security_vm_enough_memory_mm(mm, vma_pages(vma)))
 		return -ENOMEM;
+
+	if (vma->vm_file && mmap_uprobe(vma))
+		return -EINVAL;
+
 	vma_link(mm, vma, prev, rb_link, rb_parent);
 	return 0;
 }
@@ -2354,6 +2373,10 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
 			new_vma->vm_pgoff = pgoff;
 			if (new_vma->vm_file) {
 				get_file(new_vma->vm_file);
+
+				if (mmap_uprobe(new_vma))
+					goto out_free_mempol;
+
 				if (vma->vm_flags & VM_EXECUTABLE)
 					added_exe_file_vma(mm);
 			}
#25 lore raw

PATCH v10 2/9 uprobes: handle breakpoint and signal step exception.

In reply to Srikar Dronamraju

Uprobes uses exception notifiers to get to know if a thread hit a breakpoint or singlestep exception.

When a thread hits a uprobe or is singlestepping post a uprobe hit, the uprobe exception notifier, sets its TIF_UPROBE bit, which will then be checked on its return to userspace path (do_notify_resume() ->uprobe_notify_resume()), where the consumers handlers are run (in task context) based on the defined filters.

Uprobe hits are thread specific and hence we need to maintain information about if a task hit a uprobe, what uprobe was hit, the slot where the original instruction was copied for xol so that it can be singlestepped with appropriate fixups.

In some cases, special care is needed for instructions that are executed out of line (xol). These are architecture specific artefacts, such as handling RIP relative instructions on x86_64.

Since the instruction at which the uprobe was inserted is executed out of line, architecture specific fixups are added so that the thread continues normal execution in the presence of a uprobe.

Postpone the signals until we execute the probed insn. post_xol() path does a recalc_sigpending() before return to user-mode, this ensures the signal can't be lost.

Uprobes relies on DIE_DEBUG notification to notify if a singlestep is complete.

Adds x86 specific uprobe exception notifiers and appropriate hooks needed to determine a uprobe hit and subsequent post processing.

Add requisite x86 fixups for xol for uprobes. Specific cases needing fixups include relative jumps (x86_64), calls, etc.

Where possible, we check and skip singlestepping the breakpointed instructions. For now we skip single byte as well as few multibyte nop instructions. However this can be extended to other instructions too.

Credits to Oleg Nesterov for suggestions/patches related to signal, breakpoint, singlestep handling code.

---
(Changelog (since v9): Use instruction_pointer_set instead of set_instruction_pointer.
Changed can_skip_xol to uprobe_skip_sstep as suggested by Ananth

(Changelog (since v7)): Resolve comments from Dan Carpenter.
- add_utask returns NULL on error.
- Handles architecture agnostic parts of a uprobe breakpoint hit and subsequent xol singlestepping.

Changelog (since v6)
- added x86 specific hook for aborting xol.

Changelog (since v5)
- Use srcu_raw instead of synchronize_sched
- Introduce per task srcu_id to store the srcu_id
- Modified comments.
- No more do a i386 specific enable interrupts. (Its not part of another patch posted separately)

 arch/x86/include/asm/thread_info.h |    2 
 arch/x86/include/asm/uprobes.h     |   16 ++
 arch/x86/kernel/signal.c           |    6 +
 arch/x86/kernel/uprobes.c          |  262 ++++++++++++++++++++++++++++++++++
 include/linux/sched.h              |    4 +
 include/linux/uprobes.h            |   46 ++++++
 kernel/fork.c                      |    7 +
 kernel/signal.c                    |    3 
 kernel/uprobes.c                   |  275 ++++++++++++++++++++++++++++++++++++
 9 files changed, 619 insertions(+), 2 deletions(-)
arch/x86/include/asm/thread_info.h +2 -0
index bc817cd..114dca1 100644
@@ -85,6 +85,7 @@ struct thread_info {
 #define TIF_SECCOMP		8	/* secure computing */
 #define TIF_MCE_NOTIFY		10	/* notify userspace of an MCE */
 #define TIF_USER_RETURN_NOTIFY	11	/* notify kernel of userspace return */
+#define TIF_UPROBE		12	/* breakpointed or singlestepping */
 #define TIF_NOTSC		16	/* TSC is not accessible in userland */
 #define TIF_IA32		17	/* 32bit process */
 #define TIF_FORK		18	/* ret_from_fork */
@@ -107,6 +108,7 @@ struct thread_info {
 #define _TIF_SECCOMP		(1 << TIF_SECCOMP)
 #define _TIF_MCE_NOTIFY		(1 << TIF_MCE_NOTIFY)
 #define _TIF_USER_RETURN_NOTIFY	(1 << TIF_USER_RETURN_NOTIFY)
+#define _TIF_UPROBE		(1 << TIF_UPROBE)
 #define _TIF_NOTSC		(1 << TIF_NOTSC)
 #define _TIF_IA32		(1 << TIF_IA32)
 #define _TIF_FORK		(1 << TIF_FORK)
arch/x86/include/asm/uprobes.h +16 -0
index 8208234..88df7ec 100644
@@ -23,6 +23,8 @@
  *	Jim Keniston
  */
 
+#include <linux/notifier.h>
+
 typedef u8 uprobe_opcode_t;
 #define MAX_UINSN_BYTES 16
 #define UPROBES_XOL_SLOT_BYTES	128	/* to keep it cache aligned */
@@ -37,6 +39,20 @@ struct uprobe_arch_info {
 #endif
 };
 
+struct uprobe_task_arch_info {
+	unsigned long saved_trap_no;
+#ifdef CONFIG_X86_64
+	unsigned long saved_scratch_register;
+#endif
+};
+
 struct uprobe;
+
 extern int analyze_insn(struct mm_struct *mm, struct uprobe *uprobe);
+extern int pre_xol(struct uprobe *uprobe, struct pt_regs *regs);
+extern int post_xol(struct uprobe *uprobe, struct pt_regs *regs);
+extern bool xol_was_trapped(struct task_struct *tsk);
+extern int uprobe_exception_notify(struct notifier_block *self,
+				       unsigned long val, void *data);
+extern void abort_xol(struct pt_regs *regs, struct uprobe *uprobe);
 #endif	/* _ASM_UPROBES_H */
arch/x86/kernel/signal.c +6 -0
index 46a01bd..f190103 100644
@@ -20,6 +20,7 @@
 #include <linux/personality.h>
 #include <linux/uaccess.h>
 #include <linux/user-return-notifier.h>
+#include <linux/uprobes.h>
 
 #include <asm/processor.h>
 #include <asm/ucontext.h>
@@ -816,6 +817,11 @@ do_notify_resume(struct pt_regs *regs, void *unused, __u32 thread_info_flags)
 		mce_notify_process();
 #endif /* CONFIG_X86_64 && CONFIG_X86_MCE */
 
+	if (thread_info_flags & _TIF_UPROBE) {
+		clear_thread_flag(TIF_UPROBE);
+		uprobe_notify_resume(regs);
+	}
+
 	/* deal with pending signal delivery */
 	if (thread_info_flags & _TIF_SIGPENDING)
 		do_signal(regs);
arch/x86/kernel/uprobes.c +262 -0

275 lines not on this page · raw message

include/linux/sched.h +4 -0
index 2234985..4a485ea 100644
@@ -1590,6 +1590,10 @@ struct task_struct {
 #ifdef CONFIG_HAVE_HW_BREAKPOINT
 	atomic_t ptrace_bp_refcnt;
 #endif
+#ifdef CONFIG_UPROBES
+	struct uprobe_task *utask;
+	int uprobes_srcu_id;
+#endif
 };
 
 /* Future-safe accessor for struct task_struct's cpus_allowed. */
include/linux/uprobes.h +45 -1

76 lines not on this page · raw message

kernel/fork.c +7 -0
index 051f090..4e81a01 100644
@@ -66,6 +66,7 @@
 #include <linux/user-return-notifier.h>
 #include <linux/oom.h>
 #include <linux/khugepaged.h>
+#include <linux/uprobes.h>
 
 #include <asm/pgtable.h>
 #include <asm/pgalloc.h>
@@ -680,6 +681,8 @@ void mm_release(struct task_struct *tsk, struct mm_struct *mm)
 		exit_pi_state_list(tsk);
 #endif
 
+	free_uprobe_utask(tsk);
+
 	/* Get rid of any cached register state */
 	deactivate_mm(tsk, mm);
 
@@ -1272,6 +1275,10 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 	INIT_LIST_HEAD(&p->pi_state_list);
 	p->pi_state_cache = NULL;
 #endif
+#ifdef CONFIG_UPROBES
+	p->utask = NULL;
+	p->uprobes_srcu_id = -1;
+#endif
 	/*
 	 * sigaltstack should be cleared when sharing the same VM
 	 */
kernel/signal.c +3 -0
index c73c428..412f0dc 100644
@@ -2182,6 +2182,9 @@ int get_signal_to_deliver(siginfo_t *info, struct k_sigaction *return_ka,
 	struct signal_struct *signal = current->signal;
 	int signr;
 
+	if (unlikely(uprobe_deny_signal()))
+		return 0;
+
 relock:
 	/*
 	 * We'll jump back here after any time we were stopped in TASK_STOPPED.
kernel/uprobes.c +274 -1

317 lines not on this page · raw message

#26 lore raw

PATCH v10 3/9 uprobes: slot allocation.

In reply to Srikar Dronamraju

Uprobes executes the original instruction at a probed location out of line. For this, we allocate a page (per mm) upon the first uprobe hit, in the process' user address space, divide it into slots that are used to store the actual instructions to be singlestepped.

Care is taken to ensure that the allocation is in an unmapped area as close to the top of the user address space as possible, with appropriate permission settings to keep selinux like frameworks happy.

Upon a uprobe hit, a free slot is acquired, and is released after the singlestep completes.

[ Folded a fix for build issue on powerpc fixed and reported by Stephen Rothwell]

Lots of improvements courtesy suggestions/inputs from Peter and Oleg.

---
Changelog (since v5)
- no more spin lock needed for slot allocation.
- use install_special_mapping to add a vma. (previous approach used init_creds)
- set uprobes_xol_area while holding map_sem exclusively.

 include/linux/mm_types.h |    4 +
 include/linux/uprobes.h  |   25 ++++++
 kernel/fork.c            |    4 +
 kernel/uprobes.c         |  202 ++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 235 insertions(+), 0 deletions(-)
include/linux/mm_types.h +4 -0
index 3cc3062..9ade86e 100644
@@ -12,6 +12,7 @@
 #include <linux/completion.h>
 #include <linux/cpumask.h>
 #include <linux/page-debug-flags.h>
+#include <linux/uprobes.h>
 #include <asm/page.h>
 #include <asm/mmu.h>
 
@@ -388,6 +389,9 @@ struct mm_struct {
 #ifdef CONFIG_CPUMASK_OFFSTACK
 	struct cpumask cpumask_allocation;
 #endif
+#ifdef CONFIG_UPROBES
+	struct uprobes_xol_area *uprobes_xol_area;
+#endif
 };
 
 static inline void mm_init_cpumask(struct mm_struct *mm)
include/linux/uprobes.h +25 -0
index 333e775..c9ad7fc 100644
@@ -27,6 +27,7 @@
 #include <linux/rbtree.h>
 
 struct vm_area_struct;
+struct mm_struct;
 #ifdef CONFIG_ARCH_SUPPORTS_UPROBES
 #include <asm/uprobes.h>
 #else
@@ -92,6 +93,26 @@ struct uprobe_task {
 	struct uprobe *active_uprobe;
 };
 
+/*
+ * On a breakpoint hit, thread contests for a slot.  It free the
+ * slot after singlestep.  Only definite number of slots are
+ * allocated.
+ */
+
+struct uprobes_xol_area {
+	wait_queue_head_t wq;	/* if all slots are busy */
+	atomic_t slot_count;	/* currently in use slots */
+	unsigned long *bitmap;	/* 0 = free slot */
+	struct page *page;
+
+	/*
+	 * We keep the vma's vm_start rather than a pointer to the vma
+	 * itself.  The probed process or a naughty kernel module could make
+	 * the vma go away, and we must handle that reasonably gracefully.
+	 */
+	unsigned long vaddr;		/* Page(s) of instruction slots */
+};
+
 #ifdef CONFIG_UPROBES
 extern int __weak set_bkpt(struct mm_struct *mm, struct uprobe *uprobe,
 							unsigned long vaddr);
@@ -103,6 +124,7 @@ extern int register_uprobe(struct inode *inode, loff_t offset,
 extern void unregister_uprobe(struct inode *inode, loff_t offset,
 				struct uprobe_consumer *consumer);
 extern void free_uprobe_utask(struct task_struct *tsk);
+extern void free_uprobes_xol_area(struct mm_struct *mm);
 extern int mmap_uprobe(struct vm_area_struct *vma);
 extern unsigned long __weak get_uprobe_bkpt_addr(struct pt_regs *regs);
 extern int uprobe_post_notifier(struct pt_regs *regs);
@@ -138,5 +160,8 @@ static inline unsigned long get_uprobe_bkpt_addr(struct pt_regs *regs)
 static inline void free_uprobe_utask(struct task_struct *tsk)
 {
 }
+static inline void free_uprobes_xol_area(struct mm_struct *mm)
+{
+}
 #endif /* CONFIG_UPROBES */
 #endif	/* _LINUX_UPROBES_H */
kernel/fork.c +4 -0
index 4e81a01..8e65a55 100644
@@ -553,6 +553,7 @@ void mmput(struct mm_struct *mm)
 	might_sleep();
 
 	if (atomic_dec_and_test(&mm->mm_users)) {
+		free_uprobes_xol_area(mm);
 		exit_aio(mm);
 		ksm_exit(mm);
 		khugepaged_exit(mm); /* must run before exit_mmap */
@@ -739,6 +740,9 @@ struct mm_struct *dup_mm(struct task_struct *tsk)
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
 	mm->pmd_huge_pte = NULL;
 #endif
+#ifdef CONFIG_UPROBES
+	mm->uprobes_xol_area = NULL;
+#endif
 
 	if (!mm_init(mm, tsk))
 		goto fail_nomem;
kernel/uprobes.c +202 -0

232 lines not on this page · raw message

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#27 lore raw

PATCH v10 4/9 uprobes: counter to optimize probe hits.

In reply to Srikar Dronamraju

Maintain a per-mm counter (number of uprobes that are inserted on this process address space). This counter can be used at probe hit time to determine if we need to do a uprobe lookup in the uprobes rbtree. Everytime a probe gets inserted successfully, the probe count is incremented and everytime a probe gets removed successfully the probe count is removed.

A new hook munmap_uprobe is added to keep the counter to be correct even when a region is unmapped or remapped. This patch expects that once a munmap_uprobe() is called, the vma either go away or a subsequent mmap_uprobe gets called before a removal of a probe from unregister_uprobe in the same address space.

On every executable vma thats cowed at fork, mmap_uprobe is called so that the mm_uprobes_count is in sync.

When a vma of interest is mapped, insert the breakpoint at the right address. Upon munmap, just make sure the data structures are adjusted/cleaned up.

On process creation, make sure the probes count in the child is set correctly.

Special cases that are taken care include:
a. mremap()
b. VM_DONTCOPY vmas on fork()
c. insertion/removal races in the parent during fork().

---
Changelog (since v7)
- Separate this patch from the patch that implements mmap_uprobe.
- Increment counter only after verifying that the probe lies underneath.

Changelog (since v5)
- While forking, handle vma's that have VM_DONTCOPY.
- While forking, handle race of new breakpoints being inserted / removed in the parent process.

 include/linux/mm_types.h |    1 
 include/linux/uprobes.h  |    4 ++
 kernel/fork.c            |    4 ++
 kernel/uprobes.c         |  103 ++++++++++++++++++++++++++++++++++++++++++++--
 mm/mmap.c                |   10 ++++
 5 files changed, 117 insertions(+), 5 deletions(-)
include/linux/mm_types.h +1 -0
index 9ade86e..62d5aeb 100644
@@ -390,6 +390,7 @@ struct mm_struct {
 	struct cpumask cpumask_allocation;
 #endif
 #ifdef CONFIG_UPROBES
+	atomic_t mm_uprobes_count;
 	struct uprobes_xol_area *uprobes_xol_area;
 #endif
 };
include/linux/uprobes.h +4 -0
index c9ad7fc..0f6cc1a 100644
@@ -126,6 +126,7 @@ extern void unregister_uprobe(struct inode *inode, loff_t offset,
 extern void free_uprobe_utask(struct task_struct *tsk);
 extern void free_uprobes_xol_area(struct mm_struct *mm);
 extern int mmap_uprobe(struct vm_area_struct *vma);
+extern void munmap_uprobe(struct vm_area_struct *vma);
 extern unsigned long __weak get_uprobe_bkpt_addr(struct pt_regs *regs);
 extern int uprobe_post_notifier(struct pt_regs *regs);
 extern int uprobe_bkpt_notifier(struct pt_regs *regs);
@@ -146,6 +147,9 @@ static inline int mmap_uprobe(struct vm_area_struct *vma)
 {
 	return 0;
 }
+static inline void munmap_uprobe(struct vm_area_struct *vma)
+{
+}
 static inline void uprobe_notify_resume(struct pt_regs *regs)
 {
 }
kernel/fork.c +4 -0
index 8e65a55..53e7959 100644
@@ -420,6 +420,9 @@ static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
 
 		if (retval)
 			goto out;
+
+		if (file && mmap_uprobe(tmp))
+			goto out;
 	}
 	/* a new mm has just been created */
 	arch_dup_mmap(oldmm, mm);
@@ -741,6 +744,7 @@ struct mm_struct *dup_mm(struct task_struct *tsk)
 	mm->pmd_huge_pte = NULL;
 #endif
 #ifdef CONFIG_UPROBES
+	atomic_set(&mm->mm_uprobes_count, 0);
 	mm->uprobes_xol_area = NULL;
 #endif
 
kernel/uprobes.c +99 -4

150 lines not on this page · raw message

mm/mmap.c +9 -1
index 1aed183..e7f5e3c 100644
@@ -218,6 +218,7 @@ void unlink_file_vma(struct vm_area_struct *vma)
 		mutex_lock(&mapping->i_mmap_mutex);
 		__remove_shared_vm_struct(vma, file, mapping);
 		mutex_unlock(&mapping->i_mmap_mutex);
+		munmap_uprobe(vma);
 	}
 }
 
@@ -546,8 +547,14 @@ again:			remove_next = 1 + (end > next->vm_end);
 
 	if (file) {
 		mapping = file->f_mapping;
-		if (!(vma->vm_flags & VM_NONLINEAR))
+		if (!(vma->vm_flags & VM_NONLINEAR)) {
 			root = &mapping->i_mmap;
+			munmap_uprobe(vma);
+
+			if (adjust_next)
+				munmap_uprobe(next);
+		}
+
 		mutex_lock(&mapping->i_mmap_mutex);
 		if (insert) {
 			/*
@@ -626,6 +633,7 @@ again:			remove_next = 1 + (end > next->vm_end);
 
 	if (remove_next) {
 		if (file) {
+			munmap_uprobe(next);
 			fput(file);
 			if (next->vm_flags & VM_EXECUTABLE)
 				removed_exe_file_vma(mm);

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#28 lore raw

PATCH v10 5/9 tracing: modify is_delete, is_return from ints to bool.

In reply to Srikar Dronamraju

is_delete and is_return can take atmost 2 values and are better of being a boolean than a int.

---

Changelog (since v5):
- extracted from the next patch on Masami's suggestion.

 kernel/trace/trace_kprobe.c |   16 ++++++++--------
 1 files changed, 8 insertions(+), 8 deletions(-)
kernel/trace/trace_kprobe.c +8 -8
index 00d527c..2490dd1 100644
@@ -651,7 +651,7 @@ static struct trace_probe *alloc_trace_probe(const char *group,
 					     void *addr,
 					     const char *symbol,
 					     unsigned long offs,
-					     int nargs, int is_return)
+					     int nargs, bool is_return)
 {
 	struct trace_probe *tp;
 	int ret = -ENOMEM;
@@ -944,7 +944,7 @@ static int split_symbol_offset(char *symbol, unsigned long *offset)
 #define PARAM_MAX_STACK (THREAD_SIZE / sizeof(unsigned long))
 
 static int parse_probe_vars(char *arg, const struct fetch_type *t,
-			    struct fetch_param *f, int is_return)
+			    struct fetch_param *f, bool is_return)
 {
 	int ret = 0;
 	unsigned long param;
@@ -977,7 +977,7 @@ static int parse_probe_vars(char *arg, const struct fetch_type *t,
 
 /* Recursive argument parser */
 static int __parse_probe_arg(char *arg, const struct fetch_type *t,
-			     struct fetch_param *f, int is_return)
+			     struct fetch_param *f, bool is_return)
 {
 	int ret = 0;
 	unsigned long param;
@@ -1089,7 +1089,7 @@ static int __parse_bitfield_probe_arg(const char *bf,
 
 /* String length checking wrapper */
 static int parse_probe_arg(char *arg, struct trace_probe *tp,
-			   struct probe_arg *parg, int is_return)
+			   struct probe_arg *parg, bool is_return)
 {
 	const char *t;
 	int ret;
@@ -1162,7 +1162,7 @@ static int create_trace_probe(int argc, char **argv)
 	 */
 	struct trace_probe *tp;
 	int i, ret = 0;
-	int is_return = 0, is_delete = 0;
+	bool is_return = false, is_delete = false;
 	char *symbol = NULL, *event = NULL, *group = NULL;
 	char *arg;
 	unsigned long offset = 0;
@@ -1171,11 +1171,11 @@ static int create_trace_probe(int argc, char **argv)
 
 	/* argc must be >= 1 */
 	if (argv[0][0] == 'p')
-		is_return = 0;
+		is_return = false;
 	else if (argv[0][0] == 'r')
-		is_return = 1;
+		is_return = true;
 	else if (argv[0][0] == '-')
-		is_delete = 1;
+		is_delete = true;
 	else {
 		pr_info("Probe definition must be started with 'p', 'r' or"
 			" '-'.\n");
#29 lore raw

PATCH v10 6/9 tracing: Extract out common code for kprobes/uprobes traceevents.

In reply to Srikar Dronamraju

Move parts of trace_kprobe.c that can be shared with upcoming trace_uprobe.c. Common code to kernel/trace/trace_probe.h and kernel/trace/trace_probe.c.

---
Changelog (since v5)
- Extracted out int to bool changes to a separate patch.
- Fix a bug in kprobe_trace_self_tests_init that was introduced in previous patchset.

Changelog (since v7)
- Modified Copyright as suggested by Steven Rostedt.

 kernel/trace/Kconfig        |    4 
 kernel/trace/Makefile       |    1 
 kernel/trace/trace_kprobe.c |  889 +------------------------------------------
 kernel/trace/trace_probe.c  |  780 ++++++++++++++++++++++++++++++++++++++
 kernel/trace/trace_probe.h  |  161 ++++++++
 5 files changed, 964 insertions(+), 871 deletions(-)
 create mode 100644 kernel/trace/trace_probe.c
 create mode 100644 kernel/trace/trace_probe.h
kernel/trace/Kconfig +4 -0
index cd31345..520106a 100644
@@ -373,6 +373,7 @@ config KPROBE_EVENT
 	depends on HAVE_REGS_AND_STACK_ACCESS_API
 	bool "Enable kprobes-based dynamic events"
 	select TRACING
+	select PROBE_EVENTS
 	default y
 	help
 	  This allows the user to add tracing events (similar to tracepoints)
@@ -385,6 +386,9 @@ config KPROBE_EVENT
 	  This option is also required by perf-probe subcommand of perf tools.
 	  If you want to use perf tools, this option is strongly recommended.
 
+config PROBE_EVENTS
+	def_bool n
+
 config DYNAMIC_FTRACE
 	bool "enable/disable ftrace tracepoints dynamically"
 	depends on FUNCTION_TRACER
kernel/trace/Makefile +1 -0
index 5f39a07..fa10d5c 100644
@@ -61,5 +61,6 @@ endif
 ifeq ($(CONFIG_TRACING),y)
 obj-$(CONFIG_KGDB_KDB) += trace_kdb.o
 endif
+obj-$(CONFIG_PROBE_EVENTS) += trace_probe.o
 
 libftrace-y := ftrace.o
kernel/trace/trace_kprobe.c +18 -871

987 lines not on this page · raw message

kernel/trace/trace_probe.c new file +780 -0

780 lines not on this page · raw message

kernel/trace/trace_probe.h new file +161 -0

161 lines not on this page · raw message

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#30 lore raw

PATCH v10 7/9 tracing: uprobes trace_event interface

In reply to Srikar Dronamraju

Implements trace_event support for uprobes. In its current form it can be used to put probes at a specified offset in a file and dump the required registers when the code flow reaches the probed address.

The following example shows how to dump the instruction pointer and %ax a register at the probed text address. Here we are trying to probe zfree in /bin/zsh

# cd /sys/kernel/debug/tracing/
# cat /proc/`pgrep  zsh`/maps | grep /bin/zsh | grep r-xp
00400000-0048a000 r-xp 00000000 08:03 130904 /bin/zsh
# objdump -T /bin/zsh | grep -w zfree
0000000000446420 g    DF .text  0000000000000012  Base        zfree
# echo 'p /bin/zsh:0x46420 %ip %ax' > uprobe_events
# cat uprobe_events
p:uprobes/p_zsh_0x46420 /bin/zsh:0x0000000000046420
# echo 1 > events/uprobes/enable
# sleep 20
# echo 0 > events/uprobes/enable
# cat trace
# tracer: nop
#
#           TASK-PID    CPU#    TIMESTAMP  FUNCTION
#              | |       |          |         |
             zsh-24842 [006] 258544.995456: p_zsh_0x46420: (0x446420) arg1=446421 arg2=79
             zsh-24842 [007] 258545.000270: p_zsh_0x46420: (0x446420) arg1=446421 arg2=79
             zsh-24842 [002] 258545.043929: p_zsh_0x46420: (0x446420) arg1=446421 arg2=79
             zsh-24842 [004] 258547.046129: p_zsh_0x46420: (0x446420) arg1=446421 arg2=79

TODO: Connect a filter to a consumer.

---
Changelog (since v9)
- Disable preemption while in perf handler as suggested by Jiri Olsa.

Changelog (since v5)
- Added uprobe tracer documentation to this patch.

 Documentation/trace/uprobetracer.txt |   93 ++++
 arch/Kconfig                         |   10 
 kernel/trace/Kconfig                 |   16 +
 kernel/trace/Makefile                |    1 
 kernel/trace/trace.h                 |    5 
 kernel/trace/trace_kprobe.c          |    4 
 kernel/trace/trace_probe.c           |   14 -
 kernel/trace/trace_probe.h           |    3 
 kernel/trace/trace_uprobe.c          |  772 ++++++++++++++++++++++++++++++++++
 9 files changed, 902 insertions(+), 16 deletions(-)
 create mode 100644 Documentation/trace/uprobetracer.txt
 create mode 100644 kernel/trace/trace_uprobe.c
Documentation/trace/uprobetracer.txt new file +93 -0
new file mode 100644
index 0000000..457932f
@@ -0,0 +1,93 @@
+		Uprobe-tracer: Uprobe-based Event Tracing
+		=========================================
+                 Documentation is written by Srikar Dronamraju
+
+Overview
+--------
+These events are similar to kprobe based events.
+To enable this feature, build your kernel with CONFIG_UPROBE_EVENTS=y.
+
+Similar to the kprobe-event tracer, this doesn't need to be activated via
+current_tracer. Instead of that, add probe points via
+/sys/kernel/debug/tracing/uprobe_events, and enable it via
+/sys/kernel/debug/tracing/events/uprobes/<EVENT>/enabled.
+
+
+Synopsis of uprobe_tracer
+-------------------------
+  p[:[GRP/]EVENT] PATH:SYMBOL[+offs] [FETCHARGS]	: Set a probe
+
+ GRP		: Group name. If omitted, use "uprobes" for it.
+ EVENT		: Event name. If omitted, the event name is generated
+		  based on SYMBOL+offs.
+ PATH		: path to an executable or a library.
+ SYMBOL[+offs]	: Symbol+offset where the probe is inserted.
+
+ FETCHARGS	: Arguments. Each probe can have up to 128 args.
+  %REG		: Fetch register REG
+
+Event Profiling
+---------------
+ You can check the total number of probe hits and probe miss-hits via
+/sys/kernel/debug/tracing/uprobe_profile.
+ The first column is event name, the second is the number of probe hits,
+the third is the number of probe miss-hits.
+
+Usage examples
+--------------
+To add a probe as a new event, write a new definition to uprobe_events
+as below.
+
+  echo 'p: /bin/bash:0x4245c0' > /sys/kernel/debug/tracing/uprobe_events
+
+ This sets a uprobe at an offset of 0x4245c0 in the executable /bin/bash
+
+
+  echo > /sys/kernel/debug/tracing/uprobe_events
+
+ This clears all probe points.
+
+The following example shows how to dump the instruction pointer and %ax
+a register at the probed text address.  Here we are trying to probe
+function zfree in /bin/zsh
+
+    # cd /sys/kernel/debug/tracing/
+    # cat /proc/`pgrep  zsh`/maps | grep /bin/zsh | grep r-xp
+    00400000-0048a000 r-xp 00000000 08:03 130904 /bin/zsh
+    # objdump -T /bin/zsh | grep -w zfree
+    0000000000446420 g    DF .text  0000000000000012  Base        zfree
+
+0x46420 is the offset of zfree in object /bin/zsh that is loaded at
+0x00400000. Hence the command to probe would be :
+
+    # echo 'p /bin/zsh:0x46420 %ip %ax' > uprobe_events
+
+We can see the events that are registered by looking at the uprobe_events
+file.
+
+    # cat uprobe_events
+    p:uprobes/p_zsh_0x46420 /bin/zsh:0x0000000000046420
+
+Right after definition, each event is disabled by default. For tracing these
+events, you need to enable it by:
+
+    # echo 1 > events/uprobes/enable
+
+Lets disable the event after sleeping for some time.
+    # sleep 20
+    # echo 0 > events/uprobes/enable
+
+And you can see the traced information via /sys/kernel/debug/tracing/trace.
+
+    # cat trace
+    # tracer: nop
+    #
+    #           TASK-PID    CPU#    TIMESTAMP  FUNCTION
+    #              | |       |          |         |
+                 zsh-24842 [006] 258544.995456: p_zsh_0x46420: (0x446420) arg1=446421 arg2=79
+                 zsh-24842 [007] 258545.000270: p_zsh_0x46420: (0x446420) arg1=446421 arg2=79
+                 zsh-24842 [002] 258545.043929: p_zsh_0x46420: (0x446420) arg1=446421 arg2=79
+                 zsh-24842 [004] 258547.046129: p_zsh_0x46420: (0x446420) arg1=446421 arg2=79
+
+Each line shows us probes were triggered for a pid 24842 with ip being
+0x446421 and contents of ax register being 79.
arch/Kconfig +1 -9
index 284f589..ebb86e5 100644
@@ -66,15 +66,7 @@ config OPTPROBES
 	depends on !PREEMPT
 
 config UPROBES
-	bool "User-space probes (EXPERIMENTAL)"
-	depends on ARCH_SUPPORTS_UPROBES
-	default n
-	help
-	  Uprobes enables kernel subsystems to establish probepoints
-	  in user applications and execute handler functions when
-	  the probepoints are hit.
-
-	  If in doubt, say "N".
+	def_bool n
 
 config HAVE_EFFICIENT_UNALIGNED_ACCESS
 	bool
kernel/trace/Kconfig +16 -0
index 520106a..b001fb1 100644
@@ -386,6 +386,22 @@ config KPROBE_EVENT
 	  This option is also required by perf-probe subcommand of perf tools.
 	  If you want to use perf tools, this option is strongly recommended.
 
+config UPROBE_EVENT
+	bool "Enable uprobes-based dynamic events"
+	depends on ARCH_SUPPORTS_UPROBES
+	depends on MMU
+	select UPROBES
+	select PROBE_EVENTS
+	select TRACING
+	default n
+	help
+	  This allows the user to add tracing events on top of userspace dynamic
+	  events (similar to tracepoints) on the fly via the traceevents interface.
+	  Those events can be inserted wherever uprobes can probe, and record
+	  various registers.
+	  This option is required if you plan to use perf-probe subcommand of perf
+	  tools on user space applications.
+
 config PROBE_EVENTS
 	def_bool n
 
kernel/trace/Makefile +1 -0
index fa10d5c..1734c03 100644
@@ -62,5 +62,6 @@ ifeq ($(CONFIG_TRACING),y)
 obj-$(CONFIG_KGDB_KDB) += trace_kdb.o
 endif
 obj-$(CONFIG_PROBE_EVENTS) += trace_probe.o
+obj-$(CONFIG_UPROBE_EVENT) += trace_uprobe.o
 
 libftrace-y := ftrace.o
kernel/trace/trace.h +5 -0
index b93ecba..03a5818 100644
@@ -97,6 +97,11 @@ struct kretprobe_trace_entry_head {
 	unsigned long		ret_ip;
 };
 
+struct uprobe_trace_entry_head {
+	struct trace_entry	ent;
+	unsigned long		ip;
+};
+
 /*
  * trace_flag_type is an enumeration that holds different
  * states when a trace occurs. These are:
kernel/trace/trace_kprobe.c +2 -2
index 967e634..60384df 100644
@@ -524,8 +524,8 @@ static int create_trace_probe(int argc, char **argv)
 		}
 
 		/* Parse fetch argument */
-		ret = traceprobe_parse_probe_arg(arg, &tp->size, &tp->args[i],
-								is_return);
+		ret = traceprobe_parse_probe_arg(arg, &tp->size,
+					&tp->args[i], is_return, true);
 		if (ret) {
 			pr_info("Parse error at argument[%d]. (%d)\n", i, ret);
 			goto error;
kernel/trace/trace_probe.c +10 -4
index e79a9e5..c0a98e6 100644
@@ -529,13 +529,17 @@ static int parse_probe_vars(char *arg, const struct fetch_type *t,
 
 /* Recursive argument parser */
 static int parse_probe_arg(char *arg, const struct fetch_type *t,
-		     struct fetch_param *f, bool is_return)
+		     struct fetch_param *f, bool is_return, bool is_kprobe)
 {
 	int ret = 0;
 	unsigned long param;
 	long offset;
 	char *tmp;
 
+	/* Until uprobe_events supports only reg arguments */
+	if (!is_kprobe && arg[0] != '%')
+		return -EINVAL;
+
 	switch (arg[0]) {
 	case '$':
 		ret = parse_probe_vars(arg + 1, t, f, is_return);
@@ -585,7 +589,8 @@ static int parse_probe_arg(char *arg, const struct fetch_type *t,
 			if (!dprm)
 				return -ENOMEM;
 			dprm->offset = offset;
-			ret = parse_probe_arg(arg, t2, &dprm->orig, is_return);
+			ret = parse_probe_arg(arg, t2, &dprm->orig, is_return,
+							is_kprobe);
 			if (ret)
 				kfree(dprm);
 			else {
@@ -640,7 +645,7 @@ static int __parse_bitfield_probe_arg(const char *bf,
 
 /* String length checking wrapper */
 int traceprobe_parse_probe_arg(char *arg, ssize_t *size,
-		struct probe_arg *parg, bool is_return)
+		struct probe_arg *parg, bool is_return, bool is_kprobe)
 {
 	const char *t;
 	int ret;
@@ -666,7 +671,8 @@ int traceprobe_parse_probe_arg(char *arg, ssize_t *size,
 	}
 	parg->offset = *size;
 	*size += parg->type->size;
-	ret = parse_probe_arg(arg, parg->type, &parg->fetch, is_return);
+	ret = parse_probe_arg(arg, parg->type, &parg->fetch, is_return,
+							is_kprobe);
 	if (ret >= 0 && t != NULL)
 		ret = __parse_bitfield_probe_arg(t, parg->type, &parg->fetch);
 	if (ret >= 0) {
kernel/trace/trace_probe.h +2 -1
index 84eef0a..31e635e 100644
@@ -66,6 +66,7 @@
 #define TP_FLAG_TRACE	1
 #define TP_FLAG_PROFILE	2
 #define TP_FLAG_REGISTERED 4
+#define TP_FLAG_UPROBE	8
 
 
 /* data_rloc: data relative location, compatible with u32 */
@@ -144,7 +145,7 @@ static inline int is_good_name(const char *name)
 }
 
 extern int traceprobe_parse_probe_arg(char *arg, ssize_t *size,
-		   struct probe_arg *parg, bool is_return);
+		   struct probe_arg *parg, bool is_return, bool is_kprobe);
 
 extern int traceprobe_conflict_field_name(const char *name,
 			       struct probe_arg *args, int narg);
kernel/trace/trace_uprobe.c new file +772 -0

772 lines not on this page · raw message

#31 lore raw

PATCH v10 8/9 perf: rename target_module to target

In reply to Srikar Dronamraju

This is a precursor patch that modifies names that refer to kernel/module to also refer to user space names.

---
 tools/perf/builtin-probe.c    |   12 ++++++------
 tools/perf/util/probe-event.c |   26 +++++++++++++-------------
 2 files changed, 19 insertions(+), 19 deletions(-)
tools/perf/builtin-probe.c +6 -6
index 59d43ab..833aa8c 100644
@@ -60,7 +60,7 @@ static struct {
 	struct perf_probe_event events[MAX_PROBES];
 	struct strlist *dellist;
 	struct line_range line_range;
-	const char *target_module;
+	const char *target;
 	int max_probe_points;
 	struct strfilter *filter;
 } params;
@@ -248,7 +248,7 @@ static const struct option options[] = {
 		   "file", "vmlinux pathname"),
 	OPT_STRING('s', "source", &symbol_conf.source_prefix,
 		   "directory", "path to kernel source"),
-	OPT_STRING('m', "module", &params.target_module,
+	OPT_STRING('m', "module", &params.target,
 		   "modname|path",
 		   "target module name (for online) or path (for offline)"),
 #endif
@@ -335,7 +335,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 		if (!params.filter)
 			params.filter = strfilter__new(DEFAULT_FUNC_FILTER,
 						       NULL);
-		ret = show_available_funcs(params.target_module,
+		ret = show_available_funcs(params.target,
 					   params.filter);
 		strfilter__delete(params.filter);
 		if (ret < 0)
@@ -356,7 +356,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 			usage_with_options(probe_usage, options);
 		}
 
-		ret = show_line_range(&params.line_range, params.target_module);
+		ret = show_line_range(&params.line_range, params.target);
 		if (ret < 0)
 			pr_err("  Error: Failed to show lines. (%d)\n", ret);
 		return ret;
@@ -373,7 +373,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 
 		ret = show_available_vars(params.events, params.nevents,
 					  params.max_probe_points,
-					  params.target_module,
+					  params.target,
 					  params.filter,
 					  params.show_ext_vars);
 		strfilter__delete(params.filter);
@@ -395,7 +395,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 	if (params.nevents) {
 		ret = add_perf_probe_events(params.events, params.nevents,
 					    params.max_probe_points,
-					    params.target_module,
+					    params.target,
 					    params.force_add);
 		if (ret < 0) {
 			pr_err("  Error: Failed to add events. (%d)\n", ret);
tools/perf/util/probe-event.c +13 -13
index eb25900..d54eefb 100644
@@ -275,10 +275,10 @@ static int add_module_to_probe_trace_events(struct probe_trace_event *tevs,
 /* Try to find perf_probe_event with debuginfo */
 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
 					  struct probe_trace_event **tevs,
-					  int max_tevs, const char *module)
+					  int max_tevs, const char *target)
 {
 	bool need_dwarf = perf_probe_event_need_dwarf(pev);
-	struct debuginfo *dinfo = open_debuginfo(module);
+	struct debuginfo *dinfo = open_debuginfo(target);
 	int ntevs, ret = 0;
 
 	if (!dinfo) {
@@ -297,9 +297,9 @@ static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
 
 	if (ntevs > 0) {	/* Succeeded to find trace events */
 		pr_debug("find %d probe_trace_events.\n", ntevs);
-		if (module)
+		if (target)
 			ret = add_module_to_probe_trace_events(*tevs, ntevs,
-							       module);
+							       target);
 		return ret < 0 ? ret : ntevs;
 	}
 
@@ -1798,14 +1798,14 @@ static int __add_probe_trace_events(struct perf_probe_event *pev,
 
 static int convert_to_probe_trace_events(struct perf_probe_event *pev,
 					  struct probe_trace_event **tevs,
-					  int max_tevs, const char *module)
+					  int max_tevs, const char *target)
 {
 	struct symbol *sym;
 	int ret = 0, i;
 	struct probe_trace_event *tev;
 
 	/* Convert perf_probe_event with debuginfo */
-	ret = try_to_find_probe_trace_events(pev, tevs, max_tevs, module);
+	ret = try_to_find_probe_trace_events(pev, tevs, max_tevs, target);
 	if (ret != 0)
 		return ret;	/* Found in debuginfo or got an error */
 
@@ -1821,8 +1821,8 @@ static int convert_to_probe_trace_events(struct perf_probe_event *pev,
 		goto error;
 	}
 
-	if (module) {
-		tev->point.module = strdup(module);
+	if (target) {
+		tev->point.module = strdup(target);
 		if (tev->point.module == NULL) {
 			ret = -ENOMEM;
 			goto error;
@@ -1886,7 +1886,7 @@ struct __event_package {
 };
 
 int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
-			  int max_tevs, const char *module, bool force_add)
+			  int max_tevs, const char *target, bool force_add)
 {
 	int i, j, ret;
 	struct __event_package *pkgs;
@@ -1909,7 +1909,7 @@ int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
 		ret  = convert_to_probe_trace_events(pkgs[i].pev,
 						     &pkgs[i].tevs,
 						     max_tevs,
-						     module);
+						     target);
 		if (ret < 0)
 			goto end;
 		pkgs[i].ntevs = ret;
@@ -2065,7 +2065,7 @@ static int filter_available_functions(struct map *map __unused,
 	return 1;
 }
 
-int show_available_funcs(const char *module, struct strfilter *_filter)
+int show_available_funcs(const char *target, struct strfilter *_filter)
 {
 	struct map *map;
 	int ret;
@@ -2076,9 +2076,9 @@ int show_available_funcs(const char *module, struct strfilter *_filter)
 	if (ret < 0)
 		return ret;
 
-	map = kernel_get_module_map(module);
+	map = kernel_get_module_map(target);
 	if (!map) {
-		pr_err("Failed to find %s map.\n", (module) ? : "kernel");
+		pr_err("Failed to find %s map.\n", (target) ? : "kernel");
 		return -EINVAL;
 	}
 	available_func_filter = _filter;

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#33 lore raw

PATCH v10 9/9 perf: perf interface for uprobes

In reply to Srikar Dronamraju

- Enhances perf probe to user space executables and libraries.
- Enhances -F/--funcs option of "perf probe" to list possible probe points in an executable file or library.
- Documents userspace probing support in perf.

[ Probing a function in the executable using function name ] perf probe -x /bin/zsh zfree

[ Probing a library function using function name ] perf probe -x /lib64/libc.so.6 malloc

[ list probe-able functions in an executable ]
perf probe -F -x /bin/zsh

[ list probe-able functions in an library]
perf probe -F -x /lib/libc.so.6

---
(Changelog (since v9)
- Handled comments from Masami Hiramatsu that helps reduce code changes.
- Handled usability comment(print complete name of file) from Ingo Molnar.

(Changelog (since v5)
- Removed the separate documentation change patch and added the documentation changes as part of this patch.

[root@localhost ~]# perf probe -x /bin/zsh zfree
Add new event:
probe_zsh:zfree (on /bin/zsh:0x45400)

You can now use it on all perf tools, such as:

perf record -e probe_zsh:zfree -aR sleep 1

[root@localhost ~]# perf record -e probe_zsh:zfree -aR sleep 15 [ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.314 MB perf.data (~13715 samples) ] [root@localhost ~]# perf report --stdio
# Events: 3K probe_zsh:zfree
#

# Overhead  Command  Shared Object  Symbol
# ........  .......  .............  ......

#
100.00% zsh zsh [.] zfree

#
# (For a higher level overview, try: perf report --sort comm,dso) #
[root@localhost ~]

[ Probing a library function using function name ]
--------------------------------------------------
[root@localhost]#

[root@localhost]# perf probe -x /lib64/libc.so.6 malloc
Add new event:
  probe_libc:malloc    (on /lib64/libc-2.5.so:0x74dc0)

You can now use it on all perf tools, such as:

perf record -e probe_libc:malloc -aR sleep 1

[root@localhost]#

[root@localhost]# perf probe --list
  probe_libc:malloc    (on /lib64/libc-2.5.so:0x0000000000074dc0)

Show last 10 functions in /bin/zsh.

# perf probe -F -x /bin/zsh | tail
zstrtol
ztrcmp
ztrdup
ztrduppfx
ztrftime
ztrlen
ztrncpy
ztrsub
zwarn
zwarnnam

Show first 10 functions in /lib/libc.so.6

# perf probe -F -x /lib/libc.so.6 | head
_IO_adjust_column
_IO_adjust_wcolumn
_IO_default_doallocate
_IO_default_finish
_IO_default_pbackfail
_IO_default_uflow
_IO_default_xsgetn
_IO_default_xsputn
_IO_do_write@@GLIBC_2.2.5
_IO_doallocbuf
 tools/perf/Documentation/perf-probe.txt |   14 +
 tools/perf/builtin-probe.c              |   41 +++
 tools/perf/util/probe-event.c           |  415 ++++++++++++++++++++++++-------
 tools/perf/util/probe-event.h           |   12 +
 tools/perf/util/symbol.c                |    8 +
 tools/perf/util/symbol.h                |    1 
 6 files changed, 391 insertions(+), 100 deletions(-)
tools/perf/Documentation/perf-probe.txt +14 -0
index 2780d9c..be88378 100644
@@ -78,6 +78,8 @@ OPTIONS
 -F::
 --funcs::
 	Show available functions in given module or kernel.
+	With -x/--exec, can also list functions in a user space executable
+	/ shared library.
 
 --filter=FILTER::
 	(Only for --vars and --funcs) Set filter. FILTER is a combination of glob
@@ -98,6 +100,11 @@ OPTIONS
 --max-probes::
 	Set the maximum number of probe points for an event. Default is 128.
 
+-x::
+--exec=PATH::
+	Specify path to the executable or shared library file for user
+	space tracing. Can also be used with --funcs option.
+
 PROBE SYNTAX
 ------------
 Probe points are defined by following syntax.
@@ -182,6 +189,13 @@ Delete all probes on schedule().
 
  ./perf probe --del='schedule*'
 
+Add probes at zfree() function on /bin/zsh
+
+ ./perf probe -x /bin/zsh zfree
+
+Add probes at malloc() function on libc
+
+ ./perf probe -x /lib/libc.so.6 malloc
 
 SEE ALSO
 --------
tools/perf/builtin-probe.c +35 -6

89 lines not on this page · raw message

tools/perf/util/probe-event.c +326 -89

643 lines not on this page · raw message

tools/perf/util/probe-event.h +7 -5
index a7dee83..f9f3de8 100644
@@ -7,7 +7,7 @@
 
 extern bool probe_event_dry_run;
 
-/* kprobe-tracer tracing point */
+/* kprobe-tracer and uprobe-tracer tracing point */
 struct probe_trace_point {
 	char		*symbol;	/* Base symbol */
 	char		*module;	/* Module name */
@@ -21,7 +21,7 @@ struct probe_trace_arg_ref {
 	long				offset;	/* Offset value */
 };
 
-/* kprobe-tracer tracing argument */
+/* kprobe-tracer and uprobe-tracer tracing argument */
 struct probe_trace_arg {
 	char				*name;	/* Argument name */
 	char				*value;	/* Base value */
@@ -29,12 +29,13 @@ struct probe_trace_arg {
 	struct probe_trace_arg_ref	*ref;	/* Referencing offset */
 };
 
-/* kprobe-tracer tracing event (point + arg) */
+/* kprobe-tracer and uprobe-tracer tracing event (point + arg) */
 struct probe_trace_event {
 	char				*event;	/* Event name */
 	char				*group;	/* Group name */
 	struct probe_trace_point	point;	/* Trace point */
 	int				nargs;	/* Number of args */
+	bool				uprobes;	/* uprobes only */
 	struct probe_trace_arg		*args;	/* Arguments */
 };
 
@@ -70,6 +71,7 @@ struct perf_probe_event {
 	char			*group;	/* Group name */
 	struct perf_probe_point	point;	/* Probe point */
 	int			nargs;	/* Number of arguments */
+	bool			uprobes;
 	struct perf_probe_arg	*args;	/* Arguments */
 };
 
@@ -129,8 +131,8 @@ extern int show_line_range(struct line_range *lr, const char *module);
 extern int show_available_vars(struct perf_probe_event *pevs, int npevs,
 			       int max_probe_points, const char *module,
 			       struct strfilter *filter, bool externs);
-extern int show_available_funcs(const char *module, struct strfilter *filter);
-
+extern int show_available_funcs(const char *module, struct strfilter *filter,
+				bool user);
 
 /* Maximum index number of event-name postfix */
 #define MAX_EVENT_INDEX	1024
tools/perf/util/symbol.c +8 -0
index 215d50f..d19cda0 100644
@@ -2762,3 +2762,11 @@ int machine__load_vmlinux_path(struct machine *machine, enum map_type type,
 
 	return ret;
 }
+
+struct map *dso__new_map(const char *name)
+{
+	struct dso *dso = dso__new(name);
+	struct map *map = map__new2(0, dso, MAP__FUNCTION);
+
+	return map;
+}
tools/perf/util/symbol.h +1 -0
index 123c2e1..2627a11 100644
@@ -218,6 +218,7 @@ void dso__set_long_name(struct dso *dso, char *name);
 void dso__set_build_id(struct dso *dso, void *build_id);
 void dso__read_running_kernel_build_id(struct dso *dso,
 				       struct machine *machine);
+struct map *dso__new_map(const char *name);
 struct symbol *dso__find_symbol(struct dso *dso, enum map_type type,
 				u64 addr);
 struct symbol *dso__find_symbol_by_name(struct dso *dso, enum map_type type,

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#2 lore raw

Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

In reply to Srikar Dronamraju
Quoted 2 lines · Srikar Dronamraju

Changelog: (Since v9) : Use insn_offset_modrm as suggested by Masami Hiramatsu.

Would you add REX.B clearing code to handle_riprel_insn() too? Of course, that might not happen because it's a non-effective bit, however user can program it and pass it to uprobes.

arch/x86/kernel/uprobes.c line 301

Quoted 13 lines
arch/x86/kernel/uprobes.c new file +13 -0
+static void handle_riprel_insn(struct mm_struct *mm, struct uprobe *uprobe,
+							struct insn *insn)
+{
+	u8 *cursor;
+	u8 reg;
+
+	if (mm->context.ia32_compat)
+		return;
+
+	uprobe->arch_info.rip_rela_target_address = 0x0;
+	if (!insn_rip_relative(insn))
+		return;
+

So, here you need a REX.B clearing, like below.

insn_get_length(insn);

if (insn->rex_prefix.nbytes) {
	cursor = uprobe->insn + insn_offset_rex_prefix(insn);
	*cursor &= 0xfe;	/* Clearing REX.B bit */
}
Quoted 33 lines
arch/x86/kernel/uprobes.c new file +33 -0
+	/*
+	 * Point cursor at the modrm byte.  The next 4 bytes are the
+	 * displacement.  Beyond the displacement, for some instructions,
+	 * is the immediate operand.
+	 */
+	cursor = uprobe->insn + insn_offset_modrm(insn);
+	insn_get_length(insn);
+
+	/*
+	 * Convert from rip-relative addressing to indirect addressing
+	 * via a scratch register.  Change the r/m field from 0x5 (%rip)
+	 * to 0x0 (%rax) or 0x1 (%rcx), and squeeze out the offset field.
+	 */
+	reg = MODRM_REG(insn);
+	if (reg == 0) {
+		/*
+		 * The register operand (if any) is either the A register
+		 * (%rax, %eax, etc.) or (if the 0x4 bit is set in the
+		 * REX prefix) %r8.  In any case, we know the C register
+		 * is NOT the register operand, so we use %rcx (register
+		 * #1) for the scratch register.
+		 */
+		uprobe->arch_info.fixups = UPROBES_FIX_RIP_CX;
+		/* Change modrm from 00 000 101 to 00 000 001. */
+		*cursor = 0x1;
+	} else {
+		/* Use %rax (register #0) for the scratch register. */
+		uprobe->arch_info.fixups = UPROBES_FIX_RIP_AX;
+		/* Change modrm from 00 xxx 101 to 00 xxx 000 */
+		*cursor = (reg << 3);
+	}
+
+	/* Target address = address of next instruction + (signed) offset */

arch/x86/kernel/uprobes.c line 344

Quoted 10 lines
arch/x86/kernel/uprobes.c new file +10 -0
+	uprobe->arch_info.rip_rela_target_address = (long)insn->length
+					+ insn->displacement.value;
+	/* Displacement field is gone; slide immediate field (if any) over. */
+	if (insn->immediate.nbytes) {
+		cursor++;
+		memmove(cursor, cursor + insn->displacement.nbytes,
+						insn->immediate.nbytes);
+	}
+	return;
+}

Thank you,

Signature · 11 lines
Masami HIRAMATSU
Software Platform Research Dept. Linux Technology Center
Hitachi, Ltd., Yokohama Research Laboratory
E-mail: [email protected]

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#3 lore raw

Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

In reply to Srikar Dronamraju

Added code to clear REX.B as pointed by Denys Vlasenko and fix suggested by Masami Hiramatsu.

---
From: Srikar Dronamraju <[email protected]>

Uprobes are maintained in an rb-tree indexed by inode and offset (the offset here is from the start of the mapping). For a unique (inode, offset) tuple, there can be atmost one uprobe in the rb-tree.

Since the (inode, offset) tuple identifies a unique uprobe, more than one user may be interested in the same uprobe. Provides the ability to hook multiple 'consumers' for the same uprobe.

Each consumer defines a handler and a filter (optional). The 'handler' is run every time the uprobe is hit, if it matches the 'filter' criteria.

The first consumer of a uprobe causes the breakpoint to be inserted at the specified address and subsequent consumers are appended to this list. On subsequent probes, the consumer gets appended to the existing list of consumers. The breakpoint is removed when the last consumer unregisters. For all other unregisterations, the consumer is removed from the list of consumers.

Given a inode, we get a list of the mms that have mapped the inode. Do the actual registration if mm maps the page where a probe needs to be inserted/removed.

We use a temporary list to walk thro the vmas that map the inode.
- The number of maps that map the inode, is not known before we walk the rmap and keeps changing.
- extending vm_area_struct wasnt recommended.
- There can be more than one maps of the inode in the same mm.

Hook mmap to keep an eye on text vmas that are of interest to uprobes. When a vma of interest is mapped, insert the breakpoint at the right address.

Uprobe works by replacing the instruction at the address defined by (inode, offset) with the arch specific breakpoint instruction. Save a copy of the original instruction at the uprobed address.

This is needed for:
a. executing the instruction out-of-line (xol).
b. instruction analysis for any subsequent fixups.
c. restoring the instruction back when the uprobe is unregistered.

We insert or delete a breakpoint instruction, and this breakpoint instruction is assumed to be the smallest instruction available on the platform. For fixed size instruction platforms this is trivially true, for variable size instruction platforms the breakpoint instruction is typically the smallest (often a single byte).

Writing the instruction is done by COWing the page and changing the instruction during the copy, this even though most platforms allow atomic writes of the breakpoint instruction. This also mirrors the behaviour of a ptrace() memory write to a PRIVATE file map.

The core worker is derived from ksm's replace_page() logic.

In essence, similar to ksm:
a. allocate a new page and copy over contents of the page that has the
uprobed vaddr
b. modify the copy and insert the breakpoint at the required address c. switch the original page with the copy containing the breakpoint d. flush page tables.

replace_page is being replicated here because of some minor changes in the type of pages and also because Hugh Dickins had plans to improve replace_page for ksm specific work.

Instruction analysis on x86 is based on instruction decoder and determines if an instruction can be probed and determines the necessary fixups after singlestep. Instruction analysis is done at probe insertion time so that we avoid having to repeat the same analysis every time a probe is hit.

A lot of code here is due to the improvement/suggestions/inputs from Peter Zijlstra.

---

Changelog: (Since v10): Add code to clear REX.B prefix pointed out by Denys Vlasenko and fix suggested by Masami Hiramatsu.

Changelog: (Since v9) : Use insn_offset_modrm as suggested by Masami Hiramatsu.

Changelog: (Since v7) : Handle comments from Peter Zijlstra
- Dont take reference to inode. (expect inode to register_uprobe to be sane).
- Use PTR_ERR to set the return value.
- No need to take reference to inode.
- use PTR_ERR to return error value.
- register and unregister_uprobe share code.

Changelog:(Since v5)
- Modified del_consumer as per comments from Peter.
- Drop reference to inode before dropping reference to uprobe.
- Use i_size_read(inode) instead of inode->i_size.
- Ensure uprobe->consumers is NULL, before __unregister_uprobe() is called.
- Includes errno.h as recommended by Stephen Rothwell to fix a build issue on sparc defconfig
- Remove restrictions while unregistering.
- Earlier code leaked inode references under some conditions while registering/unregistering.
- Continue the vma-rmap walk even if the intermediate vma doesnt meet the requirements.
- Validate the vma found by find_vma before inserting/removing the breakpoint
- Call del_consumer under mutex_lock.
- Use hash locks.
- Handle mremap.
- Introduce find_least_offset_node() instead of close match logic in find_uprobe
- Uprobes no more depends on MM_OWNER; No reference to task_structs while inserting/removing a probe.
- Uses read_mapping_page instead of grab_cache_page so that the pages have valid content.
- pass NULL to get_user_pages for the task parameter.
- call SetPageUptodate on the new page allocated in write_opcode.
- fix leaking a reference to the new page under certain conditions.
- Include Instruction Decoder if Uprobes gets defined.
- Remove const attributes for instruction prefix arrays.
- Uses mm_context to know if the application is 32 bit.

 arch/Kconfig                   |   11 
 arch/x86/Kconfig               |    5 
 arch/x86/include/asm/uprobes.h |   42 ++
 arch/x86/kernel/Makefile       |    1 
 arch/x86/kernel/uprobes.c      |  404 +++++++++++++++++
 include/linux/uprobes.h        |   98 ++++
 kernel/Makefile                |    1 
 kernel/uprobes.c               |  976 ++++++++++++++++++++++++++++++++++++++++
 mm/mmap.c                      |   23 +
 9 files changed, 1560 insertions(+), 1 deletions(-)
 create mode 100644 arch/x86/include/asm/uprobes.h
 create mode 100644 arch/x86/kernel/uprobes.c
 create mode 100644 include/linux/uprobes.h
 create mode 100644 kernel/uprobes.c
arch/Kconfig +11 -0
index 4f55c73..284f589 100644
@@ -65,6 +65,17 @@ config OPTPROBES
 	depends on KPROBES && HAVE_OPTPROBES
 	depends on !PREEMPT
 
+config UPROBES
+	bool "User-space probes (EXPERIMENTAL)"
+	depends on ARCH_SUPPORTS_UPROBES
+	default n
+	help
+	  Uprobes enables kernel subsystems to establish probepoints
+	  in user applications and execute handler functions when
+	  the probepoints are hit.
+
+	  If in doubt, say "N".
+
 config HAVE_EFFICIENT_UNALIGNED_ACCESS
 	bool
 	help
arch/x86/Kconfig +4 -1
index 5bed94e..481dbfc 100644
@@ -84,7 +84,7 @@ config X86
 	select GENERIC_IOMAP
 
 config INSTRUCTION_DECODER
-	def_bool (KPROBES || PERF_EVENTS)
+	def_bool (KPROBES || PERF_EVENTS || UPROBES)
 
 config OUTPUT_FORMAT
 	string
@@ -240,6 +240,9 @@ config ARCH_CPU_PROBE_RELEASE
 	def_bool y
 	depends on HOTPLUG_CPU
 
+config ARCH_SUPPORTS_UPROBES
+	def_bool y
+
 source "init/Kconfig"
 source "kernel/Kconfig.freezer"
 
arch/x86/include/asm/uprobes.h new file +42 -0

42 lines not on this page · raw message

arch/x86/kernel/Makefile +1 -0
index 5369059..8c8c365 100644
@@ -100,6 +100,7 @@ obj-$(CONFIG_X86_CHECK_BIOS_CORRUPTION) += check.o
 
 obj-$(CONFIG_SWIOTLB)			+= pci-swiotlb.o
 obj-$(CONFIG_OF)			+= devicetree.o
+obj-$(CONFIG_UPROBES)			+= uprobes.o
 
 ###
 # 64 bit specific files
arch/x86/kernel/uprobes.c new file +404 -0

404 lines not on this page · raw message

include/linux/uprobes.h new file +98 -0

98 lines not on this page · raw message

kernel/Makefile +1 -0
index 2d9de86..8609dd3 100644
@@ -107,6 +107,7 @@ obj-$(CONFIG_USER_RETURN_NOTIFIER) += user-return-notifier.o
 obj-$(CONFIG_PADATA) += padata.o
 obj-$(CONFIG_CRASH_DUMP) += crash_dump.o
 obj-$(CONFIG_JUMP_LABEL) += jump_label.o
+obj-$(CONFIG_UPROBES) += uprobes.o
 
 $(obj)/configs.o: $(obj)/config_data.h
 
kernel/uprobes.c new file +976 -0

976 lines not on this page · raw message

mm/mmap.c +23 -0
index 3f758c7..1aed183 100644
@@ -30,6 +30,7 @@
 #include <linux/perf_event.h>
 #include <linux/audit.h>
 #include <linux/khugepaged.h>
+#include <linux/uprobes.h>
 
 #include <asm/uaccess.h>
 #include <asm/cacheflush.h>
@@ -616,6 +617,13 @@ again:			remove_next = 1 + (end > next->vm_end);
 	if (mapping)
 		mutex_unlock(&mapping->i_mmap_mutex);
 
+	if (root) {
+		mmap_uprobe(vma);
+
+		if (adjust_next)
+			mmap_uprobe(next);
+	}
+
 	if (remove_next) {
 		if (file) {
 			fput(file);
@@ -637,6 +645,8 @@ again:			remove_next = 1 + (end > next->vm_end);
 			goto again;
 		}
 	}
+	if (insert && file)
+		mmap_uprobe(insert);
 
 	validate_mm(mm);
 
@@ -1329,6 +1339,11 @@ unsigned long mmap_region(struct file *file, unsigned long addr,
 			mm->locked_vm += (len >> PAGE_SHIFT);
 	} else if ((flags & MAP_POPULATE) && !(flags & MAP_NONBLOCK))
 		make_pages_present(addr, addr + len);
+
+	if (file && mmap_uprobe(vma))
+		/* matching probes but cannot insert */
+		goto unmap_and_free_vma;
+
 	return addr;
 
 unmap_and_free_vma:
@@ -2285,6 +2300,10 @@ int insert_vm_struct(struct mm_struct * mm, struct vm_area_struct * vma)
 	if ((vma->vm_flags & VM_ACCOUNT) &&
 	     security_vm_enough_memory_mm(mm, vma_pages(vma)))
 		return -ENOMEM;
+
+	if (vma->vm_file && mmap_uprobe(vma))
+		return -EINVAL;
+
 	vma_link(mm, vma, prev, rb_link, rb_parent);
 	return 0;
 }
@@ -2354,6 +2373,10 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
 			new_vma->vm_pgoff = pgoff;
 			if (new_vma->vm_file) {
 				get_file(new_vma->vm_file);
+
+				if (mmap_uprobe(new_vma))
+					goto out_free_mempol;
+
 				if (vma->vm_flags & VM_EXECUTABLE)
 					added_exe_file_vma(mm);
 			}

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#32 lore raw

[tip:perf/core] perf probe: Rename target_module to target

In reply to Srikar Dronamraju
Commit-ID:  4eced2347c447c9409877368fc52478c356b4767
Gitweb:     http://git.kernel.org/tip/4eced2347c447c9409877368fc52478c356b4767
Author:     Srikar Dronamraju <[email protected]>
AuthorDate: Thu, 2 Feb 2012 19:50:40 +0530
Committer:  Arnaldo Carvalho de Melo <[email protected]>
CommitDate: Thu, 2 Feb 2012 17:39:15 -0200

perf probe: Rename target_module to target

This is a precursor patch that modifies names that refer to kernel/module to also refer to user space names.

Cc Ananth N Mavinakayanahalli <[email protected]>
Cc Andi Kleen <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Anton Arapov <[email protected]>
Cc Christoph Hellwig <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Jim Keniston <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Linux-mm <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Oleg Nesterov <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Roland McGrath <[email protected]>
Cc Stephen Rothwell <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Thomas Gleixner <[email protected]>
---
 tools/perf/builtin-probe.c    |   12 ++++++------
 tools/perf/util/probe-event.c |   26 +++++++++++++-------------
 2 files changed, 19 insertions(+), 19 deletions(-)
tools/perf/builtin-probe.c +6 -6
index fb85661..4935c09 100644
@@ -58,7 +58,7 @@ static struct {
 	struct perf_probe_event events[MAX_PROBES];
 	struct strlist *dellist;
 	struct line_range line_range;
-	const char *target_module;
+	const char *target;
 	int max_probe_points;
 	struct strfilter *filter;
 } params;
@@ -246,7 +246,7 @@ static const struct option options[] = {
 		   "file", "vmlinux pathname"),
 	OPT_STRING('s', "source", &symbol_conf.source_prefix,
 		   "directory", "path to kernel source"),
-	OPT_STRING('m', "module", &params.target_module,
+	OPT_STRING('m', "module", &params.target,
 		   "modname|path",
 		   "target module name (for online) or path (for offline)"),
 #endif
@@ -333,7 +333,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 		if (!params.filter)
 			params.filter = strfilter__new(DEFAULT_FUNC_FILTER,
 						       NULL);
-		ret = show_available_funcs(params.target_module,
+		ret = show_available_funcs(params.target,
 					   params.filter);
 		strfilter__delete(params.filter);
 		if (ret < 0)
@@ -354,7 +354,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 			usage_with_options(probe_usage, options);
 		}
 
-		ret = show_line_range(&params.line_range, params.target_module);
+		ret = show_line_range(&params.line_range, params.target);
 		if (ret < 0)
 			pr_err("  Error: Failed to show lines. (%d)\n", ret);
 		return ret;
@@ -371,7 +371,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 
 		ret = show_available_vars(params.events, params.nevents,
 					  params.max_probe_points,
-					  params.target_module,
+					  params.target,
 					  params.filter,
 					  params.show_ext_vars);
 		strfilter__delete(params.filter);
@@ -393,7 +393,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 	if (params.nevents) {
 		ret = add_perf_probe_events(params.events, params.nevents,
 					    params.max_probe_points,
-					    params.target_module,
+					    params.target,
 					    params.force_add);
 		if (ret < 0) {
 			pr_err("  Error: Failed to add events. (%d)\n", ret);
tools/perf/util/probe-event.c +13 -13
index b9bbdd2..c1a513e 100644
@@ -273,10 +273,10 @@ static int add_module_to_probe_trace_events(struct probe_trace_event *tevs,
 /* Try to find perf_probe_event with debuginfo */
 static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
 					  struct probe_trace_event **tevs,
-					  int max_tevs, const char *module)
+					  int max_tevs, const char *target)
 {
 	bool need_dwarf = perf_probe_event_need_dwarf(pev);
-	struct debuginfo *dinfo = open_debuginfo(module);
+	struct debuginfo *dinfo = open_debuginfo(target);
 	int ntevs, ret = 0;
 
 	if (!dinfo) {
@@ -295,9 +295,9 @@ static int try_to_find_probe_trace_events(struct perf_probe_event *pev,
 
 	if (ntevs > 0) {	/* Succeeded to find trace events */
 		pr_debug("find %d probe_trace_events.\n", ntevs);
-		if (module)
+		if (target)
 			ret = add_module_to_probe_trace_events(*tevs, ntevs,
-							       module);
+							       target);
 		return ret < 0 ? ret : ntevs;
 	}
 
@@ -1796,14 +1796,14 @@ static int __add_probe_trace_events(struct perf_probe_event *pev,
 
 static int convert_to_probe_trace_events(struct perf_probe_event *pev,
 					  struct probe_trace_event **tevs,
-					  int max_tevs, const char *module)
+					  int max_tevs, const char *target)
 {
 	struct symbol *sym;
 	int ret = 0, i;
 	struct probe_trace_event *tev;
 
 	/* Convert perf_probe_event with debuginfo */
-	ret = try_to_find_probe_trace_events(pev, tevs, max_tevs, module);
+	ret = try_to_find_probe_trace_events(pev, tevs, max_tevs, target);
 	if (ret != 0)
 		return ret;	/* Found in debuginfo or got an error */
 
@@ -1819,8 +1819,8 @@ static int convert_to_probe_trace_events(struct perf_probe_event *pev,
 		goto error;
 	}
 
-	if (module) {
-		tev->point.module = strdup(module);
+	if (target) {
+		tev->point.module = strdup(target);
 		if (tev->point.module == NULL) {
 			ret = -ENOMEM;
 			goto error;
@@ -1884,7 +1884,7 @@ struct __event_package {
 };
 
 int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
-			  int max_tevs, const char *module, bool force_add)
+			  int max_tevs, const char *target, bool force_add)
 {
 	int i, j, ret;
 	struct __event_package *pkgs;
@@ -1907,7 +1907,7 @@ int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
 		ret  = convert_to_probe_trace_events(pkgs[i].pev,
 						     &pkgs[i].tevs,
 						     max_tevs,
-						     module);
+						     target);
 		if (ret < 0)
 			goto end;
 		pkgs[i].ntevs = ret;
@@ -2063,7 +2063,7 @@ static int filter_available_functions(struct map *map __unused,
 	return 1;
 }
 
-int show_available_funcs(const char *module, struct strfilter *_filter)
+int show_available_funcs(const char *target, struct strfilter *_filter)
 {
 	struct map *map;
 	int ret;
@@ -2074,9 +2074,9 @@ int show_available_funcs(const char *module, struct strfilter *_filter)
 	if (ret < 0)
 		return ret;
 
-	map = kernel_get_module_map(module);
+	map = kernel_get_module_map(target);
 	if (!map) {
-		pr_err("Failed to find %s map.\n", (module) ? : "kernel");
+		pr_err("Failed to find %s map.\n", (target) ? : "kernel");
 		return -EINVAL;
 	}
 	available_func_filter = _filter;

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#4 lore raw

Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

In reply to Srikar Dronamraju
Quoted 2 lines · Srikar Dronamraju

Changelog: (Since v10): Add code to clear REX.B prefix pointed out by Denys Vlasenko and fix suggested by Masami Hiramatsu.

...

Quoted 9 lines

+       /*
+        * Point cursor at the modrm byte.  The next 4 bytes are the
+        * displacement.  Beyond the displacement, for some instructions,
+        * is the immediate operand.
+        */
+       cursor = uprobe->insn + insn_offset_modrm(insn);
+       insn_get_length(insn);
+       if (insn->rex_prefix.nbytes)
+               *cursor &= 0xfe;        /* Clearing REX.B bit */

It looks like cursor points to mod/reg/rm byte, not rex byte. Comment above says it too. You seem to be clearing a bit in a wrong byte. I think it should be

        /* Clear REX.b bit (extension of MODRM.rm field):
         * we want to encode rax/rcx, not r8/r9.
         */
        if (insn->rex_prefix.nbytes)
                insn->rex_prefix.bytes[0] &= 0xfe;
Signature · 8 lines
vda

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#5 lore raw

Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

Quoted 15 lines · Denys Vlasenko
Quoted 2 lines · Srikar Dronamraju

Changelog: (Since v10): Add code to clear REX.B prefix pointed out by Denys Vlasenko and fix suggested by Masami Hiramatsu.

...

arch/x86/kernel/uprobes.c line 310

Quoted 9 lines
arch/x86/kernel/uprobes.c new file +9 -0
+       /*
+        * Point cursor at the modrm byte.  The next 4 bytes are the
+        * displacement.  Beyond the displacement, for some instructions,
+        * is the immediate operand.
+        */
+       cursor = uprobe->insn + insn_offset_modrm(insn);
+       insn_get_length(insn);
+       if (insn->rex_prefix.nbytes)
+               *cursor &= 0xfe;        /* Clearing REX.B bit */
Quoted 3 lines

It looks like cursor points to mod/reg/rm byte, not rex byte. Comment above says it too. You seem to be clearing a bit in a wrong byte. I think it should be

Oh okay, Will correct this and send out a new patch.

Quoted 6 lines
        /* Clear REX.b bit (extension of MODRM.rm field):
         * we want to encode rax/rcx, not r8/r9.
         */
        if (insn->rex_prefix.nbytes)
                insn->rex_prefix.bytes[0] &= 0xfe;
Signature · 9 lines
Thanks and Regards
Srikar

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#12 lore raw

Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

In reply to Srikar Dronamraju

Added code to clear REX.B as suggested by Denys Vlasenko and Masami Hiramatsu.

From: Srikar Dronamraju <[email protected]>

Uprobes are maintained in an rb-tree indexed by inode and offset (the offset here is from the start of the mapping). For a unique (inode, offset) tuple, there can be atmost one uprobe in the rb-tree.

Since the (inode, offset) tuple identifies a unique uprobe, more than one user may be interested in the same uprobe. Provides the ability to hook multiple 'consumers' for the same uprobe.

Each consumer defines a handler and a filter (optional). The 'handler' is run every time the uprobe is hit, if it matches the 'filter' criteria.

The first consumer of a uprobe causes the breakpoint to be inserted at the specified address and subsequent consumers are appended to this list. On subsequent probes, the consumer gets appended to the existing list of consumers. The breakpoint is removed when the last consumer unregisters. For all other unregisterations, the consumer is removed from the list of consumers.

Given a inode, we get a list of the mms that have mapped the inode. Do the actual registration if mm maps the page where a probe needs to be inserted/removed.

We use a temporary list to walk thro the vmas that map the inode.
- The number of maps that map the inode, is not known before we walk the rmap and keeps changing.
- extending vm_area_struct wasnt recommended.
- There can be more than one maps of the inode in the same mm.

Hook mmap to keep an eye on text vmas that are of interest to uprobes. When a vma of interest is mapped, insert the breakpoint at the right address.

Uprobe works by replacing the instruction at the address defined by (inode, offset) with the arch specific breakpoint instruction. Save a copy of the original instruction at the uprobed address.

This is needed for:
a. executing the instruction out-of-line (xol).
b. instruction analysis for any subsequent fixups.
c. restoring the instruction back when the uprobe is unregistered.

We insert or delete a breakpoint instruction, and this breakpoint instruction is assumed to be the smallest instruction available on the platform. For fixed size instruction platforms this is trivially true, for variable size instruction platforms the breakpoint instruction is typically the smallest (often a single byte).

Writing the instruction is done by COWing the page and changing the instruction during the copy, this even though most platforms allow atomic writes of the breakpoint instruction. This also mirrors the behaviour of a ptrace() memory write to a PRIVATE file map.

The core worker is derived from ksm's replace_page() logic.

In essence, similar to ksm:
a. allocate a new page and copy over contents of the page that has the
uprobed vaddr
b. modify the copy and insert the breakpoint at the required address c. switch the original page with the copy containing the breakpoint d. flush page tables.

replace_page is being replicated here because of some minor changes in the type of pages and also because Hugh Dickins had plans to improve replace_page for ksm specific work.

Instruction analysis on x86 is based on instruction decoder and determines if an instruction can be probed and determines the necessary fixups after singlestep. Instruction analysis is done at probe insertion time so that we avoid having to repeat the same analysis every time a probe is hit.

A lot of code here is due to the improvement/suggestions/inputs from Peter Zijlstra.

---

Changelog: (Since v10): Add code to clear REX.B prefix as suggested by Denys Vlasenko and Masami Hiramatsu.

Changelog: (Since v9) : Use insn_offset_modrm as suggested by Masami Hiramatsu.

Changelog: (Since v7) : Handle comments from Peter Zijlstra
- Dont take reference to inode. (expect inode to register_uprobe to be sane).
- Use PTR_ERR to set the return value.
- No need to take reference to inode.
- use PTR_ERR to return error value.
- register and unregister_uprobe share code.

Changelog:(Since v5)
- Modified del_consumer as per comments from Peter.
- Drop reference to inode before dropping reference to uprobe.
- Use i_size_read(inode) instead of inode->i_size.
- Ensure uprobe->consumers is NULL, before __unregister_uprobe() is called.
- Includes errno.h as recommended by Stephen Rothwell to fix a build issue on sparc defconfig
- Remove restrictions while unregistering.
- Earlier code leaked inode references under some conditions while registering/unregistering.
- Continue the vma-rmap walk even if the intermediate vma doesnt meet the requirements.
- Validate the vma found by find_vma before inserting/removing the breakpoint
- Call del_consumer under mutex_lock.
- Use hash locks.
- Handle mremap.
- Introduce find_least_offset_node() instead of close match logic in find_uprobe
- Uprobes no more depends on MM_OWNER; No reference to task_structs while inserting/removing a probe.
- Uses read_mapping_page instead of grab_cache_page so that the pages have valid content.
- pass NULL to get_user_pages for the task parameter.
- call SetPageUptodate on the new page allocated in write_opcode.
- fix leaking a reference to the new page under certain conditions.
- Include Instruction Decoder if Uprobes gets defined.
- Remove const attributes for instruction prefix arrays.
- Uses mm_context to know if the application is 32 bit.

 arch/Kconfig                   |   11 
 arch/x86/Kconfig               |    5 
 arch/x86/include/asm/uprobes.h |   42 ++
 arch/x86/kernel/Makefile       |    1 
 arch/x86/kernel/uprobes.c      |  408 +++++++++++++++++
 include/linux/uprobes.h        |   98 ++++
 kernel/Makefile                |    1 
 kernel/uprobes.c               |  976 ++++++++++++++++++++++++++++++++++++++++
 mm/mmap.c                      |   23 +
 9 files changed, 1564 insertions(+), 1 deletions(-)
 create mode 100644 arch/x86/include/asm/uprobes.h
 create mode 100644 arch/x86/kernel/uprobes.c
 create mode 100644 include/linux/uprobes.h
 create mode 100644 kernel/uprobes.c
arch/Kconfig +11 -0
index 4f55c73..284f589 100644
@@ -65,6 +65,17 @@ config OPTPROBES
 	depends on KPROBES && HAVE_OPTPROBES
 	depends on !PREEMPT
 
+config UPROBES
+	bool "User-space probes (EXPERIMENTAL)"
+	depends on ARCH_SUPPORTS_UPROBES
+	default n
+	help
+	  Uprobes enables kernel subsystems to establish probepoints
+	  in user applications and execute handler functions when
+	  the probepoints are hit.
+
+	  If in doubt, say "N".
+
 config HAVE_EFFICIENT_UNALIGNED_ACCESS
 	bool
 	help
arch/x86/Kconfig +4 -1
index 5bed94e..481dbfc 100644
@@ -84,7 +84,7 @@ config X86
 	select GENERIC_IOMAP
 
 config INSTRUCTION_DECODER
-	def_bool (KPROBES || PERF_EVENTS)
+	def_bool (KPROBES || PERF_EVENTS || UPROBES)
 
 config OUTPUT_FORMAT
 	string
@@ -240,6 +240,9 @@ config ARCH_CPU_PROBE_RELEASE
 	def_bool y
 	depends on HOTPLUG_CPU
 
+config ARCH_SUPPORTS_UPROBES
+	def_bool y
+
 source "init/Kconfig"
 source "kernel/Kconfig.freezer"
 
arch/x86/include/asm/uprobes.h new file +42 -0

42 lines not on this page · raw message

arch/x86/kernel/Makefile +1 -0
index 5369059..8c8c365 100644
@@ -100,6 +100,7 @@ obj-$(CONFIG_X86_CHECK_BIOS_CORRUPTION) += check.o
 
 obj-$(CONFIG_SWIOTLB)			+= pci-swiotlb.o
 obj-$(CONFIG_OF)			+= devicetree.o
+obj-$(CONFIG_UPROBES)			+= uprobes.o
 
 ###
 # 64 bit specific files
arch/x86/kernel/uprobes.c new file +408 -0

408 lines not on this page · raw message

include/linux/uprobes.h new file +98 -0

98 lines not on this page · raw message

kernel/Makefile +1 -0
index 2d9de86..8609dd3 100644
@@ -107,6 +107,7 @@ obj-$(CONFIG_USER_RETURN_NOTIFIER) += user-return-notifier.o
 obj-$(CONFIG_PADATA) += padata.o
 obj-$(CONFIG_CRASH_DUMP) += crash_dump.o
 obj-$(CONFIG_JUMP_LABEL) += jump_label.o
+obj-$(CONFIG_UPROBES) += uprobes.o
 
 $(obj)/configs.o: $(obj)/config_data.h
 
kernel/uprobes.c new file +976 -0

976 lines not on this page · raw message

mm/mmap.c +23 -0
index 3f758c7..1aed183 100644
@@ -30,6 +30,7 @@
 #include <linux/perf_event.h>
 #include <linux/audit.h>
 #include <linux/khugepaged.h>
+#include <linux/uprobes.h>
 
 #include <asm/uaccess.h>
 #include <asm/cacheflush.h>
@@ -616,6 +617,13 @@ again:			remove_next = 1 + (end > next->vm_end);
 	if (mapping)
 		mutex_unlock(&mapping->i_mmap_mutex);
 
+	if (root) {
+		mmap_uprobe(vma);
+
+		if (adjust_next)
+			mmap_uprobe(next);
+	}
+
 	if (remove_next) {
 		if (file) {
 			fput(file);
@@ -637,6 +645,8 @@ again:			remove_next = 1 + (end > next->vm_end);
 			goto again;
 		}
 	}
+	if (insert && file)
+		mmap_uprobe(insert);
 
 	validate_mm(mm);
 
@@ -1329,6 +1339,11 @@ unsigned long mmap_region(struct file *file, unsigned long addr,
 			mm->locked_vm += (len >> PAGE_SHIFT);
 	} else if ((flags & MAP_POPULATE) && !(flags & MAP_NONBLOCK))
 		make_pages_present(addr, addr + len);
+
+	if (file && mmap_uprobe(vma))
+		/* matching probes but cannot insert */
+		goto unmap_and_free_vma;
+
 	return addr;
 
 unmap_and_free_vma:
@@ -2285,6 +2300,10 @@ int insert_vm_struct(struct mm_struct * mm, struct vm_area_struct * vma)
 	if ((vma->vm_flags & VM_ACCOUNT) &&
 	     security_vm_enough_memory_mm(mm, vma_pages(vma)))
 		return -ENOMEM;
+
+	if (vma->vm_file && mmap_uprobe(vma))
+		return -EINVAL;
+
 	vma_link(mm, vma, prev, rb_link, rb_parent);
 	return 0;
 }
@@ -2354,6 +2373,10 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
 			new_vma->vm_pgoff = pgoff;
 			if (new_vma->vm_file) {
 				get_file(new_vma->vm_file);
+
+				if (mmap_uprobe(new_vma))
+					goto out_free_mempol;
+
 				if (vma->vm_flags & VM_EXECUTABLE)
 					added_exe_file_vma(mm);
 			}

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#6 lore raw

Re: Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

In reply to Denys Vlasenko
Quoted 15 lines · Denys Vlasenko
Quoted 2 lines · Srikar Dronamraju

Changelog: (Since v10): Add code to clear REX.B prefix pointed out by Denys Vlasenko and fix suggested by Masami Hiramatsu.

...

arch/x86/kernel/uprobes.c line 310

Quoted 9 lines
arch/x86/kernel/uprobes.c new file +9 -0
+       /*
+        * Point cursor at the modrm byte.  The next 4 bytes are the
+        * displacement.  Beyond the displacement, for some instructions,
+        * is the immediate operand.
+        */
+       cursor = uprobe->insn + insn_offset_modrm(insn);
+       insn_get_length(insn);
+       if (insn->rex_prefix.nbytes)
+               *cursor &= 0xfe;        /* Clearing REX.B bit */
Quoted 3 lines

It looks like cursor points to mod/reg/rm byte, not rex byte. Comment above says it too. You seem to be clearing a bit in a wrong byte. I think it should be

Right, but...

Quoted 6 lines
        /* Clear REX.b bit (extension of MODRM.rm field):
         * we want to encode rax/rcx, not r8/r9.
         */
        if (insn->rex_prefix.nbytes)
                insn->rex_prefix.bytes[0] &= 0xfe;

No, that is a meaningless operation.
As I originally said,

Quoted 5 lines

insn_get_length(insn);

if (insn->rex_prefix.nbytes) {
	cursor = uprobe->insn + insn_offset_rex_prefix(insn);
	*cursor &= 0xfe;	/* Clearing REX.B bit */
}

You have to move the cursor itself, since the .rex_prefix is just a copied data...

Thanks,

Signature · 11 lines
Masami HIRAMATSU
Software Platform Research Dept. Linux Technology Center
Hitachi, Ltd., Yokohama Research Laboratory
E-mail: [email protected]

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#7 lore raw

Re: Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

Quoted 10 lines

No, that is a meaningless operation.
As I originally said,

Quoted 5 lines

insn_get_length(insn);

if (insn->rex_prefix.nbytes) {
	cursor = uprobe->insn + insn_offset_rex_prefix(insn);
	*cursor &= 0xfe;	/* Clearing REX.B bit */
}

I am confused by why we need to call insn_get_length(insn) before checking insn->rex_prefix.nbytes? Is it needed.

Denys and Masami, can you please confirm if below is fine.

#ifdef CONFIG_X86_64
/*
* If uprobe->insn doesn't use rip-relative addressing, return
* immediately. Otherwise, rewrite the instruction so that it accesses
* its memory operand indirectly through a scratch register. Set
* uprobe->arch_info.fixups and uprobe->arch_info.rip_rela_target_address
* accordingly. (The contents of the scratch register will be saved
* before we single-step the modified instruction, and restored
* afterward.)
*
* We do this because a rip-relative instruction can access only a
* relatively small area (+/- 2 GB from the instruction), and the XOL
* area typically lies beyond that area. At least for instructions
* that store to memory, we can't execute the original instruction
* and "fix things up" later, because the misdirected store could be
* disastrous.
*
* Some useful facts about rip-relative instructions:
* - There's always a modrm byte.
* - There's never a SIB byte.
* - The displacement is always 4 bytes.
*/
static void handle_riprel_insn(struct mm_struct *mm, struct uprobe *uprobe,
struct insn *insn)

{
	u8 *cursor;
	u8 reg;

	if (mm->context.ia32_compat)
		return;

	uprobe->arch_info.rip_rela_target_address = 0x0;
	if (!insn_rip_relative(insn))
		return;

	/* Clear REX.b bit (extension of MODRM.rm field):
	 * we want to encode rax/rcx, not r8/r9.
	 */
	if (insn->rex_prefix.nbytes) {
		cursor = uprobe->insn + insn_offset_rex_prefix(insn);
		*cursor &= 0xfe;
	}

	/*
	 * Point cursor at the modrm byte.  The next 4 bytes are the
	 * displacement.  Beyond the displacement, for some instructions,
	 * is the immediate operand.
	 */
	cursor = uprobe->insn + insn_offset_modrm(insn);
	insn_get_length(insn);

	/*
	 * Convert from rip-relative addressing to indirect addressing
	 * via a scratch register.  Change the r/m field from 0x5 (%rip)
	 * to 0x0 (%rax) or 0x1 (%rcx), and squeeze out the offset field.
	 */
	reg = MODRM_REG(insn);
	if (reg == 0) {
		/*
		 * The register operand (if any) is either the A register
		 * (%rax, %eax, etc.) or (if the 0x4 bit is set in the
		 * REX prefix) %r8.  In any case, we know the C register
		 * is NOT the register operand, so we use %rcx (register
		 * #1) for the scratch register.
		 */
		uprobe->arch_info.fixups = UPROBES_FIX_RIP_CX;
		/* Change modrm from 00 000 101 to 00 000 001. */
		*cursor = 0x1;
	} else {
		/* Use %rax (register #0) for the scratch register. */
		uprobe->arch_info.fixups = UPROBES_FIX_RIP_AX;
		/* Change modrm from 00 xxx 101 to 00 xxx 000 */
		*cursor = (reg << 3);
	}

	/* Target address = address of next instruction + (signed) offset */
	uprobe->arch_info.rip_rela_target_address = (long)insn->length
					+ insn->displacement.value;
	/* Displacement field is gone; slide immediate field (if any) over. */
	if (insn->immediate.nbytes) {
		cursor++;
		memmove(cursor, cursor + insn->displacement.nbytes,
						insn->immediate.nbytes);
	}
	return;
}

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#8 lore raw

Re: Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

Quoted 3 lines · Srikar Dronamraju
	/* Clear REX.b bit (extension of MODRM.rm field):
	 * we want to encode rax/rcx, not r8/r9.
	 */

Small stylistic nit, just saw this chunk fly by - the proper comment style is like this one:

Quoted 5 lines

/*
* Point cursor at the modrm byte. The next 4 bytes are the
* displacement. Beyond the displacement, for some instructions,
* is the immediate operand.
*/

Thanks,

Ingo

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#10 lore raw

Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

In reply to Srikar Dronamraju
Quoted 11 lines · Srikar Dronamraju
Quoted 10 lines

No, that is a meaningless operation.
As I originally said,

Quoted 5 lines

insn_get_length(insn);

if (insn->rex_prefix.nbytes) {
	cursor = uprobe->insn + insn_offset_rex_prefix(insn);
	*cursor &= 0xfe;	/* Clearing REX.B bit */
}
Quoted 2 lines

I am confused by why we need to call insn_get_length(insn) before checking insn->rex_prefix.nbytes? Is it needed.

Ah, certainly, no, if the insn is already decoded.

Quoted 29 lines

Denys and Masami, can you please confirm if below is fine.

#ifdef CONFIG_X86_64
/*
* If uprobe->insn doesn't use rip-relative addressing, return
* immediately. Otherwise, rewrite the instruction so that it accesses
* its memory operand indirectly through a scratch register. Set
* uprobe->arch_info.fixups and uprobe->arch_info.rip_rela_target_address
* accordingly. (The contents of the scratch register will be saved
* before we single-step the modified instruction, and restored
* afterward.)
*
* We do this because a rip-relative instruction can access only a
* relatively small area (+/- 2 GB from the instruction), and the XOL
* area typically lies beyond that area. At least for instructions
* that store to memory, we can't execute the original instruction
* and "fix things up" later, because the misdirected store could be
* disastrous.
*
* Some useful facts about rip-relative instructions:
* - There's always a modrm byte.
* - There's never a SIB byte.
* - The displacement is always 4 bytes.
*/
static void handle_riprel_insn(struct mm_struct *mm, struct uprobe *uprobe,
struct insn *insn)
{

Quoted 9 lines
	u8 *cursor;
	u8 reg;

	if (mm->context.ia32_compat)
		return;

	uprobe->arch_info.rip_rela_target_address = 0x0;
	if (!insn_rip_relative(insn))
		return;

Here, I think it is better to add a comment that
insn_rip_relative() decodes until modrm. :)

Quoted 44 lines
	/* Clear REX.b bit (extension of MODRM.rm field):
	 * we want to encode rax/rcx, not r8/r9.
	 */
	if (insn->rex_prefix.nbytes) {
		cursor = uprobe->insn + insn_offset_rex_prefix(insn);
		*cursor &= 0xfe;
	}

	/*
	 * Point cursor at the modrm byte.  The next 4 bytes are the
	 * displacement.  Beyond the displacement, for some instructions,
	 * is the immediate operand.
	 */
	cursor = uprobe->insn + insn_offset_modrm(insn);
	insn_get_length(insn);

	/*
	 * Convert from rip-relative addressing to indirect addressing
	 * via a scratch register.  Change the r/m field from 0x5 (%rip)
	 * to 0x0 (%rax) or 0x1 (%rcx), and squeeze out the offset field.
	 */
	reg = MODRM_REG(insn);
	if (reg == 0) {
		/*
		 * The register operand (if any) is either the A register
		 * (%rax, %eax, etc.) or (if the 0x4 bit is set in the
		 * REX prefix) %r8.  In any case, we know the C register
		 * is NOT the register operand, so we use %rcx (register
		 * #1) for the scratch register.
		 */
		uprobe->arch_info.fixups = UPROBES_FIX_RIP_CX;
		/* Change modrm from 00 000 101 to 00 000 001. */
		*cursor = 0x1;
	} else {
		/* Use %rax (register #0) for the scratch register. */
		uprobe->arch_info.fixups = UPROBES_FIX_RIP_AX;
		/* Change modrm from 00 xxx 101 to 00 xxx 000 */
		*cursor = (reg << 3);
	}

	/* Target address = address of next instruction + (signed) offset */
	uprobe->arch_info.rip_rela_target_address = (long)insn->length
					+ insn->displacement.value;
Quoted 8 lines
	/* Displacement field is gone; slide immediate field (if any) over. */
	if (insn->immediate.nbytes) {
		cursor++;
		memmove(cursor, cursor + insn->displacement.nbytes,
						insn->immediate.nbytes);
	}
	return;
}

Confirmed, this looks good to me ;)

Thanks!

Signature · 11 lines
Masami HIRAMATSU
Software Platform Research Dept. Linux Technology Center
Hitachi, Ltd., Yokohama Research Laboratory
E-mail: [email protected]

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#9 lore raw

Re: Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

In reply to Ingo Molnar
Quoted 9 lines · Ingo Molnar
Quoted 3 lines · Srikar Dronamraju
	/* Clear REX.b bit (extension of MODRM.rm field):
	 * we want to encode rax/rcx, not r8/r9.
	 */

Small stylistic nit, just saw this chunk fly by - the proper comment style is like this one:

Okay, Will correct that in the patch that I send.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#11 lore raw

Re: [PATCH v10 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

In reply to Masami Hiramatsu
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

I am confused by why we need to call insn_get_length(insn) before checking insn->rex_prefix.nbytes? Is it needed.

Ah, certainly, no, if the insn is already decoded.

Okay,

Quoted 7 lines
Quoted 4 lines
	uprobe->arch_info.rip_rela_target_address = 0x0;
	if (!insn_rip_relative(insn))
		return;

Here, I think it is better to add a comment that
insn_rip_relative() decodes until modrm. :)

Will do.

Quoted 7 lines
Quoted 3 lines
	return;
}

Confirmed, this looks good to me ;)

Thanks!

Okay, Thanks for confirming,

Do you have a handy instruction whose REX.B is set that I could use to test.

Signature · 9 lines
Thanks and Regards
Srikar

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#13 lore raw

Re: [PATCH v10 take 3 3.3-rc2 1/9] uprobes: Install and remove breakpoints.

In reply to Srikar Dronamraju

Added code to clear REX.B as suggested by Denys Vlasenko and Masami Hiramatsu.

From: Srikar Dronamraju <[email protected]>

Uprobes are maintained in an rb-tree indexed by inode and offset (the offset here is from the start of the mapping). For a unique (inode, offset) tuple, there can be atmost one uprobe in the rb-tree.

Since the (inode, offset) tuple identifies a unique uprobe, more than one user may be interested in the same uprobe. Provides the ability to hook multiple 'consumers' for the same uprobe.

Each consumer defines a handler and a filter (optional). The 'handler' is run every time the uprobe is hit, if it matches the 'filter' criteria.

The first consumer of a uprobe causes the breakpoint to be inserted at the specified address and subsequent consumers are appended to this list. On subsequent probes, the consumer gets appended to the existing list of consumers. The breakpoint is removed when the last consumer unregisters. For all other unregisterations, the consumer is removed from the list of consumers.

Given a inode, we get a list of the mms that have mapped the inode. Do the actual registration if mm maps the page where a probe needs to be inserted/removed.

We use a temporary list to walk thro the vmas that map the inode.
- The number of maps that map the inode, is not known before we walk the rmap and keeps changing.
- extending vm_area_struct wasnt recommended.
- There can be more than one maps of the inode in the same mm.

Hook mmap to keep an eye on text vmas that are of interest to uprobes. When a vma of interest is mapped, insert the breakpoint at the right address.

Uprobe works by replacing the instruction at the address defined by (inode, offset) with the arch specific breakpoint instruction. Save a copy of the original instruction at the uprobed address.

This is needed for:
a. executing the instruction out-of-line (xol).
b. instruction analysis for any subsequent fixups.
c. restoring the instruction back when the uprobe is unregistered.

We insert or delete a breakpoint instruction, and this breakpoint instruction is assumed to be the smallest instruction available on the platform. For fixed size instruction platforms this is trivially true, for variable size instruction platforms the breakpoint instruction is typically the smallest (often a single byte).

Writing the instruction is done by COWing the page and changing the instruction during the copy, this even though most platforms allow atomic writes of the breakpoint instruction. This also mirrors the behaviour of a ptrace() memory write to a PRIVATE file map.

The core worker is derived from ksm's replace_page() logic.

In essence, similar to ksm:
a. allocate a new page and copy over contents of the page that has the
uprobed vaddr
b. modify the copy and insert the breakpoint at the required address c. switch the original page with the copy containing the breakpoint d. flush page tables.

replace_page is being replicated here because of some minor changes in the type of pages and also because Hugh Dickins had plans to improve replace_page for ksm specific work.

Instruction analysis on x86 is based on instruction decoder and determines if an instruction can be probed and determines the necessary fixups after singlestep. Instruction analysis is done at probe insertion time so that we avoid having to repeat the same analysis every time a probe is hit.

A lot of code here is due to the improvement/suggestions/inputs from Peter Zijlstra.

---

Changelog: (Since v10): Add code to clear REX.B prefix as suggested by Denys Vlasenko and Masami Hiramatsu.

Changelog: (Since v9) : Use insn_offset_modrm as suggested by Masami Hiramatsu.

Changelog: (Since v7) : Handle comments from Peter Zijlstra
- Dont take reference to inode. (expect inode to register_uprobe to be sane).
- Use PTR_ERR to set the return value.
- No need to take reference to inode.
- use PTR_ERR to return error value.
- register and unregister_uprobe share code.

Changelog:(Since v5)
- Modified del_consumer as per comments from Peter.
- Drop reference to inode before dropping reference to uprobe.
- Use i_size_read(inode) instead of inode->i_size.
- Ensure uprobe->consumers is NULL, before __unregister_uprobe() is called.
- Includes errno.h as recommended by Stephen Rothwell to fix a build issue on sparc defconfig
- Remove restrictions while unregistering.
- Earlier code leaked inode references under some conditions while registering/unregistering.
- Continue the vma-rmap walk even if the intermediate vma doesnt meet the requirements.
- Validate the vma found by find_vma before inserting/removing the breakpoint
- Call del_consumer under mutex_lock.
- Use hash locks.
- Handle mremap.
- Introduce find_least_offset_node() instead of close match logic in find_uprobe
- Uprobes no more depends on MM_OWNER; No reference to task_structs while inserting/removing a probe.
- Uses read_mapping_page instead of grab_cache_page so that the pages have valid content.
- pass NULL to get_user_pages for the task parameter.
- call SetPageUptodate on the new page allocated in write_opcode.
- fix leaking a reference to the new page under certain conditions.
- Include Instruction Decoder if Uprobes gets defined.
- Remove const attributes for instruction prefix arrays.
- Uses mm_context to know if the application is 32 bit.

 arch/Kconfig                   |   11 
 arch/x86/Kconfig               |    5 
 arch/x86/include/asm/uprobes.h |   42 ++
 arch/x86/kernel/Makefile       |    1 
 arch/x86/kernel/uprobes.c      |  412 +++++++++++++++++
 include/linux/uprobes.h        |   98 ++++
 kernel/Makefile                |    1 
 kernel/uprobes.c               |  976 ++++++++++++++++++++++++++++++++++++++++
 mm/mmap.c                      |   23 +
 9 files changed, 1568 insertions(+), 1 deletions(-)
 create mode 100644 arch/x86/include/asm/uprobes.h
 create mode 100644 arch/x86/kernel/uprobes.c
 create mode 100644 include/linux/uprobes.h
 create mode 100644 kernel/uprobes.c
arch/Kconfig +11 -0
index 4f55c73..284f589 100644
@@ -65,6 +65,17 @@ config OPTPROBES
 	depends on KPROBES && HAVE_OPTPROBES
 	depends on !PREEMPT
 
+config UPROBES
+	bool "User-space probes (EXPERIMENTAL)"
+	depends on ARCH_SUPPORTS_UPROBES
+	default n
+	help
+	  Uprobes enables kernel subsystems to establish probepoints
+	  in user applications and execute handler functions when
+	  the probepoints are hit.
+
+	  If in doubt, say "N".
+
 config HAVE_EFFICIENT_UNALIGNED_ACCESS
 	bool
 	help
arch/x86/Kconfig +4 -1
index 5bed94e..481dbfc 100644
@@ -84,7 +84,7 @@ config X86
 	select GENERIC_IOMAP
 
 config INSTRUCTION_DECODER
-	def_bool (KPROBES || PERF_EVENTS)
+	def_bool (KPROBES || PERF_EVENTS || UPROBES)
 
 config OUTPUT_FORMAT
 	string
@@ -240,6 +240,9 @@ config ARCH_CPU_PROBE_RELEASE
 	def_bool y
 	depends on HOTPLUG_CPU
 
+config ARCH_SUPPORTS_UPROBES
+	def_bool y
+
 source "init/Kconfig"
 source "kernel/Kconfig.freezer"
 
arch/x86/include/asm/uprobes.h new file +42 -0

42 lines not on this page · raw message

arch/x86/kernel/Makefile +1 -0
index 5369059..8c8c365 100644
@@ -100,6 +100,7 @@ obj-$(CONFIG_X86_CHECK_BIOS_CORRUPTION) += check.o
 
 obj-$(CONFIG_SWIOTLB)			+= pci-swiotlb.o
 obj-$(CONFIG_OF)			+= devicetree.o
+obj-$(CONFIG_UPROBES)			+= uprobes.o
 
 ###
 # 64 bit specific files
arch/x86/kernel/uprobes.c new file +412 -0

412 lines not on this page · raw message

include/linux/uprobes.h new file +98 -0

98 lines not on this page · raw message

kernel/Makefile +1 -0
index 2d9de86..8609dd3 100644
@@ -107,6 +107,7 @@ obj-$(CONFIG_USER_RETURN_NOTIFIER) += user-return-notifier.o
 obj-$(CONFIG_PADATA) += padata.o
 obj-$(CONFIG_CRASH_DUMP) += crash_dump.o
 obj-$(CONFIG_JUMP_LABEL) += jump_label.o
+obj-$(CONFIG_UPROBES) += uprobes.o
 
 $(obj)/configs.o: $(obj)/config_data.h
 
kernel/uprobes.c new file +976 -0

976 lines not on this page · raw message

mm/mmap.c +23 -0
index 3f758c7..1aed183 100644
@@ -30,6 +30,7 @@
 #include <linux/perf_event.h>
 #include <linux/audit.h>
 #include <linux/khugepaged.h>
+#include <linux/uprobes.h>
 
 #include <asm/uaccess.h>
 #include <asm/cacheflush.h>
@@ -616,6 +617,13 @@ again:			remove_next = 1 + (end > next->vm_end);
 	if (mapping)
 		mutex_unlock(&mapping->i_mmap_mutex);
 
+	if (root) {
+		mmap_uprobe(vma);
+
+		if (adjust_next)
+			mmap_uprobe(next);
+	}
+
 	if (remove_next) {
 		if (file) {
 			fput(file);
@@ -637,6 +645,8 @@ again:			remove_next = 1 + (end > next->vm_end);
 			goto again;
 		}
 	}
+	if (insert && file)
+		mmap_uprobe(insert);
 
 	validate_mm(mm);
 
@@ -1329,6 +1339,11 @@ unsigned long mmap_region(struct file *file, unsigned long addr,
 			mm->locked_vm += (len >> PAGE_SHIFT);
 	} else if ((flags & MAP_POPULATE) && !(flags & MAP_NONBLOCK))
 		make_pages_present(addr, addr + len);
+
+	if (file && mmap_uprobe(vma))
+		/* matching probes but cannot insert */
+		goto unmap_and_free_vma;
+
 	return addr;
 
 unmap_and_free_vma:
@@ -2285,6 +2300,10 @@ int insert_vm_struct(struct mm_struct * mm, struct vm_area_struct * vma)
 	if ((vma->vm_flags & VM_ACCOUNT) &&
 	     security_vm_enough_memory_mm(mm, vma_pages(vma)))
 		return -ENOMEM;
+
+	if (vma->vm_file && mmap_uprobe(vma))
+		return -EINVAL;
+
 	vma_link(mm, vma, prev, rb_link, rb_parent);
 	return 0;
 }
@@ -2354,6 +2373,10 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
 			new_vma->vm_pgoff = pgoff;
 			if (new_vma->vm_file) {
 				get_file(new_vma->vm_file);
+
+				if (mmap_uprobe(new_vma))
+					goto out_free_mempol;
+
 				if (vma->vm_flags & VM_EXECUTABLE)
 					added_exe_file_vma(mm);
 			}

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#14 lore raw

[tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

Commit-ID:  2b144498350860b6ee9dc57ff27a93ad488de5dc
Gitweb:     http://git.kernel.org/tip/2b144498350860b6ee9dc57ff27a93ad488de5dc
Author:     Srikar Dronamraju <[email protected]>
AuthorDate: Thu, 9 Feb 2012 14:56:42 +0530
Committer:  Ingo Molnar <[email protected]>
CommitDate: Fri, 17 Feb 2012 10:00:01 +0100

uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

Add uprobes support to the core kernel, with x86 support.

This commit adds the kernel facilities, the actual uprobes user-space ABI and perf probe support comes in later commits.

General design:

Uprobes are maintained in an rb-tree indexed by inode and offset (the offset here is from the start of the mapping). For a unique (inode, offset) tuple, there can be at most one uprobe in the rb-tree.

Since the (inode, offset) tuple identifies a unique uprobe, more than one user may be interested in the same uprobe. This provides the ability to connect multiple 'consumers' to the same uprobe.

Each consumer defines a handler and a filter (optional). The 'handler' is run every time the uprobe is hit, if it matches the 'filter' criteria.

The first consumer of a uprobe causes the breakpoint to be inserted at the specified address and subsequent consumers are appended to this list. On subsequent probes, the consumer gets appended to the existing list of consumers. The breakpoint is removed when the last consumer unregisters. For all other unregisterations, the consumer is removed from the list of consumers.

Given a inode, we get a list of the mms that have mapped the inode. Do the actual registration if mm maps the page where a probe needs to be inserted/removed.

We use a temporary list to walk through the vmas that map the inode.

- The number of maps that map the inode, is not known before we walk the rmap and keeps changing.
- extending vm_area_struct wasn't recommended, it's a size-critical data structure.
- There can be more than one maps of the inode in the same mm.

We add callbacks to the mmap methods to keep an eye on text vmas that are of interest to uprobes. When a vma of interest is mapped, we insert the breakpoint at the right address.

Uprobe works by replacing the instruction at the address defined by (inode, offset) with the arch specific breakpoint instruction. We save a copy of the original instruction at the uprobed address.

This is needed for:

a. executing the instruction out-of-line (xol).
b. instruction analysis for any subsequent fixups.
c. restoring the instruction back when the uprobe is unregistered.

We insert or delete a breakpoint instruction, and this breakpoint instruction is assumed to be the smallest instruction available on the platform. For fixed size instruction platforms this is trivially true, for variable size instruction platforms the breakpoint instruction is typically the smallest (often a single byte).

Writing the instruction is done by COWing the page and changing the instruction during the copy, this even though most platforms allow atomic writes of the breakpoint instruction. This also mirrors the behaviour of a ptrace() memory write to a PRIVATE file map.

The core worker is derived from KSM's replace_page() logic.

In essence, similar to KSM:

a. allocate a new page and copy over contents of the page that
has the uprobed vaddr
b. modify the copy and insert the breakpoint at the required
address
c. switch the original page with the copy containing the
breakpoint
d. flush page tables.

replace_page() is being replicated here because of some minor changes in the type of pages and also because Hugh Dickins had plans to improve replace_page() for KSM specific work.

Instruction analysis on x86 is based on instruction decoder and determines if an instruction can be probed and determines the necessary fixups after singlestep. Instruction analysis is done at probe insertion time so that we avoid having to repeat the same analysis every time a probe is hit.

A lot of code here is due to the improvement/suggestions/inputs from Peter Zijlstra.

Changelog:

(v10):
- Add code to clear REX.B prefix as suggested by Denys Vlasenko and Masami Hiramatsu.

(v9):
- Use insn_offset_modrm as suggested by Masami Hiramatsu.

(v7):

Handle comments from Peter Zijlstra:

- Dont take reference to inode. (expect inode to uprobe_register to be sane).
- Use PTR_ERR to set the return value.
- No need to take reference to inode.
- use PTR_ERR to return error value.
- register and uprobe_unregister share code.

(v5):

- Modified del_consumer as per comments from Peter.
- Drop reference to inode before dropping reference to uprobe.
- Use i_size_read(inode) instead of inode->i_size.
- Ensure uprobe->consumers is NULL, before __uprobe_unregister() is called.
- Includes errno.h as recommended by Stephen Rothwell to fix a build issue on sparc defconfig
- Remove restrictions while unregistering.
- Earlier code leaked inode references under some conditions while registering/unregistering.
- Continue the vma-rmap walk even if the intermediate vma doesnt meet the requirements.
- Validate the vma found by find_vma before inserting/removing the breakpoint
- Call del_consumer under mutex_lock.
- Use hash locks.
- Handle mremap.
- Introduce find_least_offset_node() instead of close match logic in find_uprobe
- Uprobes no more depends on MM_OWNER; No reference to task_structs while inserting/removing a probe.
- Uses read_mapping_page instead of grab_cache_page so that the pages have valid content.
- pass NULL to get_user_pages for the task parameter.
- call SetPageUptodate on the new page allocated in write_opcode.
- fix leaking a reference to the new page under certain conditions.
- Include Instruction Decoder if Uprobes gets defined.
- Remove const attributes for instruction prefix arrays.
- Uses mm_context to know if the application is 32 bit.

Cc Oleg Nesterov <[email protected]>
Cc Andi Kleen <[email protected]>
Cc Christoph Hellwig <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Roland McGrath <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Anton Arapov <[email protected]>
Cc Ananth N Mavinakayanahalli <[email protected]>
Cc Stephen Rothwell <[email protected]>
Cc Denys Vlasenko <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Andrew Morton <[email protected]>
Cc Linux-mm <[email protected]>
[ Made various small edits to the commit log ]
---
 arch/Kconfig                                     |   11 +
 arch/x86/Kconfig                                 |    5 +-
 arch/x86/include/asm/{inat_types.h => uprobes.h} |   31 +-
 arch/x86/kernel/Makefile                         |    1 +
 arch/x86/kernel/uprobes.c                        |  412 +++++++++
 include/linux/uprobes.h                          |   98 +++
 kernel/Makefile                                  |    1 +
 kernel/uprobes.c                                 |  976 ++++++++++++++++++++++
 mm/mmap.c                                        |   23 +
 9 files changed, 1548 insertions(+), 10 deletions(-)
arch/Kconfig +11 -0
index 4f55c73..284f589 100644
@@ -65,6 +65,17 @@ config OPTPROBES
 	depends on KPROBES && HAVE_OPTPROBES
 	depends on !PREEMPT
 
+config UPROBES
+	bool "User-space probes (EXPERIMENTAL)"
+	depends on ARCH_SUPPORTS_UPROBES
+	default n
+	help
+	  Uprobes enables kernel subsystems to establish probepoints
+	  in user applications and execute handler functions when
+	  the probepoints are hit.
+
+	  If in doubt, say "N".
+
 config HAVE_EFFICIENT_UNALIGNED_ACCESS
 	bool
 	help
arch/x86/Kconfig +4 -1
index 5bed94e..481dbfc 100644
@@ -84,7 +84,7 @@ config X86
 	select GENERIC_IOMAP
 
 config INSTRUCTION_DECODER
-	def_bool (KPROBES || PERF_EVENTS)
+	def_bool (KPROBES || PERF_EVENTS || UPROBES)
 
 config OUTPUT_FORMAT
 	string
@@ -240,6 +240,9 @@ config ARCH_CPU_PROBE_RELEASE
 	def_bool y
 	depends on HOTPLUG_CPU
 
+config ARCH_SUPPORTS_UPROBES
+	def_bool y
+
 source "init/Kconfig"
 source "kernel/Kconfig.freezer"
 
arch/x86/include/asm/uprobes.h renamed from arch/x86/include/asm/inat_types.h +22 -9
similarity index 55%
copy from arch/x86/include/asm/inat_types.h
copy to arch/x86/include/asm/uprobes.h
index cb3c20c..8208234 100644
@@ -1,9 +1,7 @@
-#ifndef _ASM_X86_INAT_TYPES_H
-#define _ASM_X86_INAT_TYPES_H
+#ifndef _ASM_UPROBES_H
+#define _ASM_UPROBES_H
 /*
- * x86 instruction attributes
- *
- * Written by Masami Hiramatsu <[email protected]>
+ * Userspace Probes (UProbes) for x86
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -19,11 +17,26 @@
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  *
+ * Copyright (C) IBM Corporation, 2008-2011
+ * Authors:
+ *	Srikar Dronamraju
+ *	Jim Keniston
  */
 
-/* Instruction attributes */
-typedef unsigned int insn_attr_t;
-typedef unsigned char insn_byte_t;
-typedef signed int insn_value_t;
+typedef u8 uprobe_opcode_t;
+#define MAX_UINSN_BYTES 16
+#define UPROBES_XOL_SLOT_BYTES	128	/* to keep it cache aligned */
+
+#define UPROBES_BKPT_INSN 0xcc
+#define UPROBES_BKPT_INSN_SIZE 1
 
+struct uprobe_arch_info {
+	u16			fixups;
+#ifdef CONFIG_X86_64
+	unsigned long rip_rela_target_address;
 #endif
+};
+
+struct uprobe;
+extern int analyze_insn(struct mm_struct *mm, struct uprobe *uprobe);
+#endif	/* _ASM_UPROBES_H */
arch/x86/kernel/Makefile +1 -0
index 5369059..8c8c365 100644
@@ -100,6 +100,7 @@ obj-$(CONFIG_X86_CHECK_BIOS_CORRUPTION) += check.o
 
 obj-$(CONFIG_SWIOTLB)			+= pci-swiotlb.o
 obj-$(CONFIG_OF)			+= devicetree.o
+obj-$(CONFIG_UPROBES)			+= uprobes.o
 
 ###
 # 64 bit specific files
arch/x86/kernel/uprobes.c new file +412 -0

412 lines not on this page · raw message

include/linux/uprobes.h new file +98 -0

98 lines not on this page · raw message

kernel/Makefile +1 -0
index 2d9de86..8609dd3 100644
@@ -107,6 +107,7 @@ obj-$(CONFIG_USER_RETURN_NOTIFIER) += user-return-notifier.o
 obj-$(CONFIG_PADATA) += padata.o
 obj-$(CONFIG_CRASH_DUMP) += crash_dump.o
 obj-$(CONFIG_JUMP_LABEL) += jump_label.o
+obj-$(CONFIG_UPROBES) += uprobes.o
 
 $(obj)/configs.o: $(obj)/config_data.h
 
kernel/uprobes.c new file +976 -0

976 lines not on this page · raw message

mm/mmap.c +23 -0
index 3f758c7..1aed183 100644
@@ -30,6 +30,7 @@
 #include <linux/perf_event.h>
 #include <linux/audit.h>
 #include <linux/khugepaged.h>
+#include <linux/uprobes.h>
 
 #include <asm/uaccess.h>
 #include <asm/cacheflush.h>
@@ -616,6 +617,13 @@ again:			remove_next = 1 + (end > next->vm_end);
 	if (mapping)
 		mutex_unlock(&mapping->i_mmap_mutex);
 
+	if (root) {
+		mmap_uprobe(vma);
+
+		if (adjust_next)
+			mmap_uprobe(next);
+	}
+
 	if (remove_next) {
 		if (file) {
 			fput(file);
@@ -637,6 +645,8 @@ again:			remove_next = 1 + (end > next->vm_end);
 			goto again;
 		}
 	}
+	if (insert && file)
+		mmap_uprobe(insert);
 
 	validate_mm(mm);
 
@@ -1329,6 +1339,11 @@ out:
 			mm->locked_vm += (len >> PAGE_SHIFT);
 	} else if ((flags & MAP_POPULATE) && !(flags & MAP_NONBLOCK))
 		make_pages_present(addr, addr + len);
+
+	if (file && mmap_uprobe(vma))
+		/* matching probes but cannot insert */
+		goto unmap_and_free_vma;
+
 	return addr;
 
 unmap_and_free_vma:
@@ -2285,6 +2300,10 @@ int insert_vm_struct(struct mm_struct * mm, struct vm_area_struct * vma)
 	if ((vma->vm_flags & VM_ACCOUNT) &&
 	     security_vm_enough_memory_mm(mm, vma_pages(vma)))
 		return -ENOMEM;
+
+	if (vma->vm_file && mmap_uprobe(vma))
+		return -EINVAL;
+
 	vma_link(mm, vma, prev, rb_link, rb_parent);
 	return 0;
 }
@@ -2354,6 +2373,10 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
 			new_vma->vm_pgoff = pgoff;
 			if (new_vma->vm_file) {
 				get_file(new_vma->vm_file);
+
+				if (mmap_uprobe(new_vma))
+					goto out_free_mempol;
+
 				if (vma->vm_flags & VM_EXECUTABLE)
 					added_exe_file_vma(mm);
 			}

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

maintainer
#15 lore raw

Re: [tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

Quoted 8 lines · On Fri, 17 Feb 2012 01:58:36 -0800 tip-bot for Srikar Dronamraju…
Commit-ID:  2b144498350860b6ee9dc57ff27a93ad488de5dc
Gitweb:     http://git.kernel.org/tip/2b144498350860b6ee9dc57ff27a93ad488de5dc
Author:     Srikar Dronamraju <[email protected]>
AuthorDate: Thu, 9 Feb 2012 14:56:42 +0530
Committer:  Ingo Molnar <[email protected]>
CommitDate: Fri, 17 Feb 2012 10:00:01 +0100

uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

hm, we seem to have conflicting commits between mainline and linux-next. During the merge window. Again. Nobody knows why this happens.

static void unmap_single_vma(struct mmu_gather *tlb,
struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr,
struct zap_details *details)

{
	unsigned long start = max(vma->vm_start, start_addr);
	unsigned long end;

	if (start >= vma->vm_end)
		return;
	end = min(vma->vm_end, end_addr);
	if (end <= vma->vm_start)
		return;

<<<<<<< HEAD
=======

	if (vma->vm_file)
		uprobe_munmap(vma, start, end);

	if (vma->vm_flags & VM_ACCOUNT)
		*nr_accounted += (end - start) >> PAGE_SHIFT;
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

linux-next/akpm-base

	if (unlikely(is_pfn_mapping(vma)))
		untrack_pfn_vma(vma, 0, 0);

It made me look at uprobes. Noticed a few things...

Quoted 7 lines

Add uprobes support to the core kernel, with x86 support.

...

kernel/uprobes.c new file +3 -0
+static struct rb_root uprobes_tree = RB_ROOT;
+static DEFINE_SPINLOCK(uprobes_treelock);	/* serialize rbtree access */
+

kernel/uprobes.c line 46

Quoted 10 lines
kernel/uprobes.c new file +10 -0
+#define UPROBES_HASH_SZ	13
+/* serialize (un)register */
+static struct mutex uprobes_mutex[UPROBES_HASH_SZ];
+#define uprobes_hash(v)	(&uprobes_mutex[((unsigned long)(v)) %\
+						UPROBES_HASH_SZ])
+
+/* serialize uprobe->pending_list */
+static struct mutex uprobes_mmap_mutex[UPROBES_HASH_SZ];
+#define uprobes_mmap_hash(v)	(&uprobes_mmap_mutex[((unsigned long)(v)) %\
+						UPROBES_HASH_SZ])

Presumably these locks were hashed for scalability reasons?

If so, this won't be terribly effective when we have multiple mutexes occupying a single cacheline - the array entries should be padded out. Of course, that's all a complete waste of space on uniprocessor machines, but nobody seems to think of that any more ;(

There was no need to code the accessor functions as macros. It is, as always, better to use a nice C function which takes an argument which is as strictly typed as possible. ie, it *could* take a void*, but it would be better if it required an inode*.

If that makes no difference in performance testing then probably we didn't need to hash it at all and we can go to a single lock and be nice to uniprocessor.

Quoted 9 lines

...

kernel/uprobes.c new file +6 -0
+static int read_opcode(struct mm_struct *mm, unsigned long vaddr,
+						uprobe_opcode_t *opcode)
+{
+	struct page *page;
+	void *vaddr_new;
+	int ret;

kernel/uprobes.c line 294

Quoted 10 lines
kernel/uprobes.c new file +10 -0
+
+	ret = get_user_pages(NULL, mm, vaddr, 1, 0, 0, &page, NULL);
+	if (ret <= 0)
+		return ret;
+
+	lock_page(page);
+	vaddr_new = kmap_atomic(page);
+	vaddr &= ~PAGE_MASK;
+	memcpy(opcode, vaddr_new + vaddr, uprobe_opcode_sz);
+	kunmap_atomic(vaddr_new);

This is modifying user memory? flush_dcache_page() needed? Or perhaps we will need different primitives to diddle the instruction memory on architectures which care.

Quoted 29 lines
kernel/uprobes.c new file +26 -0
+	unlock_page(page);
+	put_page(page);		/* we did a get_user_pages in the beginning */
+	return 0;
+}
+
 
...
 
+int mmap_uprobe(struct vm_area_struct *vma)
+{
+	struct list_head tmp_list;
+	struct uprobe *uprobe, *u;
+	struct inode *inode;
+	int ret = 0;
+
+	if (!atomic_read(&uprobe_events) || !valid_vma(vma, true))
+		return ret;	/* Bail-out */
+
+	inode = vma->vm_file->f_mapping->host;
+	if (!inode)
+		return ret;
+
+	INIT_LIST_HEAD(&tmp_list);
+	mutex_lock(uprobes_mmap_hash(inode));
+	build_probe_list(inode, &tmp_list);
+	list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) {
+		loff_t vaddr;
+
+		list_del(&uprobe->pending_list);

kernel/uprobes.c line 950

Quoted 10 lines
kernel/uprobes.c new file +10 -0
+		if (!ret) {
+			vaddr = vma_address(vma, uprobe->offset);
+			if (vaddr < vma->vm_start || vaddr >= vma->vm_end) {
+				put_uprobe(uprobe);
+				continue;
+			}
+			ret = install_breakpoint(vma->vm_mm, uprobe, vma,
+								vaddr);
+			if (ret == -EEXIST)
+				ret = 0;

This now has the comment "Ignore double add:". That is a poor comment, because it doesn't tell us *why* a double-add is ignored.

kernel/uprobes.c

Quoted 12 lines
kernel/uprobes.c new file +9 -0
+		}
+		put_uprobe(uprobe);
+	}
+
+	mutex_unlock(uprobes_mmap_hash(inode));
+
+	return ret;
+}
+
 
...

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#16 lore raw

Re: [tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

Quoted 3 lines · Andrew Morton

hm, we seem to have conflicting commits between mainline and linux-next. During the merge window.  Again.  Nobody knows why this happens.

I didn't have my trivial cleanup branches in linux-next, I'm afraid. Usually my pending cleanups are just small patches that I carry along without even committing them, this time around I had slightly more than that.

Quoted 15 lines

static void unmap_single_vma(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr,
               struct zap_details *details)
{
       unsigned long start = max(vma->vm_start, start_addr); unsigned long end;

       if (start >= vma->vm_end)
               return;
       end = min(vma->vm_end, end_addr);
       if (end <= vma->vm_start)
               return;

Quoted 9 lines

<<<<<<< HEAD
=======
       if (vma->vm_file)
               uprobe_munmap(vma, start, end);

       if (vma->vm_flags & VM_ACCOUNT) *nr_accounted += (end - start) >> PAGE_SHIFT;

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

linux-next/akpm-base

Just remove the VM_ACCOUNT and *nr_accounted lines - they're done in the caller now. They always should have been, I'm not sure why it was in the "walk the page tables" path, which has nothing to do with it.

That said, I think that's true of uprobes too. Why the f*ck would uprobes do it's "munmap" operation when we walk the page tables? This function was called by more than just the actual unmapping, it was called by stuff that wants to zap the pages but leave the mapping around.

So that uprobe_munmap() could probably also be better moved into the caller - where we actually remove the vma. Maybe.

Linus

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

maintainer
#17 lore raw

Re: [tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

Quoted 7 lines · On Mon, 21 May 2012 15:00:28 -0700 Linus Torvalds…
Quoted 3 lines · Andrew Morton

hm, we seem to have conflicting commits between mainline and linux-next. During the merge window. __Again. __Nobody knows why this happens.

I didn't have my trivial cleanup branches in linux-next, I'm afraid.

Well, it's a broader issue than that. I often see a large number of rejects when syncing mainline with linux-next during the merge window. Right now:

Documentation/nfc/nfc-hci.txt:<<<<<<< HEAD Documentation/nfc/nfc-hci.txt:<<<<<<< HEAD Documentation/nfc/nfc-hci.txt:<<<<<<< HEAD Documentation/nfc/nfc-hci.txt:<<<<<<< HEAD Documentation/nfc/nfc-hci.txt:<<<<<<< HEAD arch/sparc/Kconfig:<<<<<<< HEAD arch/sparc/include/asm/thread_info_32.h:<<<<<<< HEAD drivers/net/ethernet/emulex/benet/be.h:<<<<<<< HEAD drivers/net/ethernet/emulex/benet/be_cmds.c:<<<<<<< HEAD drivers/net/ethernet/emulex/benet/be_main.c:<<<<<<< HEAD drivers/net/ethernet/emulex/benet/be_main.c:<<<<<<< HEAD drivers/net/virtio_net.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/htc_pipe.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/htc_pipe.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/htc_pipe.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/htc_pipe.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/usb.c:<<<<<<< HEAD drivers/net/wireless/ath/ath6kl/usb.c:<<<<<<< HEAD drivers/net/wireless/brcm80211/brcmfmac/bcmsdh.c:<<<<<<< HEAD drivers/net/wireless/brcm80211/brcmfmac/bcmsdh.c:<<<<<<< HEAD drivers/net/wireless/brcm80211/brcmfmac/bcmsdh.c:<<<<<<< HEAD drivers/net/wireless/brcm80211/brcmfmac/sdio_host.h:<<<<<<< HEAD drivers/net/wireless/brcm80211/brcmsmac/channel.c:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-agn-lib.c:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-agn-lib.c:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-agn-lib.c:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-agn-lib.c:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-agn-lib.c:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-agn-rxon.c:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-agn-tx.c:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-commands.h:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-commands.h:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-mac80211.c:<<<<<<< HEAD drivers/net/wireless/iwlwifi/iwl-power.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/cfg80211.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/decl.h:<<<<<<< HEAD drivers/net/wireless/mwifiex/fw.h:<<<<<<< HEAD drivers/net/wireless/mwifiex/fw.h:<<<<<<< HEAD drivers/net/wireless/mwifiex/fw.h:<<<<<<< HEAD drivers/net/wireless/mwifiex/main.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/main.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/main.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/main.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/main.h:<<<<<<< HEAD drivers/net/wireless/mwifiex/main.h:<<<<<<< HEAD drivers/net/wireless/mwifiex/main.h:<<<<<<< HEAD drivers/net/wireless/mwifiex/sta_cmd.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/sta_cmdresp.c:<<<<<<< HEAD drivers/net/wireless/mwifiex/sta_ioctl.c:<<<<<<< HEAD drivers/net/wireless/ti/wl12xx/Kconfig:<<<<<<< HEAD drivers/net/wireless/ti/wlcore/Kconfig:<<<<<<< HEAD drivers/net/wireless/ti/wlcore/boot.c:<<<<<<< HEAD drivers/net/wireless/ti/wlcore/boot.c:<<<<<<< HEAD drivers/net/wireless/ti/wlcore/wlcore.h:<<<<<<< HEAD drivers/net/wireless/ti/wlcore/wlcore.h:<<<<<<< HEAD drivers/nfc/pn533.c:<<<<<<< HEAD fs/nfs/nfs4proc.c:<<<<<<< HEAD
fs/stat.c:<<<<<<< HEAD
include/linux/filter.h:<<<<<<< HEAD include/net/mac80211.h:<<<<<<< HEAD include/net/mac80211.h:<<<<<<< HEAD include/net/nfc/hci.h:<<<<<<< HEAD include/net/nfc/hci.h:<<<<<<< HEAD include/net/nfc/nfc.h:<<<<<<< HEAD include/net/nfc/nfc.h:<<<<<<< HEAD include/net/nfc/shdlc.h:<<<<<<< HEAD mm/memory.c:<<<<<<< HEAD
net/ceph/osdmap.c:<<<<<<< HEAD net/mac80211/agg-tx.c:<<<<<<< HEAD net/mac80211/agg-tx.c:<<<<<<< HEAD net/mac80211/ibss.c:<<<<<<< HEAD net/mac80211/iface.c:<<<<<<< HEAD net/mac80211/mesh.c:<<<<<<< HEAD net/mac80211/mesh_plink.c:<<<<<<< HEAD net/mac80211/mesh_plink.c:<<<<<<< HEAD net/mac80211/mesh_plink.c:<<<<<<< HEAD net/mac80211/mesh_plink.c:<<<<<<< HEAD net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD
net/nfc/core.c:<<<<<<< HEAD net/nfc/hci/Kconfig:<<<<<<< HEAD net/nfc/hci/core.c:<<<<<<< HEAD net/nfc/hci/core.c:<<<<<<< HEAD net/nfc/hci/core.c:<<<<<<< HEAD net/nfc/hci/core.c:<<<<<<< HEAD net/nfc/hci/core.c:<<<<<<< HEAD net/nfc/hci/core.c:<<<<<<< HEAD net/nfc/hci/core.c:<<<<<<< HEAD net/nfc/hci/shdlc.c:<<<<<<< HEAD net/nfc/hci/shdlc.c:<<<<<<< HEAD net/nfc/nci/core.c:<<<<<<< HEAD

and that is typical. I've never really bothered working out why this is happening.

I suspect monkey business is afoot. People are magically finding new patches or new versions of old patches when the merge window opens up.

Also, some dope has just gone and added sys_numa_mbind() and sys_numa_tbind() to linux-next, nicely trashing a few things which were lined up for 3.5-rc1.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#22 lore raw

Re: [tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

In reply to Linus Torvalds

Hi Linus,

Quoted 11 lines · On Mon, 21 May 2012 15:00:28 -0700 Linus Torvalds…
Quoted 3 lines · Andrew Morton

hm, we seem to have conflicting commits between mainline and linux-next. During the merge window.  Again.  Nobody knows why this happens.

I didn't have my trivial cleanup branches in linux-next, I'm afraid. Usually my pending cleanups are just small patches that I carry along without even committing them, this time around I had slightly more than that.

You could set up a branch that is merged into linux-next if you want to ... it may lower the suprise factor.

Signature · 3 lines
Cheers,
Stephen Rothwell                    [email protected]
http://www.canb.auug.org.au/~sfr/
#18 lore raw

Re: [tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

In reply to Andrew Morton

Hi Andrew,

Quoted 7 lines · On Mon, 21 May 2012 15:13:23 -0700 Andrew Morton <[email protected]>…
Quoted 3 lines · On Mon, 21 May 2012 15:00:28 -0700 Linus Torvalds…
Quoted 1 line · Andrew Morton
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

hm, we seem to have conflicting commits between mainline and linux-next. During the merge window. __Again. __Nobody knows why this happens.

I didn't have my trivial cleanup branches in linux-next, I'm afraid.

Well, it's a broader issue than that. I often see a large number of rejects when syncing mainline with linux-next during the merge window. Right now:

Some of that is because your patch series is based on the end of linux-next and part way through the merge window only some of that has been merged by Linus. Also some of it gets rebased before Linus is asked to pull (a real pain) - there hasn't been much of that (yet) this merge window (but its early days :-(). Also, sometimes Linus' merge resolutions are different to mine.

I have been meaning to talk to you about basing the majority of your patch series on Linus' tree. This would give it mush greater stability and would make the merge resolution my problem (and Linus', of course).

There will be bits that may need to be based on other work in linux-next, but I suspect that it is not very much.

Signature · 2 lines
Cheers,
Stephen Rothwell                    [email protected]
maintainer
#19 lore raw

Re: [tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

Quoted 26 lines · On Tue, 22 May 2012 11:16:18 +1000 Stephen Rothwell <[email protected]>…

Hi Andrew,

Quoted 7 lines · On Mon, 21 May 2012 15:13:23 -0700 Andrew Morton <[email protected]>…
Quoted 3 lines · On Mon, 21 May 2012 15:00:28 -0700 Linus Torvalds…
Quoted 1 line · Andrew Morton
Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

hm, we seem to have conflicting commits between mainline and linux-next. During the merge window. __Again. __Nobody knows why this happens.

I didn't have my trivial cleanup branches in linux-next, I'm afraid.

Well, it's a broader issue than that. I often see a large number of rejects when syncing mainline with linux-next during the merge window. Right now:

Some of that is because your patch series is based on the end of linux-next and part way through the merge window only some of that has been merged by Linus. Also some of it gets rebased before Linus is asked to pull (a real pain) - there hasn't been much of that (yet) this merge window (but its early days :-(). Also, sometimes Linus' merge resolutions are different to mine.

Quoted 3 lines

I have been meaning to talk to you about basing the majority of your patch series on Linus' tree. This would give it mush greater stability and would make the merge resolution my problem (and Linus', of course).

Confused. None of those conflicts have anything to do with the -mm
patches: the only trees involved there are mainline and trees-in-next-other-than-mm.

Quoted 2 lines

There will be bits that may need to be based on other work in linux-next, but I suspect that it is not very much.

Well, there are a number of reasons why I base off linux-next. To see whether others have merged patches which I have merged (and, sometimes, missed later fixes to them). Explicit fixes against -next material. To get visibility into upcoming merge problems. And so that I and others test -next too.

Basing -mm on next is never a problem (for me). What is a problem is the mess which happens when people merge things into mainline which are (I assume) either slightly different from what they merged in -next or which never were in -next at all.

That's guessing - it's a long time since I sat down and worked out exactly what is causing this.

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#23 lore raw

Re: [tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

In reply to Linus Torvalds
Quoted 7 lines

That said, I think that's true of uprobes too. Why the f*ck would uprobes do it's "munmap" operation when we walk the page tables? This function was called by more than just the actual unmapping, it was called by stuff that wants to zap the pages but leave the mapping around.

This was pointed out by Oleg earlier and I had moved the code to unlink_file_vma.

However by the time unlink_file_vma() is called, the pages would have been unmapped (in unmap_vmas()) and the task->rss_stat counts accounted (in zap_pte_range()).

If the exiting process has probepoints, uprobe_munmap() checks if the breakpoint instruction was around before decrementing the probe count. This check results in a file backed page being re-read by uprobe_munmap() and also it cannot find the breakpoint (because we read a file backed page).

i.e

1. The task->rss_stat counts gets incremented again because we have read a page.

2. mm->uprobes_state.count which should have decremented, doesnt get decremented as uprobe_munmap fails to see the breakpoint.

Hence I had to move back the callback to zap pages so that we do the cleanup before the task->rss_stat counts are accounted.

That said, Oleg has a in-works patch/idea for removing uprobe_munmap and mm->uprobes_state.count, which when done, will remove the uprobe_munmap hook. https://lkml.org/lkml/2012/4/16/594

Please do let me know if you have better ideas to handle this.

Signature · 9 lines
Thanks and Regards
Srikar

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Fight unfair telecom internet charges in Canada: sign http://stopthemeter.ca/
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#20 lore raw

Re: [tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

In reply to Andrew Morton

Hi Andrew,

Quoted 10 lines · On Mon, 21 May 2012 19:27:00 -0700 Andrew Morton <[email protected]>…
Quoted 3 lines · On Tue, 22 May 2012 11:16:18 +1000 Stephen Rothwell <[email protected]>…

I have been meaning to talk to you about basing the majority of your patch series on Linus' tree. This would give it mush greater stability and would make the merge resolution my problem (and Linus', of course).

Confused. None of those conflicts have anything to do with the -mm
patches: the only trees involved there are mainline and trees-in-next-other-than-mm.

Right, its a separate issue. Though I do end up coping with conflicts in the -mm tree as I have to rebase it everyday.

Quoted 8 lines
Quoted 2 lines

There will be bits that may need to be based on other work in linux-next, but I suspect that it is not very much.

Well, there are a number of reasons why I base off linux-next. To see whether others have merged patches which I have merged (and, sometimes, missed later fixes to them). Explicit fixes against -next material. To get visibility into upcoming merge problems. And so that I and others test -next too.

I guess I see a separation between what you are working on and what you are publishing. You used to publish a reasonable amount of subseries for others and most of this I suspect could just be based on Linus' tree. Anyway, not a big problem except when I get days like yesterday (when I saw some of the conflicts you are noting).

Quoted 4 lines

Basing -mm on next is never a problem (for me). What is a problem is the mess which happens when people merge things into mainline which are (I assume) either slightly different from what they merged in -next or which never were in -next at all.

Indeed. Some of what you have seen this time is just last minute updates of other trees and bug fixes in Linus' tree. We had about 2000 (net) commits added to linux-next in the past week (800+ over the weekend). Some of this has now migrated to Linus' tree already.

Quoted 2 lines

That's guessing - it's a long time since I sat down and worked out exactly what is causing this.

Which is not a trivial problem. I will run my stats script and see what pops out.

Signature · 2 lines
Cheers,
Stephen Rothwell                    [email protected]
#24 lore raw

Re: [tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

In reply to Andrew Morton
Quoted 23 lines

static void unmap_single_vma(struct mmu_gather *tlb,
struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr,
struct zap_details *details)

{
	unsigned long start = max(vma->vm_start, start_addr);
	unsigned long end;

	if (start >= vma->vm_end)
		return;
	end = min(vma->vm_end, end_addr);
	if (end <= vma->vm_start)
		return;

<<<<<<< HEAD
=======

	if (vma->vm_file)
		uprobe_munmap(vma, start, end);

	if (vma->vm_flags & VM_ACCOUNT)
		*nr_accounted += (end - start) >> PAGE_SHIFT;
Quoted 7 lines
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

linux-next/akpm-base

	if (unlikely(is_pfn_mapping(vma)))
		untrack_pfn_vma(vma, 0, 0);

It made me look at uprobes. Noticed a few things...

I have responded to why I had to add a callback in unmap_single_vma in response to Linus.

Quoted 17 lines
Quoted 5 lines

...

kernel/uprobes.c new file +3 -0
+static struct rb_root uprobes_tree = RB_ROOT;
+static DEFINE_SPINLOCK(uprobes_treelock);	/* serialize rbtree access */
+

kernel/uprobes.c line 46

Quoted 10 lines
kernel/uprobes.c new file +10 -0
+#define UPROBES_HASH_SZ	13
+/* serialize (un)register */
+static struct mutex uprobes_mutex[UPROBES_HASH_SZ];
+#define uprobes_hash(v)	(&uprobes_mutex[((unsigned long)(v)) %\
+						UPROBES_HASH_SZ])
+
+/* serialize uprobe->pending_list */
+static struct mutex uprobes_mmap_mutex[UPROBES_HASH_SZ];
+#define uprobes_mmap_hash(v)	(&uprobes_mmap_mutex[((unsigned long)(v)) %\
+						UPROBES_HASH_SZ])

Presumably these locks were hashed for scalability reasons?

Yes,

uprobe_mmap_mutex is taken on every mmap/munmap operation. Since we do a per file operation per mm operation, (walk thro the rmap and insert/remove breakpoints), we looked at using i_mutex. However Christoph wasnt happy to overload the usage of i_mutex. He suggested two options,
1. adding another mutex in the inode structure
2. adding global hash locks. (which he recommended)

Adding a mutex in the inode structure, is a overkill.
But having just one mutex to guard all uprobe_mmap is a contention on different mmaps. So we narrowed down to a hash mutex.

Quoted 6 lines

If so, this won't be terribly effective when we have multiple mutexes occupying a single cacheline - the array entries should be padded out. Of course, that's all a complete waste of space on uniprocessor machines, but nobody seems to think of that any more ;(

Okay, I agree that having each mutex in a different cacheline helps. If everyone agrees to this, I will have a addon patch that will move the mutexes.

Quoted 5 lines

There was no need to code the accessor functions as macros. It is, as always, better to use a nice C function which takes an argument which is as strictly typed as possible. ie, it *could* take a void*, but it would be better if it required an inode*.

I will add this change as part of the add-on patch.

Quoted 6 lines
Quoted 6 lines

...

kernel/uprobes.c new file +3 -0
+static int read_opcode(struct mm_struct *mm, unsigned long vaddr,
+						uprobe_opcode_t *opcode)
+{

[.....]

Quoted 9 lines

kernel/uprobes.c line 294

Quoted 4 lines
kernel/uprobes.c new file +4 -0
+	vaddr_new = kmap_atomic(page);
+	vaddr &= ~PAGE_MASK;
+	memcpy(opcode, vaddr_new + vaddr, uprobe_opcode_sz);
+	kunmap_atomic(vaddr_new);

This is modifying user memory? flush_dcache_page() needed? Or perhaps we will need different primitives to diddle the instruction memory on architectures which care.

Here, we are just reading from the user memory,
The part where we insert/remove the breakpoint (write_opcode) does the flush.

Quoted 26 lines
Quoted 26 lines
kernel/uprobes.c new file +26 -0
+int mmap_uprobe(struct vm_area_struct *vma)
+{
+	struct list_head tmp_list;
+	struct uprobe *uprobe, *u;
+	struct inode *inode;
+	int ret = 0;
+
+	if (!atomic_read(&uprobe_events) || !valid_vma(vma, true))
+		return ret;	/* Bail-out */
+
+	inode = vma->vm_file->f_mapping->host;
+	if (!inode)
+		return ret;
+
+	INIT_LIST_HEAD(&tmp_list);
+	mutex_lock(uprobes_mmap_hash(inode));
+	build_probe_list(inode, &tmp_list);
+	list_for_each_entry_safe(uprobe, u, &tmp_list, pending_list) {
+		loff_t vaddr;
+
+		list_del(&uprobe->pending_list);
+		if (!ret) {
+			vaddr = vma_address(vma, uprobe->offset);
+			if (vaddr < vma->vm_start || vaddr >= vma->vm_end) {
+				put_uprobe(uprobe);
+				continue;
Quoted 9 lines

kernel/uprobes.c line 950

Quoted 5 lines
kernel/uprobes.c new file +5 -0
+			}
+			ret = install_breakpoint(vma->vm_mm, uprobe, vma,
+								vaddr);
+			if (ret == -EEXIST)
+				ret = 0;

This now has the comment "Ignore double add:". That is a poor comment, because it doesn't tell us *why* a double-add is ignored.

We actually dont ignore the "Double-add".

install_breakpoint() has comments on when we return EEXIST.

uprobe_mmap() has comments on why EEXIST should be considered successful as part of commit 682968e0 (uprobes/core: Optimize probe hits with the help of a counter) which is

/*
* Unable to insert a breakpoint, but
* breakpoint lies underneath. Increment the
* probe count
*/

i.e insert_breakpoint() needs to insert a breakpoint, but if a breakpoint is already there, then it doesnt need to do anything.

I will go ahead and remove the "Ignore double-add" comment.

Signature · 2 lines
thanks and regards
Srikar
#21 lore raw

Re: [tip:perf/uprobes] uprobes, mm, x86: Add the ability to install and remove uprobes breakpoints

In reply to Andrew Morton

Hi Andrew,

I have been thinking about this some more.

Quoted 10 lines · On Mon, 21 May 2012 15:13:23 -0700 Andrew Morton <[email protected]>…
Quoted 6 lines · On Mon, 21 May 2012 15:00:28 -0700 Linus Torvalds…
Quoted 3 lines · Andrew Morton

hm, we seem to have conflicting commits between mainline and linux-next. During the merge window. __Again. __Nobody knows why this happens.

Quoted 7 lines
Quoted 1 line

I didn't have my trivial cleanup branches in linux-next, I'm afraid.

Well, it's a broader issue than that. I often see a large number of rejects when syncing mainline with linux-next during the merge window. Right now:

Documentation/nfc/nfc-hci.txt:<<<<<<< HEAD

	.
	.
	.
Quoted 2 lines

net/nfc/hci/shdlc.c:<<<<<<< HEAD
net/nfc/nci/core.c:<<<<<<< HEAD

What two SHA1s did you try to merge to get that. I can get some of it but nothing like that.

Signature · 2 lines
Cheers,
Stephen Rothwell                    [email protected]