Skip to contentSkip to conversation

0: Uprobes Patches

PATCH In review Srikar Dronamraju 7 participants 71 messages Aug 25, 2010 – Nov 4, 2010

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

v11 cover 0: Uprobes Patches

Changelog from V10:
* Replaced function pointers in user_bkpt structure with weak functions as suggested by Peter Zijlstra.
* CONFIG_PROBE_EVENTS now selects uprobe-tracer and kprobe-tracer as suggested by Frederic.
* Split perf-probe listing patches into smaller patches.

Changelog from V9:
* Resolved comments from Arnaldo on perf support for uprobes.
* perf probe -S will now list only global binding functions as requested by Christoph Hellwig.
* Moved Changelog to below Signed-off-by: line, so that its not part of the patch description. (Suggested by Christoph.)

Changelog from V8:
* Fix build issues reported by Christoph.
* List available probes in a file without need to specify pid.

Changelog from V7:
* New feature: perf probe lists available probes.
* Fix perf probes for uprobes to exit with a error message on dwarf based probes.
* Merge changes to kprobes traceevent infrastructure.
* Merge changes to perf.

Changelog from V6:
* Remove perf adjust symbols patch.

Changelog from V5:
* Merged user_bkpt and user_bkpt_xol into uprobes.
* Addressed comments till now.

Changelog from V4:
* Rebased to tip tree. (2.6.35-rc3-tip)

Changelog from v3:
* Reverted to background page replacement as suggested by Peter Zijlstra.
* Dso in 'perf probe' can be either be a short name or a absolute path.
* Addressed comments from Masami, Frederic, Steven on traceevents and perf

Changelog from v2:
* Addressed comments from Oleg, including removal of interrupt context handlers, reverting background page replacement in favour of access_process_vm().

* Provides perf interface for uprobes.

Changelog from v1:
* Added trace_event interface for uprobes.
* Addressed comments from Andrew Morton and Randy Dunlap.

For previous posting: please refer:
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 implements Uprobes which enables you to dynamically break into any routine in a user space application and collect information non-disruptively.

This patchset is a rework based on suggestions from discussions on lkml in January and March 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.

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-process "execution out of line (XOL) area". Currently XOL area is allocated as one page vma.

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.

Here is the list of TODO Items.

- Perf automatically adds probes for high-overhead functions.
- Allow trace scripts to insert probes
- Syscall integration and TRACE_EVENT() universe. (Need clarity/discussion on API)
- Allowing probes across fork.
- Allowing probes per-executable/per dso.
- Allow multiple probes to share a probepoint.
- Return probes.
- Support for other architectures.
- Uprobes booster.
- Merge uprobes and kprobes trace_event.
- replace macro W with bits in inat table.

Please do provide your valuable comments.

Thanks in advance.
Srikar

---

Srikar Dronamraju(15)
1: mm: Move replace_page() / write_protect_page() to mm/memory.c 2: uprobes: Breakpoint insertion/removal in user space applications. 3: uprobes: Slot allocation for Execution out of line(XOL)
4: uprobes: x86 specific functions for user space breakpointing. 5: uprobes: Uprobes (un)registration and exception handling. 6: uprobes: X86 support for Uprobes
7: uprobes: Uprobes Documentation
8: tracing: Extract out common code for kprobes/uprobes traceevents. 9: tracing: uprobes trace_event interface
10: tracing: config option to enable both kprobe-tracer and uprobe-tracer. 11: perf: list symbols in a dso in ascending order.
12: perf: show possible probes in a given file.
13: perf: Loop thro each of the maps in a map_group.
14: perf: perf interface for uprobes
15: perf: Show Potential probe points.

 Documentation/uprobes.txt          |  188 +++++
 arch/Kconfig                       |    6 +
 arch/x86/Kconfig                   |    1 +
 arch/x86/include/asm/thread_info.h |    2 +
 arch/x86/include/asm/uprobes.h     |   43 ++
 arch/x86/kernel/Makefile           |    2 +
 arch/x86/kernel/signal.c           |   13 +
 arch/x86/kernel/uprobes.c          |  613 ++++++++++++++++
 fs/exec.c                          |    4 +
 include/linux/mm.h                 |    4 +
 include/linux/mm_types.h           |    4 +
 include/linux/sched.h              |    3 +
 include/linux/uprobes.h            |  305 ++++++++
 kernel/Makefile                    |    1 +
 kernel/fork.c                      |   21 +
 kernel/trace/Kconfig               |   61 ++-
 kernel/trace/Makefile              |    2 +
 kernel/trace/trace.h               |    5 +
 kernel/trace/trace_kprobe.c        |  752 +-------------------
 kernel/trace/trace_probe.c         |  654 +++++++++++++++++
 kernel/trace/trace_probe.h         |  157 ++++
 kernel/trace/trace_uprobe.c        |  739 +++++++++++++++++++
 kernel/uprobes.c                   | 1405 ++++++++++++++++++++++++++++++++++++
 mm/ksm.c                           |  112 ---
 mm/memory.c                        |  120 +++
 tools/perf/builtin-probe.c         |   55 ++-
 tools/perf/util/map.h              |   27 +
 tools/perf/util/probe-event.c      |  503 +++++++++++--
 tools/perf/util/probe-event.h      |   13 +-
 tools/perf/util/symbol.c           |   22 +
 tools/perf/util/symbol.h           |    2 +
 31 files changed, 4886 insertions(+), 953 deletions(-)
#1 lore raw

PATCH v11 1/15 1: mm: Move replace_page() / write_protect_page() to mm/memory.c

User bkpt will use background page replacement approach to insert/delete breakpoints. Background page replacement approach will be based on replace_page and write_protect_page.
Now replace_page() loses its static attribute.

---

 include/linux/mm.h |    4 ++
 mm/ksm.c           |  112 -------------------------------------------------
 mm/memory.c        |  120 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 124 insertions(+), 112 deletions(-)
include/linux/mm.h +4 -0
index 831c693..3f014e4 100644
@@ -863,6 +863,10 @@ void account_page_dirtied(struct page *page, struct address_space *mapping);
 int set_page_dirty(struct page *page);
 int set_page_dirty_lock(struct page *page);
 int clear_page_dirty_for_io(struct page *page);
+int replace_page(struct vm_area_struct *vma, struct page *page,
+					struct page *kpage, pte_t orig_pte);
+int write_protect_page(struct vm_area_struct *vma, struct page *page,
+						      pte_t *orig_pte);
 
 extern unsigned long move_page_tables(struct vm_area_struct *vma,
 		unsigned long old_addr, struct vm_area_struct *new_vma,
mm/ksm.c +0 -112

118 lines not on this page · raw message

mm/memory.c +120 -0

126 lines not on this page · raw message

#2 lore raw

PATCH v11 2/15 2: uprobes: Breakpoint insertion/removal in user space applications.

In reply to Srikar Dronamraju

Provides a mechanism in kernel to insert/remove breakpoints in user space applications including
- architecture independent mechanism to establish breakpoints in userspace applications.
- helper functions for reading/writing/validating data/opcodes from target process's address space.
- wrappers and default implementation(whereever possible) of architecture dependent functions(setting breakpoint)
- preprocessing and postprocessing of singlestep on breakpoint hit

Single stepping inline is the traditional method where original instructions replace the breakpointed instructions on a breakpoint hit. This method works well with single threaded applications. However its racy with multithreaded applications.

In execution out of line, threads single steps on a copy of the instruction. This method works well for both single-threaded and multithreaded applications.

Uprobes uses execution out of line method.

There could be other strategies like emulating an instruction. However they are currently not implemented.

Insertion and removal of breakpoints is by "Background page replacement". i.e make a copy of the page, modify its the contents, set the pagetable and flush the tlbs. This page uses enhanced replace_page to cow the page. Modified page is only reflected for the interested process. Others sharing the page will still see the old copy.

You need to follow this up with the uprobes patch for your architecture to define architecture specific functionality for reading/writing/validating data/opcodes.

---

Changelog from V10: (replace function pointers with weak functions)
* Removed architecture specific function pointers in user_bkpt structure and replaced them with weak functions as suggested by Peter Zijlstra.

Changelog from V5: (Merge user_bkpt into uprobes)
* Merged user_bkpt into uprobes as suggested by Christoph Hellwig and Peter Zijlstra.

Changelog from V3: (reimplement background page replacement)
* Replemented background page replacement based on inputs from Peter Zijlstra.

Changelog from v2: (addressing comments from Oleg)
* Use access_process_vm instead of replace_page based background page replacement.

Changelog from v1:
* Use k(un)map_atomic instead of k(un)map.
* Remove BUG_ON.
* Few parameter changes to be more consistent with sparse.
* Added kernel-doc comments whereever necessary.
* Introduce a check to detect if post_xol can sleep.

 arch/Kconfig            |   14 +
 include/linux/uprobes.h |  160 ++++++++++++++++
 kernel/Makefile         |    1 
 kernel/uprobes.c        |  475 +++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 650 insertions(+), 0 deletions(-)
 create mode 100644 include/linux/uprobes.h
 create mode 100644 kernel/uprobes.c
arch/Kconfig +14 -0
index 4877a8c..87bd26b 100644
@@ -47,6 +47,17 @@ config OPTPROBES
 	depends on !PREEMPT
 	select KALLSYMS_ALL
 
+config UPROBES
+	bool "User-space probes (EXPERIMENTAL)"
+	depends on ARCH_SUPPORTS_UPROBES
+	depends on MMU
+	help
+	  Uprobes enables kernel subsystems to establish probepoints
+	  in user applications and execute handler functions when
+	  the probepoints are hit. For more information, refer to
+	  Documentation/uprobes.txt.
+	  If in doubt, say "N".
+
 config HAVE_EFFICIENT_UNALIGNED_ACCESS
 	bool
 	help
@@ -80,6 +91,9 @@ config USER_RETURN_NOTIFIER
 	  Provide a kernel-internal notification when a cpu is about to
 	  switch to user mode.
 
+config ARCH_SUPPORTS_UPROBES
+	def_bool n
+
 config HAVE_IOREMAP_PROT
 	bool
 
include/linux/uprobes.h new file +160 -0

160 lines not on this page · raw message

kernel/Makefile +1 -0
index 17046b6..af4ec3f 100644
@@ -105,6 +105,7 @@ obj-$(CONFIG_PERF_EVENTS) += perf_event.o
 obj-$(CONFIG_HAVE_HW_BREAKPOINT) += hw_breakpoint.o
 obj-$(CONFIG_USER_RETURN_NOTIFIER) += user-return-notifier.o
 obj-$(CONFIG_PADATA) += padata.o
+obj-$(CONFIG_UPROBES) += uprobes.o
 
 ifneq ($(CONFIG_SCHED_OMIT_FRAME_POINTER),y)
 # According to Alan Modra <[email protected]>, the -fno-omit-frame-pointer is
kernel/uprobes.c new file +475 -0

475 lines not on this page · raw message

maintainer
#3 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 2/15] 2: uprobes: Breakpoint insertion/removal in user space applications.

Quoted 1 line · Srikar Dronamraju

+struct user_bkpt_arch_info *arch = &user_bkpt_arch_info;

That really wants to be static, 'arch' is a way too generic a name to inject in the global namespace.

Quoted 15 lines
kernel/uprobes.c new file +14 -0
+unsigned long uprobes_read_vm(struct task_struct *tsk, void __user *vaddr,
+					void *kbuf, unsigned long nbytes)
+{
+	if (tsk == current) {
+		unsigned long nleft = copy_from_user(kbuf, vaddr, nbytes);
+		return nbytes - nleft;
+	} else
+		return access_process_vm(tsk, (unsigned long) vaddr, kbuf,
+							nbytes, 0);
+}
+
 
+unsigned long uprobes_write_data(struct task_struct *tsk,
+				void __user *vaddr, const void *kbuf,
+				unsigned long nbytes)

kernel/uprobes.c line 81

Quoted 10 lines
kernel/uprobes.c new file +10 -0
+{
+	unsigned long nleft;
+
+	if (tsk == current) {
+		nleft = copy_to_user(vaddr, kbuf, nbytes);
+		return nbytes - nleft;
+	} else
+		return access_process_vm(tsk, (unsigned long) vaddr,
+						(void *) kbuf, nbytes, 1);
+}

either: s/uprobes_read_vm/uprobes_read_data/ or
s/uproves_write_data/uproves_write_vm/

Quoted 20 lines
kernel/uprobes.c new file +20 -0
+static int write_opcode(struct task_struct *tsk, unsigned long vaddr,
+						user_bkpt_opcode_t opcode)
+{
+	struct mm_struct *mm;
+	struct vm_area_struct *vma;
+	struct page *old_page, *new_page;
+	void *vaddr_old, *vaddr_new;
+	pte_t orig_pte;
+	int ret = -EINVAL;
+
+	if (!tsk)
+		return ret;
+
+	mm = get_task_mm(tsk);
+	if (!mm)
+		return ret;
+
+	down_read(&mm->mmap_sem);
+
+	/* Read the page with vaddr into memory */

kernel/uprobes.c line 112

Quoted 10 lines
kernel/uprobes.c new file +10 -0
+	ret = get_user_pages(tsk, mm, vaddr, 1, 1, 1, &old_page, &vma);
+	if (ret <= 0)
+		goto mmput_out;
+
+	/*
+	 * check if the page we are interested is read-only mapped
+	 * Since we are interested in text pages, Our pages of interest
+	 * should be mapped read-only.
+	 */
+	if ((vma->vm_flags && (VM_READ|VM_WRITE)) != VM_READ) {

s/&&/&/

kernel/uprobes.c line 121

Quoted 9 lines
kernel/uprobes.c new file +9 -0
+		ret = -EINVAL;
+		goto put_out;
+	}
+
+	/* If its VM_SHARED vma, lets not write to such vma's.  */
+	if (vma->vm_flags & VM_SHARED) {
+		ret = -EINVAL;
+		goto put_out;
+	}

Something like:

/* private, read-only, executable maps only */
if ((vma->vm_flags & (VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)) != (VM_READ|VM_EXEC))

maybe?

Quoted 6 lines
kernel/uprobes.c new file +6 -0
+	/* Allocate a page */
+	new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vaddr);
+	if (!new_page) {
+		ret = -ENOMEM;
+		goto put_out;
+	}

kernel/uprobes.c line 221

Quoted 10 lines
kernel/uprobes.c new file +9 -0
 
+int __weak set_orig_insn(struct task_struct *tsk,
+			struct user_bkpt *user_bkpt, bool verify)
+{
+	if (verify) {
+		user_bkpt_opcode_t opcode;
+		int result = read_opcode(tsk, user_bkpt->vaddr, &opcode);
+		if (result)
+			return result;
+		if (opcode != arch->bkpt_insn)

This assumes user_bkpt_opcode_t is a scalar value, but there's no assertion of that, if someone were to define it like char[5] or somesuch the comparison would still compile but not do what you'd expect.

Quoted 15 lines
kernel/uprobes.c new file +14 -0
+			return -EINVAL;
+	}
+	return write_opcode(tsk, user_bkpt->vaddr, user_bkpt->opcode);
+}
 
+/**
+ * check_vma - verify if the address is in a executable vma.
+ * @tsk: the probed task
+ * @vaddr: virtual address of the instruction to be verified.
+ *
+ * Return 0 if vaddr is in an executable VM area,
+ * or -EINVAL otherwise.
+ */
+static int check_vma(struct task_struct *tsk, unsigned long vaddr)
+{

kernel/uprobes.c line 246

Quoted 10 lines
kernel/uprobes.c new file +10 -0
+	struct vm_area_struct *vma;
+	struct mm_struct *mm;
+	int ret = -EINVAL;
+
+	mm = get_task_mm(tsk);
+	if (!mm)
+		return -EINVAL;
+	down_read(&mm->mmap_sem);
+	vma = find_vma(mm, vaddr);
+	if (vma && vaddr >= vma->vm_start && (vma->vm_flags & VM_EXEC))

you fail to check vma->vm_end

Also, do we want to do the full private,ro,exec check here again?

kernel/uprobes.c line 272

Quoted 10 lines
kernel/uprobes.c new file +9 -0
+		ret = 0;
+	up_read(&mm->mmap_sem);
+	mmput(mm);
+	return ret;
+}
 
+int __weak validate_address(struct task_struct *tsk, unsigned long vaddr)
+{
+	return check_vma(tsk, vaddr);
+}

So here check_vma() is the default implementation of validate_address(), so why not name them accordingly?

Quoted 7 lines

+/*
+ * __insert_bkpt - insert breakpoint
+ * Insert a breakpoint into the process that includes @tsk, at the
+ * virtual address @user_bkpt->vaddr.
+ *
+ * All threads of the probed process must be stopped while
+ * @__insert_bkpt() runs.

I hope not,.. the pte swizzle we do above does not require any such thing, stale comment?

Quoted 12 lines

+ * Possible errors:
+ * -%ENOSYS: user_bkpt not supported for this architecture
+ * -%EINVAL: invalid instruction address
+ * -%EEXIST: breakpoint instruction already exists at that address
+ * -%EPERM: cannot probe this instruction
+ * -%EFAULT: failed to insert breakpoint instruction
+ */

kernel/uprobes.c new file +2 -0
+static int pre_sstep(struct task_struct *tsk, struct user_bkpt *user_bkpt,
+		struct user_bkpt_task_arch_info *tskinfo, struct pt_regs *regs)

kernel/uprobes.c line 378

Quoted 10 lines
kernel/uprobes.c new file +9 -0
+{
+	return pre_xol(tsk, user_bkpt, tskinfo, regs);
+}
+
 
+static int post_sstep(struct task_struct *tsk, struct user_bkpt *user_bkpt,
+		struct user_bkpt_task_arch_info *tskinfo, struct pt_regs *regs)
+{
+	return post_xol(tsk, user_bkpt, tskinfo, regs);
+}

What's the point of these functions?

kernel/uprobes.c line 407

Quoted 7 lines
kernel/uprobes.c new file +7 -0
+static int __remove_bkpt(struct task_struct *tsk,
+					struct user_bkpt *user_bkpt)
+{
+	if (validate_address(tsk, user_bkpt->vaddr) != 0)
+		return -EINVAL;
+	return set_orig_insn(tsk, user_bkpt, true);
+}

Why would we even consider calling this function on something that would fail the validate_address() test? If that fails we would not have installed the breakpoint to begin with, hence there would be no reason to remove it.

kernel/uprobes.c line 429

Quoted 4 lines
kernel/uprobes.c new file +4 -0
+bool __weak is_bkpt_insn(struct user_bkpt *user_bkpt)
+{
+	return (user_bkpt->opcode == arch->bkpt_insn);
+}

Again, assumes the instruction thing is a scalar.

The big thing I'm missing in this patch is generic code handling the actual breakpoint.. but maybe that's somewhere in the next patches.. /me goes look.

#4 lore raw

PATCH v11 3/15 3: uprobes: Slot allocation for Execution out of line(XOL)

In reply to Srikar Dronamraju

Provides slot allocation mechanism for execution out of line for use with user space breakpointing.

Traditional method of replacing the original instructions on breakpoint hit are racy when used on multithreaded applications.

Alternatives for the traditional method include:
- Emulating the breakpointed instruction.
- Execution out of line.

Emulating the instruction:
This approach would use a in-kernel instruction emulator to
emulate the breakpointed instruction. This approach could be looked in at a later point of time.

Execution out of line:
In execution out of line strategy, a new vma is injected into
the target process, a copy of the instructions which are breakpointed is stored in one of the slots. On breakpoint hit, the copy of the instruction is single-stepped leaving the breakpoint instruction as is. This method is architecture independent.

This method is useful while handling multithreaded processes.

This patch allocates one page per process for slots to be used to copy the breakpointed instructions.

Current slot allocation mechanism:
1. Allocate one dedicated slot per user breakpoint. Each slot is big enuf to accomodate the biggest instruction for that architecture. (16 bytes for x86).
2. We currently allocate only one page for slots. Hence the number of slots is limited to active breakpoint hits on that process.
3. Bitmap to track used slots.

---

Changelog from V5: Merged into uprobes.

Changelog form V3:
* Added a memory barrier after the slot gets initialized.

Changelog from V2: (addressing Oleg's comments)
* Removed code in !CONFIG_UPROBES_XOL
* Functions now pass pointer to uprobes_xol_area instead of pointer to void.

 include/linux/uprobes.h |    2 
 kernel/uprobes.c        |  283 +++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 285 insertions(+), 0 deletions(-)
include/linux/uprobes.h +2 -0
index faacb2f..84a078c 100644
@@ -37,6 +37,8 @@ struct user_bkpt_task_arch_info {};
 struct user_bkpt_arch_info;
 #endif
 
+#define UINSNS_PER_PAGE	(PAGE_SIZE/UPROBES_XOL_SLOT_BYTES)
+#define MAX_UPROBES_XOL_SLOTS UINSNS_PER_PAGE
 
 struct task_struct;
 struct pt_regs;
kernel/uprobes.c +283 -0

295 lines not on this page · raw message

maintainer
#5 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 477

Quoted 12 lines · Srikar Dronamraju
kernel/uprobes.c +11 -0
+/* Slot allocation for XOL */
+
+/*
+ * Every probepoint gets its own slot.  Once it's assigned a slot, it
+ * keeps that slot until the probepoint goes away. Only definite number
+ * of slots are allocated.
+ */
+
+struct uprobes_xol_area {
+	spinlock_t lock;	/* protects bitmap and slot (de)allocation*/
+	unsigned long *bitmap;	/* 0 = free slot */

Since you have a static sized bitmap, why not simply declare it here?

	DECLARE_BITMAP(bitmap, MAX_UPROBES_XOL_SLOTS;

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 483

Quoted 5 lines
kernel/uprobes.c +5 -0
+	/*
+	 * 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.
+	 */

Naughty kernel modules we don't care about, but yeah, it appears vma's installed using install_special_mapping() can be unmapped by the process itself,.. curious.

Anyway, you could install your own vm_ops and provide a close method to track this.

Quoted 39 lines
kernel/uprobes.c +39 -0
+	unsigned long vaddr;		/* Page(s) of instruction slots */
+};
+
+static int xol_add_vma(struct uprobes_xol_area *area)
+{
+	struct vm_area_struct *vma;
+	struct mm_struct *mm;
+	struct file *file;
+	unsigned long addr;
+
+	mm = get_task_mm(current);
+	if (!mm)
+		return -ESRCH;
+
+	down_write(&mm->mmap_sem);
+	/*
+	 * Find the end of the top mapping and skip a page.
+	 * If there is no space for PAGE_SIZE above
+	 * that, mmap will ignore our address hint.
+	 *
+	 * We allocate a "fake" unlinked shmem file because
+	 * anonymous memory might not be granted execute
+	 * permission when the selinux security hooks have
+	 * their way.
+	 */
+	vma = rb_entry(rb_last(&mm->mm_rb), struct vm_area_struct, vm_rb);
+	addr = vma->vm_end + PAGE_SIZE;
+	file = shmem_file_setup("uprobes/xol", PAGE_SIZE, VM_NORESERVE);
+	if (!file) {
+		printk(KERN_ERR "uprobes_xol failed to setup shmem_file "
+			"while allocating vma for pid/tgid %d/%d for "
+			"single-stepping out of line.\n",
+			current->pid, current->tgid);
+		goto fail;
+	}
+	addr = do_mmap_pgoff(file, addr, PAGE_SIZE, PROT_EXEC, MAP_PRIVATE, 0);
+	fput(file);
+
+	if (addr & ~PAGE_MASK) {

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 532

Quoted 10 lines
kernel/uprobes.c +10 -0
+		printk(KERN_ERR "uprobes_xol failed to allocate a vma for "
+				"pid/tgid %d/%d for single-stepping out of "
+				"line.\n", current->pid, current->tgid);
+		goto fail;
+	}
+	vma = find_vma(mm, addr);
+
+	/* Don't expand vma on mremap(). */
+	vma->vm_flags |= VM_DONTEXPAND | VM_DONTCOPY;
+	area->vaddr = vma->vm_start;

Seems interesting,.. why not use install_special_mapping(), that's what the VDSO uses.

Quoted 4 lines
kernel/uprobes.c +4 -0
+	up_write(&mm->mmap_sem);
+	mmput(mm);
+	return 0;
+

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 546

Quoted 10 lines
kernel/uprobes.c +10 -0
+fail:
+	up_write(&mm->mmap_sem);
+	mmput(mm);
+	return -ENOMEM;
+}
+
+/*
+ * xol_alloc_area - Allocate process's uprobes_xol_area.
+ * This area will be used for storing instructions for execution out of
+ * line.

It doesn't actually do that, xol_add_vma() does that, this allocates the storage management bits.

Quoted 1 line

+ * Called with mm->uproc->mutex locked.

There's a nice way to not have to write that:

  lockdep_assert_held(&mm->uproc->mutex);
Quoted 6 lines

+ * Returns the allocated area or NULL.
+ */

+/*
+ * xol_free_area - Free the area allocated for slots.

Again, it doesn't actually free the slots itself.

Quoted 10 lines

+ * @xol_area refers the unique per process uprobes_xol_area for
+ * this process.
+ *
+ */

+/*
+ * Find a slot
+ * - searching in existing vmas for a free slot.
+ * - If no free slot in existing vmas, return 0;

I would call that allocate, find would imply a constant operation, but you actually change the state.

Quoted 1 line

+ * Called when holding xol_area->lock

  lockdep_assert_held(&area->lock);

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 602

Quoted 9 lines

+ */

kernel/uprobes.c +8 -0
+static unsigned long xol_take_insn_slot(struct uprobes_xol_area *area)
+{
+	unsigned long slot_addr;
+	int slot_nr;
+
+	slot_nr = find_first_zero_bit(area->bitmap, UINSNS_PER_PAGE);
+	if (slot_nr < UINSNS_PER_PAGE) {
+		set_bit(slot_nr, area->bitmap);

Since its all serialized by xol_area->lock, why use an atomic bitop?

Quoted 30 lines
kernel/uprobes.c +30 -0
+		slot_addr = area->vaddr +
+				(slot_nr * UPROBES_XOL_SLOT_BYTES);
+		return slot_addr;
+	}
+
+	return 0;
+}
+
+/*
+ * xol_get_insn_slot - If user_bkpt  was not allocated a slot, then
+ * allocate a slot. If uprobes_insert_bkpt is already called, (i.e
+ * user_bkpt.vaddr != 0) then copy the instruction into the slot.
+ * @user_bkpt: probepoint information
+ * @xol_area refers the unique per process uprobes_xol_area for
+ * this process.
+ *
+ * Called with mm->uproc->mutex locked.
+ * Returns the allocated slot address or 0.
+ */
+static unsigned long xol_get_insn_slot(struct user_bkpt *user_bkpt,
+				struct uprobes_xol_area *xol_area)
+{
+	unsigned long flags, xol_vaddr = 0;
+	int len;
+
+	if (unlikely(!xol_area))
+		return 0;
+
+	if (user_bkpt->xol_vaddr)
+		return user_bkpt->xol_vaddr;

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 642

Quoted 10 lines
kernel/uprobes.c +10 -0
+
+	spin_lock_irqsave(&xol_area->lock, flags);
+	xol_vaddr = xol_take_insn_slot(xol_area);
+	spin_unlock_irqrestore(&xol_area->lock, flags);
+
+	/*
+	 * Initialize the slot if user_bkpt->vaddr points to valid
+	 * instruction slot.
+	 */
+	if (likely(xol_vaddr) && user_bkpt->vaddr) {

if (!xol_vaddr)
goto bail;

gives nices code, and saves an indent level.

Also, why would we ever get here with !user_bkpt->vaddr.

(fwiw, my fingers hate bkpt, they either want to type bp, or brkpt)

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 654

Quoted 12 lines
kernel/uprobes.c +12 -0
+		len = access_process_vm(current, xol_vaddr, user_bkpt->insn,
+						UPROBES_XOL_SLOT_BYTES, 1);
+		if (unlikely(len < UPROBES_XOL_SLOT_BYTES))
+			printk(KERN_ERR "Failed to copy instruction at %#lx "
+					"len = %d\n", user_bkpt->vaddr, len);
+	}
+
+	/*
+	 * Update user_bkpt->xol_vaddr after giving a chance for the slot to
+	 * be initialized.
+	 */
+	mb();

Where is the matching barrier?

Quoted 28 lines
kernel/uprobes.c +28 -0
+	user_bkpt->xol_vaddr = xol_vaddr;
+	return user_bkpt->xol_vaddr;
+}
+
+/*
+ * xol_free_insn_slot - If slot was earlier allocated by
+ * @xol_get_insn_slot(), make the slot available for
+ * subsequent requests.
+ * @slot_addr: slot address as returned by
+ * @xol_get_insn_area().
+ * @xol_area refers the unique per process uprobes_xol_area for
+ * this process.
+ */
+static void xol_free_insn_slot(unsigned long slot_addr,
+				struct uprobes_xol_area *xol_area)
+{
+	unsigned long vma_end;
+	int found = 0;
+
+	if (unlikely(!slot_addr || IS_ERR_VALUE(slot_addr)))
+		return;
+
+	if (unlikely(!xol_area))
+		return;
+
+	vma_end = xol_area->vaddr + PAGE_SIZE;
+	if (xol_area->vaddr <= slot_addr && slot_addr < vma_end) {
+		int slot_nr;

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 692

Quoted 10 lines
kernel/uprobes.c +10 -0
+		unsigned long offset = slot_addr - xol_area->vaddr;
+		unsigned long flags;
+
+		BUG_ON(offset % UPROBES_XOL_SLOT_BYTES);
+
+		slot_nr = offset / UPROBES_XOL_SLOT_BYTES;
+		BUG_ON(slot_nr >= UINSNS_PER_PAGE);
+
+		spin_lock_irqsave(&xol_area->lock, flags);
+		clear_bit(slot_nr, xol_area->bitmap);

Again, using atomic bitops while already holding a lock... pick one.

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 699

Quoted 7 lines
kernel/uprobes.c +7 -0
+		spin_unlock_irqrestore(&xol_area->lock, flags);
+		found = 1;
+	}
+
+	if (!found)
+		printk(KERN_ERR "%s: no XOL vma for slot address %#lx\n",
+						__func__, slot_addr);

funny code flow,.. s/found = 1/return/ and loose the conditional and indent?

Quoted 32 lines
kernel/uprobes.c +32 -0
+}
+
+/*
+ * xol_validate_vaddr - Verify if the specified address is in an
+ * executable vma, but not in an XOL vma.
+ *	- Return 0 if the specified virtual address is in an
+ *	  executable vma, but not in an XOL vma.
+ *	- Return 1 if the specified virtual address is in an
+ *	  XOL vma.
+ *	- Return -EINTR otherwise.(i.e non executable vma, or
+ *	  not a valid address
+ * @pid: the probed process
+ * @vaddr: virtual address of the instruction to be validated.
+ * @xol_area refers the unique per process uprobes_xol_area for
+ * this process.
+ */
+static int xol_validate_vaddr(struct pid *pid, unsigned long vaddr,
+				struct uprobes_xol_area *xol_area)
+{
+	struct task_struct *tsk;
+	unsigned long vma_end;
+	int result;
+
+	if (unlikely(!xol_area))
+		return 0;
+
+	tsk = get_pid_task(pid, PIDTYPE_PID);
+	if (unlikely(!tsk))
+		return -EINVAL;
+
+	result = validate_address(tsk, vaddr);
+	if (result != 0)

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 741

Quoted 10 lines
kernel/uprobes.c +10 -0
+		goto validate_end;
+
+	vma_end = xol_area->vaddr + PAGE_SIZE;
+	if (xol_area->vaddr <= vaddr && vaddr < vma_end)
+		result = 1;
+
+validate_end:
+	put_task_struct(tsk);
+	return result;
+}

This doesn't actually appear used in this patch,.. does it want to live elsewhere?

#6 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

Quoted 7 lines

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 477

Quoted 3 lines
kernel/uprobes.c +3 -0
+struct uprobes_xol_area {
+	spinlock_t lock;	/* protects bitmap and slot (de)allocation*/
+	unsigned long *bitmap;	/* 0 = free slot */

Since you have a static sized bitmap, why not simply declare it here?

	DECLARE_BITMAP(bitmap, MAX_UPROBES_XOL_SLOTS;

Okay, will do.

Quoted 10 lines

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 483

Quoted 6 lines
kernel/uprobes.c +5 -0
+	/*
+	 * 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.
+	 */

Naughty kernel modules we don't care about, but yeah, it appears vma's installed using install_special_mapping() can be unmapped by the process itself,.. curious.

Will clean this up.

Quoted 7 lines

Anyway, you could install your own vm_ops and provide a close method to track this.

Quoted 3 lines
kernel/uprobes.c +3 -0
+	unsigned long vaddr;		/* Page(s) of instruction slots */
+};
+

<snipped>

Quoted 8 lines

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 532

Quoted 5 lines
kernel/uprobes.c +5 -0
+	vma = find_vma(mm, addr);
+
+	/* Don't expand vma on mremap(). */
+	vma->vm_flags |= VM_DONTEXPAND | VM_DONTCOPY;
+	area->vaddr = vma->vm_start;

Seems interesting,.. why not use install_special_mapping(), that's what the VDSO uses.

Okay, I hadnt looked at install_special_mapping earlier so I will take a look and incorporate it. However I am not clear at this point what install_special_mapping is giving us here. Also install_special_mapping is already defining its own vm_ops esp a close method thats doesnt seem to be doing anything. So at this point I am not clear how we are link the vm_ops, the close method and install_special_mapping.

Quoted 8 lines
Quoted 5 lines

+/*
+ * xol_alloc_area - Allocate process's uprobes_xol_area.
+ * This area will be used for storing instructions for execution out of
+ * line.

It doesn't actually do that, xol_add_vma() does that, this allocates the storage management bits.

Okay, will clean up.

Quoted 6 lines
Quoted 2 lines

+ * Called with mm->uproc->mutex locked.

There's a nice way to not have to write that:

  lockdep_assert_held(&mm->uproc->mutex);

Okay, will do.

Quoted 4 lines

I would call that allocate, find would imply a constant operation, but you actually change the state.

Okay,

Quoted 4 lines
Quoted 1 line

+ * Called when holding xol_area->lock

  lockdep_assert_held(&area->lock);
Quoted 11 lines

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 602

Quoted 9 lines

+ */

kernel/uprobes.c +8 -0
+static unsigned long xol_take_insn_slot(struct uprobes_xol_area *area)
+{
+	unsigned long slot_addr;
+	int slot_nr;
+
+	slot_nr = find_first_zero_bit(area->bitmap, UINSNS_PER_PAGE);
+	if (slot_nr < UINSNS_PER_PAGE) {
+		set_bit(slot_nr, area->bitmap);

Since its all serialized by xol_area->lock, why use an atomic bitop?

Okay will use the non-atomic set_bit.

Quoted 9 lines
Quoted 9 lines
kernel/uprobes.c +8 -0
+		slot_addr = area->vaddr +
+				(slot_nr * UPROBES_XOL_SLOT_BYTES);
+		return slot_addr;
+	}
+
+	return 0;
+}
+

<snipped>

Quoted 9 lines

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 642

Quoted 5 lines
kernel/uprobes.c +5 -0
+	/*
+	 * Initialize the slot if user_bkpt->vaddr points to valid
+	 * instruction slot.
+	 */
+	if (likely(xol_vaddr) && user_bkpt->vaddr) {

if (!xol_vaddr)
goto bail;

Quoted 3 lines

gives nices code, and saves an indent level.

Also, why would we ever get here with !user_bkpt->vaddr.

For now, user_bkpt->vaddr will always be set when we are here. However when we add uretprobe support, we would then get here with user_bkpt->vaddr being NULL.

I would drop the check for now, but add it later when we add the return probe support.

Quoted 3 lines

(fwiw, my fingers hate bkpt, they either want to type bp, or brkpt)

I had renamed the structure from ubp to user_bkpt based on your comments. I had actually mentioned this in the summary mail that I had sent on Jan 22 this year. I am fine to rename it to user_bp if that helps but if you feel ubp is better, I can revert to ubp too.

Quoted 6 lines
Quoted 6 lines
kernel/uprobes.c +6 -0
+		len = access_process_vm(current, xol_vaddr, user_bkpt->insn,
+						UPROBES_XOL_SLOT_BYTES, 1);
+		if (unlikely(len < UPROBES_XOL_SLOT_BYTES))
+			printk(KERN_ERR "Failed to copy instruction at %#lx "
+					"len = %d\n", user_bkpt->vaddr, len);
+	}
Quoted 8 lines

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 654

Quoted 6 lines
kernel/uprobes.c +6 -0
+
+	/*
+	 * Update user_bkpt->xol_vaddr after giving a chance for the slot to
+	 * be initialized.
+	 */
+	mb();

Where is the matching barrier?

I dont want the compiler to reorder the instructions and do the assignment for user_bkpt to be done before we complete the copy above.

If the assignment happens before we copy the content into the slot, someother thread that might hit the same probe actually things the slot is ready and tries to jump to that slot even before the slot is initialized.

Please let me know if I could have done it differently.

Quoted 5 lines
Quoted 5 lines
kernel/uprobes.c +4 -0
+	user_bkpt->xol_vaddr = xol_vaddr;
+	return user_bkpt->xol_vaddr;
+}
+

<snipped>

Quoted 11 lines

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 699

Quoted 8 lines
kernel/uprobes.c +7 -0
+		spin_unlock_irqrestore(&xol_area->lock, flags);
+		found = 1;
+	}
+
+	if (!found)
+		printk(KERN_ERR "%s: no XOL vma for slot address %#lx\n",
+						__func__, slot_addr);

funny code flow,.. s/found = 1/return/ and loose the conditional and indent?

Okay, will do.

Quoted 22 lines
Quoted 22 lines
kernel/uprobes.c +21 -0
+static int xol_validate_vaddr(struct pid *pid, unsigned long vaddr,
+				struct uprobes_xol_area *xol_area)
+{
+	struct task_struct *tsk;
+	unsigned long vma_end;
+	int result;
+
+	if (unlikely(!xol_area))
+		return 0;
+
+	tsk = get_pid_task(pid, PIDTYPE_PID);
+	if (unlikely(!tsk))
+		return -EINVAL;
+
+	result = validate_address(tsk, vaddr);
+	if (result != 0)
+		goto validate_end;
+
+	vma_end = xol_area->vaddr + PAGE_SIZE;
+	if (xol_area->vaddr <= vaddr && vaddr < vma_end)
+		result = 1;
Quoted 8 lines

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 741

Quoted 5 lines
kernel/uprobes.c +5 -0
+
+validate_end:
+	put_task_struct(tsk);
+	return result;
+}

This doesn't actually appear used in this patch,.. does it want to live elsewhere?

Yes, xol_validate_vaddr gets used in the next patch. So probably it can be moved to the next patch.

--
Thanks and Regards
Srikar

maintainer
#7 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

Quoted 7 lines · Srikar Dronamraju
Quoted 3 lines
Quoted 1 line

+ mb();

Where is the matching barrier?

I dont want the compiler to reorder the instructions and do the assignment for user_bkpt to be done before we complete the copy above.

Quoted 6 lines

If the assignment happens before we copy the content into the slot, someother thread that might hit the same probe actually things the slot is ready and tries to jump to that slot even before the slot is initialized.

Please let me know if I could have done it differently.

If you want a compiler barrier, use barrier(), but here you seem to describe a multi-threaded situation, in which case the observer thread needs at least a rmb() in order for that mb() to mean anything other than the compiler barrier it implies.

Also, use smp_* barriers.

#8 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

Quoted 16 lines · Peter Zijlstra
Quoted 7 lines · Srikar Dronamraju
Quoted 3 lines
Quoted 1 line

+ mb();

Where is the matching barrier?

I dont want the compiler to reorder the instructions and do the assignment for user_bkpt to be done before we complete the copy above.

Quoted 6 lines

If the assignment happens before we copy the content into the slot, someother thread that might hit the same probe actually things the slot is ready and tries to jump to that slot even before the slot is initialized.

Please let me know if I could have done it differently.

Quoted 9 lines

If you want a compiler barrier, use barrier(), but here you seem to describe a multi-threaded situation, in which case the observer thread needs at least a rmb() in order for that mb() to mean anything other than the compiler barrier it implies.

Also, use smp_* barriers.

Okay, would something like this suffice?

static unsigned long xol_get_insn_slot(struct user_bkpt *user_bkpt,
struct uprobes_xol_area *xol_area)

{
	unsigned long flags, xol_vaddr = 0;
	int len;

	if (unlikely(!xol_area))
		return 0;

	smp_rmb();
	if (user_bkpt->xol_vaddr)
		return user_bkpt->xol_vaddr;

	spin_lock_irqsave(&xol_area->lock, flags);
	xol_vaddr = xol_take_insn_slot(xol_area);
	spin_unlock_irqrestore(&xol_area->lock, flags);

	/*
	 * Initialize the slot if user_bkpt->vaddr points to valid
	 * instruction slot.
	 */
	if (!xol_vaddr)
		return 0;

	len = access_process_vm(current, xol_vaddr, user_bkpt->insn,
					UPROBES_XOL_SLOT_BYTES, 1);
	if (unlikely(len < UPROBES_XOL_SLOT_BYTES))
		printk(KERN_ERR "Failed to copy instruction at %#lx "
				"len = %d\n", user_bkpt->vaddr, len);

	/*
	 * Update user_bkpt->xol_vaddr after giving a chance for the slot to
	 * be initialized.
	 */
	smp_mb();
	user_bkpt->xol_vaddr = xol_vaddr;
	return user_bkpt->xol_vaddr;
}
Signature · 2 lines
Thanks and Regards
Srikar
maintainer
#9 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

Quoted 32 lines · Srikar Dronamraju

static unsigned long xol_get_insn_slot(struct user_bkpt *user_bkpt,
struct uprobes_xol_area *xol_area)

{
        unsigned long flags, xol_vaddr = 0;
        int len;

        if (unlikely(!xol_area))
                return 0;

        smp_rmb();
        if (user_bkpt->xol_vaddr)
                return user_bkpt->xol_vaddr;

        spin_lock_irqsave(&xol_area->lock, flags);
        xol_vaddr = xol_take_insn_slot(xol_area);
        spin_unlock_irqrestore(&xol_area->lock, flags);

        /*
         * Initialize the slot if user_bkpt->vaddr points to valid
         * instruction slot.
         */
        if (!xol_vaddr)
                return 0;

        len = access_process_vm(current, xol_vaddr, user_bkpt->insn,
                                        UPROBES_XOL_SLOT_BYTES, 1);
        if (unlikely(len < UPROBES_XOL_SLOT_BYTES))
                printk(KERN_ERR "Failed to copy instruction at %#lx "
                                "len = %d\n", user_bkpt->vaddr, len);
Quoted 8 lines
        /*
         * Update user_bkpt->xol_vaddr after giving a chance for the slot to
         * be initialized.
         */
        smp_mb();
        user_bkpt->xol_vaddr = xol_vaddr;
        return user_bkpt->xol_vaddr;
} 

Racy like you won't believe..

Suppose multiple threads hitting the trap at the same time, every thread will end up failing the check and allocating a new slot for it, at the end the slowest thread will end up setting the value.

#10 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

Quoted 40 lines
Quoted 31 lines

static unsigned long xol_get_insn_slot(struct user_bkpt *user_bkpt,
struct uprobes_xol_area *xol_area)

{
        unsigned long flags, xol_vaddr = 0;
        int len;

        if (unlikely(!xol_area))
                return 0;

        smp_rmb();
        if (user_bkpt->xol_vaddr)
                return user_bkpt->xol_vaddr;

        spin_lock_irqsave(&xol_area->lock, flags);
        xol_vaddr = xol_take_insn_slot(xol_area);
        spin_unlock_irqrestore(&xol_area->lock, flags);

        /*
         * Initialize the slot if user_bkpt->vaddr points to valid
         * instruction slot.
         */
        if (!xol_vaddr)
                return 0;

        len = access_process_vm(current, xol_vaddr, user_bkpt->insn,
                                        UPROBES_XOL_SLOT_BYTES, 1);
        if (unlikely(len < UPROBES_XOL_SLOT_BYTES))
                printk(KERN_ERR "Failed to copy instruction at %#lx "
                                "len = %d\n", user_bkpt->vaddr, len);
Quoted 8 lines
        /*
         * Update user_bkpt->xol_vaddr after giving a chance for the slot to
         * be initialized.
         */
        smp_mb();
        user_bkpt->xol_vaddr = xol_vaddr;
        return user_bkpt->xol_vaddr;
} 
Quoted 6 lines

Racy like you won't believe..

Suppose multiple threads hitting the trap at the same time, every thread will end up failing the check and allocating a new slot for it, at the end the slowest thread will end up setting the value.

Agree, I shall fix this up.
Since set_bit and clear_bit are atomic, I shall change the area->lock from a spinlock to a mutex, and have the mutex released after the slot has been updated with the "single-stepping instruction".

--
Thanks and Regards
Srikar

maintainer
#11 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

In reply to Srikar Dronamraju
Quoted 9 lines · Srikar Dronamraju
Quoted 8 lines

kernel/uprobes.c static int bad_arch_param(const char *param_name, int value) · line 532

Quoted 5 lines
kernel/uprobes.c +5 -0
+   vma = find_vma(mm, addr);
+
+   /* Don't expand vma on mremap(). */
+   vma->vm_flags |= VM_DONTEXPAND | VM_DONTCOPY;
+   area->vaddr = vma->vm_start;

Seems interesting,.. why not use install_special_mapping(), that's what the VDSO uses.

Quoted 6 lines

Okay, I hadnt looked at install_special_mapping earlier so I will take a look and incorporate it. However I am not clear at this point what install_special_mapping is giving us here. Also install_special_mapping is already defining its own vm_ops esp a close method thats doesnt seem to be doing anything. So at this point I am not clear how we are link the vm_ops, the close method and install_special_mapping.

What you're doing might well be the right thing, I was just wondering.

I think that, after thinking about it more, that the shmem file thing you're doing has the added benefit that the things gets auto-magic paging, which is a good thing.

maintainer
#12 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

In reply to Srikar Dronamraju
Quoted 7 lines · Srikar Dronamraju

Current slot allocation mechanism:
1. Allocate one dedicated slot per user breakpoint. Each slot is big enuf to accomodate the biggest instruction for that architecture. (16 bytes for x86).
2. We currently allocate only one page for slots. Hence the number of slots is limited to active breakpoint hits on that process.
3. Bitmap to track used slots.

An alternative method would be to have 1 slot per cpu, and manage the slot content using preemption notifiers. That gives you a fixed number of slots and an unlimited number of probe points.

If the preemption happens to be a migration you need to rewrite the userspace IP to point to the new slot -- if indeed the task was inside one when it got preempted -- but that all should be doable.

#13 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

Quoted 8 lines
Quoted 7 lines

Current slot allocation mechanism:
1. Allocate one dedicated slot per user breakpoint. Each slot is big enuf to accomodate the biggest instruction for that architecture. (16 bytes for x86).
2. We currently allocate only one page for slots. Hence the number of slots is limited to active breakpoint hits on that process.
3. Bitmap to track used slots.

Quoted 8 lines

An alternative method would be to have 1 slot per cpu, and manage the slot content using preemption notifiers. That gives you a fixed number of slots and an unlimited number of probe points.

If the preemption happens to be a migration you need to rewrite the userspace IP to point to the new slot -- if indeed the task was inside one when it got preempted -- but that all should be doable.

Certainly doable but it has its share of drawbacks.
1. On every probe hit we have to copy the instruction into the slot, so there is a performance penalty.

2 This might complicate booster probe, because the jump instruction that follows the original instruction now actually have to coded every time.

3. Yes migration is an issue esp
- if a thread of the same process that hit a breakpoint is scheduled into the same cpu and that newly scheduled thread hits a breakpoint.
- Something similar can happen if a multithreaded process runs on a
uniprocessor machine.

4. I dont see a need for clearing slots after post processing, but if we need to clear we then are adding more penalties because not only are we clearing the slots but the post processing then cant happen in interrupt context.

5. I think we are covered on the cpu hotplug too, (i.e not sure if we have to make uprobes cpu hot plug aware.).

6. We would still be allocating a page for the slots. Unless we want to expand to more slots than available in one page, I dont see the disadvantages with the current approach.

--
Thanks and Regards
Srikar

maintainer
#14 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

Quoted 12 lines · Srikar Dronamraju
Quoted 12 lines
Quoted 7 lines

Current slot allocation mechanism:
1. Allocate one dedicated slot per user breakpoint. Each slot is big enuf to accomodate the biggest instruction for that architecture. (16 bytes for x86).
2. We currently allocate only one page for slots. Hence the number of slots is limited to active breakpoint hits on that process.
3. Bitmap to track used slots.

An alternative method would be to have 1 slot per cpu, and manage the slot content using preemption notifiers. That gives you a fixed number of slots and an unlimited number of probe points.

Quoted 8 lines
Quoted 4 lines

If the preemption happens to be a migration you need to rewrite the userspace IP to point to the new slot -- if indeed the task was inside one when it got preempted -- but that all should be doable.

Certainly doable but it has its share of drawbacks.
1. On every probe hit we have to copy the instruction into the slot, so there is a performance penalty.

Yeah, although I imagine its nearly free since you need to pay the cache-miss anyway.

Quoted 3 lines

2 This might complicate booster probe, because the jump instruction that follows the original instruction now actually have to coded every time.

Why can't you keep the whole replacement sequence in-tact? Simply copy it out into the slot each time.

Quoted 4 lines

3. Yes migration is an issue esp
- if a thread of the same process that hit a breakpoint is scheduled into the same cpu and that newly scheduled thread hits a breakpoint.
- Something similar can happen if a multithreaded process runs on a
uniprocessor machine.

-ENOPARSE ?!

Quoted 4 lines

4. I dont see a need for clearing slots after post processing, but if we need to clear we then are adding more penalties because not only are we clearing the slots but the post processing then cant happen in interrupt context.

post-processing? you mean the probe handler? Why couldn't that be done from interrupt context?

Quoted 2 lines

5. I think we are covered on the cpu hotplug too, (i.e not sure if we have to make uprobes cpu hot plug aware.).

Not if you use a slot per cpu and use preemption notifiers, the preemption notifiers will migrate the slots around.

Quoted 3 lines

6. We would still be allocating a page for the slots. Unless we want to expand to more slots than available in one page, I dont see the disadvantages with the current approach.

The current approach limits the number of probes to what fits in a page. The slot per cpu approach will have no such limit.

#15 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

Quoted 14 lines
Quoted 13 lines
Quoted 8 lines

An alternative method would be to have 1 slot per cpu, and manage the slot content using preemption notifiers. That gives you a fixed number of slots and an unlimited number of probe points.

If the preemption happens to be a migration you need to rewrite the userspace IP to point to the new slot -- if indeed the task was inside one when it got preempted -- but that all should be doable.

3. Yes migration is an issue esp
- if a thread of the same process that hit a breakpoint is scheduled into the same cpu and that newly scheduled thread hits a breakpoint.
- Something similar can happen if a multithreaded process runs on a
uniprocessor machine.

Quoted 5 lines
Quoted 2 lines

5. I think we are covered on the cpu hotplug too, (i.e not sure if we have to make uprobes cpu hot plug aware.).

Not if you use a slot per cpu and use preemption notifiers, the preemption notifiers will migrate the slots around.

Lets say the thread while singlestepping the process gets pre-empted. Eventually the cpu might run some other thread of the same process before picking the first run thread. Or the first run thread could after migration due to load balancing or whatever end up running on a different thread? How do we handle these cases?

Quoted 7 lines
Quoted 4 lines

6. We would still be allocating a page for the slots. Unless we want to expand to more slots than available in one page, I dont see the disadvantages with the current approach.

The current approach limits the number of probes to what fits in a page. The slot per cpu approach will have no such limit.

yes the limit on number of probes is a limitation. For now the implementation would be straight and easy. We could either rework on the algorithm or add more pages depending on how often uprobes gets used.

Quoted 6 lines
Quoted 3 lines

2 This might complicate booster probe, because the jump instruction that follows the original instruction now actually have to coded every time.

Why can't you keep the whole replacement sequence in-tact? Simply copy it out into the slot each time.

Yes, if we use jump absolute then the replacement sequence stays in-tact.

--
Thanks and Regards
Srikar

maintainer
#16 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

Quoted 6 lines · Srikar Dronamraju

Lets say the thread while singlestepping the process gets pre-empted. Eventually the cpu might run some other thread of the same process before picking the first run thread. Or the first run thread could after migration due to load balancing or whatever end up running on a different thread? How do we handle these cases?

So assuming we're preempted while the IP is inside the slot:

On the preempt-out we store the slot relative ip (ip - start_of_slot), on preempt-in we write the replacement instructions in our cpu slot (could be the same cpu, could be another) and re-position the ip to point to the same relative position inside that slot, then go!

It really doesn't matter what happens in between.

maintainer
#17 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 3/15] 3: uprobes: Slot allocation for Execution out of line(XOL)

In reply to Srikar Dronamraju
Quoted 7 lines · Srikar Dronamraju
Quoted 2 lines

The current approach limits the number of probes to what fits in a page. The slot per cpu approach will have no such limit.

yes the limit on number of probes is a limitation. For now the implementation would be straight and easy. We could either rework on the algorithm or add more pages depending on how often uprobes gets used.

Right, but with the proposed slot-per-cpu we'd be able to have unlimited active probes within that single page, even with boosted probes, assuming 16 bytes per instruction:

push reg
mov reg,foo
insn
pop reg
jmp

and cacheline alignment we'd end up with 128 bytes per slot, we can service 32 cpus per page. Which, for now, means that all my machines need but a single page.

#18 lore raw

PATCH v11 4/15 4: uprobes: x86 specific functions for user space breakpointing.

In reply to Srikar Dronamraju

Provides x86 specific functions for instruction analysis and instruction validation and x86 specific pre-processing and post-processing of singlestep especially for RIP relative instructions. Uses "x86: instruction decoder API" for validation and analysis of user space instructions. This analysis is used at the time of post-processing of breakpoint hit to do the necessary fix-ups. There is support for breakpointing RIP relative instructions. However there are still few instructions that cannot be singlestepped.

Also defines TIF_UPROBE flag for x86.

This patch requires "x86: instruction decoder API"
http://lkml.org/lkml/2009/6/1/459

---

Changelog from V10: (replace function pointers with weak function
* Removed architecture specific function pointers in user_bkpt structure and replaced them with weak functions as suggested Peter Zijlstra.

Changelog from V5: Merged into uprobes layer.

Changelog from V1:
set UPROBES_FIX_SLEEPY if post_xol might sleep.

---
 arch/x86/Kconfig                   |    1 
 arch/x86/include/asm/thread_info.h |    2 
 arch/x86/include/asm/uprobes.h     |   43 +++
 arch/x86/kernel/Makefile           |    2 
 arch/x86/kernel/uprobes.c          |  561 ++++++++++++++++++++++++++++++++++++
 5 files changed, 609 insertions(+), 0 deletions(-)
 create mode 100644 arch/x86/include/asm/uprobes.h
 create mode 100644 arch/x86/kernel/uprobes.c
arch/x86/Kconfig +1 -0
index f0ee331..4710268 100644
@@ -54,6 +54,7 @@ config X86
 	select HAVE_KERNEL_LZO
 	select HAVE_HW_BREAKPOINT
 	select HAVE_MIXED_BREAKPOINTS_REGS
+	select ARCH_SUPPORTS_UPROBES
 	select PERF_EVENTS
 	select HAVE_PERF_EVENTS_NMI
 	select ANON_INODES
arch/x86/include/asm/thread_info.h +2 -0
index f0b6e5d..5b9c9f0 100644
@@ -84,6 +84,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 new file +43 -0

43 lines not on this page · raw message

arch/x86/kernel/Makefile +2 -0
index 801127c..4ef1efa 100644
@@ -115,6 +115,8 @@ obj-$(CONFIG_X86_CHECK_BIOS_CORRUPTION) += check.o
 
 obj-$(CONFIG_SWIOTLB)			+= pci-swiotlb.o
 
+obj-$(CONFIG_UPROBES)			+= uprobes.o
+
 ###
 # 64 bit specific files
 ifeq ($(CONFIG_X86_64),y)
arch/x86/kernel/uprobes.c new file +561 -0

561 lines not on this page · raw message

#19 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 4/15] 4: uprobes: x86 specific functions for user space breakpointing.

Srikar Dronamraju <[email protected]> writes:

Quick high level review. I did not attempt to validate the basic algorithm, more the kernel interface.

Quoted 8 lines

Provides x86 specific functions for instruction analysis and instruction validation and x86 specific pre-processing and post-processing of singlestep especially for RIP relative instructions. Uses "x86: instruction decoder API" for validation and analysis of user space instructions. This analysis is used at the time of post-processing of breakpoint hit to do the necessary fix-ups. There is support for breakpointing RIP relative instructions. However there are still few instructions that cannot be singlestepped.

One general comment here: since with uprobes the instruction decoder becomes security critical did you do any fuzz tests on it (e.g. like using it on crashme or on code that has been corrupted with a few bitflips) ?

Quoted 1 line

+typedef u8 user_bkpt_opcode_t;

Maybe it's me, but I would prefer breakpoint instead of bkpt

arch/x86/kernel/uprobes.c line 35

Quoted 5 lines
arch/x86/kernel/uprobes.c new file +5 -0
+#ifdef CONFIG_X86_32
+#define is_32bit_app(tsk) 1
+#else
+#define is_32bit_app(tsk) (test_tsk_thread_flag(tsk, TIF_IA32))
+#endif

This probably should be elsewhere.

Quoted 17 lines
arch/x86/kernel/uprobes.c new file +17 -0
+
+#define UPROBES_FIX_RIP_AX	0x8000
+#define UPROBES_FIX_RIP_CX	0x4000
+
+/* Adaptations for mhiramat x86 decoder v14. */
+#define OPCODE1(insn) ((insn)->opcode.bytes[0])
+#define OPCODE2(insn) ((insn)->opcode.bytes[1])
+#define OPCODE3(insn) ((insn)->opcode.bytes[2])
+#define MODRM_REG(insn) X86_MODRM_REG(insn->modrm.value)
+
+/*
+ * @reg: reflects the saved state of the task
+ * @vaddr: the virtual address to jump to.
+ * Return 0 on success or a -ve number on error.
+ */
+void set_ip(struct pt_regs *regs, unsigned long vaddr)
+{

arch/x86/kernel/uprobes.c line 62

Quoted 10 lines
arch/x86/kernel/uprobes.c new file +10 -0
+	regs->ip = vaddr;
+}
+
+#ifdef CONFIG_X86_64
+static bool is_riprel_insn(struct user_bkpt *user_bkpt)
+{
+	return ((user_bkpt->fixups &
+			(UPROBES_FIX_RIP_AX | UPROBES_FIX_RIP_CX)) != 0);
+}
+

Shouldn't all this stuff be in the instruction decoder?

It seems weird to have the knowledge spread over multiple files.

Quoted 10 lines
arch/x86/kernel/uprobes.c new file +10 -0
+
+static void report_bad_prefix(void)
+{
+	printk(KERN_ERR "uprobes does not currently support probing "
+		"instructions with any of the following prefixes: "
+		"cs:, ds:, es:, ss:, lock:\n");
+}
+
+static void report_bad_1byte_opcode(int mode, user_bkpt_opcode_t op)
+{

arch/x86/kernel/uprobes.c line 227

Quoted 10 lines
arch/x86/kernel/uprobes.c new file +10 -0
+	printk(KERN_ERR "In %d-bit apps, "
+		"uprobes does not currently support probing "
+		"instructions whose first byte is 0x%2.2x\n", mode, op);
+}
+
+static void report_bad_2byte_opcode(user_bkpt_opcode_t op)
+{
+	printk(KERN_ERR "uprobes does not currently support probing "
+		"instructions with the 2-byte opcode 0x0f 0x%2.2x\n", op);
+}

These functions that just do a single printk seem weird. I would do that in the caller. Also the message could be shortened I guess and should just dump the bytes.

Quoted 8 lines
arch/x86/kernel/uprobes.c new file +8 -0
+
+/**
+ * analyze_insn - instruction analysis including validity and fixups.
+ * @tsk: the probed task.
+ * @user_bkpt: the probepoint information.
+ * Return 0 on success or a -ve number on error.
+ */
+int analyze_insn(struct task_struct *tsk, struct user_bkpt *user_bkpt)

arch/x86/kernel/uprobes.c line 348

Quoted 10 lines
arch/x86/kernel/uprobes.c new file +10 -0
+{
+	int ret;
+	struct insn insn;
+
+	user_bkpt->fixups = 0;
+#ifdef CONFIG_X86_64
+	user_bkpt->arch_info.rip_target_address = 0x0;
+#endif
+
+	if (is_32bit_app(tsk))

This check is not fully correct because it's valid to have 32bit code in 64bit programs and vice versa. The only good way to check that is to look at the code segment at runtime though (and it gets complicated if you want to handle LDTs, but that could be optional). May be difficult to do though.

Also the compat bit is not necessarily set if no system call is executing. You would rather need to check the exec_domain.

Quoted 4 lines

+ */

arch/x86/kernel/uprobes.c new file +3 -0
+static int adjust_ret_addr(struct task_struct *tsk, unsigned long sp,
+							long correction)
+{

arch/x86/kernel/uprobes.c line 485

Quoted 10 lines
arch/x86/kernel/uprobes.c new file +10 -0
+	int rasize, ncopied;
+	long ra = 0;
+
+	if (is_32bit_app(tsk))
+		rasize = 4;
+	else
+		rasize = 8;
+	ncopied = uprobes_read_vm(tsk, (void __user *) sp, &ra, rasize);
+	if (unlikely(ncopied != rasize))
+		goto fail;

goto is automatically unlikely and unlikely is deprecated anyways.

-Andi

Signature · 1 line
[email protected] -- Speaking for myself only.
#20 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 4/15] 4: uprobes: x86 specific functions for user space breakpointing.

Quoted 5 lines

One general comment here: since with uprobes the instruction decoder becomes security critical did you do any fuzz tests on it (e.g. like using it on crashme or on code that has been corrupted with a few bitflips) ?

I havent tried any fuzz tests with the instruction decoder. But I am not sure if Masami has tried that out some of these.
One question: Do you want to test uprobes with crashme or test instruction decoder with crashme.

Quoted 4 lines
Quoted 2 lines

+typedef u8 user_bkpt_opcode_t;

Maybe it's me, but I would prefer breakpoint instead of bkpt

Even Peter wasnt comfortable with user_bkpt. How about user_bp? i.e the above field would be user_bp_opcode_t. I felt user_breakpoint_opcode_t might look long. Also we would have to rename other structures accordingly like user_bkpt_task_arch_info would become user_breakpoint_task_arch_info. Do let me know your choice.

Quoted 7 lines

arch/x86/kernel/uprobes.c line 35

Quoted 5 lines
arch/x86/kernel/uprobes.c new file +5 -0
+#ifdef CONFIG_X86_32
+#define is_32bit_app(tsk) 1
+#else
+#define is_32bit_app(tsk) (test_tsk_thread_flag(tsk, TIF_IA32))
+#endif

This probably should be elsewhere.

Would this fit in x86 Instruction decoder?

Quoted 31 lines
Quoted 18 lines
arch/x86/kernel/uprobes.c new file +17 -0
+
+#define UPROBES_FIX_RIP_AX	0x8000
+#define UPROBES_FIX_RIP_CX	0x4000
+
+/* Adaptations for mhiramat x86 decoder v14. */
+#define OPCODE1(insn) ((insn)->opcode.bytes[0])
+#define OPCODE2(insn) ((insn)->opcode.bytes[1])
+#define OPCODE3(insn) ((insn)->opcode.bytes[2])
+#define MODRM_REG(insn) X86_MODRM_REG(insn->modrm.value)
+
+/*
+ * @reg: reflects the saved state of the task
+ * @vaddr: the virtual address to jump to.
+ * Return 0 on success or a -ve number on error.
+ */
+void set_ip(struct pt_regs *regs, unsigned long vaddr)
+{

arch/x86/kernel/uprobes.c line 62

Quoted 10 lines
arch/x86/kernel/uprobes.c new file +10 -0
+	regs->ip = vaddr;
+}
+
+#ifdef CONFIG_X86_64
+static bool is_riprel_insn(struct user_bkpt *user_bkpt)
+{
+	return ((user_bkpt->fixups &
+			(UPROBES_FIX_RIP_AX | UPROBES_FIX_RIP_CX)) != 0);
+}
+

Shouldn't all this stuff be in the instruction decoder?

Quoted 1 line

It seems weird to have the knowledge spread over multiple files.

Agree, Shall move it to instruction decoder.

Quoted 17 lines
Quoted 17 lines
arch/x86/kernel/uprobes.c new file +16 -0
+
+static void report_bad_prefix(void)
+{
+	printk(KERN_ERR "uprobes does not currently support probing "
+		"instructions with any of the following prefixes: "
+		"cs:, ds:, es:, ss:, lock:\n");
+}
+
+static void report_bad_1byte_opcode(int mode, user_bkpt_opcode_t op)
+{
+	printk(KERN_ERR "In %d-bit apps, "
+		"uprobes does not currently support probing "
+		"instructions whose first byte is 0x%2.2x\n", mode, op);
+}
+
+static void report_bad_2byte_opcode(user_bkpt_opcode_t op)
Quoted 9 lines

arch/x86/kernel/uprobes.c line 227

Quoted 4 lines
arch/x86/kernel/uprobes.c new file +4 -0
+{
+	printk(KERN_ERR "uprobes does not currently support probing "
+		"instructions with the 2-byte opcode 0x0f 0x%2.2x\n", op);
+}

These functions that just do a single printk seem weird. I would do that in the caller. Also the message could be shortened I guess and should just dump the bytes.

Okay, I can move the printk to the caller, I will try to shorten the message, Would something like "uprobes: no support for 2-byte opcode 0x0f 0x%2" look fine?

Quoted 16 lines
Quoted 16 lines
arch/x86/kernel/uprobes.c new file +16 -0
+
+/**
+ * analyze_insn - instruction analysis including validity and fixups.
+ * @tsk: the probed task.
+ * @user_bkpt: the probepoint information.
+ * Return 0 on success or a -ve number on error.
+ */
+int analyze_insn(struct task_struct *tsk, struct user_bkpt *user_bkpt)
+{
+	int ret;
+	struct insn insn;
+
+	user_bkpt->fixups = 0;
+#ifdef CONFIG_X86_64
+	user_bkpt->arch_info.rip_target_address = 0x0;
+#endif
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+	if (is_32bit_app(tsk))

This check is not fully correct because it's valid to have 32bit code in 64bit programs and vice versa. The only good way to check that is to look at the code segment at runtime though (and it gets complicated if you want to handle LDTs, but that could be optional). May be difficult to do though.

validate_insn_32bit is able to identify all valid instructions in a 32 bit app and validate_insn_64bits is a superset of validate_insn_32bits; i.e it considers valid 32 bit codes as valid too.

Did you get a chance to look at validate_insn_32bit/validate_insn_64bits? If you feel that validate_insn_32bit/validate_insn_64bits? are unable to detect valid codes, then I will certainly rework.

Quoted 3 lines

Also the compat bit is not necessarily set if no system call is executing. You would rather need to check the exec_domain.

Okay, I shall check and revert on this.

Quoted 8 lines
Quoted 8 lines

+ */

arch/x86/kernel/uprobes.c new file +7 -0
+static int adjust_ret_addr(struct task_struct *tsk, unsigned long sp,
+							long correction)
+{
+	int rasize, ncopied;
+	long ra = 0;
+
+	if (is_32bit_app(tsk))
Quoted 8 lines

arch/x86/kernel/uprobes.c line 485

Quoted 6 lines
arch/x86/kernel/uprobes.c new file +6 -0
+		rasize = 4;
+	else
+		rasize = 8;
+	ncopied = uprobes_read_vm(tsk, (void __user *) sp, &ra, rasize);
+	if (unlikely(ncopied != rasize))
+		goto fail;

goto is automatically unlikely and unlikely is deprecated anyways.

Okay, shall remove unlikely from the above.

--
Thanks and Regards
Srikar

maintainer
#21 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 4/15] 4: uprobes: x86 specific functions for user space breakpointing.

Quoted 3 lines · Srikar Dronamraju
Quoted 1 line

Maybe it's me, but I would prefer breakpoint instead of bkpt

Even Peter wasnt comfortable with user_bkpt.

My main objection was the uprobe.c and user_bkpt.c splitup, its all about uprobes, but as to this name, you can simply name it uprobe_opcode_t, no need to preserve the whole user breakpoint thing at all.

#22 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 4/15] 4: uprobes: x86 specific functions for user space breakpointing.

In reply to Srikar Dronamraju

On Fri, 3 Sep 2010 23:18:32 +0530
Srikar Dronamraju <[email protected]> wrote:

[cutting down cc list]

Quoted 10 lines
Quoted 5 lines

One general comment here: since with uprobes the instruction decoder becomes security critical did you do any fuzz tests on it (e.g. like using it on crashme or on code that has been corrupted with a few bitflips) ?

I havent tried any fuzz tests with the instruction decoder. But I am not sure if Masami has tried that out some of these.
One question: Do you want to test uprobes with crashme or test instruction decoder with crashme.

Ideally both, but as a minimum the part that is exposed to user space, that is uprobes.

BTW if you test it I would test it both with real crashme and varying legal code that just has a few bits flipped.

Quoted 9 lines
Quoted 7 lines

arch/x86/kernel/uprobes.c line 35

Quoted 5 lines
arch/x86/kernel/uprobes.c new file +5 -0
+#ifdef CONFIG_X86_32
+#define is_32bit_app(tsk) 1
+#else
+#define is_32bit_app(tsk) (test_tsk_thread_flag(tsk, TIF_IA32))
+#endif

This probably should be elsewhere.

Would this fit in x86 Instruction decoder?

compat.h probably.

Quoted 3 lines

Okay, I can move the printk to the caller, I will try to shorten the message, Would something like "uprobes: no support for 2-byte opcode 0x0f 0x%2" look fine?

Yes that's fine. Optionally you could supply a short script like scripts/decodecode that feeds it through objdump -d This might need dumping a few more bytes.

Quoted 10 lines
Quoted 5 lines

This check is not fully correct because it's valid to have 32bit code in 64bit programs and vice versa. The only good way to check that is to look at the code segment at runtime though (and it gets complicated if you want to handle LDTs, but that could be optional). May be difficult to do though.

validate_insn_32bit is able to identify all valid instructions in a 32 bit app and validate_insn_64bits is a superset of validate_insn_32bits; i.e it considers valid 32 bit codes as valid too.

How can this be? e.g. 32bit has 1 byte INC/DEC but on 64bit these are REX prefixes and can be in front of nearly anything. So a super set cannot be correct. It has to be either / or.

Quoted 5 lines

Did you get a chance to look at validate_insn_32bit/validate_insn_64bits? If you feel that validate_insn_32bit/validate_insn_64bits? are unable to detect valid codes, then I will certainly rework.

I don't think you can do a 100% solution because for 100% you would need to know the code segment the CPU is going to use later, and that's not possible in advance.

A heuristic is reasonable (and leave out applications that generate 64bit code from 32bit executables or vice versa) but you need to test the right personality bits for that.

Quoted 4 lines
Quoted 2 lines

Also the compat bit is not necessarily set if no system call is executing. You would rather need to check the exec_domain.

Okay, I shall check and revert on this.

Hmm actually I double checked and this is a separate bit. So scratch that, TIF_32BIT is ok to test.

-Andi

Signature · 1 line
[email protected] -- Speaking for myself only.
#23 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 4/15] 4: uprobes: x86 specific functions for user space breakpointing.

[adding Masami and Jim to the copy list]

Quoted 7 lines
Quoted 4 lines

I havent tried any fuzz tests with the instruction decoder. But I am not sure if Masami has tried that out some of these.
One question: Do you want to test uprobes with crashme or test instruction decoder with crashme.

Ideally both, but as a minimum the part that is exposed to user space, that is uprobes.

Okay, I will test uprobes with crashme.

Quoted 11 lines
Quoted 6 lines

validate_insn_32bit is able to identify all valid instructions in a 32 bit app and validate_insn_64bits is a superset of validate_insn_32bits; i.e it considers valid 32 bit codes as valid too.

How can this be? e.g. 32bit has 1 byte INC/DEC but on 64bit these are REX prefixes and can be in front of nearly anything. So a super set cannot be correct. It has to be either / or.

You are right, the validate_insn_32bits refers to good_insns_32 and validate_insn_64bits refers to good_insns_64 to decode 1 byte instructions. Some instructions like 0x06 and 0x0e seem to be valid in good_insns_32 but not in good_insns_64.

Quoted 10 lines
Quoted 5 lines

Did you get a chance to look at validate_insn_32bit/validate_insn_64bits? If you feel that validate_insn_32bit/validate_insn_64bits? are unable to detect valid codes, then I will certainly rework.

I don't think you can do a 100% solution because for 100% you would need to know the code segment the CPU is going to use later, and that's not possible in advance.

I think you are referring to RIP related instructions, this how we handle them.
Please correct us if we are wrong, but here is what we do
- While analyzing the instruction, take into account which register acts as the code segment register.

- When interrupted (but before singlestep), copy the contents of the register which we think acts as code segment register in our above analysis into per-task scratch variable.

- After singlestepping we retrieve the saved per-task scratch variable into the corresponding register.

Quoted 5 lines

A heuristic is reasonable (and leave out applications that generate 64bit code from 32bit executables or vice versa) but you need to test the right personality bits for that.

Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

Also the compat bit is not necessarily set if no system call is executing. You would rather need to check the exec_domain.

Okay, I shall check and revert on this.

Hmm actually I double checked and this is a separate bit. So scratch that, TIF_32BIT is ok to test.

Okay, Thanks for confirming this.

--
Thanks and Regards
Srikar

#24 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 4/15] 4: uprobes: x86 specific functions for user space breakpointing.

Quoted 11 lines · On Mon, 6 Sep 2010 19:14:07 +0530 Srikar Dronamraju…

[adding Masami and Jim to the copy list]

Quoted 7 lines
Quoted 4 lines

I havent tried any fuzz tests with the instruction decoder. But I am not sure if Masami has tried that out some of these. One question: Do you want to test uprobes with crashme or test instruction decoder with crashme.

Ideally both, but as a minimum the part that is exposed to user space, that is uprobes.

Okay, I will test uprobes with crashme.

crashme and valid 1/2 bit corrupted code please if possible. I'm not sure crashme alone has enough coverage.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

Did you get a chance to look at validate_insn_32bit/validate_insn_64bits? If you feel that validate_insn_32bit/validate_insn_64bits? are unable to detect valid codes, then I will certainly rework.

Quoted 7 lines
Quoted 4 lines

I don't think you can do a 100% solution because for 100% you would need to know the code segment the CPU is going to use later, and that's not possible in advance.

I think you are referring to RIP related instructions, this how we handle them.

I just meant regarding long mode vs compat mode which defines whether REX prefixes are valid or not. Because this can change any time (if the application does a long jump) you cannot know in advance what it is going to use. But it's also very rare to use long jumps at all, so this can be probably ignored (but should be documented somewhere), and just guess based on the executable. I just wanted to point out that it's not a 100% solution.

I don't think you need to care about segment bases either. While they can be used (16bit Wine or dosemu) it's quite rare and not supporting uprobes for this is totally reasonable.

-Andi

Signature · 1 line
[email protected] -- Speaking for myself only.
#25 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 4/15] 4: uprobes: x86 specific functions for user space breakpointing.

In reply to Srikar Dronamraju
Quoted 6 lines · Srikar Dronamraju

[adding Masami and Jim to the copy list]

Quoted 4 lines
Quoted 4 lines

I havent tried any fuzz tests with the instruction decoder. But I am not sure if Masami has tried that out some of these.
One question: Do you want to test uprobes with crashme or test instruction decoder with crashme.

As you can see in kernel tree, x86 insn decoder has a test which decodes vmlinux and compares results with objdump. Similar tests had been done for glibc etc. by Jim. But crashme looks better. :)

Quoted 17 lines
Quoted 2 lines

Ideally both, but as a minimum the part that is exposed to user space, that is uprobes.

Okay, I will test uprobes with crashme.

Quoted 11 lines
Quoted 6 lines

validate_insn_32bit is able to identify all valid instructions in a 32 bit app and validate_insn_64bits is a superset of validate_insn_32bits; i.e it considers valid 32 bit codes as valid too.

How can this be? e.g. 32bit has 1 byte INC/DEC but on 64bit these are REX prefixes and can be in front of nearly anything. So a super set cannot be correct. It has to be either / or.

Quoted 4 lines

You are right, the validate_insn_32bits refers to good_insns_32 and validate_insn_64bits refers to good_insns_64 to decode 1 byte instructions. Some instructions like 0x06 and 0x0e seem to be valid in good_insns_32 but not in good_insns_64.

Hmm, if you need to validate all instructions, you'd better to enhance x86 decoder for checking bad instructions.
I think it can be done mostly by adding inat bitflags.

Thank you,

Quoted 37 lines
Quoted 9 lines
Quoted 4 lines

Did you get a chance to look at validate_insn_32bit/validate_insn_64bits? If you feel that validate_insn_32bit/validate_insn_64bits? are unable to detect valid codes, then I will certainly rework.

I don't think you can do a 100% solution because for 100% you would need to know the code segment the CPU is going to use later, and that's not possible in advance.

I think you are referring to RIP related instructions, this how we handle them.
Please correct us if we are wrong, but here is what we do
- While analyzing the instruction, take into account which register acts as the code segment register.

- When interrupted (but before singlestep), copy the contents of the register which we think acts as code segment register in our above analysis into per-task scratch variable.

- After singlestepping we retrieve the saved per-task scratch variable into the corresponding register.

Quoted 5 lines

A heuristic is reasonable (and leave out applications that generate 64bit code from 32bit executables or vice versa) but you need to test the right personality bits for that.

Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

Also the compat bit is not necessarily set if no system call is executing. You would rather need to check the exec_domain.

Okay, I shall check and revert on this.

Hmm actually I double checked and this is a separate bit. So scratch that, TIF_32BIT is ok to test.

Okay, Thanks for confirming this.

#26 lore raw

PATCH v11 5/15 5: uprobes: Uprobes (un)registration and exception handling.

In reply to Srikar Dronamraju

The uprobes infrastructure enables a user to dynamically establish probepoints in user applications and collect information by executing a handler function when a probepoint is hit.

The user specifies the virtual address and the pid of the process of interest along with the action to be performed. Uprobes uses the execution out of line strategy and follows lazy slot allocation. I.e, on the first probe hit for that process, a new vma (to hold the probed instructions for execution out of line) is allocated. Once allocated, this vma remains for the life of the process, and is reused as needed for subsequent probes. A slot in the vma is allocated for a probepoint when it is first hit.

A slot is marked for reuse only when the probe gets unregistered and there are no threads in the vicinity.

In a multithreaded process, a probepoint once registered is active for all threads of a process. If a thread specific action for a probepoint is required then the handler should be implemented to do the same.

If a breakpoint already exists at a particular address (irrespective of who inserted the breakpoint including uprobes), uprobes will refuse to register any more probes at that address.

You need to follow this up with the uprobes patch for your architecture.

For more information: please refer to Documentation/uprobes.txt

TODO:
1. Allow multiple probes at a probepoint.
2. Booster probes.
3. Allow probes to be inherited across fork.
4. probing function returns.

---

Changelog from V5:
- Merged user_bkpt and user_bkpt_xol layers into uprobes.

Changelog from V2:
- Introduce TIF_UPROBE flag.
- uprobes hooks now in fork/exec/exit paths instead of tracehooks.
- uprobe_process is now part of the mm struct and is shared between processes that share the mm.
- per thread information is now allocated on the fly.
* Hence allocation and freeing of this information is lockless.
- find_probept() takes the spinlock; unlike previously when it was expected that the spinlock was taken before calling it.
- For now run the handler in task context. The reasons for this change being.
* utask (per task meta data structure is now allocated on the fly. Hence first request on the thread and first request for the breakpoint have to be anyway allocated in task context.
* Measurements showed task based handler had negligible overhead over interrupt based handlers.
* Feedback from Oleg and few others.
* Feedback at LFCS.
* Simplicity atleast till uprobes stabilizes.
(However we introduce interrupt based handlers at a later time.)

Changelog from v1:
- If fixup might sleep; then do the post singlestep processing in task context.

 arch/Kconfig             |    1 
 fs/exec.c                |    4 
 include/linux/mm_types.h |    4 
 include/linux/sched.h    |    3 
 include/linux/uprobes.h  |  143 ++++++++++
 kernel/fork.c            |   21 +
 kernel/uprobes.c         |  653 ++++++++++++++++++++++++++++++++++++++++++++++
 7 files changed, 826 insertions(+), 3 deletions(-)
arch/Kconfig +1 -0
index 87bd26b..c8c8e3f 100644
@@ -49,6 +49,7 @@ config OPTPROBES
 
 config UPROBES
 	bool "User-space probes (EXPERIMENTAL)"
+	default n
 	depends on ARCH_SUPPORTS_UPROBES
 	depends on MMU
 	help
fs/exec.c +4 -0
index 2d94552..d7e64d0 100644
@@ -1053,6 +1053,10 @@ void setup_new_exec(struct linux_binprm * bprm)
 			
 	flush_signal_handlers(current, 0);
 	flush_old_files(current->files);
+#ifdef CONFIG_UPROBES
+	if (unlikely(current->utask))
+		uprobe_free_utask(current);
+#endif
 }
 EXPORT_SYMBOL(setup_new_exec);
 
include/linux/mm_types.h +4 -0
index cb57d65..8f79e51 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>
 
@@ -310,6 +311,9 @@ struct mm_struct {
 #ifdef CONFIG_MMU_NOTIFIER
 	struct mmu_notifier_mm *mmu_notifier_mm;
 #endif
+#ifdef CONFIG_UPROBES
+	struct uprobe_process *uproc;	/* per mm uprobes info */
+#endif
 };
 
 /* Future-safe accessor for struct mm_struct's cpu_vm_mask. */
include/linux/sched.h +3 -0
index e18473f..e237ba2 100644
@@ -1496,6 +1496,9 @@ struct task_struct {
 		unsigned long memsw_bytes; /* uncharged mem+swap usage */
 	} memcg_batch;
 #endif
+#ifdef CONFIG_UPROBES
+	struct uprobe_task *utask;
+#endif
 };
 
 /* Future-safe accessor for struct task_struct's cpus_allowed. */
include/linux/uprobes.h +143 -0

153 lines not on this page · raw message

kernel/fork.c +21 -0
index b7e9d60..d78cf5d 100644
@@ -187,6 +187,11 @@ void __put_task_struct(struct task_struct *tsk)
 	delayacct_tsk_free(tsk);
 	put_signal_struct(tsk->signal);
 
+#ifdef CONFIG_UPROBES
+	if (unlikely(tsk->utask))
+		uprobe_free_utask(tsk);
+#endif
+
 	if (!profile_handoff_task(tsk))
 		free_task(tsk);
 }
@@ -525,6 +530,10 @@ void __mmdrop(struct mm_struct *mm)
 	mm_free_pgd(mm);
 	destroy_context(mm);
 	mmu_notifier_mm_destroy(mm);
+#ifdef CONFIG_UPROBES
+	if (unlikely(mm->uproc))
+		uprobe_put_uprocess(mm);
+#endif
 	free_mm(mm);
 }
 EXPORT_SYMBOL_GPL(__mmdrop);
@@ -683,6 +692,9 @@ struct mm_struct *dup_mm(struct task_struct *tsk)
 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
 		goto free_pt;
 
+#ifdef CONFIG_UPROBES
+	mm->uproc = NULL;
+#endif
 	return mm;
 
 free_pt:
@@ -1190,6 +1202,9 @@ 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;
+#endif
 	/*
 	 * sigaltstack should be cleared when sharing the same VM
 	 */
@@ -1288,6 +1303,12 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 	proc_fork_connector(p);
 	cgroup_post_fork(p);
 	perf_event_fork(p);
+#ifdef CONFIG_UPROBES
+	if ((current->mm) && !(clone_flags & CLONE_VM)) {
+		if (unlikely(current->mm->uproc))
+			uprobe_handle_fork(p);
+	}
+#endif
 	return p;
 
 bad_fork_free_pid:
kernel/uprobes.c +650 -3

696 lines not on this page · raw message

maintainer
#27 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 4 lines · Srikar Dronamraju

TODO:
1. Allow multiple probes at a probepoint.
2. Booster probes.
3. Allow probes to be inherited across fork.

I wouldn't worry about that, focus on inode attached probes and you get fork for free.

Quoted 20 lines

4. probing function returns.

---

 arch/Kconfig             |    1 
 fs/exec.c                |    4 
 include/linux/mm_types.h |    4 
 include/linux/sched.h    |    3 
 include/linux/uprobes.h  |  143 ++++++++++
 kernel/fork.c            |   21 +
 kernel/uprobes.c         |  653 ++++++++++++++++++++++++++++++++++++++++++++++
 7 files changed, 826 insertions(+), 3 deletions(-)
arch/Kconfig +0 -0
index 87bd26b..c8c8e3f 100644

arch/Kconfig config OPTPROBES · line 55

Quoted 7 lines
arch/Kconfig +1 -0
@@ -49,6 +49,7 @@ config OPTPROBES
 
 config UPROBES
 	bool "User-space probes (EXPERIMENTAL)"
+	default n
 	depends on ARCH_SUPPORTS_UPROBES
 	depends on MMU
 	help

Seems like a weird place for this hunk, does this want to live elsewhere?

fs/exec.c void setup_new_exec(struct linux_binprm * bprm) · line 1059

Quoted 12 lines
fs/exec.c +4 -0
index 2d94552..d7e64d0 100644
@@ -1053,6 +1053,10 @@ void setup_new_exec(struct linux_binprm * bprm)
 
 	flush_signal_handlers(current, 0);
 	flush_old_files(current->files);
+#ifdef CONFIG_UPROBES
+	if (unlikely(current->utask))
+		uprobe_free_utask(current);
+#endif

A nicer way is to provide flush_uprobes() unconditionally.

Quoted 16 lines
fs/exec.c +0 -0
 }
 EXPORT_SYMBOL(setup_new_exec);
 
include/linux/mm_types.h +1 -0
index cb57d65..8f79e51 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>
 

include/linux/mm_types.h struct mm_struct { · line 317

Quoted 7 lines
include/linux/mm_types.h +3 -0
@@ -310,6 +311,9 @@ struct mm_struct {
 #ifdef CONFIG_MMU_NOTIFIER
 	struct mmu_notifier_mm *mmu_notifier_mm;
 #endif
+#ifdef CONFIG_UPROBES
+	struct uprobe_process *uproc;	/* per mm uprobes info */
+#endif
 };

I find the _process postfix a bit weird in this context, how about something like:

struct mm_uprobes *mm_uprobes;

instead?

include/linux/sched.h struct task_struct { · line 1502

Quoted 13 lines
include/linux/mm_types.h +0 -0
 /* Future-safe accessor for struct mm_struct's cpu_vm_mask. */
include/linux/sched.h +3 -0
index e18473f..e237ba2 100644
@@ -1496,6 +1496,9 @@ struct task_struct {
 		unsigned long memsw_bytes; /* uncharged mem+swap usage */
 	} memcg_batch;
 #endif
+#ifdef CONFIG_UPROBES
+	struct uprobe_task *utask;
+#endif
 };

Make that:

	struct uprobe_task_state uprobe_state;

And provide an empty struct for !CONFIG_UPROBE, see below.

include/linux/sched.h struct task_struct {

Quoted 7 lines
include/linux/sched.h +7 -0
+/* This is what the user supplies us. */
+struct uprobe {
+	/*
+	 * The pid of the probed process.  Currently, this can be the
+	 * thread ID (task->pid) of any active thread in the process.
+	 */
+	pid_t pid;

Would fail for pid namespaces I guess...

include/linux/sched.h

Quoted 6 lines
include/linux/sched.h +6 -0
+	/* Location of the probepoint */
+	unsigned long vaddr;
+
+	/* Handler to run when the probepoint is hit */
+	void (*handler)(struct uprobe*, struct pt_regs*);
+};

Like previously said, I would much rather see an inode/offset based interface and do the pid/fork/pgroup/cgroup etc.. stuff as filters on top of that.

Quoted 2 lines

+/*
+ * uprobe_process -- not a user-visible struct.

Seems like a weird comment for kernel code..

Quoted 7 lines

+ * A uprobe_process represents a probed process. A process can have
+ * multiple probepoints (each represented by a uprobe_probept) and
+ * one or more threads (each represented by a uprobe_task).
+ *
+ * All processes/threads that share a mm share the same uprobe_process.
+ */
+struct uprobe_process {

struct mm_uprobes {

Quoted 4 lines
include/linux/sched.h +4 -0
+	/*
+	 * mutex locked for any change to the uprobe_process's
+	 * graph (including uprobe_probept, taking a slot in xol_area) --
+	 * e.g., due to probe [un]registration or special events like exit.

include/linux/sched.h

Quoted 10 lines
include/linux/sched.h +10 -0
+	 */
+	struct mutex mutex;
+
+	/* Table of uprobe_probepts registered for this process */
+	struct list_head uprobe_list;
+
+	atomic_t refcount;
+
+	/* lock held while traversing/modifying uprobe_list and n_ppts */
+	spinlock_t pptlist_lock;	/* protects uprobe_list */

Its customary to write it like:

	spinlock_t	 list_lock; /* protects uprobe_list, nr_uprobes */
	struct list_head uprobe_list;
	int		 nr_uprobes;

include/linux/sched.h

Quoted 9 lines
include/linux/sched.h +9 -0
+
+	/* number of probept allocated for this process */
+	int n_ppts;
+
+	/*
+	 * Manages slots for instruction-copies to be single-stepped
+	 * out of line.
+	 */
+	void *xol_area;

Why void * and not simply:

	struct uprobes_xol_area xol_area;

That struct is small enough and you only get one per mm and saves you an allocation/pointer-chase.

include/linux/sched.h

Quoted 8 lines
include/linux/sched.h +8 -0
+};
+
+/*
+ * uprobe_probept -- not a user-visible struct.
+ * A uprobe_probept represents a probepoint.
+ * Guarded by uproc->lock.
+ */
+struct uprobe_probept {

you really got a way with names, uprobe_point would be so much better.

Quoted 6 lines
include/linux/sched.h +6 -0
+	/* breakpoint/XOL details */
+	struct user_bkpt user_bkpt;
+
+	/*
+	 * ppt goes in the uprobe_process->uprobe_table when registered --
+	 * even before the breakpoint has been inserted.

include/linux/sched.h

Quoted 10 lines
include/linux/sched.h +10 -0
+	 */
+	struct list_head ut_node;
+
+	atomic_t refcount;
+
+	/* The parent uprobe_process */
+	struct uprobe_process *uproc;
+
+	struct uprobe *uprobe;
+};

So this thing is a link between the process and the probe, I'm not quite sure what you need the refcount for, it seems to me you can only have on of these per process/probe combination.

If you had used inode/offset based probes they would have been unique in the system and you could have had an {inode,offset} indexed global tree (or possibly a tree per inode, but that would mean adding to the inode structure, which I think is best avoided).

That would also reduce the mm state to purely the xol area, no need to manage this process to probe map.

Quoted 8 lines
include/linux/sched.h +8 -0
+enum uprobe_task_state {
+	UTASK_RUNNING,
+	UTASK_BP_HIT,
+	UTASK_SSTEP
+};
+
+/*
+ * uprobe_utask -- not a user-visible struct.

include/linux/sched.h

Quoted 10 lines
include/linux/sched.h +10 -0
+ * Corresponds to a thread in a probed process.
+ * Guarded by uproc->mutex.
+ */
+struct uprobe_task {
+	struct user_bkpt_task_arch_info arch_info;
+
+	enum uprobe_task_state state;
+
+	struct uprobe_probept *active_ppt;
+};

I would be thinking you can obtain the active probe point from the address the task is stuck at and the state seems fairly redundant. Which leaves you with the arch state, which afaict is exactly as large as the pointer currently in the task struct.

Quoted 50 lines

--git a/kernel/fork.c b/kernel/fork.c
index b7e9d60..d78cf5d 100644

kernel/fork.c +15 -0
@@ -187,6 +187,11 @@ void __put_task_struct(struct task_struct *tsk)
 	delayacct_tsk_free(tsk);
 	put_signal_struct(tsk->signal);
 
+#ifdef CONFIG_UPROBES
+	if (unlikely(tsk->utask))
+		uprobe_free_utask(tsk);
+#endif
+
 	if (!profile_handoff_task(tsk))
 		free_task(tsk);
 }
@@ -525,6 +530,10 @@ void __mmdrop(struct mm_struct *mm)
 	mm_free_pgd(mm);
 	destroy_context(mm);
 	mmu_notifier_mm_destroy(mm);
+#ifdef CONFIG_UPROBES
+	if (unlikely(mm->uproc))
+		uprobe_put_uprocess(mm);
+#endif
 	free_mm(mm);
 }
 EXPORT_SYMBOL_GPL(__mmdrop);
@@ -683,6 +692,9 @@ struct mm_struct *dup_mm(struct task_struct *tsk)
 	if (mm->binfmt && !try_module_get(mm->binfmt->module))
 		goto free_pt;
 
+#ifdef CONFIG_UPROBES
+	mm->uproc = NULL;
+#endif
 	return mm;
 
 free_pt:
@@ -1190,6 +1202,9 @@ 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;
+#endif
 	/*
 	 * sigaltstack should be cleared when sharing the same VM
 	 */
@@ -1288,6 +1303,12 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 	proc_fork_connector(p);
 	cgroup_post_fork(p);

kernel/fork.c static struct task_struct *copy_process(unsigned long clone_flags, · line 1314

Quoted 10 lines
kernel/fork.c +6 -0
 	perf_event_fork(p);
+#ifdef CONFIG_UPROBES
+	if ((current->mm) && !(clone_flags & CLONE_VM)) {
+		if (unlikely(current->mm->uproc))
+			uprobe_handle_fork(p);
+	}
+#endif
 	return p;
 
 bad_fork_free_pid:

All that can be replaced by unconditional functions, simply stub them out for !CONFIG_UPROBE.

Quoted 41 lines
kernel/uprobes.c +6 -2
index 230adf3..38c7abb 100644
@@ -21,6 +21,7 @@
  *	Jim Keniston
  */
 #include <linux/kernel.h>
+#include <linux/types.h>
 #include <linux/init.h>
 #include <linux/module.h>
 #include <linux/sched.h>
@@ -36,6 +37,9 @@
 #include <linux/file.h>
 #include <linux/pid.h>
 #include <linux/slab.h>
+#include <linux/string.h>
+#include <linux/kdebug.h>
+
 
 struct user_bkpt_arch_info *arch = &user_bkpt_arch_info;
 
@@ -345,7 +349,7 @@ static int __insert_bkpt(struct task_struct *tsk,
  *	@__insert_bkpt(). @user_bkpt->xol_vaddr must be the
  *	address of an XOL instruction slot that is allocated to this
  *	probepoint at least until after the completion of
- *	@uprobes_post_sstep(), and populated with the contents of
+ *	@post_sstep(), and populated with the contents of
  *	@user_bkpt->insn.
  *	@tskinfo: points to a @user_bkpt_task_arch_info object for @tsk.
  *	@regs: reflects the saved user state of @tsk.  pre_sstep()
@@ -356,7 +360,7 @@ static int __insert_bkpt(struct task_struct *tsk,
  *
  * The client must ensure that the contents of @user_bkpt are not
  * changed during the single-step operation -- i.e., between when
- * @uprobes_pre_sstep() is called and when @uprobes_post_sstep() returns.
+ * @pre_sstep() is called and when @post_sstep() returns.
  */
 static int pre_sstep(struct task_struct *tsk, struct user_bkpt *user_bkpt,
 		struct user_bkpt_task_arch_info *tskinfo, struct pt_regs *regs)

kernel/uprobes.c static unsigned long xol_take_insn_slot(struct uprobes_xol_area *area) · line 620

Quoted 8 lines
kernel/uprobes.c +1 -1
@@ -610,7 +614,7 @@ static unsigned long xol_take_insn_slot(struct uprobes_xol_area *area)
 
 /*
  * xol_get_insn_slot - If user_bkpt  was not allocated a slot, then
- * allocate a slot. If uprobes_insert_bkpt is already called, (i.e
+ * allocate a slot. If insert_bkpt is already called, (i.e
  * user_bkpt.vaddr != 0) then copy the instruction into the slot.
  * @user_bkpt: probepoint information
  * @xol_area refers the unique per process uprobes_xol_area for

Wandering hunks, these seem to want to get folded back to wherever the original text comes from..

Quoted 4 lines
kernel/uprobes.c +0 -0
@@ -741,6 +745,642 @@ validate_end:
 }
 /* end of slot allocation for XOL */
 

kernel/uprobes.c validate_end: · line 757

Quoted 10 lines
kernel/uprobes.c +10 -0
+
+struct notifier_block uprobes_exception_nb = {
+	.notifier_call = uprobes_exception_notify,
+	.priority = 0x7ffffff0,
+};
+
+typedef void (*uprobe_handler_t)(struct uprobe*, struct pt_regs*);
+
+/* Guards lookup, creation, and deletion of uproc. */
+static DEFINE_MUTEX(uprobe_mutex);

uproc is per mm, why a global mutex?

kernel/uprobes.c validate_end: · line 1232

Quoted 10 lines
kernel/uprobes.c +10 -0
+/*
+ * Fork callback: The current task has spawned a process.
+ * NOTE: For now, we don't pass on uprobes from the parent to the
+ * child. We now do the necessary clearing of breakpoints in the
+ * child's address space.
+ * This function handles the case where vm is not shared between
+ * the parent and the child.
+ *
+ * TODO:
+ *	- Provide option for child to inherit uprobes.

Don't bother with that...

Quoted 6 lines
kernel/uprobes.c +6 -0
+ */
+void uprobe_handle_fork(struct task_struct *child)
+{
+	struct uprobe_process *uproc;
+	struct uprobe_probept *ppt;
+	int ret;

kernel/uprobes.c validate_end: · line 1248

Quoted 10 lines
kernel/uprobes.c +10 -0
+
+	uproc = current->mm->uproc;
+
+	/*
+	 * New process spawned by parent but not sharing the same mm.
+	 * Remove the probepoints in the child's text.
+	 *
+	 * We also hold the uproc->mutex for the parent - so no
+	 * new uprobes will be registered 'til we return.
+	 */

The grand thing about not having any of this process state is that you dont need to clean it up either..

Quoted 39 lines
kernel/uprobes.c +39 -0
+	mutex_lock(&uproc->mutex);
+	list_for_each_entry(ppt, &uproc->uprobe_list, ut_node) {
+		ret = __remove_bkpt(child, &ppt->user_bkpt);
+		if (ret && ret != -EINVAL) {
+			/* Ratelimit this? */
+			printk(KERN_ERR "Pid %d forked %d; failed to"
+				" remove probepoint at %#lx in child\n",
+				current->pid, child->pid,
+				ppt->user_bkpt.vaddr);
+		}
+	}
+	mutex_unlock(&uproc->mutex);
+}
+
+/*
+ * uprobe_notify_resume gets called in task context just before returning
+ * to userspace.
+ *
+ *  If its the first time the probepoint is hit, slot gets allocated here.
+ *  If its the first time the thread hit a breakpoint, utask gets
+ *  allocated here.
+ */
+void uprobe_notify_resume(struct pt_regs *regs)
+{
+	struct uprobe_process *uproc;
+	struct uprobe_probept *ppt;
+	struct uprobe_task *utask;
+	struct uprobe *u;
+	unsigned long probept;
+
+	utask = current->utask;
+	uproc = current->mm->uproc;
+	if (unlikely(!utask)) {
+		utask = add_utask(uproc);
+
+		/* Failed to allocate utask for the current task. */
+		BUG_ON(!utask);
+		probept = uprobes_get_bkpt_addr(regs);
+		ppt = find_probept(uproc, probept);

kernel/uprobes.c validate_end: · line 1297

Quoted 10 lines
kernel/uprobes.c +10 -0
+
+		/*
+		 * The probept was refcounted in uprobe_bkpt_notifier;
+		 * Hence it would be mysterious to miss ppt now
+		 */
+		WARN_ON(!ppt);
+		utask->active_ppt = ppt;
+		utask->state = UTASK_BP_HIT;
+	} else
+		ppt = utask->active_ppt;

You can replace this with:

addr = instruction_pointer(task_pt_regs(current)) -
ip_advancement_by_brkpt_insn;

and then proceed from there like described below to obtain the struct uprobe.

You can infer the SS/HIT state by checking if the user-addr is in the XOL area or not.

Quoted 26 lines
kernel/uprobes.c +26 -0
+	if (utask->state == UTASK_BP_HIT) {
+		utask->state = UTASK_SSTEP;
+		u = ppt->uprobe;
+		if (u && u->handler)
+			u->handler(u, regs);
+
+		if (!pre_ssout(ppt, regs))
+			arch_uprobe_enable_sstep(regs);
+	} else if (utask->state == UTASK_SSTEP) {
+		if (sstep_complete(regs, ppt)) {
+			put_probept(ppt);
+			utask->active_ppt = NULL;
+			utask->state = UTASK_RUNNING;
+			arch_uprobe_disable_sstep(regs);
+		}
+	}
+}
+
+/*
+ * uprobe_bkpt_notifier gets called from interrupt context
+ * it gets a reference to the ppt and sets TIF_UPROBE flag,
+ */
+int uprobe_bkpt_notifier(struct pt_regs *regs)
+{
+	struct uprobe_process *uproc;
+	struct uprobe_probept *ppt;

kernel/uprobes.c validate_end: · line 1334

Quoted 10 lines
kernel/uprobes.c +10 -0
+	struct uprobe_task *utask;
+	unsigned long probept;
+
+	if (!current->mm || !current->mm->uproc)
+		/* task is currently not uprobed */
+		return 0;
+
+	uproc = current->mm->uproc;
+	utask = current->utask;
+	probept = uprobes_get_bkpt_addr(regs);

Its an address, not a struct uprobe_probept * so call it addr if anything.

kernel/uprobes.c validate_end: · line 1342

Quoted 8 lines
kernel/uprobes.c +8 -0
+	ppt = find_probept(uproc, probept);
+	if (!ppt)
+		return 0;
+	get_probept(ppt);
+	if (utask) {
+		utask->active_ppt = ppt;
+		utask->state = UTASK_BP_HIT;
+	}

Right, so all this should die..

Obtain the address, lookup the vma, get the file, compute the offset inside that file -> {inode,offset}

Do the lookup in the global tree to obtain the uprobe, and possibly execute the probe handler right here in interrupt context, if it fails with -EFAULT, continue with the below:

kernel/uprobes.c validate_end: · line 1345

Quoted 3 lines
kernel/uprobes.c +3 -0
+#ifdef CONFIG_ARCH_SUPPORTS_UPROBES
+	set_thread_flag(TIF_UPROBE);
+#endif

How can we ever get here if the architecture doesn't support uprobes?

Quoted 56 lines
kernel/uprobes.c +45 -0
+	return 1;
+}
+
+/*
+ * uprobe_post_notifier gets called in interrupt context.
+ * It completes the single step operation.
+ */
+int uprobe_post_notifier(struct pt_regs *regs)
+{
+	struct uprobe_probept *ppt;
+	struct uprobe_task *utask;
+
+	if (!current->mm || !current->mm->uproc || !current->utask)
+		/* task is currently not uprobed */
+		return 0;
+
+	utask = current->utask;
+
+	ppt = utask->active_ppt;
+	if (!ppt)
+		return 0;
+
+	if (uprobes_resume_can_sleep(&ppt->user_bkpt)) {
+#ifdef CONFIG_ARCH_SUPPORTS_UPROBES
+		set_thread_flag(TIF_UPROBE);
+#endif
+		return 1;
+	}
+	if (sstep_complete(regs, ppt)) {
+		put_probept(ppt);
+		arch_uprobe_disable_sstep(regs);
+		utask->active_ppt = NULL;
+		utask->state = UTASK_RUNNING;
+		return 1;
+	}
+	return 0;
+}
+
 static int __init init_uprobes(void)
 {
 	int result = 0;
@@ -752,7 +1392,14 @@ static int __init init_uprobes(void)
 	if (arch->ip_advancement_by_bkpt_insn > arch->max_insn_bytes)
 		result = bad_arch_param("ip_advancement_by_bkpt_insn",
 				arch->ip_advancement_by_bkpt_insn);
+
+	register_die_notifier(&uprobes_exception_nb);
 	return result;
 }
 
+static void __exit exit_uprobes(void)
+{
+}
+
 module_init(init_uprobes);
+module_exit(exit_uprobes);
maintainer
#28 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 30 lines · Peter Zijlstra
Quoted 17 lines
kernel/uprobes.c +17 -0
+void uprobe_notify_resume(struct pt_regs *regs)
+{
+     struct uprobe_process *uproc;
+     struct uprobe_probept *ppt;
+     struct uprobe_task *utask;
+     struct uprobe *u;
+     unsigned long probept;
+
+     utask = current->utask;
+     uproc = current->mm->uproc;
+     if (unlikely(!utask)) {
+             utask = add_utask(uproc);
+
+             /* Failed to allocate utask for the current task. */
+             BUG_ON(!utask);
+             probept = uprobes_get_bkpt_addr(regs);
+             ppt = find_probept(uproc, probept);

kernel/uprobes.c validate_end: · line 1297

Quoted 10 lines
kernel/uprobes.c +10 -0
+
+             /*
+              * The probept was refcounted in uprobe_bkpt_notifier;
+              * Hence it would be mysterious to miss ppt now
+              */
+             WARN_ON(!ppt);
+             utask->active_ppt = ppt;
+             utask->state = UTASK_BP_HIT;
+     } else
+             ppt = utask->active_ppt;

You can replace this with:

Quoted 8 lines

addr = instruction_pointer(task_pt_regs(current)) -
ip_advancement_by_brkpt_insn;

and then proceed from there like described below to obtain the struct uprobe.

You can infer the SS/HIT state by checking if the user-addr is in the XOL area or not.

Right, so one problem I overlooked is that you need to have the actual probe to compute the jump address, but that could be fixed by implementing boosted probes.

Quoted 49 lines
Quoted 26 lines
kernel/uprobes.c +26 -0
+     if (utask->state == UTASK_BP_HIT) {
+             utask->state = UTASK_SSTEP;
+             u = ppt->uprobe;
+             if (u && u->handler)
+                     u->handler(u, regs);
+
+             if (!pre_ssout(ppt, regs))
+                     arch_uprobe_enable_sstep(regs);
+     } else if (utask->state == UTASK_SSTEP) {
+             if (sstep_complete(regs, ppt)) {
+                     put_probept(ppt);
+                     utask->active_ppt = NULL;
+                     utask->state = UTASK_RUNNING;
+                     arch_uprobe_disable_sstep(regs);
+             }
+     }
+}
+
+/*
+ * uprobe_bkpt_notifier gets called from interrupt context
+ * it gets a reference to the ppt and sets TIF_UPROBE flag,
+ */
+int uprobe_bkpt_notifier(struct pt_regs *regs)
+{
+     struct uprobe_process *uproc;
+     struct uprobe_probept *ppt;

kernel/uprobes.c validate_end: · line 1334

Quoted 10 lines
kernel/uprobes.c +10 -0
+     struct uprobe_task *utask;
+     unsigned long probept;
+
+     if (!current->mm || !current->mm->uproc)
+             /* task is currently not uprobed */
+             return 0;
+
+     uproc = current->mm->uproc;
+     utask = current->utask;
+     probept = uprobes_get_bkpt_addr(regs);

Its an address, not a struct uprobe_probept * so call it addr if anything.

kernel/uprobes.c validate_end: · line 1342

Quoted 8 lines
kernel/uprobes.c +8 -0
+     ppt = find_probept(uproc, probept);
+     if (!ppt)
+             return 0;
+     get_probept(ppt);
+     if (utask) {
+             utask->active_ppt = ppt;
+             utask->state = UTASK_BP_HIT;
+     }
Quoted 4 lines

Right, so all this should die..

Obtain the address, lookup the vma, get the file, compute the offset inside that file -> {inode,offset}

Except we need to stabilize the vma tree to do the lookup and that currently requires mmap_sem, I guess until we get Nick's per-pte vma-tree we could fudge that by adding a spinlock around the rb_tree modifications -- I've got a patch for that somewhere I think.

Quoted 12 lines

Do the lookup in the global tree to obtain the uprobe, and possibly execute the probe handler right here in interrupt context, if it fails with -EFAULT, continue with the below:

kernel/uprobes.c validate_end: · line 1345

Quoted 3 lines
kernel/uprobes.c +3 -0
+#ifdef CONFIG_ARCH_SUPPORTS_UPROBES
+     set_thread_flag(TIF_UPROBE);
+#endif

How can we ever get here if the architecture doesn't support uprobes?

Quoted 2 lines
(quoted diff) +2 -0
+     return 1;
+} 
#29 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

In reply to Peter Zijlstra
Quoted 9 lines · Peter Zijlstra
Quoted 4 lines · Srikar Dronamraju

TODO:
1. Allow multiple probes at a probepoint.
2. Booster probes.
3. Allow probes to be inherited across fork.

I wouldn't worry about that, focus on inode attached probes and you get fork for free.

I am working on the file based probing. It compiles but havent got it to test it yet, I can post the patch if you are interested. It should achieve similar to inode probing.

However I would have an issue with making inode based probing the default.
1. Making all probing based on inode can be a performance hog.

2. Since unlike kernel space, every process has a different space, so why would we have to insert breakpoints in each of its process space if we are not interested in them.

3. Ingo has a requirement for allowing normal users to use uprobes thro perf. When this feature gets implemented, we have to be careful about a normal users trying to just trace their application resulting in it hitting performance all other users.

For example: one user places a probe on /usr/lib/libc.so: malloc
- Another normal users looks at the current userspace probes and constructs a program that just does malloc/free just to degrade the performance of the system.

- user could be interested in just one process which could be calling malloc just 10 times. However during the same time there are 1000 processes which could all together call 100000 times during the same time.

So even when we allow file based tracing across the system, it should be restricted to just the root user.

As we discussed in previous discussions, Inode based tracing wasnt accepted back in 2006. May be the approach was a problem then but what was suggested then was pid based tracing.

Quoted 6 lines
Quoted 6 lines
arch/Kconfig +0 -0
index 87bd26b..c8c8e3f 100644
@@ -49,6 +49,7 @@ config OPTPROBES
 
Quoted 10 lines

arch/Kconfig config OPTPROBES · line 55

Quoted 6 lines
arch/Kconfig +1 -0
 config UPROBES
 	bool "User-space probes (EXPERIMENTAL)"
+	default n
 	depends on ARCH_SUPPORTS_UPROBES
 	depends on MMU
 	help

Seems like a weird place for this hunk, does this want to live elsewhere?

Okay, will cleanup.

Quoted 6 lines

arch/Kconfig

Quoted 4 lines
arch/Kconfig +4 -0
+#ifdef CONFIG_UPROBES
+	if (unlikely(current->utask))
+		uprobe_free_utask(current);
+#endif

A nicer way is to provide flush_uprobes() unconditionally.

Okay will do

Quoted 9 lines

arch/Kconfig

Quoted 5 lines
arch/Kconfig +3 -0
+#ifdef CONFIG_UPROBES
+	struct uprobe_process *uproc;	/* per mm uprobes info */
+#endif
 };

I find the _process postfix a bit weird in this context, how about something like:

Quoted 3 lines

struct mm_uprobes *mm_uprobes;

instead?

Okay, will do

Quoted 12 lines

arch/Kconfig struct task_struct { · line 1502

Quoted 9 lines
arch/Kconfig +3 -0
@@ -1496,6 +1496,9 @@ struct task_struct {
 		unsigned long memsw_bytes; /* uncharged mem+swap usage */
 	} memcg_batch;
 #endif
+#ifdef CONFIG_UPROBES
+	struct uprobe_task *utask;
+#endif
 };

Make that:

Quoted 4 lines
	struct uprobe_task_state uprobe_state;

And provide an empty struct for !CONFIG_UPROBE, see below.

Okay, will do

Quoted 10 lines

arch/Kconfig struct task_struct {

Quoted 8 lines
arch/Kconfig +7 -0
+/* This is what the user supplies us. */
+struct uprobe {
+	/*
+	 * The pid of the probed process.  Currently, this can be the
+	 * thread ID (task->pid) of any active thread in the process.
+	 */
+	pid_t pid;

Would fail for pid namespaces I guess...

Can you explain a bit more?

Quoted 9 lines
Quoted 7 lines
arch/Kconfig +6 -0
+	/* Location of the probepoint */
+	unsigned long vaddr;
+
+	/* Handler to run when the probepoint is hit */
+	void (*handler)(struct uprobe*, struct pt_regs*);
+};
Quoted 4 lines
Quoted 2 lines

+/*
+ * uprobe_process -- not a user-visible struct.

Seems like a weird comment for kernel code..

Okay, will cleanup.

Quoted 10 lines

arch/Kconfig

Quoted 3 lines
arch/Kconfig +2 -0
+	/* lock held while traversing/modifying uprobe_list and n_ppts */
+	spinlock_t pptlist_lock;	/* protects uprobe_list */

Its customary to write it like:

	spinlock_t	 list_lock; /* protects uprobe_list, nr_uprobes */
	struct list_head uprobe_list;
	int		 nr_uprobes;

Okay, will do

Quoted 12 lines

arch/Kconfig

Quoted 9 lines
arch/Kconfig +9 -0
+
+	/* number of probept allocated for this process */
+	int n_ppts;
+
+	/*
+	 * Manages slots for instruction-copies to be single-stepped
+	 * out of line.
+	 */
+	void *xol_area;

Why void * and not simply:

Quoted 1 line
	struct uprobes_xol_area xol_area;

Okay, will do

Quoted 13 lines

That struct is small enough and you only get one per mm and saves you an allocation/pointer-chase.

arch/Kconfig

Quoted 8 lines
arch/Kconfig +8 -0
+};
+
+/*
+ * uprobe_probept -- not a user-visible struct.
+ * A uprobe_probept represents a probepoint.
+ * Guarded by uproc->lock.
+ */
+struct uprobe_probept {

you really got a way with names, uprobe_point would be so much better.

Okay,

Quoted 22 lines
Quoted 7 lines
arch/Kconfig +6 -0
+	/* breakpoint/XOL details */
+	struct user_bkpt user_bkpt;
+
+	/*
+	 * ppt goes in the uprobe_process->uprobe_table when registered --
+	 * even before the breakpoint has been inserted.

arch/Kconfig

Quoted 10 lines
arch/Kconfig +10 -0
+	 */
+	struct list_head ut_node;
+
+	atomic_t refcount;
+
+	/* The parent uprobe_process */
+	struct uprobe_process *uproc;
+
+	struct uprobe *uprobe;
+};

So this thing is a link between the process and the probe, I'm not quite sure what you need the refcount for, it seems to me you can only have on of these per process/probe combination.

Quoted 4 lines

If you had used inode/offset based probes they would have been unique in the system and you could have had an {inode,offset} indexed global tree (or possibly a tree per inode, but that would mean adding to the inode structure, which I think is best avoided).

Unlike kernel probing, uprobes has a disadvantage.
Lets assume that the request for removing a probepoint when some of the threads have actually hit the probe. Because the handlers in uprobes can sleep, we cant remove the probepoint at the same time as the request for the removing the probe. This is where refcount steps in and helps us to decide when we can remove the probepoint. Even inoode based tracing or file based tracing would need it.

Quoted 19 lines

That would also reduce the mm state to purely the xol area, no need to manage this process to probe map.

Quoted 15 lines
arch/Kconfig +15 -0
+enum uprobe_task_state {
+	UTASK_RUNNING,
+	UTASK_BP_HIT,
+	UTASK_SSTEP
+};
+
+/*
+ * uprobe_utask -- not a user-visible struct.
+ * Corresponds to a thread in a probed process.
+ * Guarded by uproc->mutex.
+ */
+struct uprobe_task {
+	struct user_bkpt_task_arch_info arch_info;
+
+	enum uprobe_task_state state;
Quoted 8 lines

arch/Kconfig

Quoted 3 lines
arch/Kconfig +3 -0
+
+	struct uprobe_probept *active_ppt;
+};

I would be thinking you can obtain the active probe point from the address the task is stuck at and the state seems fairly redundant. Which leaves you with the arch state, which afaict is exactly as large as the pointer currently in the task struct.

Lets assume the thread is about to singlestep (or has singlestepped) So the instruction pointer is pointing to one of the slot (or it could be pointing to some other arbitrary address if it has singlestepped lets say a jump instruction).

We could get the active probe point from the address the task is stuck if the instruction pointers happens to be pointing to slots. But for that we would have to maintain a relation between slots and the current probepoint it is servicing. I think its easier to cache the active_probept then try to maintain this relationship. Moreover we are never certain in some cases where the underlying instruction happened to be a jump.

state is needed so that we know at do_notify_resume time whether the thread should singlestep or has already singlestep.
Do you see a way to determine in do_notify_resume if the thread is singlestepping or not. I dont think the instruction pointer can determine if we are about to singlestep or have already singlestepped.

<snipped>

Quoted 9 lines
Quoted 9 lines
arch/Kconfig +6 -0
 	perf_event_fork(p);
+#ifdef CONFIG_UPROBES
+	if ((current->mm) && !(clone_flags & CLONE_VM)) {
+		if (unlikely(current->mm->uproc))
+			uprobe_handle_fork(p);
+	}
+#endif
 	return p;
Quoted 4 lines
Quoted 1 line

bad_fork_free_pid:

All that can be replaced by unconditional functions, simply stub them out for !CONFIG_UPROBE.

Okay.

<snipped>

Quoted 9 lines
Quoted 8 lines

/*
* xol_get_insn_slot - If user_bkpt was not allocated a slot, then
- * allocate a slot. If uprobes_insert_bkpt is already called, (i.e
+ * allocate a slot. If insert_bkpt is already called, (i.e
* user_bkpt.vaddr != 0) then copy the instruction into the slot.
* @user_bkpt: probepoint information
* @xol_area refers the unique per process uprobes_xol_area for

Quoted 3 lines

Wandering hunks, these seem to want to get folded back to wherever the original text comes from..

Okay, will check and cleanup.

Quoted 4 lines
Quoted 4 lines
arch/Kconfig +0 -0
@@ -741,6 +745,642 @@ validate_end:
 }
 /* end of slot allocation for XOL */
 
Quoted 12 lines

arch/Kconfig validate_end: · line 757

Quoted 10 lines
arch/Kconfig +10 -0
+
+struct notifier_block uprobes_exception_nb = {
+	.notifier_call = uprobes_exception_notify,
+	.priority = 0x7ffffff0,
+};
+
+typedef void (*uprobe_handler_t)(struct uprobe*, struct pt_regs*);
+
+/* Guards lookup, creation, and deletion of uproc. */
+static DEFINE_MUTEX(uprobe_mutex);

uproc is per mm, why a global mutex?

yes, uproc is per mm but gets created when the first probe on that process gets registered.
Do you have anyother lock that you have in mind?
I could have used the mmap_sem, but I am not sure if we should be taking a write lock on the mmap_sem.

Quoted 13 lines

arch/Kconfig validate_end: · line 767

Quoted 12 lines
arch/Kconfig +10 -0
+/*
+ * Fork callback: The current task has spawned a process.
+ * NOTE: For now, we don't pass on uprobes from the parent to the
+ * child. We now do the necessary clearing of breakpoints in the
+ * child's address space.
+ * This function handles the case where vm is not shared between
+ * the parent and the child.
+ *
+ * TODO:
+ *	- Provide option for child to inherit uprobes.
Quoted 1 line

Don't bother with that...

I think it would be needed down the line. Lets keep it in TODO for now.

Quoted 12 lines
Quoted 12 lines
arch/Kconfig +11 -0
+ */
+void uprobe_handle_fork(struct task_struct *child)
+{
+	struct uprobe_process *uproc;
+	struct uprobe_probept *ppt;
+	int ret;
+
+	uproc = current->mm->uproc;
+
+	/*
+	 * New process spawned by parent but not sharing the same mm.
Quoted 8 lines

arch/Kconfig validate_end: · line 783

Quoted 5 lines
arch/Kconfig +5 -0
+	 * Remove the probepoints in the child's text.
+	 *
+	 * We also hold the uproc->mutex for the parent - so no
+	 * new uprobes will be registered 'til we return.
+	 */

The grand thing about not having any of this process state is that you dont need to clean it up either..

If we had done inode based tracing and a process that has breakpoints forks, wont we have to recreate the breakpoint metadata for the child process? I dont see the child calling mmap. When and how would be the probepoint data, user_bkpt data for the breakpoints, get replicated/linked to the child?

Quoted 20 lines
Quoted 7 lines
arch/Kconfig +7 -0
+	if (unlikely(!utask)) {
+		utask = add_utask(uproc);
+
+		/* Failed to allocate utask for the current task. */
+		BUG_ON(!utask);
+		probept = uprobes_get_bkpt_addr(regs);
+		ppt = find_probept(uproc, probept);

arch/Kconfig validate_end: · line 800

Quoted 10 lines
arch/Kconfig +10 -0
+
+		/*
+		 * The probept was refcounted in uprobe_bkpt_notifier;
+		 * Hence it would be mysterious to miss ppt now
+		 */
+		WARN_ON(!ppt);
+		utask->active_ppt = ppt;
+		utask->state = UTASK_BP_HIT;
+	} else
+		ppt = utask->active_ppt;

You can replace this with:

Quoted 2 lines

addr = instruction_pointer(task_pt_regs(current)) -
ip_advancement_by_brkpt_insn;

uprobes_get_bkpt_addr does this exactly. However after we have singlestepped, we cant rely on this. Also how do we know if we have already singlestepped or not? After singlestepping we may still be pointing to some slot or the instruction pointer could be pointing something completely different.

Quoted 38 lines

and then proceed from there like described below to obtain the struct uprobe.

You can infer the SS/HIT state by checking if the user-addr is in the XOL area or not.

Quoted 31 lines
arch/Kconfig +31 -0
+	if (utask->state == UTASK_BP_HIT) {
+		utask->state = UTASK_SSTEP;
+		u = ppt->uprobe;
+		if (u && u->handler)
+			u->handler(u, regs);
+
+		if (!pre_ssout(ppt, regs))
+			arch_uprobe_enable_sstep(regs);
+	} else if (utask->state == UTASK_SSTEP) {
+		if (sstep_complete(regs, ppt)) {
+			put_probept(ppt);
+			utask->active_ppt = NULL;
+			utask->state = UTASK_RUNNING;
+			arch_uprobe_disable_sstep(regs);
+		}
+	}
+}
+
+/*
+ * uprobe_bkpt_notifier gets called from interrupt context
+ * it gets a reference to the ppt and sets TIF_UPROBE flag,
+ */
+int uprobe_bkpt_notifier(struct pt_regs *regs)
+{
+	struct uprobe_process *uproc;
+	struct uprobe_probept *ppt;
+	struct uprobe_task *utask;
+	unsigned long probept;
+
+	if (!current->mm || !current->mm->uproc)
+		/* task is currently not uprobed */
Quoted 8 lines

arch/Kconfig validate_end: · line 836

Quoted 5 lines
arch/Kconfig +5 -0
+		return 0;
+
+	uproc = current->mm->uproc;
+	utask = current->utask;
+	probept = uprobes_get_bkpt_addr(regs);

Its an address, not a struct uprobe_probept * so call it addr if anything.

Okay,

Quoted 12 lines

arch/Kconfig validate_end: · line 844

Quoted 9 lines
arch/Kconfig +8 -0
+	ppt = find_probept(uproc, probept);
+	if (!ppt)
+		return 0;
+	get_probept(ppt);
+	if (utask) {
+		utask->active_ppt = ppt;
+		utask->state = UTASK_BP_HIT;
+	}

Right, so all this should die..

Quoted 6 lines

Obtain the address, lookup the vma, get the file, compute the offset inside that file -> {inode,offset}

Do the lookup in the global tree to obtain the uprobe, and possibly execute the probe handler right here in interrupt context, if it fails with -EFAULT, continue with the below:

We dropped running the handler in interrupt context based on comments to my previous postings. It not only makes it complex at the time of handling the probe but we didnt see a difference when we compare the time it took to run the handler in task context to running the handler in interrupt context. I had even posted the timing info when register_uprobes was exported.

Quoted 6 lines

arch/Kconfig validate_end: · line 847

Quoted 4 lines
arch/Kconfig +3 -0
+#ifdef CONFIG_ARCH_SUPPORTS_UPROBES
+	set_thread_flag(TIF_UPROBE);
+#endif

How can we ever get here if the architecture doesn't support uprobes?

Right, this is not needed, the #ifdefs were added just allow to compile kernel/uprobes.o even when CONFIG_UPROBES wasnt enabled. There was a comment to one of my earlier posting on LKML about compiling kernel/uprobe.o when CONFIG_UPROBES wasnt enabled failed.

I am more than happy to remove the #ifdef.

Quoted 4 lines
Quoted 4 lines
arch/Kconfig +3 -0
+	return 1;
+}
+
maintainer
#30 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 12 lines · Srikar Dronamraju
Quoted 9 lines · Peter Zijlstra
Quoted 4 lines · Srikar Dronamraju

TODO:
1. Allow multiple probes at a probepoint.
2. Booster probes.
3. Allow probes to be inherited across fork.

I wouldn't worry about that, focus on inode attached probes and you get fork for free.

Quoted 7 lines

I am working on the file based probing. It compiles but havent got it to test it yet, I can post the patch if you are interested. It should achieve similar to inode probing.

However I would have an issue with making inode based probing the default.
1. Making all probing based on inode can be a performance hog.

How so? You can add filters if you want.

Quoted 3 lines

2. Since unlike kernel space, every process has a different space, so why would we have to insert breakpoints in each of its process space if we are not interested in them.

You don't have to, but you can. The problem I have with this stuff is that it makes the pid thing a primary interface, whereas it should be one of many filter possibilities.

Quoted 10 lines

3. Ingo has a requirement for allowing normal users to use uprobes thro perf. When this feature gets implemented, we have to be careful about a normal users trying to just trace their application resulting in it hitting performance all other users.

For example: one user places a probe on /usr/lib/libc.so: malloc
- Another normal users looks at the current userspace probes and constructs a program that just does malloc/free just to degrade the performance of the system.

Quoted 4 lines

- user could be interested in just one process which could be calling malloc just 10 times. However during the same time there are 1000 processes which could all together call 100000 times during the same time.

See the filter thing.

Quoted 11 lines
Quoted 9 lines

include/linux/uprobes.h extern int post_xol(struct task_struct *tsk, · line 180

Quoted 7 lines
include/linux/uprobes.h +7 -0
+/* This is what the user supplies us. */
+struct uprobe {
+	/*
+	 * The pid of the probed process.  Currently, this can be the
+	 * thread ID (task->pid) of any active thread in the process.
+	 */
+	pid_t pid;

Would fail for pid namespaces I guess...

Can you explain a bit more?

What pid namespace will you interpret that number in?

Quoted 34 lines
Quoted 29 lines
Quoted 14 lines
include/linux/uprobes.h +12 -0
+	/* Location of the probepoint */
+	unsigned long vaddr;
+
+	/* Handler to run when the probepoint is hit */
+	void (*handler)(struct uprobe*, struct pt_regs*);
+};
 
 
+	/* breakpoint/XOL details */
+	struct user_bkpt user_bkpt;
+
+	/*
+	 * ppt goes in the uprobe_process->uprobe_table when registered --
+	 * even before the breakpoint has been inserted.

include/linux/uprobes.h extern int post_xol(struct task_struct *tsk, · line 244

Quoted 10 lines
include/linux/uprobes.h +10 -0
+	 */
+	struct list_head ut_node;
+
+	atomic_t refcount;
+
+	/* The parent uprobe_process */
+	struct uprobe_process *uproc;
+
+	struct uprobe *uprobe;
+};

So this thing is a link between the process and the probe, I'm not quite sure what you need the refcount for, it seems to me you can only have on of these per process/probe combination.

Quoted 4 lines

If you had used inode/offset based probes they would have been unique in the system and you could have had an {inode,offset} indexed global tree (or possibly a tree per inode, but that would mean adding to the inode structure, which I think is best avoided).

Quoted 7 lines

Unlike kernel probing, uprobes has a disadvantage.
Lets assume that the request for removing a probepoint when some of the threads have actually hit the probe. Because the handlers in uprobes can sleep, we cant remove the probepoint at the same time as the request for the removing the probe. This is where refcount steps in and helps us to decide when we can remove the probepoint. Even inoode based tracing or file based tracing would need it.

Stick the refcount in the actual struct uprobe instead?

Quoted 41 lines
Quoted 19 lines

That would also reduce the mm state to purely the xol area, no need to manage this process to probe map.

Quoted 15 lines
include/linux/uprobes.h +15 -0
+enum uprobe_task_state {
+	UTASK_RUNNING,
+	UTASK_BP_HIT,
+	UTASK_SSTEP
+};
+
+/*
+ * uprobe_utask -- not a user-visible struct.
+ * Corresponds to a thread in a probed process.
+ * Guarded by uproc->mutex.
+ */
+struct uprobe_task {
+	struct user_bkpt_task_arch_info arch_info;
+
+	enum uprobe_task_state state;
Quoted 8 lines

include/linux/uprobes.h extern int post_xol(struct task_struct *tsk, · line 263

Quoted 3 lines
include/linux/uprobes.h +3 -0
+
+	struct uprobe_probept *active_ppt;
+};

I would be thinking you can obtain the active probe point from the address the task is stuck at and the state seems fairly redundant. Which leaves you with the arch state, which afaict is exactly as large as the pointer currently in the task struct.

Lets assume the thread is about to singlestep (or has singlestepped) So the instruction pointer is pointing to one of the slot (or it could be pointing to some other arbitrary address if it has singlestepped lets say a jump instruction).

We could get the active probe point from the address the task is stuck if the instruction pointers happens to be pointing to slots. But for that we would have to maintain a relation between slots and the current probepoint it is servicing. I think its easier to cache the active_probept then try to maintain this relationship. Moreover we are never certain in some cases where the underlying instruction happened to be a jump.

Quoted 5 lines

state is needed so that we know at do_notify_resume time whether the thread should singlestep or has already singlestep.
Do you see a way to determine in do_notify_resume if the thread is singlestepping or not. I dont think the instruction pointer can determine if we are about to singlestep or have already singlestepped.

The to singlestep or not would be implied by the IP pointing to the start of a slot or not, but yes, I guess that as long as you do singlestep you need some state.. sucks though. Boosted probes are much nicer, they don't need that extra arch storage either, they can simply push/pop the register.

Quoted 17 lines
Quoted 4 lines
Quoted 4 lines
kernel/uprobes.c +0 -0
@@ -741,6 +745,642 @@ validate_end:
 }
 /* end of slot allocation for XOL */
 
Quoted 12 lines

kernel/uprobes.c validate_end: · line 757

Quoted 10 lines
kernel/uprobes.c +10 -0
+
+struct notifier_block uprobes_exception_nb = {
+	.notifier_call = uprobes_exception_notify,
+	.priority = 0x7ffffff0,
+};
+
+typedef void (*uprobe_handler_t)(struct uprobe*, struct pt_regs*);
+
+/* Guards lookup, creation, and deletion of uproc. */
+static DEFINE_MUTEX(uprobe_mutex);

uproc is per mm, why a global mutex?

Quoted 5 lines

yes, uproc is per mm but gets created when the first probe on that process gets registered.
Do you have anyother lock that you have in mind?
I could have used the mmap_sem, but I am not sure if we should be taking a write lock on the mmap_sem.

No particular other lock in mind, you could cmpxchg the pointer if that's all you need it for. The problem is that if you want inode based probes without a filter this will become a rather hot lock on fork().

Quoted 21 lines
Quoted 12 lines
Quoted 12 lines
kernel/uprobes.c +11 -0
+ */
+void uprobe_handle_fork(struct task_struct *child)
+{
+	struct uprobe_process *uproc;
+	struct uprobe_probept *ppt;
+	int ret;
+
+	uproc = current->mm->uproc;
+
+	/*
+	 * New process spawned by parent but not sharing the same mm.
Quoted 8 lines

kernel/uprobes.c validate_end: · line 1248

Quoted 5 lines
kernel/uprobes.c +5 -0
+	 * Remove the probepoints in the child's text.
+	 *
+	 * We also hold the uproc->mutex for the parent - so no
+	 * new uprobes will be registered 'til we return.
+	 */

The grand thing about not having any of this process state is that you dont need to clean it up either..

Quoted 5 lines

If we had done inode based tracing and a process that has breakpoints forks, wont we have to recreate the breakpoint metadata for the child process? I dont see the child calling mmap. When and how would be the probepoint data, user_bkpt data for the breakpoints, get replicated/linked to the child?

What meta-data? You can find the uprobe itself from inode:offset, and you know the return address from the trap site + orig ins size.

You don't need the probepoint, and there'd be only a single uprobe instance.

The Xol area can be found at current->mm->xol_area, I don't think you need more to process a uprobe.

Quoted 20 lines
Quoted 20 lines
Quoted 7 lines
kernel/uprobes.c +7 -0
+	if (unlikely(!utask)) {
+		utask = add_utask(uproc);
+
+		/* Failed to allocate utask for the current task. */
+		BUG_ON(!utask);
+		probept = uprobes_get_bkpt_addr(regs);
+		ppt = find_probept(uproc, probept);

kernel/uprobes.c validate_end: · line 1297

Quoted 10 lines
kernel/uprobes.c +10 -0
+
+		/*
+		 * The probept was refcounted in uprobe_bkpt_notifier;
+		 * Hence it would be mysterious to miss ppt now
+		 */
+		WARN_ON(!ppt);
+		utask->active_ppt = ppt;
+		utask->state = UTASK_BP_HIT;
+	} else
+		ppt = utask->active_ppt;

You can replace this with:

Quoted 8 lines
Quoted 2 lines

addr = instruction_pointer(task_pt_regs(current)) -
ip_advancement_by_brkpt_insn;

uprobes_get_bkpt_addr does this exactly. However after we have singlestepped, we cant rely on this. Also how do we know if we have already singlestepped or not? After singlestepping we may still be pointing to some slot or the instruction pointer could be pointing something completely different.

if its not the start of a slot, you've already single-stepped. Ideally you'd directly implement boosted probes, but I realize that's a tad more work than keeping state.

Quoted 18 lines
Quoted 11 lines

kernel/uprobes.c validate_end: · line 1342

Quoted 8 lines
kernel/uprobes.c +8 -0
+	ppt = find_probept(uproc, probept);
+	if (!ppt)
+		return 0;
+	get_probept(ppt);
+	if (utask) {
+		utask->active_ppt = ppt;
+		utask->state = UTASK_BP_HIT;
+	}

Right, so all this should die..

Quoted 6 lines

Obtain the address, lookup the vma, get the file, compute the offset inside that file -> {inode,offset}

Do the lookup in the global tree to obtain the uprobe, and possibly execute the probe handler right here in interrupt context, if it fails with -EFAULT, continue with the below:

Quoted 6 lines

We dropped running the handler in interrupt context based on comments to my previous postings. It not only makes it complex at the time of handling the probe but we didnt see a difference when we compare the time it took to run the handler in task context to running the handler in interrupt context. I had even posted the timing info when register_uprobes was exported.

Is that because of the singlestep overhead? With boosted probes I would think it'd be much faster to take 1 trap, deal with it and continue execution, than to frob tons of kernel code in between.

A bit more about these filter thingies, add a method to struct uprobe, something like int uprobe::wants_probe(struct task_struct *p) and add a single bit to task_struct (there's a few bitfields with holes in there).

The on clone()/mmap() call the relevant wants_probe() methods, if one is true, set the task_struct::has_uprobe flag and install the probes.

If nothing in the process wants probing, you'll never install the probes and nothing ever triggers, of only one of many tasks in the process gets tagged, you'll have to look up the probe anyway to know where to continue, but you can avoid calling the handler.

#31 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 6 lines · Peter Zijlstra
Quoted 4 lines

However I would have an issue with making inode based probing the default.
1. Making all probing based on inode can be a performance hog.

How so? You can add filters if you want.

The breakpoint exception and singlestep account for a substaintial time
of the uprobes probe handling. With increasing number of breakpoint hits and singlesteps, wouldnt the overall load increase?

Quoted 8 lines
Quoted 4 lines

2. Since unlike kernel space, every process has a different space, so why would we have to insert breakpoints in each of its process space if we are not interested in them.

You don't have to, but you can. The problem I have with this stuff is that it makes the pid thing a primary interface, whereas it should be one of many filter possibilities.

I think the otherway,
Why instrument a process and filter it out, if we are not interested in it. While instrumenting kernel, we dont have this flexibility. So having a pid based filter is the right thing to do for kernel based tracing.

If we can get the per process based tracing right, we can build higher lever stuff including the file based tracing easily.

All tools/debuggers in the past have all worked with process based tracing.

Tools like gdb can actually use the displaced singlestepping feature that uprobes provides. Some gdb developers have told on LKML earlier that they would be willing to use displaced singlestepping if the kernel provides an API that they can use.

Also about the security perspective when allowing normal users use perf to trace their applications. Using this model, we dont have to write extra filters to limit them. These filters might allow uprobe handlers on only tasks belonging to that user. However it still interrupts task of other users. And as I said earlier, breakpoint exception and singlestepping actually make a very very substantial part of the handling. The actual uprobe handler depending on what it does might actually be very minimal part of the uprobe probe handling.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

include/linux/uprobes.h extern int post_xol(struct task_struct *tsk, · line 180

Quoted 2 lines
include/linux/uprobes.h +2 -0
+	 */
+	pid_t pid;

Would fail for pid namespaces I guess...

Can you explain a bit more?

What pid namespace will you interpret that number in?

Same namespace as the requestor. i.e whichever name space register_uprobe/unregister_uprobe is called.

Quoted 10 lines
Quoted 8 lines

Unlike kernel probing, uprobes has a disadvantage.
Lets assume that the request for removing a probepoint when some of the threads have actually hit the probe. Because the handlers in uprobes can sleep, we cant remove the probepoint at the same time as the request for the removing the probe. This is where refcount steps in and helps us to decide when we can remove the probepoint. Even inoode based tracing or file based tracing would need it.

Stick the refcount in the actual struct uprobe instead?

What if the called does something like this when one or more threads are processing the breakpoint. unregister_uprobe(u);
kfree(u);

In the current implementation, the probepoint structure might be released much later after the uprobe structure is released. Unlike uprobe struct, probepoint structure is allocated by uprobes sub-system and it knows how to release it cleanly. However we dont have any idea about when and how uprobe struct can be released.

Quoted 7 lines
Quoted 6 lines

state is needed so that we know at do_notify_resume time whether the thread should singlestep or has already singlestep.
Do you see a way to determine in do_notify_resume if the thread is singlestepping or not. I dont think the instruction pointer can determine if we are about to singlestep or have already singlestepped.

Quoted 5 lines

The to singlestep or not would be implied by the IP pointing to the start of a slot or not, but yes, I guess that as long as you do singlestep you need some state.. sucks though. Boosted probes are much nicer, they don't need that extra arch storage either, they can simply push/pop the register.

Yes, I agree, we may not need the state after boosted probes. I am not sure at this time if we can do boosted probes for all instructions. I think we can discuss about boosted probes later.

Quoted 12 lines
Quoted 11 lines
Quoted 5 lines

kernel/uprobes.c validate_end: · line 757

Quoted 3 lines
kernel/uprobes.c +3 -0
+
+/* Guards lookup, creation, and deletion of uproc. */
+static DEFINE_MUTEX(uprobe_mutex);

uproc is per mm, why a global mutex?

yes, uproc is per mm but gets created when the first probe on that process gets registered.
Do you have anyother lock that you have in mind?
I could have used the mmap_sem, but I am not sure if we should be taking a write lock on the mmap_sem.

Quoted 4 lines

No particular other lock in mind, you could cmpxchg the pointer if that's all you need it for. The problem is that if you want inode based probes without a filter this will become a rather hot lock on fork().

I can certainly try cmpxchg().

Quoted 8 lines
Quoted 7 lines

We dropped running the handler in interrupt context based on comments to my previous postings. It not only makes it complex at the time of handling the probe but we didnt see a difference when we compare the time it took to run the handler in task context to running the handler in interrupt context. I had even posted the timing info when register_uprobes was exported.

Quoted 4 lines

Is that because of the singlestep overhead? With boosted probes I would think it'd be much faster to take 1 trap, deal with it and continue execution, than to frob tons of kernel code in between.

The difference between running handlers in task context and running in interrupt context is the extra do_notify_resume() that gets called from task context. But we have more guarantees, flexibility and less complexity with running the handler from do_notify_resume than running the handler in interrupt context. Since do_notify_resume is the only extra thing that gets called (on the way out of the interrupt), the difference in the penalties between running the handler in task context and running the handler in interrupt context is negligible.

I would want to stick with running handlers in task context for now. We could optimize this later on depending on further results and uprobes maturing.

Quoted 6 lines

A bit more about these filter thingies, add a method to struct uprobe, something like int uprobe::wants_probe(struct task_struct *p) and add a single bit to task_struct (there's a few bitfields with holes in there).

Quoted 8 lines

The on clone()/mmap() call the relevant wants_probe() methods, if one is true, set the task_struct::has_uprobe flag and install the probes.

If nothing in the process wants probing, you'll never install the probes and nothing ever triggers, of only one of many tasks in the process gets tagged, you'll have to look up the probe anyway to know where to continue, but you can avoid calling the handler.

Yes, we can avoid calling the handler. but we still have the other penalties of breakpoint hit, searching the probe, and singlestepping. Just to clarify, I am not looking at probing per task but probing per process. So the pid field in uprobe refers to the tgid.

--
Thanks and Regards
Srikar

maintainer
#32 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 8 lines · Srikar Dronamraju
Quoted 8 lines
Quoted 7 lines

Unlike kernel probing, uprobes has a disadvantage.
Lets assume that the request for removing a probepoint when some of the threads have actually hit the probe. Because the handlers in uprobes can sleep, we cant remove the probepoint at the same time as the request for the removing the probe. This is where refcount steps in and helps us to decide when we can remove the probepoint. Even inoode based tracing or file based tracing would need it.

Quoted 6 lines
Quoted 1 line

Stick the refcount in the actual struct uprobe instead?

What if the called does something like this when one or more threads are processing the breakpoint. unregister_uprobe(u);
kfree(u);

That's what atomic_inc_unless_zero() and RCU are for.

maintainer
#33 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

In reply to Srikar Dronamraju
Quoted 7 lines · Srikar Dronamraju
Quoted 5 lines · Peter Zijlstra
Quoted 4 lines

However I would have an issue with making inode based probing the default.
1. Making all probing based on inode can be a performance hog.

Quoted 7 lines
Quoted 1 line

How so? You can add filters if you want.

The breakpoint exception and singlestep account for a substaintial time
of the uprobes probe handling. With increasing number of breakpoint hits and singlesteps, wouldnt the overall load increase?

You're really not getting it, are you? No, it would result in the exact same amount of actual breakpoints hit.

Quoted 9 lines
Quoted 8 lines
Quoted 4 lines

2. Since unlike kernel space, every process has a different space, so why would we have to insert breakpoints in each of its process space if we are not interested in them.

You don't have to, but you can. The problem I have with this stuff is that it makes the pid thing a primary interface, whereas it should be one of many filter possibilities.

Quoted 8 lines

I think the otherway,
Why instrument a process and filter it out, if we are not interested in it. While instrumenting kernel, we dont have this flexibility. So having a pid based filter is the right thing to do for kernel based tracing.

If we can get the per process based tracing right, we can build higher lever stuff including the file based tracing easily.

Creating inode based probes on top of pid based probes is terribly ugly.

Quoted 3 lines

Just to clarify, I am not looking at probing per task
but probing per process. So the pid field in uprobe refers to the tgid.

Urgh,.. I really oppose the whole pid-centric thing, if that means process wide and not per task its even worse.

#34 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 10 lines · Peter Zijlstra
Quoted 9 lines · Srikar Dronamraju
Quoted 6 lines · Peter Zijlstra
Quoted 4 lines

However I would have an issue with making inode based probing the default.
1. Making all probing based on inode can be a performance hog.

How so? You can add filters if you want.

Quoted 7 lines
Quoted 5 lines

The breakpoint exception and singlestep account for a substaintial time
of the uprobes probe handling. With increasing number of breakpoint hits and singlesteps, wouldnt the overall load increase?

You're really not getting it, are you? No, it would result in the exact same amount of actual breakpoints hit.

If there is just one instance of traced process for the inode then yes the number of breakpoints when traced with pid or based on inode would be the same. However if there are multiple instances of the traced process [example bash/zsh] (or the inode corresponds to a library that gets mapped into multiple processes example libc), and the user is interested in tracing just one instance of the process, then dont wont the inode based tracing amount to far more number of breakpoints hits?

Quoted 16 lines
Quoted 16 lines
Quoted 9 lines
Quoted 5 lines

2. Since unlike kernel space, every process has a different space, so why would we have to insert breakpoints in each of its process space if we are not interested in them.

You don't have to, but you can. The problem I have with this stuff is that it makes the pid thing a primary interface, whereas it should be one of many filter possibilities.

I think the otherway,
Why instrument a process and filter it out, if we are not interested in it. While instrumenting kernel, we dont have this flexibility. So having a pid based filter is the right thing to do for kernel based tracing.

Quoted 4 lines
Quoted 2 lines

If we can get the per process based tracing right, we can build higher lever stuff including the file based tracing easily.

Creating inode based probes on top of pid based probes is terribly ugly.

I would disagree.
Lets consider a user wants to trace his single threaded app say bash for few heavy used calls in libc say read/select systemcall stub. If this user wants to keep recording at discreet intervals. i.e record for 5 minutes, stop for 5 minutes, record again for 5 minutes, .... Can you list how you would go about inode based probe insertion / probe deletions?

Quoted 8 lines
Quoted 4 lines

Just to clarify, I am not looking at probing per task
but probing per process. So the pid field in uprobe refers to the tgid.

Urgh,.. I really oppose the whole pid-centric thing, if that means process wide and not per task its even worse.

Since breakpoints are shared across the tasks of the same process, we cant do per-task based tracing. We can only do a per process tracing and filter per-task which if the request is for per-task tracing and thats what I think you were alluding to in the filter in one of your mails. I am okay with filtering per-task within a given process.

--
Thanks and Regards
Srikar

maintainer
#35 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 10 lines · Srikar Dronamraju
Quoted 2 lines

You're really not getting it, are you? No, it would result in the exact same amount of actual breakpoints hit.

If there is just one instance of traced process for the inode then yes the number of breakpoints when traced with pid or based on inode would be the same. However if there are multiple instances of the traced process [example bash/zsh] (or the inode corresponds to a library that gets mapped into multiple processes example libc), and the user is interested in tracing just one instance of the process, then dont wont the inode based tracing amount to far more number of breakpoints hits?

Not if your filter function works.

So let me try this again, (assumes boosted probes):

struct uprobe {
struct inode *inode; /* we hold a ref */
unsigned long offset;

int (*handler)(void); /* arguments.. ? */
int (*filter)(struct task_struct *);

int insn_size; /* size of */
char insn[MAX_INSN_SIZE]; /* the original insn */

int ret_addr_offset; /* return addr offset
in the slot */
char replacement[SLOT_SIZE]; /* replacement
instructions */

atomic_t ref; /* lifetime muck */
struct rcu_head rcu;
};

static struct {
	raw_spinlock_t	tree_lock;
	rb_root		tree;
} uprobes;

static void uprobes_add(struct uprobe *uprobe)

{
	/* add to uprobes.tree, sorted on inode:offset */
}

static void uprobes_del(struct uprobe *uprobe)

{
	/* delete from uprobes.tree */
}

static struct uprobe *
uprobes_find_get(struct address_space *mapping, unsigned long offset)

{
	unsigned long flags;
	struct uprobe *uprobe;

	raw_spin_lock_irqsave(&uprobes.treelock, flags);
	uprobe = find_in_tree(&uprobes.tree);
	if (!atomic_inc_not_zero(&uprobe->ref))
		uprobe = NULL;
	raw_spin_unlock_irqrestore(&uprobes.treelock, flags);

	return uprobe;
}

static void __uprobe_free(struct rcu_head *head)

{
	struct uprobe *uprobe = container_of(head, struct uprobe, rcu);

	kfree(uprobe);
}

static void put_uprobe(struct uprobe *uprobe)

{
	if (atomic_dec_and_test(&uprobe->ref))
		call_rcu(&uprobe->rcu, __uprobe_free);
}

static inline int valid_vma(struct vm_area_struct *vma)

{
	if (!vma->vm_file)
		return 0;

	if (vma->vm_flags & (VM_READ|VM_WRITE|VM_EXEC|VM_SHARED) ==
			    (VM_READ|VM_EXEC))
		return 1;

	return 0;
}

int register_uprobe(struct uprobe *uprobe)

{
	struct vm_area_struct *vma;

	inode_get(uprobe->inode);
	atomic_set(1, &uprobe->ref);

	uprobes_add(uprobe); /* add before the rmap walk, so that 
				new mmap()s will find it too */

	for_each_rmap_vma(vma, uprobe->inode->i_mapping) {
		struct mm_struct *mm = vma->vm_mm;
		int install_probe = 0;

		if (!valid_vma(vma))
			continue;

		for_each_task_in_process(p, mm->owner) {
			if (uprobe->filter(p)) {
				p->has_uprobe = 1;
				install_probe = 1;
			}
		}

		if (install_probe) {
			mm->has_uprobes = 1;
			frob_text(uprobe, mm);
		}
	}
}

void unregister_uprobe(struct uprobe *uprobe)

{
	/* pretty much the same, except restore the original text */
	put_uprobe(uprobe);
}

void uprobe_fork(struct task_struct *child)

{
	struct vm_area_struct *vma;

	if (!child->mm->has_uprobes)	
		return;

	for_each_vma(vma, child->mm) {
		struct uprobe *uprobe;

		if (!valid_vma(vma))
			continue;

		for_each_probe_in_mapping(uprobe, vma->vm_file->f_mapping) {
			if (uprobe->filter(child)) {
				child->has_uprobe = 1;
				return;
			}
		}
	}
}

void uprobe_mmap(struct vm_area_struct *vma)

{
	struct uprobe *uprobe;

	if (!valid_vma(vma))
		return;

	for_each_probe_in_mapping(uprobe, vma->vm_file->f_mapping) {
		int install_probe = 0;

		for_each_task_in_process(p, vma->vm_mm->owner) {
			if (uprobe->filter(p)) {
				p->has_uprobe = 1;
				install_probe = 1;
			}
		}

		if (install_probe) {
			mm->has_uprobes = 1;
			frob_text(uprobe, mm);
		}
	}
}

void uprobe_hit(struct pt_regs *regs)

{
	unsigned long addr = instruction_pointer(regs);
	struct mm_struct *mm = current->mm;
	struct vm_area_struct *vma;
	unsigned long offset;

	down_read(&mm->mmap_sem);
	vma = find_vma(mm, addr);

	if (!valid_vma)
		goto fail;

	offset = addr - vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT);

	uprobe = uprobes_find_get(vma->vm_file->f_mapping, offset);
	up_read(&mm->mmap_sem);

	if (!uprobe)
		goto fail;

	if (current->has_uprobe && uprobe->filter(current))
		uprobe->handle();

	ret_addr = addr + uprobe->insn_size;

	cpu = get_cpu()
	slot = get_slot(cpu);
	memcpy(slot, uprobe->replacement, SLOT_SIZE);
	memcpy(slot + uprobe->ret_addr_offset, &ret_addr, sizeof(unsigned
long));
	set_instruction_pointer(regs, uaddr_addr_of(slot));
	put_cpu(); /* preemption notifiers would take it from here */

	put_uprobe(uprobe);
	return;

fail:
SIGTRAP
}

See, no extra traps, no funny intermediate data structures to manage, and you get the power of ->filter() to implement whatever policy you want, including simple process wide things.

#36 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 19 lines
Quoted 3 lines

multiple processes example libc), and the user is interested in tracing just one instance of the process, then dont wont the inode based tracing amount to far more number of breakpoints hits?

Not if your filter function works.

So let me try this again, (assumes boosted probes):

struct uprobe {
struct inode *inode; /* we hold a ref */
unsigned long offset;

int (*handler)(void); /* arguments.. ? */
int (*filter)(struct task_struct *);

int insn_size; /* size of */
char insn[MAX_INSN_SIZE]; /* the original insn */

Quoted 8 lines

int ret_addr_offset; /* return addr offset
in the slot */
char replacement[SLOT_SIZE]; /* replacement
instructions */

atomic_t ref; /* lifetime muck */
struct rcu_head rcu;
};

struct uprobe is a input structure. Do we want to have implementation details in it?

Quoted 16 lines
static struct {
	raw_spinlock_t	tree_lock;
	rb_root		tree;
} uprobes;

static void uprobes_add(struct uprobe *uprobe)

{
	/* add to uprobes.tree, sorted on inode:offset */
}

static void uprobes_del(struct uprobe *uprobe)

{
	/* delete from uprobes.tree */
}
Quoted 8 lines

static struct uprobe *
uprobes_find_get(struct address_space *mapping, unsigned long offset)

{
	unsigned long flags;
	struct uprobe *uprobe;

	raw_spin_lock_irqsave(&uprobes.treelock, flags);
	uprobe = find_in_tree(&uprobes.tree);

Wouldnt this be a scalability issue on bigger machines? Every probehit having to parse a global tree to figureout which uprobe it was seems a overkill.
Consider a 5000 uprobes placed on a 128 box with probes placed on heavily used functions.

Quoted 14 lines
	if (!atomic_inc_not_zero(&uprobe->ref))
		uprobe = NULL;
	raw_spin_unlock_irqrestore(&uprobes.treelock, flags);

	return uprobe;
}

static void __uprobe_free(struct rcu_head *head)

{
	struct uprobe *uprobe = container_of(head, struct uprobe, rcu);

	kfree(uprobe);
}
Quoted 4 lines

static void put_uprobe(struct uprobe *uprobe)

{
	if (atomic_dec_and_test(&uprobe->ref))
		call_rcu(&uprobe->rcu, __uprobe_free);

How are we synchronizing put_uprobe and a thread that has hit the breakpoint and searching thro global probes list?

One Nit: On probe hit we increment the ref only few times. However we are decrementing everytime. So if two probes occur on two cpus simultaneously, we have a chance of uprobe being freed after both of them are handled. (or am I missing something?)

Quoted 15 lines

}

static inline int valid_vma(struct vm_area_struct *vma)

{
	if (!vma->vm_file)
		return 0;

	if (vma->vm_flags & (VM_READ|VM_WRITE|VM_EXEC|VM_SHARED) ==
			    (VM_READ|VM_EXEC))
		return 1;

	return 0;
}

int register_uprobe(struct uprobe *uprobe)

Quoted 10 lines
{
	struct vm_area_struct *vma;

	inode_get(uprobe->inode);
	atomic_set(1, &uprobe->ref);

	uprobes_add(uprobe); /* add before the rmap walk, so that 
				new mmap()s will find it too */

	for_each_rmap_vma(vma, uprobe->inode->i_mapping) {

I understand that perf top calls perf record in a loop.
For every perf record, we would be looping thro each vma associated with the inode.
For a probe on a libc, we would iterate thro all vmas. If the tracing was per posix process, this may not be needed.

Quoted 27 lines
		struct mm_struct *mm = vma->vm_mm;
		int install_probe = 0;

		if (!valid_vma(vma))
			continue;

		for_each_task_in_process(p, mm->owner) {
			if (uprobe->filter(p)) {
				p->has_uprobe = 1;
				install_probe = 1;
			}
		}

		if (install_probe) {
			mm->has_uprobes = 1;
			frob_text(uprobe, mm);
		}
	}
}

void unregister_uprobe(struct uprobe *uprobe)

{
	/* pretty much the same, except restore the original text */
	put_uprobe(uprobe);
}

void uprobe_fork(struct task_struct *child)

Quoted 13 lines
{
	struct vm_area_struct *vma;

	if (!child->mm->has_uprobes)	
		return;

	for_each_vma(vma, child->mm) {
		struct uprobe *uprobe;

		if (!valid_vma(vma))
			continue;

		for_each_probe_in_mapping(uprobe, vma->vm_file->f_mapping) {

Are you looking at listing of uprobes per vma?
Does it again traverse the global list?

Quoted 8 lines
			if (uprobe->filter(child)) {
				child->has_uprobe = 1;
				return;
			}
		}
	}
}
Quoted 8 lines

void uprobe_mmap(struct vm_area_struct *vma)

{
	struct uprobe *uprobe;

	if (!valid_vma(vma))
		return;

	for_each_probe_in_mapping(uprobe, vma->vm_file->f_mapping) {

For each mmap, we are traversing all elements in the global tree? What would happen if we have a huge number of uprobes in a system all from one user on his app. Wont it slow down mmap for all other users?

Quoted 16 lines
		int install_probe = 0;

		for_each_task_in_process(p, vma->vm_mm->owner) {
			if (uprobe->filter(p)) {
				p->has_uprobe = 1;
				install_probe = 1;
			}
		}

		if (install_probe) {
			mm->has_uprobes = 1;
			frob_text(uprobe, mm);
		}
	}
}
Quoted 8 lines

void uprobe_hit(struct pt_regs *regs)

{
	unsigned long addr = instruction_pointer(regs);
	struct mm_struct *mm = current->mm;
	struct vm_area_struct *vma;
	unsigned long offset;

	down_read(&mm->mmap_sem);

uprobe_hit I assume is going to be called in interrupt context. I guess down_read can sleep here.

Quoted 6 lines
	vma = find_vma(mm, addr);

	if (!valid_vma)
		goto fail;

	offset = addr - vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT);

Again for every probehit, we are going through the list of vmas and checking if it has a probe which I think is unnecessary.

Nit: In some archs, the instruction pointer might be pointing to th next instruction after a breakpoint hit, we would have to adjust that.

Quoted 11 lines
	uprobe = uprobes_find_get(vma->vm_file->f_mapping, offset);
	up_read(&mm->mmap_sem);

	if (!uprobe)
		goto fail;

	if (current->has_uprobe && uprobe->filter(current))
		uprobe->handle();

	ret_addr = addr + uprobe->insn_size;
Quoted 8 lines
	cpu = get_cpu()
	slot = get_slot(cpu);
	memcpy(slot, uprobe->replacement, SLOT_SIZE);
	memcpy(slot + uprobe->ret_addr_offset, &ret_addr, sizeof(unsigned
long));
	set_instruction_pointer(regs, uaddr_addr_of(slot));
	put_cpu(); /* preemption notifiers would take it from here */

What if we were pre-empted after this. Would preemption notifiers also do a copy of instruction to the new slot? If yes, can you please update me with more pointers.

And I dont know if we can do a boosting for all instructions. I think even on kprobes we dont do a boosting for all instructions. Masami, Can you correct me on this?

Quoted 10 lines
	put_uprobe(uprobe);
	return;

fail:
SIGTRAP
}

See, no extra traps, no funny intermediate data structures to manage, and you get the power of ->filter() to implement whatever policy you want, including simple process wide things.

Yes, I see its advantages and disadvantages, I feel this implementation wouldnt scale. Just because we dont want to housekeep some information, we are looping thro the global tree to figure out if there is uprobe specific stuff to be done.

--
Thanks and Regards
Srikar

maintainer
#37 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 24 lines · Srikar Dronamraju
Quoted 24 lines
Quoted 3 lines

multiple processes example libc), and the user is interested in tracing just one instance of the process, then dont wont the inode based tracing amount to far more number of breakpoints hits?

Not if your filter function works.

So let me try this again, (assumes boosted probes):

struct uprobe {
struct inode *inode; /* we hold a ref */
unsigned long offset;

int (*handler)(void); /* arguments.. ? */
int (*filter)(struct task_struct *);

int insn_size; /* size of */
char insn[MAX_INSN_SIZE]; /* the original insn */

int ret_addr_offset; /* return addr offset
in the slot */
char replacement[SLOT_SIZE]; /* replacement
instructions */

Quoted 7 lines
Quoted 3 lines
	atomic_t	ref; /* lifetime muck */
	struct rcu_head	rcu;
};

struct uprobe is a input structure. Do we want to have implementation details in it?

I didn't consider the user-space interface at all, consuming the uprobe name for that seems silly.

Quoted 6 lines
Quoted 6 lines

static struct uprobe *
uprobes_find_get(struct address_space *mapping, unsigned long offset)

{
	unsigned long flags;
	struct uprobe *uprobe;
Quoted 8 lines
Quoted 2 lines
	raw_spin_lock_irqsave(&uprobes.treelock, flags);
	uprobe = find_in_tree(&uprobes.tree);

Wouldnt this be a scalability issue on bigger machines? Every probehit having to parse a global tree to figureout which uprobe it was seems a overkill.
Consider a 5000 uprobes placed on a 128 box with probes placed on heavily used functions.

Use a seqcount, its a read-mostly data structure, its just that the RB-tree isn't RCU friendly.

Quoted 7 lines
Quoted 6 lines
	if (!atomic_inc_not_zero(&uprobe->ref))
		uprobe = NULL;
	raw_spin_unlock_irqrestore(&uprobes.treelock, flags);

	return uprobe;
}
Quoted 7 lines
Quoted 4 lines

static void put_uprobe(struct uprobe *uprobe)

{
	if (atomic_dec_and_test(&uprobe->ref))
		call_rcu(&uprobe->rcu, __uprobe_free);

How are we synchronizing put_uprobe and a thread that has hit the breakpoint and searching thro global probes list?

RCU, see the above atomic_inc_not_zero() it will not obtain a reference after the final put, the object will stay valid until we pass an rcu quesent state.

Quoted 4 lines

One Nit: On probe hit we increment the ref only few times. However we are decrementing everytime. So if two probes occur on two cpus simultaneously, we have a chance of uprobe being freed after both of them are handled. (or am I missing something?)

-ENOPARSE.

Quoted 4 lines
Quoted 4 lines

int register_uprobe(struct uprobe *uprobe)

{
	struct vm_area_struct *vma;
Quoted 8 lines
Quoted 7 lines
	inode_get(uprobe->inode);
	atomic_set(1, &uprobe->ref);

	uprobes_add(uprobe); /* add before the rmap walk, so that 
				new mmap()s will find it too */

	for_each_rmap_vma(vma, uprobe->inode->i_mapping) {

I understand that perf top calls perf record in a loop.

It doesn't, nor do I see the relevance.

Quoted 4 lines

For every perf record, we would be looping thro each vma associated with the inode.
For a probe on a libc, we would iterate thro all vmas. If the tracing was per posix process, this may not be needed.

Feh, probe register should be considered an utter slow path.

We do rmap walks on pages all the time, I can't see it being a problem here.

Quoted 31 lines
Quoted 31 lines
		struct mm_struct *mm = vma->vm_mm;
		int install_probe = 0;

		if (!valid_vma(vma))
			continue;

		for_each_task_in_process(p, mm->owner) {
			if (uprobe->filter(p)) {
				p->has_uprobe = 1;
				install_probe = 1;
			}
		}

		if (install_probe) {
			mm->has_uprobes = 1;
			frob_text(uprobe, mm);
		}
	}
}

void uprobe_fork(struct task_struct *child)

{
	struct vm_area_struct *vma;

	if (!child->mm->has_uprobes)	
		return;

	for_each_vma(vma, child->mm) {
		struct uprobe *uprobe;
Quoted 7 lines
Quoted 4 lines
		if (!valid_vma(vma))
			continue;

		for_each_probe_in_mapping(uprobe, vma->vm_file->f_mapping) {

Are you looking at listing of uprobes per vma?
Does it again traverse the global list?

Yeah, it does a range lookup in the tree [inode:0 - inode:-1). O(log(n)) to find the first entry, O(log(n)) for each consecutive entry, unless we thread the tree.

Note that read-mostly global data is no problem.

Quoted 12 lines
Quoted 12 lines
			if (uprobe->filter(child)) {
				child->has_uprobe = 1;
				return;
			}
		}
	}
}

void uprobe_mmap(struct vm_area_struct *vma)

{
	struct uprobe *uprobe;
Quoted 8 lines
Quoted 4 lines
	if (!valid_vma(vma))
		return;

	for_each_probe_in_mapping(uprobe, vma->vm_file->f_mapping) {

For each mmap, we are traversing all elements in the global tree? What would happen if we have a huge number of uprobes in a system all from one user on his app. Wont it slow down mmap for all other users?

Only mmap() of that particular inode, the range lookup would be the regular O(log(n)) for an empty range.

But again, mmap() is a relative slow path, and you need something like this anyway if you want to support inode based probes at all.

Quoted 23 lines
Quoted 23 lines
		int install_probe = 0;

		for_each_task_in_process(p, vma->vm_mm->owner) {
			if (uprobe->filter(p)) {
				p->has_uprobe = 1;
				install_probe = 1;
			}
		}

		if (install_probe) {
			mm->has_uprobes = 1;
			frob_text(uprobe, mm);
		}
	}
}

void uprobe_hit(struct pt_regs *regs)

{
	unsigned long addr = instruction_pointer(regs);
	struct mm_struct *mm = current->mm;
	struct vm_area_struct *vma;
	unsigned long offset;
Quoted 4 lines
Quoted 1 line
	down_read(&mm->mmap_sem);

uprobe_hit I assume is going to be called in interrupt context. I guess down_read can sleep here.

I assumed process context here, but its trivial to make it work from interrupt context if you want, all we need is a spinlock/seqlock around the vm_rb mods in __vma_link_rb() and __vma_unlink().

Quoted 9 lines
Quoted 6 lines
	vma = find_vma(mm, addr);

	if (!valid_vma)
		goto fail;

	offset = addr - vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT);

Again for every probehit, we are going through the list of vmas and checking if it has a probe which I think is unnecessary.

O(log(n)) lookup, hardly a problem.

Quoted 2 lines

Nit: In some archs, the instruction pointer might be pointing to th next instruction after a breakpoint hit, we would have to adjust that.

Sure..

Quoted 20 lines
Quoted 11 lines
	uprobe = uprobes_find_get(vma->vm_file->f_mapping, offset);
	up_read(&mm->mmap_sem);

	if (!uprobe)
		goto fail;

	if (current->has_uprobe && uprobe->filter(current))
		uprobe->handle();

	ret_addr = addr + uprobe->insn_size;
Quoted 8 lines
	cpu = get_cpu()
	slot = get_slot(cpu);
	memcpy(slot, uprobe->replacement, SLOT_SIZE);
	memcpy(slot + uprobe->ret_addr_offset, &ret_addr, sizeof(unsigned
long));
	set_instruction_pointer(regs, uaddr_addr_of(slot));
	put_cpu(); /* preemption notifiers would take it from here */
Quoted 3 lines

What if we were pre-empted after this. Would preemption notifiers also do a copy of instruction to the new slot? If yes, can you please update me with more pointers.

You'd need to keep a copy of the slot in task state I think.

Quoted 3 lines

And I dont know if we can do a boosting for all instructions. I think even on kprobes we dont do a boosting for all instructions. Masami, Can you correct me on this?

You can do it with single-step if you want, just keep more task state.

Quoted 7 lines
Quoted 7 lines
	put_uprobe(uprobe);
	return;

fail:
SIGTRAP
}

Quoted 8 lines
Quoted 3 lines

See, no extra traps, no funny intermediate data structures to manage, and you get the power of ->filter() to implement whatever policy you want, including simple process wide things.

Yes, I see its advantages and disadvantages, I feel this implementation wouldnt scale. Just because we dont want to housekeep some information, we are looping thro the global tree to figure out if there is uprobe specific stuff to be done.

Its mostly read-only data (adding/removing probes is rare), its all O(log(n)), I really don't see a problem with that.

If you really worry about it you could try a hash lookup for the inode part and keep a tree per probed inode.

#38 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

In reply to Srikar Dronamraju
Quoted 39 lines · * Srikar Dronamraju ([email protected]) wrote:
Quoted 6 lines · Peter Zijlstra
Quoted 4 lines

However I would have an issue with making inode based probing the default.
1. Making all probing based on inode can be a performance hog.

How so? You can add filters if you want.

The breakpoint exception and singlestep account for a substaintial time of the uprobes probe handling. With increasing number of breakpoint hits and singlesteps, wouldnt the overall load increase?

Quoted 8 lines
Quoted 4 lines

2. Since unlike kernel space, every process has a different space, so why would we have to insert breakpoints in each of its process space if we are not interested in them.

You don't have to, but you can. The problem I have with this stuff is that it makes the pid thing a primary interface, whereas it should be one of many filter possibilities.

I think the otherway,
Why instrument a process and filter it out, if we are not interested in it. While instrumenting kernel, we dont have this flexibility. So having a pid based filter is the right thing to do for kernel based tracing.

If we can get the per process based tracing right, we can build higher lever stuff including the file based tracing easily.

All tools/debuggers in the past have all worked with process based tracing.

Tools like gdb can actually use the displaced singlestepping feature that uprobes provides. Some gdb developers have told on LKML earlier that they would be willing to use displaced singlestepping if the kernel provides an API that they can use.

Quoted 8 lines

Also about the security perspective when allowing normal users use perf to trace their applications. Using this model, we dont have to write extra filters to limit them. These filters might allow uprobe handlers on only tasks belonging to that user. However it still interrupts task of other users. And as I said earlier, breakpoint exception and singlestepping actually make a very very substantial part of the handling. The actual uprobe handler depending on what it does might actually be very minimal part of the uprobe probe handling.

I think we are both partially right in slightly different ways. I think Peter is right in that the PID should not be mandatory (e.g. specifying a PID of 0 should apply to all tasks), and you are also right in that being able to apply the "filter" directly at the executable image level is vital for performance.

So how about this: we can provide both task and inode selection arguments. The task selection argument can be 0 (apply to all tasks) or non-zero (one task specifically). The inode argument would be mandatory.

Then, eventually, we can enhance the generic filtering facility so it can be made aware of filtering shortcuts provided by the instrumentation (in this case, uprobes would provide a per-tgid filtering shortcut).

Thoughts ?

Mathieu

Signature · 4 lines
Mathieu Desnoyers
Operating System Efficiency R&D Consultant
EfficiOS Inc.
http://www.efficios.com
#39 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

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

You don't have to, but you can. The problem I have with this stuff is that it makes the pid thing a primary interface, whereas it should be one of many filter possibilities.

I think the otherway,
Why instrument a process and filter it out, if we are not interested in it. While instrumenting kernel, we dont have this flexibility. So having a pid based filter is the right thing to do for kernel based tracing.

Quoted 5 lines

If we can get the per process based tracing right, we can build higher lever stuff including the file based tracing easily.

All tools/debuggers in the past have all worked with process based tracing.

I have the feeling that you guys are at least partially talking past each other.

For the "perf probe --add" interface the only sane interface is one by filename and then symbol / liner number / etc.

But that is just the interface - these probes don't nessecarily have to be armed and cause global overhead once they are define. If the implenmentation is smart enough it will defer arming the probe until we actually use it, and that will be per-process quite often.

Which btw, brings up two more issues, one in uprobes and one in perf. For one even in userspace I think the dynamic probes will really just be the tip of the iceberg and we'll get more bang for the buck from static traces, which is something that's no supported in uprobes yet. As a start supporting the dtrace-style sdt.h header would be a great help, and then we can decide if we need somthing even better on top.

The other things is that perf currently only supports per-kernel pid recording, while we'd really need per Posix process, which may contain multiple threads for useful tracing of complex userspace applications. I also suspect that this will fit the uprobes model much better given that the probes will be in any given address space.

maintainer
#40 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 4 lines · Christoph Hellwig

But that is just the interface - these probes don't nessecarily have to be armed and cause global overhead once they are define. If the implenmentation is smart enough it will defer arming the probe until we actually use it, and that will be per-process quite often.

The implementation I outlined a few messages ago, would in fact, as you suggest, avoid arming things when not needed.

Quoted 5 lines

The other things is that perf currently only supports per-kernel pid recording, while we'd really need per Posix process, which may contain multiple threads for useful tracing of complex userspace applications. I also suspect that this will fit the uprobes model much better given that the probes will be in any given address space.

perf does report both:

* { u32 pid, tid; } && PERF_SAMPLE_TID

the pid is the process id (thread group leader like) and tid is the task/thread id.

#41 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 6 lines · Peter Zijlstra
Quoted 5 lines

The other things is that perf currently only supports per-kernel pid recording, while we'd really need per Posix process, which may contain multiple threads for useful tracing of complex userspace applications. I also suspect that this will fit the uprobes model much better given that the probes will be in any given address space.

Quoted 6 lines

perf does report both:

* { u32 pid, tid; } && PERF_SAMPLE_TID

the pid is the process id (thread group leader like) and tid is the task/thread id.

It records both, but I haven't found a way to only record samples or trace things in a Posix Process.

E.g. perf record -p seems to be only per-thread, not per-process. If that has changes recently everything is fine of course.

maintainer
#42 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 11 lines · Christoph Hellwig
Quoted 10 lines · Peter Zijlstra
Quoted 5 lines

The other things is that perf currently only supports per-kernel pid recording, while we'd really need per Posix process, which may contain multiple threads for useful tracing of complex userspace applications. I also suspect that this will fit the uprobes model much better given that the probes will be in any given address space.

perf does report both:

* { u32 pid, tid; } && PERF_SAMPLE_TID

Quoted 8 lines
Quoted 2 lines

the pid is the process id (thread group leader like) and tid is the task/thread id.

It records both, but I haven't found a way to only record samples or trace things in a Posix Process.

E.g. perf record -p seems to be only per-thread, not per-process. If that has changes recently everything is fine of course.

Hrm, the record code seems to look up all threads for -p and use only a single thread for -t, didn't actually try it though so it could be borken.

#43 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

In reply to Christoph Hellwig
Quoted 14 lines · Srikar Dronamraju
Quoted 13 lines
Quoted 3 lines

You don't have to, but you can. The problem I have with this stuff is that it makes the pid thing a primary interface, whereas it should be one of many filter possibilities.

I think the otherway,
Why instrument a process and filter it out, if we are not interested in it. While instrumenting kernel, we dont have this flexibility. So having a pid based filter is the right thing to do for kernel based tracing.

If we can get the per process based tracing right, we can build higher lever stuff including the file based tracing easily.

Quoted 8 lines
Quoted 2 lines

All tools/debuggers in the past have all worked with process based tracing.

I have the feeling that you guys are at least partially talking past each other.

For the "perf probe --add" interface the only sane interface is one by filename and then symbol / liner number / etc.

Agree, probing by file name is a requirement and I am working towards that end.

Quoted 5 lines

But that is just the interface - these probes don't nessecarily have to be armed and cause global overhead once they are define. If the implenmentation is smart enough it will defer arming the probe until we actually use it, and that will be per-process quite often.

Agree, That why I am trying to build file-based probing on pid-based probing.

Quoted 7 lines

Which btw, brings up two more issues, one in uprobes and one in perf. For one even in userspace I think the dynamic probes will really just be the tip of the iceberg and we'll get more bang for the buck from static traces, which is something that's no supported in uprobes yet. As a start supporting the dtrace-style sdt.h header would be a great help, and then we can decide if we need somthing even better on top.

Yes, Static tracing using dtrace style sdt.h is a cool thing to do. Already SystemTap has this facility. However I think its probably better done at perf user interface level.

The way I look at it is perf probe decodes the static markers and asks uprobes to place probepoints over there.
Do you see a different approach? If yes can you tell what you were looking at?

--
Thanks and Regards
Srikar

#44 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

Quoted 1 line · * Srikar Dronamraju ([email protected]) wrote:
Quoted 1 line · Srikar Dronamraju

[...]

Quoted 11 lines
Quoted 7 lines

Which btw, brings up two more issues, one in uprobes and one in perf. For one even in userspace I think the dynamic probes will really just be the tip of the iceberg and we'll get more bang for the buck from static traces, which is something that's no supported in uprobes yet. As a start supporting the dtrace-style sdt.h header would be a great help, and then we can decide if we need somthing even better on top.

Yes, Static tracing using dtrace style sdt.h is a cool thing to do. Already SystemTap has this facility. However I think its probably better done at perf user interface level.

We currently have this feature in UST. We're adding "markers" into the applications, and a UST daemon talks with an in-process library helper thread to enable/disable markers and control tracing over unix sockets.

We're currently in the process of moving from markers to the TRACE_EVENT()+tracepoints infrastructure.

Thanks,

Mathieu

Quoted 5 lines

The way I look at it is perf probe decodes the static markers and asks uprobes to place probepoints over there.
Do you see a different approach? If yes can you tell what you were looking at?

Signature · 4 lines
Mathieu Desnoyers
Operating System Efficiency R&D Consultant
EfficiOS Inc.
http://www.efficios.com
maintainer
#45 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

In reply to Srikar Dronamraju
Quoted 5 lines · Srikar Dronamraju

3. Ingo has a requirement for allowing normal users to use uprobes thro perf. When this feature gets implemented, we have to be careful about a normal users trying to just trace their application resulting in it hitting performance all other users.

For that I guess we should have a way to tie a uprobe to a filedesc or somesuch, that way whenever the owner dies, the probe goes away.

Such probes would also obviuosly get a filter that limits it to tasks of its own user etc..

maintainer
#46 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 5/15] 5: uprobes: Uprobes (un)registration and exception handling.

In reply to Srikar Dronamraju
Quoted 4 lines · Srikar Dronamraju

The uprobes infrastructure enables a user to dynamically establish probepoints in user applications and collect information by executing a handler function when a probepoint is hit.

Right, so in short, I think that if you rework this to be inode:offset based you'll end up with a much simpler codebase.

#47 lore raw

PATCH v11 6/15 6: uprobes: X86 support for Uprobes

In reply to Srikar Dronamraju

Provides x86 specific details for uprobes.
This includes interrupt notifier for uprobes, enabling/disabling singlestep.

---

Changelog from V5: Using local_irq_enable() instead of
native_irq_enable and no more disabling irqs as suggested by Oleg Nesterov.

 arch/x86/kernel/signal.c  |   13 +++++++++++
 arch/x86/kernel/uprobes.c |   52 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 65 insertions(+), 0 deletions(-)
arch/x86/kernel/signal.c +13 -0
index 4fd173c..3657563 100644
@@ -848,6 +848,19 @@ do_notify_resume(struct pt_regs *regs, void *unused, __u32 thread_info_flags)
 	if (thread_info_flags & _TIF_SIGPENDING)
 		do_signal(regs);
 
+	if (thread_info_flags & _TIF_UPROBE) {
+		clear_thread_flag(TIF_UPROBE);
+#ifdef CONFIG_X86_32
+		/*
+		 * On x86_32, do_notify_resume() gets called with
+		 * interrupts disabled. Hence enable interrupts if they
+		 * are still disabled.
+		 */
+		local_irq_enable();
+#endif
+		uprobe_notify_resume(regs);
+	}
+
 	if (thread_info_flags & _TIF_NOTIFY_RESUME) {
 		clear_thread_flag(TIF_NOTIFY_RESUME);
 		tracehook_notify_resume(regs);
arch/x86/kernel/uprobes.c +52 -0

61 lines not on this page · raw message

#48 lore raw

PATCH v11 7/15 7: uprobes: Uprobes Documentation

In reply to Srikar Dronamraju

Uprobes Documentation.

---

Changelog from V5: Removed references to Modules, Samples, and
probe Overhead.

Changelog from v3: Updated measurements.

Changelog from v2: Updated measurements.

Changelog from v1: Addressed comments from Randy Dunlap.
: Updated measurements.

 Documentation/uprobes.txt |  188 +++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 188 insertions(+), 0 deletions(-)
 create mode 100644 Documentation/uprobes.txt
Documentation/uprobes.txt new file +188 -0
new file mode 100644
index 0000000..5b620d8
@@ -0,0 +1,188 @@
+Title	: User-Space Probes (Uprobes)
+Authors	: Jim Keniston <[email protected]>
+	: Srikar Dronamraju <[email protected]>
+
+CONTENTS
+
+1. Concepts: Uprobes
+2. Architectures Supported
+3. API Reference
+4. Uprobes Features and Limitations
+5. TODO
+6. Uprobes Team
+
+1. Concepts: Uprobes
+
+Uprobes enables you to dynamically break into any routine in a
+user application and collect debugging and performance information
+non-disruptively. You can trap at any code address, specifying a
+kernel handler routine to be invoked when the breakpoint is hit.
+
+A uprobe can be inserted on any instruction in the application's
+virtual address space.  The registration function register_uprobe()
+specifies which process is to be probed, where the probe is to be
+inserted, and what handler is to be called when the probe is hit.
+
+1.1 How Does a Uprobe Work?
+
+When a uprobe is registered, Uprobes makes a copy of the probed
+instruction, stops the probed application, replaces the first byte(s)
+of the probed instruction with a breakpoint instruction (e.g., int3
+on i386 and x86_64), and allows the probed application to continue.
+(When inserting the breakpoint, Uprobes uses background page
+replacement mechanism, so that the breakpoint affects only that
+process, and not any other process running that program.  This is
+true even if the probed instruction is in a shared library.)
+
+When a CPU hits the breakpoint instruction, a trap occurs, the CPU's
+user-mode registers are saved, and uprobes notifier code finds the
+associated uprobe.  It then executes the handler associated with the
+uprobe, passing the handler the addresses of the uprobe struct and the
+saved registers. The handler can run either in interrupt context or in
+task context; this is specified by the user at the time of registration.
+When run in task context, the handler may block, but keep in mind that
+the probed thread remains stopped while your handler runs.
+
+Next, Uprobes single-steps its copy of the probed instruction and
+resumes execution of the probed process at the instruction following
+the probepoint.  (It would be simpler to single-step the actual
+instruction in place, but then Uprobes would have to temporarily
+remove the breakpoint instruction.  This would create problems in a
+multithreaded application.  For example, it would open a time window
+when another thread could sail right past the probepoint.)
+
+Instruction copies to be single-stepped are stored in a per-process
+"execution out of line (XOL) area," which is a little VM area
+created by Uprobes in each probed process's address space.
+
+Uprobes handles interesting events in the lifetime of the probed
+process, such as fork, clone, exec, and exit.
+
+1.2 Multithreaded Applications
+
+Uprobes supports the probing of multithreaded applications.  Uprobes
+imposes no limit on the number of threads in a probed application.
+All threads in a process use the same text pages, so every probe
+in a process affects all threads; of course, each thread hits the
+probepoint (and runs the handler) independently.  Multiple threads
+may run the same handler simultaneously.  If you want a particular
+thread or set of threads to run a particular handler, your handler
+should check current or current->pid to determine which thread has
+hit the probepoint.
+
+When a process clones a new thread, that thread automatically shares
+all current and future probes established for that process.
+
+2. Architectures Supported
+
+This user_bkpt based version of Uprobes is implemented on the following
+architectures:
+
+- x86
+
+3. API Reference
+
+The Uprobes API includes a "register" function and an "unregister"
+function for uprobes.  Here are terse, mini-man-page specifications for
+these functions and the associated probe handlers that you'll write.
+See the latter half of this document for examples.
+
+3.1 register_uprobe
+
+#include <linux/uprobes.h>
+int register_uprobe(struct uprobe *u);
+
+Sets a breakpoint at virtual address u->vaddr in the process whose
+pid is u->pid.  When the breakpoint is hit, Uprobes calls u->handler.
+If u->handler_in_interrupt is set, the handler runs in interrupt
+context. Otherwise it runs in task context.
+
+register_uprobe() returns 0 on success, or a negative errno
+otherwise.
+
+User's handler (u->handler):
+#include <linux/uprobes.h>
+#include <linux/ptrace.h>
+void handler(struct uprobe *u, struct pt_regs *regs);
+
+Called with u pointing to the uprobe associated with the breakpoint,
+and regs pointing to the struct containing the registers saved when
+the breakpoint was hit.
+
+3.2 unregister_uprobe
+
+#include <linux/uprobes.h>
+void unregister_uprobe(struct uprobe *u);
+
+Removes the specified probe.  The unregister function can be called
+at any time after the probe has been registered, and can be called
+from a uprobe handler.
+
+4. Uprobes Features and Limitations
+
+The user is expected to assign values to the following members
+of struct uprobe: pid, vaddr, handler.
+Uprobes may produce unexpected results if you:
+- change the contents of a uprobe object while it is registered; or
+- attempt to register a uprobe that is already registered.
+
+In this implementation, Uprobes allows only one uprobe at a particular
+address.
+
+Uprobe clients may be used to probe a particular process
+simultaneously, or probe any number of processes simultaneously.
+
+Probes are shared by all threads in a process (including newly
+created threads).
+
+If a probed process exits or execs, Uprobes automatically
+unregisters all uprobes associated with that process.  Subsequent
+attempts to unregister these probes will be treated as no-ops.
+
+On the other hand, if a probed memory area is removed from the
+process's virtual memory map (e.g., via dlclose(3) or munmap(2)),
+it's currently up to you to unregister the probes first.
+
+There is no way to specify that probes should be inherited across fork;
+Uprobes removes all probepoints in the newly created child process.
+
+To avoid interfering with interactive debuggers, Uprobes will refuse
+to insert a probepoint where a breakpoint instruction already exists.
+Some architectures may refuse to insert probes on other types of
+instructions.
+
+If you install a probe in an inline-able function, Uprobes makes
+no attempt to chase down all inline instances of the function and
+install probes there.  gcc may inline a function without being asked,
+so keep this in mind if you're not seeing the probe hits you expect.
+
+A probe handler can modify the environment of the probed function
+-- e.g., by modifying data structures, or by modifying the
+contents of the pt_regs struct (which are restored to the registers
+upon return from the breakpoint).  So Uprobes can be used, for example,
+to install a bug fix or to inject faults for testing.  Uprobes, of
+course, has no way to distinguish the deliberately injected faults
+from the accidental ones.  Don't drink and probe.
+
+When Uprobes establishes a probepoint on a previous unprobed page of
+text, Linux creates a new copy of the page via background page
+replacement  mechanism.  When probepoints are removed, Uprobes makes
+no attempt to consolidate identical copies of the same page.  This
+could affect memory availability if you probe many, many pages in
+many, many long-running processes.
+
+5. TODO
+
+a. Support for other architectures.
+b. Support for multiple probes at the same address.
+c. Support for boosted probes.
+d. Support return probes.
+
+6. Uprobes Team
+
+The following people have made major contributions to Uprobes:
+Jim Keniston - [email protected]
+Srikar Dronamraju - [email protected]
+Ananth Mavinakayanahalli - [email protected]
+Prasanna Panchamukhi - [email protected]
+Dave Wilder - [email protected]
#49 lore raw

PATCH v11 8/15 8: 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.

TODO: Merge both events to a single probe event.

---

Changelog from V10: delete references to is_kprobe and make
is_return a bool.

Changelog from V7: Merge changes due to string support in kprobes
traceevent.

Changelog from V5: Addressed comments from Masami Hiramatsu
and Steven Rostedt. Also shared lot more code from kprobes traceevents.

 kernel/trace/Kconfig        |    4 
 kernel/trace/Makefile       |    1 
 kernel/trace/trace_kprobe.c |  752 +------------------------------------------
 kernel/trace/trace_probe.c  |  648 +++++++++++++++++++++++++++++++++++++
 kernel/trace/trace_probe.h  |  155 +++++++++
 5 files changed, 822 insertions(+), 738 deletions(-)
 create mode 100644 kernel/trace/trace_probe.c
 create mode 100644 kernel/trace/trace_probe.h
kernel/trace/Kconfig +4 -0
index 538501c..d709697 100644
@@ -353,6 +353,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)
@@ -365,6 +366,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 53f3381..95d2043 100644
@@ -56,5 +56,6 @@ obj-$(CONFIG_EVENT_TRACING) += power-traces.o
 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 +14 -738

842 lines not on this page · raw message

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

648 lines not on this page · raw message

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

155 lines not on this page · raw message

#50 lore raw

PATCH v11 9/15 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 text address in a process and dump the required registers when the code flow reaches the probed address.

TODO: Documentation/trace/uprobetrace.txt

---

Changelog from v5: Addressed comments from Masami Hiramatsu and Steven
Rostedt. Some changes because of changes in common probe events.

Changelog from v4: (Merged to 2.6.35-rc3-tip)

Changelog from v2/v3: (Addressing comments from Steven Rostedt
and Frederic Weisbecker)
* removed pit field from uprobe_trace_entry.
* share common parts with kprobe trace events.
* use trace_create_file instead of debugfs_create_file.

The following example shows how to dump the instruction pointer and %ax a register at the probed text address.

Start a process to trace. Get the address to trace.
[Here pid is asssumed as 6016]
[Address to trace is 0x0000000000446420] [Registers to be dumped are %ip and %ax]

# cd /sys/kernel/debug/tracing/
# echo 'p 6016:0x0000000000446420 %ip %ax' > uprobe_events
# cat uprobe_events
p:uprobes/p_6016_0x0000000000446420 6016:0x0000000000446420 %ip=%ip %ax=%ax
# cat events/uprobes/p_6016_0x0000000000446420/enable
0
[enable the event]
# echo 1 > events/uprobes/p_6016_0x0000000000446420/enable
# cat events/uprobes/p_6016_0x0000000000446420/enable
1
# #### do some activity on the program so that it hits the breakpoint
# cat uprobe_profile
  6016 p_6016_0x0000000000446420                                234
# tracer: nop
#
#           TASK-PID    CPU#    TIMESTAMP  FUNCTION
#              | |       |          |         |
             zsh-6016  [004] 227931.093579: p_6016_0x0000000000446420: (0x446420) %ip=446421 %ax=79
             zsh-6016  [005] 227931.097541: p_6016_0x0000000000446420: (0x446420) %ip=446421 %ax=79
             zsh-6016  [000] 227931.124909: p_6016_0x0000000000446420: (0x446420) %ip=446421 %ax=79
             zsh-6016  [001] 227933.128565: p_6016_0x0000000000446420: (0x446420) %ip=446421 %ax=79
             zsh-6016  [004] 227933.132756: p_6016_0x0000000000446420: (0x446420) %ip=446421 %ax=79
             zsh-6016  [000] 227933.158802: p_6016_0x0000000000446420: (0x446420) %ip=446421 %ax=79
             zsh-6016  [001] 227935.161602: p_6016_0x0000000000446420: (0x446420) %ip=446421 %ax=79
             zsh-6016  [004] 227935.165229: p_6016_0x0000000000446420: (0x446420) %ip=446421 %ax=79
 arch/Kconfig                |   11 -
 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  |    4 
 kernel/trace/trace_uprobe.c |  739 +++++++++++++++++++++++++++++++++++++++++++
 8 files changed, 777 insertions(+), 17 deletions(-)
 create mode 100644 kernel/trace/trace_uprobe.c
arch/Kconfig +1 -10
index c8c8e3f..af167f8 100644
@@ -48,16 +48,7 @@ config OPTPROBES
 	select KALLSYMS_ALL
 
 config UPROBES
-	bool "User-space probes (EXPERIMENTAL)"
-	default n
-	depends on ARCH_SUPPORTS_UPROBES
-	depends on MMU
-	help
-	  Uprobes enables kernel subsystems to establish probepoints
-	  in user applications and execute handler functions when
-	  the probepoints are hit. For more information, refer to
-	  Documentation/uprobes.txt.
-	  If in doubt, say "N".
+	def_bool n
 
 config HAVE_EFFICIENT_UNALIGNED_ACCESS
 	bool
kernel/trace/Kconfig +16 -0
index d709697..55ba474 100644
@@ -366,6 +366,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 95d2043..67a12e3 100644
@@ -57,5 +57,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 d39b3c5..c5be8cb 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 e66450d..8b1e55e 100644
@@ -363,8 +363,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);
 			kfree(tp->args[i].name);
kernel/trace/trace_probe.c +10 -4
index 4ca48c6..5123d1c 100644
@@ -443,13 +443,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);
@@ -500,7 +504,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 {
@@ -520,7 +525,7 @@ static int parse_probe_arg(char *arg, const struct fetch_type *t,
 
 /* 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;
@@ -546,7 +551,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) {
 		parg->fetch_size.fn = get_fetch_size_function(parg->type,
kernel/trace/trace_probe.h +3 -1
index 74311ea..d905386 100644
@@ -48,6 +48,7 @@
 #define FIELD_STRING_IP "__probe_ip"
 #define FIELD_STRING_RETIP "__probe_ret_ip"
 #define FIELD_STRING_FUNC "__probe_func"
+#define FIELD_STRING_PID "__probe_pid"
 
 #undef DEFINE_FIELD
 #define DEFINE_FIELD(type, item, name, is_signed)			\
@@ -64,6 +65,7 @@
 /* Flags for trace_probe */
 #define TP_FLAG_TRACE	1
 #define TP_FLAG_PROFILE	2
+#define TP_FLAG_UPROBE	4
 
 
 /* data_rloc: data relative location, compatible with u32 */
@@ -141,7 +143,7 @@ static inline int check_event_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 +739 -0

739 lines not on this page · raw message

#51 lore raw

PATCH v11 10/15 10: tracing: config option to enable both kprobe-tracer and uprobe-tracer.

In reply to Srikar Dronamraju

Selecting CONFIG_PROBE_EVENTS enables both kprobe-based and uprobes-based dynamic events. However kprobe-tracer or uprobe-tracer can still be individually selected or disabled.

---
 kernel/trace/Kconfig |   51 +++++++++++++++++++++++++++++---------------------
 1 files changed, 30 insertions(+), 21 deletions(-)
kernel/trace/Kconfig +30 -21
index 55ba474..205c12b 100644
@@ -76,7 +76,7 @@ config RING_BUFFER_ALLOW_SWAP
 # All tracer options should select GENERIC_TRACER. For those options that are
 # enabled by all tracers (context switch and event tracer) they select TRACING.
 # This allows those options to appear when no other tracer is selected. But the
-# options do not appear when something else selects it. We need the two options
+# options do not appear when something else selects it. We need the two option
 # GENERIC_TRACER and TRACING to avoid circular dependencies to accomplish the
 # hiding of the automatic options.
 
@@ -162,7 +162,7 @@ config IRQSOFF_TRACER
 	  This option measures the time spent in irqs-off critical
 	  sections, with microsecond accuracy.
 
-	  The default measurement method is a maximum search, which is
+	  The default measurement method is a maximum search, which i
 	  disabled by default and can be runtime (re-)started
 	  via:
 
@@ -184,7 +184,7 @@ config PREEMPT_TRACER
 	  This option measures the time spent in preemption-off critical
 	  sections, with microsecond accuracy.
 
-	  The default measurement method is a maximum search, which is
+	  The default measurement method is a maximum search, which i
 	  disabled by default and can be runtime (re-)started
 	  via:
 
@@ -228,7 +228,7 @@ choice
 	prompt "Branch Profiling"
 	default BRANCH_PROFILE_NONE
 	help
-	 The branch profiling is a software profiler. It will add hooks
+	 The branch profiling is a software profiler. It will add hook
 	 into the C conditionals to test which path a branch takes.
 
 	 The likely/unlikely profiler only looks at the conditions that
@@ -252,12 +252,12 @@ config PROFILE_ANNOTATED_BRANCHES
 	bool "Trace likely/unlikely profiler"
 	select TRACE_BRANCH_PROFILING
 	help
-	  This tracer profiles all the the likely and unlikely macros
+	  This tracer profiles all the the likely and unlikely macro
 	  in the kernel. It will display the results in:
 
 	  /sys/kernel/debug/tracing/profile_annotated_branch
 
-	  Note: this will add a significant overhead; only turn this
+	  Note: this will add a significant overhead; only turn thi
 	  on if you need to profile the system's use of these macros.
 
 config PROFILE_ALL_BRANCHES
@@ -333,7 +333,7 @@ config BLK_DEV_IO_TRACE
 	select GENERIC_TRACER
 	select STACKTRACE
 	help
-	  Say Y here if you want to be able to trace the block layer actions
+	  Say Y here if you want to be able to trace the block layer action
 	  on a given queue. Tracing allows you to see any traffic happening
 	  on a block device queue. For more information (and the userspace
 	  support tools needed), fetch the blktrace tools from:
@@ -351,9 +351,8 @@ config BLK_DEV_IO_TRACE
 config KPROBE_EVENT
 	depends on KPROBES
 	depends on HAVE_REGS_AND_STACK_ACCESS_API
+	depends on PROBE_EVENTS
 	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)
@@ -370,10 +369,9 @@ config UPROBE_EVENT
 	bool "Enable uprobes-based dynamic events"
 	depends on ARCH_SUPPORTS_UPROBES
 	depends on MMU
+	depends on PROBE_EVENTS
 	select UPROBES
-	select PROBE_EVENTS
-	select TRACING
-	default n
+	default y
 	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.
@@ -383,7 +381,18 @@ config UPROBE_EVENT
 	  tools on user space applications.
 
 config PROBE_EVENTS
-	def_bool n
+	bool "Enable kprobes and uprobe based dynamic events"
+	select TRACING
+	default n
+	help
+	  This allows a user to add dynamic tracing events in
+	  kernel using kprobe-tracer and in userspace using
+	  uprobe-tracer. However users can still selectively
+	  disable one of these events.
+
+	  For more information on kprobe-tracer and uprobe-tracer
+	  please refer help under KPROBE_EVENT and UPROBE_EVENT
+	  respectively.
 
 config DYNAMIC_FTRACE
 	bool "enable/disable ftrace tracepoints dynamically"
@@ -393,14 +402,14 @@ config DYNAMIC_FTRACE
 	help
           This option will modify all the calls to ftrace dynamically
 	  (will patch them out of the binary image and replace them
-	  with a No-Op instruction) as they are called. A table is
+	  with a No-Op instruction) as they are called. A table i
 	  created to dynamically enable them again.
 
 	  This way a CONFIG_FUNCTION_TRACER kernel is slightly larger, but
 	  otherwise has native performance as long as no tracing is active.
 
 	  The changes to the code are done by a kernel thread that
-	  wakes up once a second and checks to see if any ftrace calls
+	  wakes up once a second and checks to see if any ftrace call
 	  were made. If so, it runs stop_machine (stops all CPUS)
 	  and modifies the code to jump over the call to ftrace.
 
@@ -432,7 +441,7 @@ config FTRACE_STARTUP_TEST
 	select FTRACE_SELFTEST
 	help
 	  This option performs a series of startup tests on ftrace. On bootup
-	  a series of tests are made to verify that the tracer is
+	  a series of tests are made to verify that the tracer i
 	  functioning properly. It will do tests on all the configured
 	  tracers of ftrace.
 
@@ -441,12 +450,12 @@ config EVENT_TRACE_TEST_SYSCALLS
 	depends on FTRACE_STARTUP_TEST
 	help
 	 This option will also enable testing every syscall event.
-	 It only enables the event and disables it and runs various loads
+	 It only enables the event and disables it and runs various load
 	 with the event enabled. This adds a bit more time for kernel boot
 	 up since it runs this on every system call defined.
 
 	 TBD - enable a way to actually call the syscalls as we test their
-	       events
+	       event
 
 config MMIOTRACE
 	bool "Memory mapped IO tracing"
@@ -465,7 +474,7 @@ config MMIOTRACE_TEST
 	tristate "Test module for mmiotrace"
 	depends on MMIOTRACE && m
 	help
-	  This is a dumb module for testing mmiotrace. It is very dangerous
+	  This is a dumb module for testing mmiotrace. It is very dangerou
 	  as it will write garbage to IO memory starting at a given address.
 	  However, it should be safe to use on e.g. unused portion of VRAM.
 
@@ -477,9 +486,9 @@ config RING_BUFFER_BENCHMARK
 	help
 	  This option creates a test to stress the ring buffer and benchmark it.
 	  It creates its own ring buffer such that it will not interfere with
-	  any other users of the ring buffer (such as ftrace). It then creates
+	  any other users of the ring buffer (such as ftrace). It then create
 	  a producer and consumer that will run for 10 seconds and sleep for
-	  10 seconds. Each interval it will print out the number of events
+	  10 seconds. Each interval it will print out the number of event
 	  it recorded and give a rough estimate of how long each iteration took.
 
 	  It does not disable interrupts or raise its priority, so it may be
#52 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 10/15] 10: tracing: config option to enable both kprobe-tracer and uprobe-tracer.

Quoted 15 lines · Srikar Dronamraju

Selecting CONFIG_PROBE_EVENTS enables both kprobe-based and uprobes-based dynamic events. However kprobe-tracer or uprobe-tracer can still be individually selected or disabled.

---
 kernel/trace/Kconfig |   51 +++++++++++++++++++++++++++++---------------------
 1 files changed, 30 insertions(+), 21 deletions(-)
kernel/trace/Kconfig +0 -0
index 55ba474..205c12b 100644

kernel/trace/Kconfig config RING_BUFFER_ALLOW_SWAP · line 79

Quoted 5 lines
kernel/trace/Kconfig +1 -1
@@ -76,7 +76,7 @@ config RING_BUFFER_ALLOW_SWAP
 # All tracer options should select GENERIC_TRACER. For those options that are
 # enabled by all tracers (context switch and event tracer) they select TRACING.
 # This allows those options to appear when no other tracer is selected. But the
-# options do not appear when something else selects it. We need the two options
+# options do not appear when something else selects it. We need the two option

Why are lots of end-of-line 's' character missing? :)

Quoted 79 lines
kernel/trace/Kconfig +9 -11
 # GENERIC_TRACER and TRACING to avoid circular dependencies to accomplish the
 # hiding of the automatic options.
 
@@ -162,7 +162,7 @@ config IRQSOFF_TRACER
 	  This option measures the time spent in irqs-off critical
 	  sections, with microsecond accuracy.
 
-	  The default measurement method is a maximum search, which is
+	  The default measurement method is a maximum search, which i
 	  disabled by default and can be runtime (re-)started
 	  via:
 
@@ -184,7 +184,7 @@ config PREEMPT_TRACER
 	  This option measures the time spent in preemption-off critical
 	  sections, with microsecond accuracy.
 
-	  The default measurement method is a maximum search, which is
+	  The default measurement method is a maximum search, which i
 	  disabled by default and can be runtime (re-)started
 	  via:
 
@@ -228,7 +228,7 @@ choice
 	prompt "Branch Profiling"
 	default BRANCH_PROFILE_NONE
 	help
-	 The branch profiling is a software profiler. It will add hooks
+	 The branch profiling is a software profiler. It will add hook
 	 into the C conditionals to test which path a branch takes.
 
 	 The likely/unlikely profiler only looks at the conditions that
@@ -252,12 +252,12 @@ config PROFILE_ANNOTATED_BRANCHES
 	bool "Trace likely/unlikely profiler"
 	select TRACE_BRANCH_PROFILING
 	help
-	  This tracer profiles all the the likely and unlikely macros
+	  This tracer profiles all the the likely and unlikely macro
 	  in the kernel. It will display the results in:
 
 	  /sys/kernel/debug/tracing/profile_annotated_branch
 
-	  Note: this will add a significant overhead; only turn this
+	  Note: this will add a significant overhead; only turn thi
 	  on if you need to profile the system's use of these macros.
 
 config PROFILE_ALL_BRANCHES
@@ -333,7 +333,7 @@ config BLK_DEV_IO_TRACE
 	select GENERIC_TRACER
 	select STACKTRACE
 	help
-	  Say Y here if you want to be able to trace the block layer actions
+	  Say Y here if you want to be able to trace the block layer action
 	  on a given queue. Tracing allows you to see any traffic happening
 	  on a block device queue. For more information (and the userspace
 	  support tools needed), fetch the blktrace tools from:
@@ -351,9 +351,8 @@ config BLK_DEV_IO_TRACE
 config KPROBE_EVENT
 	depends on KPROBES
 	depends on HAVE_REGS_AND_STACK_ACCESS_API
+	depends on PROBE_EVENTS
 	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)
@@ -370,10 +369,9 @@ config UPROBE_EVENT
 	bool "Enable uprobes-based dynamic events"
 	depends on ARCH_SUPPORTS_UPROBES
 	depends on MMU
+	depends on PROBE_EVENTS
 	select UPROBES
-	select PROBE_EVENTS
-	select TRACING
-	default n
+	default y
 	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.

kernel/trace/Kconfig config UPROBE_EVENT · line 386

Quoted 7 lines
kernel/trace/Kconfig +3 -1
@@ -383,7 +381,18 @@ config UPROBE_EVENT
 	  tools on user space applications.
 
 config PROBE_EVENTS
-	def_bool n
+	bool "Enable kprobes and uprobe based dynamic events"
+	select TRACING
+	default n

Hmm, without this series, KPROBE_EVENT is set "y" by default. (PROBE_EVENTS is introduced by 8/15)
I'd like to set this "y" by default, because it doesn't affect other parts.

Thank you,

Quoted 74 lines
kernel/trace/Kconfig +17 -8
+	help
+	  This allows a user to add dynamic tracing events in
+	  kernel using kprobe-tracer and in userspace using
+	  uprobe-tracer. However users can still selectively
+	  disable one of these events.
+
+	  For more information on kprobe-tracer and uprobe-tracer
+	  please refer help under KPROBE_EVENT and UPROBE_EVENT
+	  respectively.
 
 config DYNAMIC_FTRACE
 	bool "enable/disable ftrace tracepoints dynamically"
@@ -393,14 +402,14 @@ config DYNAMIC_FTRACE
 	help
           This option will modify all the calls to ftrace dynamically
 	  (will patch them out of the binary image and replace them
-	  with a No-Op instruction) as they are called. A table is
+	  with a No-Op instruction) as they are called. A table i
 	  created to dynamically enable them again.
 
 	  This way a CONFIG_FUNCTION_TRACER kernel is slightly larger, but
 	  otherwise has native performance as long as no tracing is active.
 
 	  The changes to the code are done by a kernel thread that
-	  wakes up once a second and checks to see if any ftrace calls
+	  wakes up once a second and checks to see if any ftrace call
 	  were made. If so, it runs stop_machine (stops all CPUS)
 	  and modifies the code to jump over the call to ftrace.
 
@@ -432,7 +441,7 @@ config FTRACE_STARTUP_TEST
 	select FTRACE_SELFTEST
 	help
 	  This option performs a series of startup tests on ftrace. On bootup
-	  a series of tests are made to verify that the tracer is
+	  a series of tests are made to verify that the tracer i
 	  functioning properly. It will do tests on all the configured
 	  tracers of ftrace.
 
@@ -441,12 +450,12 @@ config EVENT_TRACE_TEST_SYSCALLS
 	depends on FTRACE_STARTUP_TEST
 	help
 	 This option will also enable testing every syscall event.
-	 It only enables the event and disables it and runs various loads
+	 It only enables the event and disables it and runs various load
 	 with the event enabled. This adds a bit more time for kernel boot
 	 up since it runs this on every system call defined.
 
 	 TBD - enable a way to actually call the syscalls as we test their
-	       events
+	       event
 
 config MMIOTRACE
 	bool "Memory mapped IO tracing"
@@ -465,7 +474,7 @@ config MMIOTRACE_TEST
 	tristate "Test module for mmiotrace"
 	depends on MMIOTRACE && m
 	help
-	  This is a dumb module for testing mmiotrace. It is very dangerous
+	  This is a dumb module for testing mmiotrace. It is very dangerou
 	  as it will write garbage to IO memory starting at a given address.
 	  However, it should be safe to use on e.g. unused portion of VRAM.
 
@@ -477,9 +486,9 @@ config RING_BUFFER_BENCHMARK
 	help
 	  This option creates a test to stress the ring buffer and benchmark it.
 	  It creates its own ring buffer such that it will not interfere with
-	  any other users of the ring buffer (such as ftrace). It then creates
+	  any other users of the ring buffer (such as ftrace). It then create
 	  a producer and consumer that will run for 10 seconds and sleep for
-	  10 seconds. Each interval it will print out the number of events
+	  10 seconds. Each interval it will print out the number of event
 	  it recorded and give a rough estimate of how long each iteration took.
 
 	  It does not disable interrupts or raise its priority, so it may be
#53 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 10/15] 10: tracing: config option to enable both kprobe-tracer and uprobe-tracer.

Quoted 3 lines

Why are lots of end-of-line 's' character missing? :)

Okay will correct them.

<snipped>

Quoted 12 lines

kernel/trace/Kconfig config UPROBE_EVENT · line 386

Quoted 6 lines

config PROBE_EVENTS

kernel/trace/Kconfig +3 -1
-	def_bool n
+	bool "Enable kprobes and uprobe based dynamic events"
+	select TRACING
+	default n

Hmm, without this series, KPROBE_EVENT is set "y" by default. (PROBE_EVENTS is introduced by 8/15)
I'd like to set this "y" by default, because it doesn't affect other parts.

Quoted 2 lines

Thank you,

This is based on what we discussed here
http://lkml.org/lkml/2010/8/2/86.

To recollect,
Frederic wanted that there should be one option to select both UPROBE_EVENT and KPROBE_EVENT.

However if we make PROBE_EVENTS (which is the option to enable both events) default "Y", then both UPROBE_EVENT and KPROBE_EVENT will be selected.

Also if we look at http://lkml.org/lkml/2010/6/21/160, Steven Rostedt didnt want UPROBE_EVENT to selected by default.

I agree that we should keep UPROBE_EVENT to be 'default n' till it gets tested. Hence we have two choices. Either set the common knob to be 'default n' or dont have the common knob for now (i.e drop this patch for now).

I think we should go with the first one, i.e have a common knob thats by default unselected.

Signature · 2 lines
Thanks and Regards
Sriakr
#54 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 10/15] 10: tracing: config option to enable both kprobe-tracer and uprobe-tracer.

Quoted 28 lines · Srikar Dronamraju
Quoted 11 lines

kernel/trace/Kconfig config UPROBE_EVENT · line 386

Quoted 5 lines

config PROBE_EVENTS

kernel/trace/Kconfig +3 -1
-	def_bool n
+	bool "Enable kprobes and uprobe based dynamic events"
+	select TRACING
+	default n

Hmm, without this series, KPROBE_EVENT is set "y" by default. (PROBE_EVENTS is introduced by 8/15)
I'd like to set this "y" by default, because it doesn't affect other parts.

Quoted 2 lines

Thank you,

This is based on what we discussed here
http://lkml.org/lkml/2010/8/2/86.

To recollect,
Frederic wanted that there should be one option to select both UPROBE_EVENT and KPROBE_EVENT.

However if we make PROBE_EVENTS (which is the option to enable both events) default "Y", then both UPROBE_EVENT and KPROBE_EVENT will be selected.

Also if we look at http://lkml.org/lkml/2010/6/21/160, Steven Rostedt didnt want UPROBE_EVENT to selected by default.

Quoted 7 lines

I agree that we should keep UPROBE_EVENT to be 'default n' till it gets tested. Hence we have two choices. Either set the common knob to be 'default n' or dont have the common knob for now (i.e drop this patch for now).

I think we should go with the first one, i.e have a common knob thats by default unselected.

Yeah, I'm OK to have a common knob, but I just don't like to set KPROBE_EVENT unselected by default. I think there is no reason to change default selecting (currently, KPROBE_EVENT=y by default.)

So, I think we should have below selecting list; --- Tracers
...
[*] Enable dynamic events
[ ] Enable user-space dynamic events (EXPERIMENTAL)
...

What would you think about this ? :)

Thank you,

Signature · 4 lines
Masami HIRAMATSU
2nd Dept. Linux Technology Center
Hitachi, Ltd., Systems Development Laboratory
E-mail: [email protected]
#55 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 10/15] 10: tracing: config option to enable both kprobe-tracer and uprobe-tracer.

Quoted 7 lines
Quoted 3 lines

I think we should go with the first one, i.e have a common knob thats by default unselected.

Yeah, I'm OK to have a common knob, but I just don't like to set KPROBE_EVENT unselected by default. I think there is no reason to change default selecting (currently, KPROBE_EVENT=y by default.)

I understand your concern.

Quoted 11 lines

So, I think we should have below selecting list; --- Tracers
...
[*] Enable dynamic events
[ ] Enable user-space dynamic events (EXPERIMENTAL)
...

What would you think about this ? :)

Thank you,

Wouldnt it negate the purpose of common knob? Because people would still have go and select UPROBE_EVENTS,

I think when Frederic asked for a common knob, he was looking at enabling both or disabling both and an option to selectively select one of the tracers.

--
Thanks and Regards
Srikar

#56 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 10/15] 10: tracing: config option to enable both kprobe-tracer and uprobe-tracer.

Quoted 18 lines · Srikar Dronamraju
Quoted 7 lines
Quoted 3 lines

I think we should go with the first one, i.e have a common knob thats by default unselected.

Yeah, I'm OK to have a common knob, but I just don't like to set KPROBE_EVENT unselected by default. I think there is no reason to change default selecting (currently, KPROBE_EVENT=y by default.)

I understand your concern.

Quoted 8 lines

So, I think we should have below selecting list; --- Tracers
...
[*] Enable dynamic events
[ ] Enable user-space dynamic events (EXPERIMENTAL)
...

Quoted 7 lines
Quoted 3 lines

What would you think about this ? :)

Thank you,

Wouldnt it negate the purpose of common knob? Because people would still have go and select UPROBE_EVENTS,

Hmm, I think this just seems an enhancement of dynamic events, and also you can enable it by default on some point. I mean, eventually, there will be only "Enable dynamic events" on the screen.

Quoted 3 lines

I think when Frederic asked for a common knob, he was looking at enabling both or disabling both and an option to selectively select one of the tracers.

Yeah, but I'd like to ask Frederic that he expected disabling KPROBE_EVENT by default too, even though it changes current default config.

Thank you,

#57 lore raw

PATCH v11 10/15 10: tracing: config option to enable both kprobe-tracer and uprobe-tracer.

In reply to Masami Hiramatsu

Selecting CONFIG_PROBE_EVENTS enables both kprobe-based and uprobes-based dynamic events. However kprobe-tracer or uprobe-tracer can still be individually selected or disabled.

---

Changelog from V10: Fixed few erroneous changes: missing s at eol.
reported by Masami Hiramatsu.

 kernel/trace/Kconfig |   21 +++++++++++++++------
 1 files changed, 15 insertions(+), 6 deletions(-)
kernel/trace/Kconfig +15 -6
index 55ba474..77e04b0 100644
@@ -351,9 +351,8 @@ config BLK_DEV_IO_TRACE
 config KPROBE_EVENT
 	depends on KPROBES
 	depends on HAVE_REGS_AND_STACK_ACCESS_API
+	depends on PROBE_EVENTS
 	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)
@@ -370,10 +369,9 @@ config UPROBE_EVENT
 	bool "Enable uprobes-based dynamic events"
 	depends on ARCH_SUPPORTS_UPROBES
 	depends on MMU
+	depends on PROBE_EVENTS
 	select UPROBES
-	select PROBE_EVENTS
-	select TRACING
-	default n
+	default y
 	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.
@@ -383,7 +381,18 @@ config UPROBE_EVENT
 	  tools on user space applications.
 
 config PROBE_EVENTS
-	def_bool n
+	bool "Enable kprobes and uprobe based dynamic events"
+	select TRACING
+	default n
+	help
+	  This allows a user to add dynamic tracing events in
+	  kernel using kprobe-tracer and in userspace using
+	  uprobe-tracer. However users can still selectively
+	  disable one of these events.
+
+	  For more information on kprobe-tracer and uprobe-tracer
+	  please refer help under KPROBE_EVENT and UPROBE_EVENT
+	  respectively.
 
 config DYNAMIC_FTRACE
 	bool "enable/disable ftrace tracepoints dynamically"
#58 lore raw

PATCH v11 11/15 11: perf: list symbols in a dso in ascending order.

In reply to Srikar Dronamraju

Given a dso, list the symbols in ascending order. Needed for listing available symbols from perf-probe.

---

 tools/perf/util/symbol.c |   14 ++++++++++++++
 tools/perf/util/symbol.h |    1 +
 2 files changed, 15 insertions(+), 0 deletions(-)
tools/perf/util/symbol.c +14 -0
index 1a36773..ca22032 100644
@@ -388,6 +388,20 @@ size_t dso__fprintf_buildid(struct dso *self, FILE *fp)
 	return fprintf(fp, "%s", sbuild_id);
 }
 
+size_t dso__fprintf_symbols(struct dso *self, enum map_type type, FILE *fp)
+{
+	size_t ret = 0;
+	struct rb_node *nd;
+	struct symbol_name_rb_node *pos;
+
+	for (nd = rb_first(&self->symbol_names[type]); nd; nd = rb_next(nd)) {
+		pos = rb_entry(nd, struct symbol_name_rb_node, rb_node);
+		fprintf(fp, "%s\n", pos->sym.name);
+	}
+
+	return ret;
+}
+
 size_t dso__fprintf(struct dso *self, enum map_type type, FILE *fp)
 {
 	struct rb_node *nd;
tools/perf/util/symbol.h +1 -0
index b7a8da4..72ef973 100644
@@ -181,6 +181,7 @@ size_t machines__fprintf_dsos(struct rb_root *self, FILE *fp);
 size_t machines__fprintf_dsos_buildid(struct rb_root *self, FILE *fp, bool with_hits);
 
 size_t dso__fprintf_buildid(struct dso *self, FILE *fp);
+size_t dso__fprintf_symbols(struct dso *self, enum map_type type, FILE *fp);
 size_t dso__fprintf(struct dso *self, enum map_type type, FILE *fp);
 
 enum dso_origin {
#59 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 11/15] 11: perf: list symbols in a dso in ascending order.

Em Wed, Aug 25, 2010 at 07:13:29PM +0530, Srikar Dronamraju escreveu:

Quoted 2 lines

Given a dso, list the symbols in ascending order. Needed for listing available symbols from perf-probe.

Applied after renaming it to 'dso__fprintf_symbols_by_name', as at first I was scratching my head to figure out if we could reuse it in dso__fprintf() to then notice that it is in ascending _name_ order, not the default that is ordered by addr :-)

Please fixup the users, i.e. perf probe in your patchset.

- Arnaldo

#60 lore raw

Re: [PATCHv11 2.6.36-rc2-tip 11/15] 11: perf: list symbols in a dso in ascending order.

Quoted 8 lines · Arnaldo Carvalho de Melo

Em Wed, Aug 25, 2010 at 07:13:29PM +0530, Srikar Dronamraju escreveu:

Quoted 2 lines

Given a dso, list the symbols in ascending order. Needed for listing available symbols from perf-probe.

Applied after renaming it to 'dso__fprintf_symbols_by_name', as at first I was scratching my head to figure out if we could reuse it in dso__fprintf() to then notice that it is in ascending _name_ order, not the default that is ordered by addr :-)

Okay, Thanks for pushing it up.

Quoted 2 lines

Please fixup the users, i.e. perf probe in your patchset.

Yes, Shall send the refreshed patch now

Signature · 2 lines
Thanks and Regards
Srikar
#61 lore raw

[tip:perf/core] perf symbols: List symbols in a dso in ascending name order

In reply to Srikar Dronamraju
Commit-ID:  90f18e63fbd005133624bf18a5e8b75c92e90f4d
Gitweb:     http://git.kernel.org/tip/90f18e63fbd005133624bf18a5e8b75c92e90f4d
Author:     Srikar Dronamraju <[email protected]>
AuthorDate: Wed, 25 Aug 2010 19:13:29 +0530
Committer:  Arnaldo Carvalho de Melo <[email protected]>
CommitDate: Wed, 25 Aug 2010 17:28:59 -0300

perf symbols: List symbols in a dso in ascending name order

Given a dso, list the symbols in ascending name order. Needed for listing available symbols from perf probe.

Cc: Ananth N Mavinakayanahalli <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Christoph Hellwig <[email protected]>
Cc: "Frank Ch. Eigler" <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jim Keniston <[email protected]>
Cc: Mark Wielaard <[email protected]>
Cc: Masami Hiramatsu <[email protected]>
Cc: Mathieu Desnoyers <[email protected]>
Cc: Naren A Devaiah <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: "Paul E. McKenney" <[email protected]>
Cc: Randy Dunlap <[email protected]>
Cc: Srikar Dronamraju <[email protected]>
Cc: Steven Rostedt <[email protected]>
LKML-Reference: <[email protected]>

---
 tools/perf/util/symbol.c |   14 ++++++++++++++
 tools/perf/util/symbol.h |    1 +
 2 files changed, 15 insertions(+), 0 deletions(-)
tools/perf/util/symbol.c +14 -0
index 1a36773..a08e1cb 100644
@@ -388,6 +388,20 @@ size_t dso__fprintf_buildid(struct dso *self, FILE *fp)
 	return fprintf(fp, "%s", sbuild_id);
 }
 
+size_t dso__fprintf_symbols_by_name(struct dso *self, enum map_type type, FILE *fp)
+{
+	size_t ret = 0;
+	struct rb_node *nd;
+	struct symbol_name_rb_node *pos;
+
+	for (nd = rb_first(&self->symbol_names[type]); nd; nd = rb_next(nd)) {
+		pos = rb_entry(nd, struct symbol_name_rb_node, rb_node);
+		fprintf(fp, "%s\n", pos->sym.name);
+	}
+
+	return ret;
+}
+
 size_t dso__fprintf(struct dso *self, enum map_type type, FILE *fp)
 {
 	struct rb_node *nd;
tools/perf/util/symbol.h +1 -0
index b7a8da4..0a2c460 100644
@@ -181,6 +181,7 @@ size_t machines__fprintf_dsos(struct rb_root *self, FILE *fp);
 size_t machines__fprintf_dsos_buildid(struct rb_root *self, FILE *fp, bool with_hits);
 
 size_t dso__fprintf_buildid(struct dso *self, FILE *fp);
+size_t dso__fprintf_symbols_by_name(struct dso *self, enum map_type type, FILE *fp);
 size_t dso__fprintf(struct dso *self, enum map_type type, FILE *fp);
 
 enum dso_origin {
#62 lore raw

PATCH v11 12/15 12: perf: show possible probes in a given file.

In reply to Srikar Dronamraju

Introduces -S/--show_functions option for perf-probe.
This lists function names in a File. If no file is specified, then lists functions in the current running kernel.

---

Changelog from V10: As suggested by Arnaldo, filtering is now
based on sym.binding.

Changelog from V9: Filter labels, weak, and local binding functions from listing as suggested by Christoph Hellwig.

Show last 10 functions in /bin/zsh.

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

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

# perf probe -S -D /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

Show last 10 functions in kernel.

# perf probe -S | tail
zlib_inflateInit2
zlib_inflateReset
zlib_inflate_blob
zlib_inflate_table
zlib_inflate_workspacesize
zone_pcp_update
zone_reclaim
zone_reclaimable_pages
zone_statistics
zone_watermark_ok
 tools/perf/builtin-probe.c    |   43 ++++++++++++++++++++++++
 tools/perf/util/probe-event.c |   72 +++++++++++++++++++++++++++++++++++++++++
 tools/perf/util/probe-event.h |    1 +
 tools/perf/util/symbol.c      |    8 +++++
 tools/perf/util/symbol.h      |    1 +
 5 files changed, 124 insertions(+), 1 deletions(-)
tools/perf/builtin-probe.c +42 -1
index 199d5e1..fa63245 100644
@@ -50,9 +50,11 @@ static struct {
 	bool list_events;
 	bool force_add;
 	bool show_lines;
+	bool list_functions;
 	int nevents;
 	struct perf_probe_event events[MAX_PROBES];
 	struct strlist *dellist;
+	struct strlist *limitlist;
 	struct line_range line_range;
 	int max_probe_points;
 } params;
@@ -132,6 +134,19 @@ static int opt_show_lines(const struct option *opt __used,
 }
 #endif
 
+static int opt_limit_dsos(const struct option *opt __used,
+			       const char *str, int unset __used)
+{
+	if (str) {
+		if (!params.limitlist)
+			params.limitlist = strlist__new(true, NULL);
+		if (!params.limitlist)
+			return -1;
+		strlist__add(params.limitlist, str);
+	}
+	return 0;
+}
+
 static const char * const probe_usage[] = {
 	"perf probe [<options>] 'PROBEDEF' ['PROBEDEF' ...]",
 	"perf probe [<options>] --add 'PROBEDEF' [--add 'PROBEDEF' ...]",
@@ -188,6 +203,10 @@ static const struct option options[] = {
 	OPT__DRY_RUN(&probe_event_dry_run),
 	OPT_INTEGER('\0', "max-probes", &params.max_probe_points,
 		 "Set how many probe points can be found for a probe."),
+	OPT_BOOLEAN('S', "show_functions", &params.list_functions,
+				"Show potential probes."),
+	OPT_CALLBACK('D', "limit_dsos", NULL, "DSO",
+				"Limit Dsos.", opt_limit_dsos),
 	OPT_END()
 };
 
@@ -213,7 +232,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 		params.max_probe_points = MAX_PROBES;
 
 	if ((!params.nevents && !params.dellist && !params.list_events &&
-	     !params.show_lines))
+	     !params.show_lines && !params.list_functions))
 		usage_with_options(probe_usage, options);
 
 	if (params.list_events) {
@@ -225,12 +244,34 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 			pr_err("  Error: Don't use --list with --line.\n");
 			usage_with_options(probe_usage, options);
 		}
+		if (params.list_functions) {
+			pr_warning("  Error: Don't use --list with"
+						" --show_functions.\n");
+			usage_with_options(probe_usage, options);
+		}
 		ret = show_perf_probe_events();
 		if (ret < 0)
 			pr_err("  Error: Failed to show event list. (%d)\n",
 			       ret);
 		return ret;
 	}
+	if (params.list_functions) {
+		if (params.nevents != 0 || params.dellist) {
+			pr_err("  Error: Don't use --show_functions with"
+					" --add/--del.\n");
+			usage_with_options(probe_usage, options);
+		}
+		if (params.show_lines) {
+			pr_err("  Error: Don't use --show_functions with"
+					" --line.\n");
+			usage_with_options(probe_usage, options);
+		}
+		ret = show_possible_probes(params.limitlist);
+		if (ret < 0)
+			pr_err("  Error: Failed to show possible"
+					" probes (%d).\n", ret);
+		return ret;
+	}
 
 #ifdef DWARF_SUPPORT
 	if (params.show_lines) {
tools/perf/util/probe-event.c +72 -0

87 lines not on this page · raw message

tools/perf/util/probe-event.h +1 -0
index 5af3924..fcd0f08 100644
@@ -115,6 +115,7 @@ extern int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
 extern int del_perf_probe_events(struct strlist *dellist);
 extern int show_perf_probe_events(void);
 extern int show_line_range(struct line_range *lr);
+extern int show_possible_probes(struct strlist *availlist);
 
 
 /* Maximum index number of event-name postfix */
tools/perf/util/symbol.c +8 -0
index ca22032..385f0a4 100644
@@ -2464,3 +2464,11 @@ int machine__load_vmlinux_path(struct machine *self, enum map_type type,
 
 	return ret;
 }
+
+struct map *dso__new_map(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 72ef973..52a8126 100644
@@ -202,6 +202,7 @@ char dso__symtab_origin(const struct dso *self);
 void dso__set_long_name(struct dso *self, char *name);
 void dso__set_build_id(struct dso *self, void *build_id);
 void dso__read_running_kernel_build_id(struct dso *self, struct machine *machine);
+struct map *dso__new_map(char *name);
 struct symbol *dso__find_symbol(struct dso *self, enum map_type type, u64 addr);
 struct symbol *dso__find_symbol_by_name(struct dso *self, enum map_type type,
 					const char *name);
#63 lore raw

PATCH v11 12/15 12: perf: show possible probes in a given file.

Introduces -S/--show_functions option for perf-probe.
This lists function names in a File. If no file is specified, then lists functions in the current running kernel.

---

Changelog from V11: accomodate name change dso_fprintf_symbols_by_name.

Changelog from V10: As suggested by Arnaldo, filtering is now
based on sym.binding.

Changelog from V9: Filter labels, weak, and local binding functions from listing as suggested by Christoph Hellwig.

Show last 10 functions in /bin/zsh.

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

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

# perf probe -S -D /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

Show last 10 functions in kernel.

# perf probe -S | tail
zlib_inflateInit2
zlib_inflateReset
zlib_inflate_blob
zlib_inflate_table
zlib_inflate_workspacesize
zone_pcp_update
zone_reclaim
zone_reclaimable_pages
zone_statistics
zone_watermark_ok
---
 tools/perf/builtin-probe.c    |   43 ++++++++++++++++++++++++
 tools/perf/util/probe-event.c |   72 +++++++++++++++++++++++++++++++++++++++++
 tools/perf/util/probe-event.h |    1 +
 tools/perf/util/symbol.c      |    8 +++++
 tools/perf/util/symbol.h      |    1 +
 5 files changed, 124 insertions(+), 1 deletions(-)
tools/perf/builtin-probe.c +42 -1
index 199d5e1..fa63245 100644
@@ -50,9 +50,11 @@ static struct {
 	bool list_events;
 	bool force_add;
 	bool show_lines;
+	bool list_functions;
 	int nevents;
 	struct perf_probe_event events[MAX_PROBES];
 	struct strlist *dellist;
+	struct strlist *limitlist;
 	struct line_range line_range;
 	int max_probe_points;
 } params;
@@ -132,6 +134,19 @@ static int opt_show_lines(const struct option *opt __used,
 }
 #endif
 
+static int opt_limit_dsos(const struct option *opt __used,
+			       const char *str, int unset __used)
+{
+	if (str) {
+		if (!params.limitlist)
+			params.limitlist = strlist__new(true, NULL);
+		if (!params.limitlist)
+			return -1;
+		strlist__add(params.limitlist, str);
+	}
+	return 0;
+}
+
 static const char * const probe_usage[] = {
 	"perf probe [<options>] 'PROBEDEF' ['PROBEDEF' ...]",
 	"perf probe [<options>] --add 'PROBEDEF' [--add 'PROBEDEF' ...]",
@@ -188,6 +203,10 @@ static const struct option options[] = {
 	OPT__DRY_RUN(&probe_event_dry_run),
 	OPT_INTEGER('\0', "max-probes", &params.max_probe_points,
 		 "Set how many probe points can be found for a probe."),
+	OPT_BOOLEAN('S', "show_functions", &params.list_functions,
+				"Show potential probes."),
+	OPT_CALLBACK('D', "limit_dsos", NULL, "DSO",
+				"Limit Dsos.", opt_limit_dsos),
 	OPT_END()
 };
 
@@ -213,7 +232,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 		params.max_probe_points = MAX_PROBES;
 
 	if ((!params.nevents && !params.dellist && !params.list_events &&
-	     !params.show_lines))
+	     !params.show_lines && !params.list_functions))
 		usage_with_options(probe_usage, options);
 
 	if (params.list_events) {
@@ -225,12 +244,34 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 			pr_err("  Error: Don't use --list with --line.\n");
 			usage_with_options(probe_usage, options);
 		}
+		if (params.list_functions) {
+			pr_warning("  Error: Don't use --list with"
+						" --show_functions.\n");
+			usage_with_options(probe_usage, options);
+		}
 		ret = show_perf_probe_events();
 		if (ret < 0)
 			pr_err("  Error: Failed to show event list. (%d)\n",
 			       ret);
 		return ret;
 	}
+	if (params.list_functions) {
+		if (params.nevents != 0 || params.dellist) {
+			pr_err("  Error: Don't use --show_functions with"
+					" --add/--del.\n");
+			usage_with_options(probe_usage, options);
+		}
+		if (params.show_lines) {
+			pr_err("  Error: Don't use --show_functions with"
+					" --line.\n");
+			usage_with_options(probe_usage, options);
+		}
+		ret = show_possible_probes(params.limitlist);
+		if (ret < 0)
+			pr_err("  Error: Failed to show possible"
+					" probes (%d).\n", ret);
+		return ret;
+	}
 
 #ifdef DWARF_SUPPORT
 	if (params.show_lines) {
tools/perf/util/probe-event.c +72 -0

87 lines not on this page · raw message

tools/perf/util/probe-event.h +1 -0
index 5af3924..fcd0f08 100644
@@ -115,6 +115,7 @@ extern int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
 extern int del_perf_probe_events(struct strlist *dellist);
 extern int show_perf_probe_events(void);
 extern int show_line_range(struct line_range *lr);
+extern int show_possible_probes(struct strlist *availlist);
 
 
 /* Maximum index number of event-name postfix */
tools/perf/util/symbol.c +8 -0
index a08e1cb..1728d71 100644
@@ -2464,3 +2464,11 @@ int machine__load_vmlinux_path(struct machine *self, enum map_type type,
 
 	return ret;
 }
+
+struct map *dso__new_map(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 0a2c460..145953d 100644
@@ -202,6 +202,7 @@ char dso__symtab_origin(const struct dso *self);
 void dso__set_long_name(struct dso *self, char *name);
 void dso__set_build_id(struct dso *self, void *build_id);
 void dso__read_running_kernel_build_id(struct dso *self, struct machine *machine);
+struct map *dso__new_map(char *name);
 struct symbol *dso__find_symbol(struct dso *self, enum map_type type, u64 addr);
 struct symbol *dso__find_symbol_by_name(struct dso *self, enum map_type type,
 					const char *name);
#64 lore raw

Re: [PATCHv11a 2.6.36-rc2-tip 12/15] 12: perf: show possible probes in a given file.

Hi Srikar,

Quoted 3 lines · Srikar Dronamraju

Introduces -S/--show_functions option for perf-probe.
This lists function names in a File. If no file is specified, then lists functions in the current running kernel.

Hmm, I think the basic functionality of this patch (I mean functions in running kernel) could be merged separately from this series.

tools/perf/builtin-probe.c static const struct option options[] = { · line 209

Quoted 4 lines
tools/perf/builtin-probe.c +4 -0
+	OPT_BOOLEAN('S', "show_functions", &params.list_functions,
+				"Show potential probes."),
+	OPT_CALLBACK('D', "limit_dsos", NULL, "DSO",
+				"Limit Dsos.", opt_limit_dsos),

However, I'd rather use --funcs/-F and --dso/-D instead of above. :)

Thank you,

Signature · 4 lines
Masami HIRAMATSU
2nd Dept. Linux Technology Center
Hitachi, Ltd., Systems Development Laboratory
E-mail: [email protected]
#65 lore raw

PATCH v11 13/15 13: perf: Loop thro each of the maps in a map_group.

In reply to Srikar Dronamraju

Introduces map_groups_for_each_map that iterates over a map_group. This is useful while listing functions through perf-probe.

---
 tools/perf/util/map.h |   27 +++++++++++++++++++++++++++
 1 files changed, 27 insertions(+), 0 deletions(-)
tools/perf/util/map.h +27 -0
index 7857579..45b5f50 100644
@@ -54,6 +54,33 @@ struct map_groups {
 	struct machine	 *machine;
 };
 
+/* For map_groups iteration */
+static inline struct map *map__first(struct map_groups *self,
+						enum map_type type)
+{
+	struct rb_node *rn = rb_first(&self->maps[type]);
+	return rn ? rb_entry(rn, struct map, rb_node) : NULL;
+}
+
+static inline struct map *map__next(struct map *map)
+{
+	struct rb_node *rn;
+	if (!map)
+		return NULL;
+	rn = rb_next(&map->rb_node);
+	return rn ? rb_entry(rn, struct map, rb_node) : NULL;
+}
+
+/**
+ * map_groups__for_each_map      - iterate over a map_group
+ * @pos:	the &struct map to use as a loop cursor.
+ * @type:	the map type.
+ * @self:	the &struct map_groups for loop.
+ */
+#define map_groups__for_each_map(pos, type, self)	\
+	for (pos = map__first(self, type); pos;		\
+				pos = map__next(pos))
+
 /* Native host kernel uses -1 as pid index in machine */
 #define	HOST_KERNEL_ID			(-1)
 #define	DEFAULT_GUEST_KERNEL_ID		(0)
#66 lore raw

PATCH v11 14/15 14: perf: perf interface for uprobes

In reply to Srikar Dronamraju

Enhances perf probe to accept pid and user vaddr.
Provides very basic support for uprobes.

TODO:
Update perf-probes.txt.
Global tracing.

---

Changelog from V10: split few independent hunks into different
patches as suggested by Arnaldo.

Changelog from v9: Renaming common fields/functions to refer to probe instead of kprobe. This was suggested by Arnaldo.

Changelog from v8: Fixed a build break reported by Christoph Hellwig.

Changelog from v6: Changelog from v6: Fixed a bug reported by Masami.
i.e Throw an error message and exit if perf probe is for a dwarf based probes.

Changelog from v4: Merged to 2.6.35-rc3-tip.

Changelog from v3: (addressed comments from Masami Hiramatsu)
* Every process id has a different group name.
* event name starts with function name.
* If vaddr is specified, event name has vaddr appended along with function name, (this is to avoid subsequent probes using same event name.)
* warning if -p and --list options are used together.

Also dso can either be a short name or absolute path.

Here is a terminal snapshot of placing, using and removing a probe on a process with pid 3591 (corresponding to zsh)

[ Probing a function in the executable using function name ]
-------------------------------------------------------------

[root@ABCD]# perf probe -p 3591 zfree@zsh
Added new event:
  probe_3591:zfree                       (on 0x446420)

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

perf record -e probe_3591:zfree -a sleep 1

[root@ABCD]# perf probe --list
probe_3591:zfree                       (on 3591:0x0000000000446420)
[root@ABCD]# cat /sys/kernel/debug/tracing/uprobe_events
p:probe_3591/zfree 3591:0x0000000000446420
[root@ABCD]# perf record -f -e probe_3591:zfree -a sleep 10
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.039 MB perf.data (~1716 samples) ]
[root@ABCD]# perf probe -p 3591 --del probe_3591:zfree
Remove event: probe_3591:zfree
[root@ABCD]# perf report
# Samples: 447
#
# Overhead          Command  Shared Object  Symbol
# ........  ...............  .............  ......
#
   100.00%              zsh  zsh            [.] zfree

#
# (For a higher level overview, try: perf report --sort comm,dso) #

[ Probing a function + offset ]
-------------------------------

[root@ABCD]# perf probe -p 3591 zfree@zsh+5
Added new event:
  probe_3591:zfree                         (on 0x446425)

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

perf record -e probe_3591:zfree -a sleep 1

[root@ABCD]# perf probe --list
probe_3591:zfree                       (on 3591:0x0000000000446425)
[root@ABCD]# cat /sys/kernel/debug/tracing/uprobe_events
p:probe_3591/zfree 3591:0x0000000000446425
[root@ABCD]# perf record -f -e probe_3591:zfree -a sleep 10
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.036 MB perf.data (~1590 samples) ]
[root@ABCD]# perf probe -p 3591 --del probe_3591:zfree
Remove event: probe_3591:zfree
[root@ABCD]# perf report
# Samples: 18
#
# Overhead          Command  Shared Object  Symbol
# ........  ...............  .............  ......
#
   100.00%              zsh  zsh            [.] zfree

#
# (For a higher level overview, try: perf report --sort comm,dso) #

[ Probing a library function using function name ]
--------------------------------------------------

[root@ABCD]# perf probe -p 3591 [email protected]
Added new event:
  probe_3591:write                       (on 0x36010c6060)

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

perf record -e probe_3591:write -a sleep 1

[root@ABCD]# perf probe --list
probe_3591:write                       (on 3591:0x00000036010c6060)
[root@ABCD]# cat /sys/kernel/debug/tracing/uprobe_events
p:probe_3591/write 3591:0x00000036010c6060
[root@ABCD]# perf record -f -e probe_3591:write -a sleep 10
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.040 MB perf.data (~1738 samples) ]
[root@ABCD]# perf probe -p 3591 --del probe_3591:write
Remove event: probe_3591:write
[root@ABCD]# perf report
# Samples: 11
#
# Overhead          Command       Shared Object  Symbol
# ........  ...............  ..................  ......
#
   100.00%              zsh  libc-2.5.so         [.] __GI___libc_write

#
# (For a higher level overview, try: perf report --sort comm,dso) #

[ Probing a library function using function name and absolute path ]
---------------------------------------------------------------------

[root@ABCD]# perf probe -p 3591 write@/lib64/libc-2.5.so
Added new event:
  probe_3591:write                       (on 0x36010c6060)

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

perf record -e probe_3591:write -a sleep 1

[root@ABCD]# perf probe --list
probe_3591:write                       (on 3591:0x00000036010c6060)
[root@ABCD]# cat /sys/kernel/debug/tracing/uprobe_events
p:probe_3591/write 3591:0x00000036010c6060
[root@ABCD]# perf record -f -e probe_3591:write -a sleep 10
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.040 MB perf.data (~1738 samples) ]
[root@ABCD]# perf probe -p 3591 --del probe_3591:write
Remove event: probe_3591:write
[root@ABCD]# perf report
# Samples: 11
#
# Overhead          Command       Shared Object  Symbol
# ........  ...............  ..................  ......
#
   100.00%              zsh  libc-2.5.so         [.] __GI___libc_write

#
# (For a higher level overview, try: perf report --sort comm,dso) #

[ Probing using vaddr 0x0000000000446420 (corresponding to zfree)]
-------------------------------------------------------------------

[root@ABCD]# perf probe -p 3591 0x0000000000446420
Added new event:
  probe_3591:zfree_446420          (on 0x0000000000446420)

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

        perf record -e probe_3591:zfree_446420 -a sleep 1
[root@ABCD]# perf record -e probe_3591:zfree_446420 -a sleep 10
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.041 MB perf.data (~1797 samples) ]
[root@ABCD]# perf report
#
# Samples: 628
#
# Overhead          Command  Shared Object  Symbol
# ........  ...............  .............  ......
#
   100.00%              zsh  zsh            [.] zfree

#
# (For a higher level overview, try: perf report --sort comm,dso) #

[root@ABCD]# perf report --sort comm,dso
# Samples: 628
#
# Overhead          Command  Shared Object
# ........  ...............  .............
#
   100.00%              zsh  zsh
[root@ABCD]# perf probe --list
  probe_3591:zfree_446420          (on 3591:0x0000000000446420)
[root@ABCD]#  perf list | grep probe
  probe_3591:zfree_446420            [Tracepoint event]
[root@ABCD]# perf probe -p 3591 --del probe_3591:zfree_446420
Remove event: probe_3591:zfree_446420
[root@ABCD]#

Another example for a shared library: write stub in libc. (corresponds to 0x00000036010c6060)

on a vaddr
[ Probing a libc vaddr 0x00000036010c6060 (corresponding to write) ]

[root@ABCD]# perf probe -p 3591 0x00000036010c6060
dded new event:
  probe_3591:__GI___libc_write_36010c6060          (on 0x00000036010c6060)

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

        perf record -e probe_3591:__GI___libc_write_36010c6060 -a sleep 1
[root@ABCD]# perf record -f -e probe_3591:__GI___libc_write_36010c6060 -a sleep 10
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.040 MB perf.data (~1748 samples) ]
[root@ABCD]# perf report
# Samples: 24
#
# Overhead          Command       Shared Object  Symbol
# ........  ...............  ..................  ......
#
   100.00%              zsh  libc-2.5.so         [.] __GI___libc_write

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

[ Probing using a function without specifying a dso (corresponding to zfree)]
-------------------------------------------------------------------

[root@ABCD]# perf probe -p 3591 zfree
Added new event:
  probe_3591:zfree		          (on 0x0000000000446420)

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

perf record -e probe_3591:zfree -a sleep 1

[root@ABCD]# perf record -e probe_3591:zfree -a sleep 10
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.041 MB perf.data (~1797 samples) ]
[root@ABCD]# perf report
#
# Samples: 628
#
# Overhead          Command  Shared Object  Symbol
# ........  ...............  .............  ......
#
   100.00%              zsh  zsh            [.] zfree

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

 tools/perf/builtin-probe.c    |   12 +
 tools/perf/util/probe-event.c |  389 +++++++++++++++++++++++++++++++++--------
 tools/perf/util/probe-event.h |   10 +
 3 files changed, 328 insertions(+), 83 deletions(-)
tools/perf/builtin-probe.c +10 -2
index fa63245..afca6ae 100644
@@ -57,6 +57,7 @@ static struct {
 	struct strlist *limitlist;
 	struct line_range line_range;
 	int max_probe_points;
+	pid_t upid;
 } params;
 
 
@@ -75,6 +76,7 @@ static int parse_probe_event(const char *str)
 	/* Parse a perf-probe command into event */
 	ret = parse_perf_probe_command(str, pev);
 	pr_debug("%d arguments\n", pev->nargs);
+	pev->upid = params.upid;
 
 	return ret;
 }
@@ -207,6 +209,8 @@ static const struct option options[] = {
 				"Show potential probes."),
 	OPT_CALLBACK('D', "limit_dsos", NULL, "DSO",
 				"Limit Dsos.", opt_limit_dsos),
+	OPT_INTEGER('p', "pid", &params.upid,
+			"Specify pid of process where probe will be added"),
 	OPT_END()
 };
 
@@ -249,6 +253,10 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 						" --show_functions.\n");
 			usage_with_options(probe_usage, options);
 		}
+		if (params.upid) {
+			pr_warning("  Error: Don't use --list with --pid.\n");
+			usage_with_options(probe_usage, options);
+		}
 		ret = show_perf_probe_events();
 		if (ret < 0)
 			pr_err("  Error: Failed to show event list. (%d)\n",
@@ -274,7 +282,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 	}
 
 #ifdef DWARF_SUPPORT
-	if (params.show_lines) {
+	if (params.show_lines && !params.upid) {
 		if (params.nevents != 0 || params.dellist) {
 			pr_warning("  Error: Don't use --line with"
 				   " --add/--del.\n");
@@ -289,7 +297,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 #endif
 
 	if (params.dellist) {
-		ret = del_perf_probe_events(params.dellist);
+		ret = del_perf_probe_events(params.dellist, params.upid);
 		strlist__delete(params.dellist);
 		if (ret < 0) {
 			pr_err("  Error: Failed to delete events. (%d)\n", ret);
tools/perf/util/probe-event.c +312 -77

594 lines not on this page · raw message

tools/perf/util/probe-event.h +6 -4
index fcd0f08..9cf1bcc 100644
@@ -6,7 +6,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 */
 	unsigned long	offset;		/* Offset from symbol */
@@ -19,7 +19,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 */
@@ -27,12 +27,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 */
+	pid_t				upid;	/* uprobes only */
 	struct probe_trace_arg		*args;	/* Arguments */
 };
 
@@ -68,6 +69,7 @@ struct perf_probe_event {
 	char			*group;	/* Group name */
 	struct perf_probe_point	point;	/* Probe point */
 	int			nargs;	/* Number of arguments */
+	pid_t			upid;
 	struct perf_probe_arg	*args;	/* Arguments */
 };
 
@@ -112,7 +114,7 @@ extern int parse_line_range_desc(const char *cmd, struct line_range *lr);
 
 extern int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
 				 bool force_add, int max_probe_points);
-extern int del_perf_probe_events(struct strlist *dellist);
+extern int del_perf_probe_events(struct strlist *dellist, pid_t pid);
 extern int show_perf_probe_events(void);
 extern int show_line_range(struct line_range *lr);
 extern int show_possible_probes(struct strlist *availlist);
#67 lore raw

PATCH v11 15/15 15: perf: Show Potential probe points.

In reply to Srikar Dronamraju

Introduces an option to list potential probes to probe using perf probe command. Also introduces an option to limit the dso to list the potential probes. Listing of potential probes is sorted by dso and alphabetical order.

---

Changelog from V9:
Filter labels, weak, and local binding functions from listing
as suggested by Christoph Hellwig.
Incorporated comments from Arnaldo on Version 9 of patchset.

Show all potential probes in the current running kernel and limit to the last 10 functions.

# perf probe -S | tail
zlib_inflateInit2
zlib_inflateReset
zlib_inflate_blob
zlib_inflate_table
zlib_inflate_workspacesize
zone_pcp_update
zone_reclaim
zone_reclaimable_pages
zone_statistics
zone_watermark_ok

Show all potential probes in a process by pid 3104 across all dsos and limit to the last 10 functions.

# perf probe -S -p 3104 | tail
_nss_files_setgrent
_nss_files_sethostent
_nss_files_setnetent
_nss_files_setnetgrent
_nss_files_setprotoent
_nss_files_setpwent
_nss_files_setrpcent
_nss_files_setservent
_nss_files_setspent
_nss_netgroup_parseline

Show all potentail probes in a process by pid 3104 limit to zsh dso and limit to the last 10 functions.

# perf probe -S -p 3104 -D zsh | tail
zstrtol
ztrcmp
ztrdup
ztrduppfx
ztrftime
ztrlen
ztrncpy
ztrsub
zwarn
zwarnnam
 tools/perf/builtin-probe.c    |    2 +
 tools/perf/util/probe-event.c |   68 +++++++++++++++++++++++++++++++++--------
 tools/perf/util/probe-event.h |    4 +-
 3 files changed, 56 insertions(+), 18 deletions(-)
tools/perf/builtin-probe.c +1 -1
index afca6ae..f5893d9 100644
@@ -274,7 +274,7 @@ int cmd_probe(int argc, const char **argv, const char *prefix __used)
 					" --line.\n");
 			usage_with_options(probe_usage, options);
 		}
-		ret = show_possible_probes(params.limitlist);
+		ret = show_possible_probes(params.limitlist, params.upid);
 		if (ret < 0)
 			pr_err("  Error: Failed to show possible"
 					" probes (%d).\n", ret);
tools/perf/util/probe-event.c +54 -14

106 lines not on this page · raw message

tools/perf/util/probe-event.h +1 -3
index 9cf1bcc..4a40d2c 100644
@@ -111,14 +111,12 @@ extern void clear_perf_probe_event(struct perf_probe_event *pev);
 /* Command string to line-range */
 extern int parse_line_range_desc(const char *cmd, struct line_range *lr);
 
-
 extern int add_perf_probe_events(struct perf_probe_event *pevs, int npevs,
 				 bool force_add, int max_probe_points);
 extern int del_perf_probe_events(struct strlist *dellist, pid_t pid);
 extern int show_perf_probe_events(void);
 extern int show_line_range(struct line_range *lr);
-extern int show_possible_probes(struct strlist *availlist);
-
+extern int show_possible_probes(struct strlist *availlist, pid_t pid);
 
 /* Maximum index number of event-name postfix */
 #define MAX_EVENT_INDEX	1024
#69 lore raw
Quoted 4 lines

It's been a while since the last posting. Did you make any progress on uprobes, especially allowing to define probes based on a file name?

Thanks for checking, I discussed with Peter offline and ironed out most of the issues. I am thankful for Peter for all the suggestions

I am still getting the inode based uprobes to shape. Here is the brief summary of the discussion.

Significant differences from the previous patchset are:

- All probes would be maintained in a global rbtree sorted by inode and offset.
- There can be one or more consumers per probe. With each consumer there will be one handler and one (optional) filter.
- Filter restricts the processes/tasks that the handler is active.
- uprobe structure is dynamically created when the first consumer registers to the probe. It gets deallocated when all consumers unregisters from the probe.
- While registering a probe, we walk thro the list of vmas that are mapped to the inode, check if the consumer wants to probe the task corresponding to the vma and inserts the breakpoint.
- unregistering a probe also does something similar except for deleting the probe.
- There will be a hook in mmap/unmap to install probes as and when the vma gets loaded into process address space. This hook would walk thro the tree of probes for that inode and for each probe, walk thro the list of consumers and insert/delete breakpoints accordingly.
- There will be a hook in fork to install probes in newly created processes. This hook would walk thro the tree of probes for that inode and for each probe, walk thro the list of consumers and insert/delete breakpoints accordingly.
- Slots will still hang-out of mm_struct.
- Instead of the per-probe slot, we would have to use a per-thread slot. (This slot is for single stepping out of line). On every probehit, the slot has to be refreshed with the correct contents.
- Since probe information is stored as inode:offset, probe identification on a breakpoint hit can only happen in task context.

Current issues: Given a vma; finding all tasks that have this vma mapped. The current solution seems to walk thro all tasks in the system and check if each task's mm field. But this could be inefficient especially if the vma is part of all processes like libc etc. I dont think we can use mm->owner to walk thro all the tasks that map to this mm_struct.

Slot allocation delays: Using a per-thread slot instead of a per-probe slot leads to a 3.5X degradation in performance. If we need to use per-probe slots, we would have to have maintain metadata, i.e the slot to virtual address mapping per process. However Peter prefers that we reduce such metadata.

If a sigtrap occurs not because of a uprobe, we queue the signal only in the task context. This is because we cannot identify the cause for trap in interrupt context. If we use per-probe slots, we could avoid this.

Uprobes may not be able to trace a long-time running process if its mapped a file that got updated after the process started. This assumes the probes were placed after the process was started.

To cover the race where a breakpoint is hit while the probe is being deleted, Paul has agreed to enhance srcu to work in interrupt context.

Quoted 1 line

From a perf/ftrace perspective:

Assuming 3551 as pid
0x0000000000446420 as the vaddr of the probe for zfree 0x0000000000046420 as the offset of zfree from start of text address. 130904 as the inode number for the /bin/zsh

ftrace interface:
Previously:

# echo 'p 3551:0x0000000000446420 %ip %ax' > uprobe_events
# cat uprobe_events
p:uprobes/p_3551_0x0000000000446420 3551:0x0000000000446420 %ip=%ip %ax=%ax

Now:

# echo 'p /path-to-/file:0x0000000000046420 %ip %ax' > uprobe_events
# cat uprobe_events
p:uprobes/p_file_0x0000000000446420 130904:0x0000000000046420 %ip=%ip %ax=%ax

perf interface:
Previously:

# perf probe -p 3551 zfree@zsh
Added new event:
  probe_3551:zfree                       (on 0x446420)
# perf probe --list
probe_3551:zfree                       (on 3551:0x0000000000446420)

Now:

# perf probe zfree@zsh
Added new event:
  probe_zsh:zfree                      (on 130904:0x46420)
# perf probe --list
probe_zsh:zfree                       (on 130904:0x0000000000046420)

JFYI: v11 patchset code that I last posted to LKML is available at:
git://git.kernel.org/pub/scm/linux/kernel/git/srikar/linux-uprobes.git
branch : uprobes_v11_patchset

Peter knows the details/trade-offs of both the designs.(v11 and the inode based probes)

Signature · 2 lines
Thanks and Regards
Srikar
#70 lore raw
Quoted 4 lines · Srikar Dronamraju

Current issues: Given a vma; finding all tasks that have this vma mapped. The current solution seems to walk thro all tasks in the system and check if each task's mm field. But this could be inefficient especially if the vma is part of all processes like libc etc.

It's pretty much guaranteed to be inefficient, yes.

Quoted 2 lines

I dont think we can use mm->owner to walk thro all the tasks that map to this mm_struct.

I don't see a way around that if we have to find the task by the vma.

You'll have to start with vma->vm_mm->owner and then walk the list of thread siblings inside the heavy weight process.

Quoted 5 lines

Slot allocation delays: Using a per-thread slot instead of a per-probe slot leads to a 3.5X degradation in performance. If we need to use per-probe slots, we would have to have maintain metadata, i.e the slot to virtual address mapping per process. However Peter prefers that we reduce such metadata.

The performance numbers are pretty drastic. But I'll let Peter comment on the desire in more detail. I'm really not in enough touch with this code anymore to give too useful comments.

Quoted 1 line
Quoted 1 line

From a perf/ftrace perspective:

I really prefer the new interface. But as said before I'm just a user here and I don't care how it's implemented underneath. I'll defer to Peter and others knowing the code in more detail to make the trade offs between the different low level implementations.