mmiotrace full patch, preview 2
Subsystems (4)
RFC 1/1 mmiotrace full patch, preview 2
Hi all,
I've made some progress on mmiotrace and now it can actually work as a built-in. Previously mmio-mod.c was full of locking bugs, which never triggered, because a traced (binary) kernel module depended on the mmiotrace module.
Changes between preview 1 and preview 2 include:
- Bug and style fixes in Kconfig.debug, Makefile, testmmiotrace.c, mutex usage, and failure path in register probe function.
- RCU read-lock held over single stepping in kmmio.c
- mmio-mod.c is now a built-in with rewritten locking
- Added debugfs file to enable/disable mmiotracing, since this is not a module anymore. (Temporary solution)
- Marker file moved from /proc into debugfs.
- mmiotrace entrypoints called directly from ioremap.c, which is why this cannot be a module anymore.
It still uses relay for pushing data into user space, this would be replaced by ftrace, along with the "enabled" debugfs file.
The kernel argument mmiotrace.enable_now=1 can be used to enable mmiotracing at boot. I have tried this and it seems to work well, I get about 80k events from boot until starting the user space logger program by hand. Buffers are big enough that no event is missed due to out-of-memory.
I have also tried tracing Nouveau, started X, and disabled mmiotracing while in X. Works fine, the logger program just starts to hog cpu. The logger program will become 'cat' when we get to ftrace.
Hooking or modifying kernel module files is not needed anymore, mmiotrace will trace everything that is ioremapped after it has been enabled. Well, everything that __ioremap() actually maps, not including e.g. ISA area.
The only thing checkpatch.pl complains about is the use of "volatile", but that is part of the original declaration of iounmap().
The next step would be going for ftrace framework.
This patch is against torvalds/linux-2.6.git master. I will reply to this email with a patch for Ingo's x86/testing branch.
--- arch/x86/Kconfig.debug | 29 ++ arch/x86/mm/Makefile | 5 + arch/x86/mm/fault.c | 13 + arch/x86/mm/ioremap.c | 9 +- arch/x86/mm/kmmio.c | 533 ++++++++++++++++++++++++++++++++++ arch/x86/mm/mmio-mod.c | 666 +++++++++++++++++++++++++++++++++++++++++++ arch/x86/mm/pageattr.c | 1 + arch/x86/mm/pf_in.c | 489 +++++++++++++++++++++++++++++++ arch/x86/mm/pf_in.h | 39 +++ arch/x86/mm/testmmiotrace.c | 71 +++++ include/linux/mmiotrace.h | 120 ++++++++ 11 files changed, 1974 insertions(+), 1 deletions(-)
arch/x86/Kconfig.debug +29 -0
@@ -134,6 +134,35 @@ config IOMMU_LEAK Add a simple leak tracer to the IOMMU code. This is useful when you are debugging a buggy device driver that leaks IOMMU mappings. +config MMIOTRACE_HOOKS + bool + +config MMIOTRACE + bool "Memory mapped IO tracing" + depends on DEBUG_KERNEL && RELAY && DEBUG_FS + select MMIOTRACE_HOOKS + default y + help + Mmiotrace traces Memory Mapped I/O access and is meant for + debugging and reverse engineering. It is called from the ioremap + implementation and works via page faults. A user space program is + required to collect the MMIO data from debugfs files. + Tracing is disabled by default and can be enabled from a debugfs + file. + + See http://nouveau.freedesktop.org/wiki/MmioTrace + If you are not helping to develop drivers, say N. + +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 + 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. + + Say N, unless you absolutely know what you are doing. + # # IO delay types: #
arch/x86/mm/Makefile +5 -0
@@ -3,3 +3,8 @@ include ${srctree}/arch/x86/mm/Makefile_32 else include ${srctree}/arch/x86/mm/Makefile_64 endif + +obj-$(CONFIG_MMIOTRACE_HOOKS) += kmmio.o +obj-$(CONFIG_MMIOTRACE) += mmiotrace.o +mmiotrace-y := pf_in.o mmio-mod.o +obj-$(CONFIG_MMIOTRACE_TEST) += testmmiotrace.o
arch/x86/mm/fault.c +13 -0
@@ -25,6 +25,7 @@#include <linux/kprobes.h> #include <linux/uaccess.h> #include <linux/kdebug.h> +#include <linux/mmiotrace.h> #include <asm/system.h> #include <asm/desc.h>
@@ -49,6 +50,16 @@#define PF_RSVD (1<<3)#define PF_INSTR (1<<4) +static inline int kmmio_fault (struct pt_regs *regs,unsigned long addr) +{ +#ifdef CONFIG_MMIOTRACE_HOOKS +if (unlikely (is_kmmio_active ())) +if (kmmio_handler (regs, addr) ==1 ) +return -1 ; +#endif +return 0 ; +} +static inline int notify_page_fault (struct pt_regs *regs) {#ifdef CONFIG_KPROBES
@@ -603,6 +614,8 @@ void __kprobes do_page_fault(struct pt_regs *regs, unsigned long error_code)if (notify_page_fault (regs))return ; +if (unlikely (kmmio_fault (regs, address))) +return ;/* * We fault-in kernel-space virtual memory on-demand. The
arch/x86/mm/ioremap.c +8 -1
@@ -12,6 +12,7 @@#include <linux/module.h> #include <linux/slab.h> #include <linux/vmalloc.h> +#include <linux/mmiotrace.h> #include <asm/cacheflush.h> #include <asm/e820.h>
@@ -112,6 +113,7 @@ static void __iomem *__ioremap(unsigned long phys_addr, unsigned long size,unsigned long pfn, offset, last_addr, vaddr;struct vm_struct *area;pgprot_t prot; +void __iomem *ret_addr;/* Don't allow wraparound or zero size */ last_addr = phys_addr + size -1 ;
@@ -171,7 +173,10 @@ static void __iomem *__ioremap(unsigned long phys_addr, unsigned long size,return NULL ; } -return (void __iomem *) (vaddr + offset); + ret_addr = (void __iomem *) (vaddr + offset); +mmiotrace_ioremap (phys_addr, size, ret_addr); + +return ret_addr; }/**
@@ -229,6 +234,8 @@ void iounmap(volatile void __iomem *addr) addr < phys_to_virt(ISA_END_ADDRESS))return ; +mmiotrace_iounmap (addr); + addr = (volatile void __iomem *) (PAGE_MASK & (unsigned long __force )addr);
arch/x86/mm/kmmio.c new file +533 -0
533 lines not on this page · raw message
arch/x86/mm/mmio-mod.c new file +666 -0
666 lines not on this page · raw message
arch/x86/mm/pageattr.c +1 -0
@@ -223,6 +223,7 @@ pte_t *lookup_address(unsigned long address, unsigned int *level)return pte_offset_kernel (pmd, address); } +EXPORT_SYMBOL_GPL (lookup_address);/* * Set the new pmd in all the pgds we know about:
arch/x86/mm/pf_in.c new file +489 -0
489 lines not on this page · raw message
arch/x86/mm/pf_in.h new file +39 -0
@@ -0,0 +1,39 @@ +/* +* Fault Injection Test harness (FI) +* Copyright (C) Intel Crop. +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, +* USA. +* +*/ + +#ifndef __PF_H_ +#define __PF_H_ + +enum reason_type { +NOT_ME ,/* page fault is not in regions */ +NOTHING ,/* access others point in regions */ +REG_READ ,/* read from addr to reg */ +REG_WRITE ,/* write from reg to addr */ +IMM_WRITE ,/* write from imm to addr */ +OTHERS /* Other instructions can not intercept */ +}; + +enum reason_type get_ins_type (unsigned long ins_addr); +unsigned int get_ins_mem_width (unsigned long ins_addr); +unsigned long get_ins_reg_val (unsigned long ins_addr,struct pt_regs *regs); +unsigned long get_ins_imm_val (unsigned long ins_addr); + +#endif /* __PF_H_ */
arch/x86/mm/testmmiotrace.c new file +71 -0
71 lines not on this page · raw message
include/linux/mmiotrace.h new file +120 -0
120 lines not on this page · raw message
Quoted 1 line
From
bc32dcfb4048bb74c774fd3de724bd38e8b98c2fMon Sep 17 00:00:00 2001
From: Pekka Paalanen <[email protected]>
Date: Sun, 9 Mar 2008 13:52:25 +0200
Subject: [PATCH] x86 mmiotrace: update preview 1 to preview 2
Kconfig.debug, Makefile and testmmiotrace.c style fixes. Use real mutex instead of mutex.
Fix failure path in register probe func.
kmmio: RCU read-locked over single stepping. Generate mapping id's.
Make mmio-mod.c built-in and rewrite its locking. Add debugfs file to enable/disable mmiotracing.
kmmio: use irqsave spinlocks.
Lots of cleanups in mmio-mod.c
Marker file moved from /proc into debugfs.
Call mmiotrace entrypoints directly from ioremap.c.
--- arch/x86/Kconfig.debug | 20 +-- arch/x86/mm/Makefile | 2 +- arch/x86/mm/ioremap.c | 9 +- arch/x86/mm/kmmio.c | 72 ++++----- arch/x86/mm/mmio-mod.c | 397 ++++++++++++++++++++++++++++--------------- arch/x86/mm/testmmiotrace.c | 15 +- include/linux/mmiotrace.h | 18 ++- 7 files changed, 332 insertions(+), 201 deletions(-)
arch/x86/Kconfig.debug +8 -12
@@ -183,22 +183,19 @@ config SYSPROF config MMIOTRACE_HOOKS bool - default n config MMIOTRACE - tristate "Memory mapped IO tracing" + bool "Memory mapped IO tracing" depends on DEBUG_KERNEL && RELAY && DEBUG_FS select MMIOTRACE_HOOKS - default n + default y help - This will build a kernel module called mmiotrace. - Making this a built-in is heavily discouraged. - - Mmiotrace traces Memory Mapped I/O access and is meant for debugging - and reverse engineering. The kernel module offers wrapped - versions of the ioremap family of functions. The driver to be traced - must be modified to call these wrappers. A user space program is - required to collect the MMIO data. + Mmiotrace traces Memory Mapped I/O access and is meant for + debugging and reverse engineering. It is called from the ioremap + implementation and works via page faults. A user space program is + required to collect the MMIO data from debugfs files. + Tracing is disabled by default and can be enabled from a debugfs + file. See http://nouveau.freedesktop.org/wiki/MmioTrace If you are not helping to develop drivers, say N.
@@ -206,7 +203,6 @@ config MMIOTRACE config MMIOTRACE_TEST tristate "Test module for mmiotrace" depends on MMIOTRACE && m - default n help This is a dumb module for testing mmiotrace. It is very dangerous as it will write garbage to IO memory starting at a given address.
arch/x86/mm/Makefile +1 -1
@@ -5,7 +5,7 @@ obj-$(CONFIG_X86_32) += pgtable_32.o obj-$(CONFIG_MMIOTRACE_HOOKS) += kmmio.o obj-$(CONFIG_MMIOTRACE) += mmiotrace.o -mmiotrace-objs := pf_in.o mmio-mod.o +mmiotrace-y := pf_in.o mmio-mod.o obj-$(CONFIG_MMIOTRACE_TEST) += testmmiotrace.o obj-$(CONFIG_HUGETLB_PAGE) += hugetlbpage.o
arch/x86/mm/ioremap.c +8 -1
@@ -12,6 +12,7 @@#include <linux/module.h> #include <linux/slab.h> #include <linux/vmalloc.h> +#include <linux/mmiotrace.h> #include <asm/cacheflush.h> #include <asm/e820.h>
@@ -124,6 +125,7 @@ static void __iomem *__ioremap(unsigned long phys_addr, unsigned long size,unsigned long pfn, offset, last_addr, vaddr;struct vm_struct *area;pgprot_t prot; +void __iomem *ret_addr;/* Don't allow wraparound or zero size */ last_addr = phys_addr + size -1 ;
@@ -191,7 +193,10 @@ static void __iomem *__ioremap(unsigned long phys_addr, unsigned long size,return NULL ; } -return (void __iomem *) (vaddr + offset); + ret_addr = (void __iomem *) (vaddr + offset); +mmiotrace_ioremap (phys_addr, size, ret_addr); + +return ret_addr; }/**
@@ -249,6 +254,8 @@ void iounmap(volatile void __iomem *addr) addr < phys_to_virt(ISA_END_ADDRESS))return ; +mmiotrace_iounmap (addr); + addr = (volatile void __iomem *) (PAGE_MASK & (unsigned long __force )addr);
arch/x86/mm/kmmio.c +32 -40
197 lines not on this page · raw message
arch/x86/mm/mmio-mod.c +261 -136
601 lines not on this page · raw message
arch/x86/mm/testmmiotrace.c +5 -10
@@ -4,10 +4,6 @@#include <linux/module.h> #include <asm/io.h> -extern void __iomem *ioremap_nocache_trace (unsigned long offset, -unsigned long size); -extern void iounmap_trace (volatile void __iomem *addr); -#define MODULE_NAME "testmmiotrace"static unsigned long mmio_address;
@@ -28,25 +24,24 @@ static void do_write_test(void __iomem *p)static void do_read_test (void __iomem *p) {unsigned int i; -volatile unsigned int v;for (i =0 ; i <256 ; i++) - v =ioread8 (p + i); +ioread8 (p + i);for (i =1024 ; i < (5 *1024 ); i +=2 ) - v =ioread16 (p + i); +ioread16 (p + i);for (i = (5 *1024 ); i < (16 *1024 ); i +=4 ) - v =ioread32 (p + i); +ioread32 (p + i); }static void do_test (void ) { -void __iomem *p =ioremap_nocache_trace (mmio_address,0x4000 ); +void __iomem *p =ioremap_nocache (mmio_address,0x4000 );if (!p) {pr_err (MODULE_NAME ": could not ioremap, aborting.\n" );return ; }do_write_test (p);do_read_test (p); -iounmap_trace (p); +iounmap (p); }static int __init init (void )
include/linux/mmiotrace.h +17 -1
@@ -16,11 +16,12 @@ typedef void (*kmmio_post_handler_t)(struct kmmio_probe *, unsigned long condition, struct pt_regs *);struct kmmio_probe { -struct list_head list; +struct list_head list;/* kmmio internal list */ unsigned long addr;/* start location of the probe point */ unsigned long len;/* length of the probe region */ kmmio_pre_handler_t pre_handler;/* Called before addr is executed. */ kmmio_post_handler_t post_handler;/* Called after addr is executed */ +void *user_data; };/* kmmio is active by some kmmio_probes? */
@@ -38,6 +39,21 @@ extern void unregister_kmmio_probe(struct kmmio_probe *p);/* Called from page fault handler. */ extern int kmmio_handler (struct pt_regs *regs,unsigned long addr); +/* Called from ioremap.c */ +#ifdef CONFIG_MMIOTRACE +extern void +mmiotrace_ioremap (unsigned long offset,unsigned long size,void __iomem *addr); +extern void mmiotrace_iounmap (volatile void __iomem *addr); +#else +static inline void +mmiotrace_ioremap (unsigned long offset,unsigned long size,void __iomem *addr) +{ +} +static inline void mmiotrace_iounmap (volatile void __iomem *addr) +{ +} +#endif /* CONFIG_MMIOTRACE_HOOKS */ +#endif /* __KERNEL__ */
Signature · 1 line
1.5.3.7
Hi,
I may of course be wrong, but... Shouldn't the post_kmmio_handler(), called from the die notifier chain, check for the DR_STEP condition? This makes sure that the function is not called in the cases where the source of the debug exception was not a single-stepping event. Though I guess you'll also have other checks in place to notice that the interrupt was not the one you were expecting. I guess a little extra safety won't hurt though?
Quoted 9 lines · Pekka Paalanen
+/*
+ * Interrupts are disabled on entry as trap1 is an interrupt gate
+ * and they remain disabled thorough out this function.
+ * This must always get called as the pair tokmmio_handler().
+ */
+static intpost_kmmio_handler(unsigned long condition, struct pt_regs *regs)+{
+ int ret = 0;
+ structkmmio_context*ctx =&get_cpu_var(kmmio_ctx);
if (!(condition & DR_STEP))
return;
Vegard
Quoted 19 lines · On Fri, 28 Mar 2008 00:13:48 +0100 "Vegard Nossum" <[email protected]>…
I may of course be wrong, but... Shouldn't the
post_kmmio_handler(), called from the die notifier chain, check for theDR_STEPcondition? This makes sure that the function is not called in the cases where the source of the debug exception was not a single-stepping event. Though I guess you'll also have other checks in place to notice that the interrupt was not the one you were expecting. I guess a little extra safety won't hurt though?Quoted 9 lines · Pekka Paalanen
+/*
+ * Interrupts are disabled on entry as trap1 is an interrupt gate
+ * and they remain disabled thorough out this function.
+ * This must always get called as the pair tokmmio_handler().
+ */
+static intpost_kmmio_handler(unsigned long condition, struct pt_regs *regs)+{
+ int ret = 0;
+ structkmmio_context*ctx =&get_cpu_var(kmmio_ctx);
Quoted 2 lines
if (!(condition &
DR_STEP))return;
I guess that would be appropriate. I think it should go into this function:
+static int kmmio_die_notifier(struct notifier_block *nb, unsigned long val,
+ void *args)
+{
+ struct die_args *arg = args;
+
+ if (val == DIE_DEBUG)
+ if (post_kmmio_handler(arg->err, arg->regs) == 1)
+ return NOTIFY_STOP;
+
+ return NOTIFY_DONE;
+}
On the other hand I am thinking of not using the die notifier chain at all and adding a direct call from do_debug() or something. This is the last dynamic hook remaining from the out-of-tree module era of mmiotrace.
I guess with the notifier list there is a possibility that another module intercepts my single step trap, so that this is never called, which would leave mmiotrace half blind, and also trigger a recursive probe hit.
btw. what if someone uses kmemcheck and mmiotrace at the same time? Mmiotrace will not fiddle with any other pages than returned via __ioremap(), but can kmemcheck "hide" the same mmio pages? Also keeping in mind, that some day I'd like to make mmiotrace able to catch mmio accesses originating in user space.
Thanks.
Signature · 2 lines
Pekka Paalanen http://www.iki.fi/pq/
mmiotrace bug: recursive probe hit
In reply to Pekka PaalanenHi all,
jb17some reported a recursive probe hit when mmiotracing the nvidia proprietary driver (the blob) on SMP. I'll introduce the basic mechanisms in mmiotrace, provide some test results and then ask the question:
Why does disarm_kmmio_fault_page() occasionally not do its job on SMP?
Mmiotrace works by hooking into __ioremap() and marks the returned pages as not present. Any access to these pages, specifically memory mapped IO access, triggers a page fault. The fault handler, kmmio_handler(), marks the hit page as present by calling disarm_kmmio_fault_page(), and sets the TR flag. It also clears IF flag to prevent interrupts being enabled when returning from the fault. The faulting instruction is re-executed, this time without a fault, and the debug trap is hit. The debug trap handler, post_kmmio_handler() re-arms the page and restores cpu flags.
kmmio_handler() and post_kmmio_handler() need to share some state, and they must be called strictly in pairs, hence clearing IF and holding locks from the first handler to the second. This is a per-cpu requirement, different cpus are allowed to run concurrently here.
Here is the relevant code, quoted from my preview 2 email.
Quoted 173 lines
arch/x86/mm/kmmio.c new file +173
-0+/** Mark the given page as not present. Access to it will trigger a fault. */ +static void arm_kmmio_fault_page (unsigned long page,int *page_level) +{ +unsigned long address = page &PAGE_MASK ; +int level; +pte_t *pte =lookup_address (address, &level); + +if (!pte) { +pr_err ("kmmio: Error in %s: no pte for page 0x%08lx\n" , + __func__, page); +return ; + } + +if (level ==PG_LEVEL_2M ) { +pmd_t *pmd = (pmd_t *)pte; +set_pmd (pmd,__pmd (pmd_val (*pmd) & ~_PAGE_PRESENT)); + }else { +/* PG_LEVEL_4K */ +set_pte (pte,__pte (pte_val (*pte) & ~_PAGE_PRESENT)); + } + +if (page_level) + *page_level = level; + +__flush_tlb_one (page); +} + +/** Mark the given page as present. */ +static void disarm_kmmio_fault_page (unsigned long page,int *page_level) +{ +unsigned long address = page &PAGE_MASK ; +int level; +pte_t *pte =lookup_address (address, &level); + +if (!pte) { +pr_err ("kmmio: Error in %s: no pte for page 0x%08lx\n" , + __func__, page); +return ; + } + +if (level ==PG_LEVEL_2M ) { +pmd_t *pmd = (pmd_t *)pte; +set_pmd (pmd,__pmd (pmd_val (*pmd) | _PAGE_PRESENT)); + }else { +/* PG_LEVEL_4K */ +set_pte (pte,__pte (pte_val (*pte) | _PAGE_PRESENT)); + } + +if (page_level) + *page_level = level; + +__flush_tlb_one (page); +} + +/* +* This is being called from do_page_fault(). +* +* We may be in an interrupt or a critical section. Also prefecthing may +* trigger a page fault. We may be in the middle of process switch. +* We cannot take any locks, because we could be executing especially +* within a kmmio critical section. +* +* Local interrupts are disabled, so preemption cannot happen. +* Do not enable interrupts, do not sleep, and watch out for other CPUs. +*/ +/* +* Interrupts are disabled on entry as trap3 is an interrupt gate +* and they remain disabled thorough out this function. +*/ +int kmmio_handler (struct pt_regs *regs,unsigned long addr) +{ +struct kmmio_context *ctx; +struct kmmio_fault_page *faultpage; + +/* +* Preemption is now disabled to prevent process switch during +* single stepping. We can only handle one active kmmio trace +* per cpu, so ensure that we finish it before something else +* gets to run. We also hold the RCU read lock over single +* stepping to avoid looking up the probe and kmmio_fault_page +* again. +*/ +preempt_disable (); +rcu_read_lock (); + + faultpage =get_kmmio_fault_page (addr); +if (!faultpage) { +/* +* Either this page fault is not caused by kmmio, or +* another CPU just pulled the kmmio probe from under +* our feet. In the latter case all hell breaks loose. +*/ + goto no_kmmio; + } + + ctx = &get_cpu_var (kmmio_ctx); +if (ctx->active) { +/* +* Prevent overwriting already in-flight context. +* If this page fault really was due to kmmio trap, +* all hell breaks loose. +*/ +pr_emerg ("kmmio: recursive probe hit on CPU %d, " +"for address 0x%08lx. Ignoring.\n" , +smp_processor_id (), addr); + goto no_kmmio_ctx; + } + ctx->active++; + + ctx->fpage = faultpage; + ctx->probe =get_kmmio_probe (addr); + ctx->saved_flags = (regs->flags & (TF_MASK |IF_MASK )); + ctx->addr = addr; + +if (ctx->probe && ctx->probe->pre_handler) + ctx->probe->pre_handler (ctx->probe, regs, addr); + +/* +* Enable single-stepping and disable interrupts for the faulting +* context. Local interrupts must not get enabled during stepping. +*/ + regs->flags |=TF_MASK ; + regs->flags &= ~IF_MASK ; + +/* Now we set present bit in PTE and single step. */ +disarm_kmmio_fault_page (ctx->fpage->page,NULL ); + +/* +* If another cpu accesses the same page while we are stepping, +* the access will not be caught. It will simply succeed and the +* only downside is we lose the event. If this becomes a problem, +* the user should drop to single cpu before tracing. +*/ + +put_cpu_var (kmmio_ctx); +return 1 ; + +no_kmmio_ctx: +put_cpu_var (kmmio_ctx); +no_kmmio: +rcu_read_unlock (); +preempt_enable_no_resched (); +return 0 ;/* page fault not handled by kmmio */ +} + +/* +* Interrupts are disabled on entry as trap1 is an interrupt gate +* and they remain disabled thorough out this function. +* This must always get called as the pair to kmmio_handler(). +*/ +static int post_kmmio_handler (unsigned long condition,struct pt_regs *regs) +{ +int ret =0 ; +struct kmmio_context *ctx = &get_cpu_var (kmmio_ctx); + +if (!ctx->active) + goto out; + +if (ctx->probe && ctx->probe->post_handler) + ctx->probe->post_handler (ctx->probe, condition, regs); + +arm_kmmio_fault_page (ctx->fpage->page,NULL ); + + regs->flags &= ~TF_MASK ; + regs->flags |= ctx->saved_flags; + +/* These were acquired in kmmio_handler(). */ + ctx->active--; +BUG_ON (ctx->active); +rcu_read_unlock (); +preempt_enable_no_resched (); + +/*
arch/x86/mm/kmmio.c line 352
Quoted 10 lines
arch/x86/mm/kmmio.c new file +10
-0+* if somebody else is singlestepping across a probe point, flags +* will have TF set, in which case, continue the remaining processing +* of do_debug, as if this is not a probe hit. +*/ +if (!(regs->flags &TF_MASK )) + ret =1 ; +out: +put_cpu_var (kmmio_ctx); +return ret; +}
A recursive probe hit means that kmmio_handler() is called twice without a a call to post_kmmio_handler() in between. This situation is explicitly checked for (if (ctx->active)), and the current solution is to ignore the fault and fall through to do_page_fault() triggering an error there. According to experience, this does not happen on a uniprocessor machine.
However, on an SMP machine this can occasionally occur. I have reproduced it on my Core 2 Duo laptop while tracing the blob. Recursive probe hit is very rare compared to the events logged, I can run two glxgears at the same time for half an hour generating at least millions of events and never hit it. Repeatedly start and stop a single glxgears, and I have a fairly good chance of hitting it. It is random, but reproducible.
Here is a kernel oops log via netconsole:
kmmio: recursive probe hit on CPU 0, for address 0xffffc20004500140. Ignoring.
BUG: unable to handle kernel paging request at ffffc20004500140 IP: [<ffffffffa04e7b38>] :nvidia:_nv003832rm+0x1d/0x22 PGD 3e8d9067 PUD 3e8da067 PMD 3cd58067 PTE 80000000d600017a Oops: 0000 [1] PREEMPT SMP DEBUG_PAGEALLOC CPU 0 Modules linked in: nvidia(P) netconsole snd_seq_oss snd_seq_midi_event snd_seq
snd_seq_device snd_pcm_oss snd_mixer_oss sha256_generic cpufreq_stats acpi_cpufreq video output fan button arc4 ecb snd_hda_intel snd_pcm snd_timer snd snd_page_alloc iwl4965 mac80211 ehci_hcd uhci_hcd usbcore ohci1394 ieee1394 psmouse e1000 pcspkr sg i2c_i801 i2c_core yenta_socket rsrc_nonstatic [last unloaded: nvidia]
Pid: 0, comm: swapper Tainted: P 2.6.25-rc6-sched-devel.git-x86-latest.git #2
RIP: 0010:[<ffffffffa04e7b38>] [<ffffffffa04e7b38>] :nvidia:_nv003832rm+0x1d/0x22 RSP: 0018:ffffffff806cfe38 EFLAGS: 00010106 RAX: 0000000000000050 RBX: ffff810019a49000 RCX: 0000000000000140 RDX: ffffc20004500000 RSI: ffff810019a49000 RDI: ffff81001ae5a7f0 RBP: ffff810019b1f148 R08: ffff81001ad6a000 R09: ffffffff806cfe18 R10: ffffffff80428f60 R11: ffff81003cc63140 R12: ffff81001ae5a7f0 R13: 0000000000000140 R14: 0000000000000001 R15: ffff8100194b3000 FS: 0000000000000000(0000) GS:ffffffff80662000(0000) knlGS:0000000000000000 CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b CR2: ffffc20004500140 CR3: 000000001af2a000 CR4: 00000000000006e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000ffff4ff0 DR7: 0000000000000400 Process swapper (pid: 0, threadinfo ffffffff80684000, task ffffffff8061f4e0) Stack: ffffffffa03b978e ffff810019a49000 ffff81001ad6ebf0 ffffc200040b0000 0000000000000001 ffff8100194b3000 ffffffffa04e8655 ffffc200040b0000 ffff810019a49000 ffffc200040b0000 ffff810019b1c180 ffffffff806cff18 Call Trace: <IRQ> [<ffffffffa03b978e>] ? :nvidia:_nv008123rm+0x2a/0xc7 [<ffffffffa04e8655>] ? :nvidia:_nv003822rm+0x163/0x256 [<ffffffffa04e6b82>] ? :nvidia:_nv003815rm+0x4f/0x76 [<ffffffffa04edc13>] ? :nvidia:rm_isr+0xaa/0x10a [<ffffffffa059ac61>] ? :nvidia:nv_kern_isr+0x7d/0xb1 [<ffffffff8025f567>] ? handle_IRQ_event+0x20/0x55 [<ffffffff802609c5>] ? handle_fasteoi_irq+0x9c/0xdc [<ffffffff8020e95a>] ? do_IRQ+0x105/0x17f [<ffffffff8020b7e6>] ? ret_from_intr+0x0/0xf <EOI> [<ffffffff80421c12>] ? poll_idle+0x16/0x63 [<ffffffff80421c17>] ? poll_idle+0x1b/0x63 [<ffffffff80421c12>] ? poll_idle+0x16/0x63 [<ffffffff80422039>] ? cpuidle_idle_call+0x7e/0xad [<ffffffff80421fbb>] ? cpuidle_idle_call+0x0/0xad [<ffffffff8020a1f5>] ? cpu_idle+0x92/0xd0 [<ffffffff804c6025>] ? rest_init+0x69/0x6b Code: 89 c8 d1 e8 89 c0 0f b7 04 42 0f b7 c0 c3 89 d1 b8 00 00 00 00 39 96
0c 02 00 00 76 11 48 8b 96 40 02 00 00 89 c8 c1 e8 02 89 c0 <8b> 04 82 f3 c3 39 96 14 02 00 00 76 0c 89 d2 48 8b 86 58 02 00
RIP [<ffffffffa04e7b38>] :nvidia:_nv003832rm+0x1d/0x22
RSP <ffffffff806cfe38>
CR2: ffffc20004500140
---[ end trace 0a8c36f3081eaf7e ]--- Kernel panic - not syncing: Aiee, killing interrupt handler!
Next, after discussion with Enberg and Nossum, I tried the following patch:
@@ -272,6 +272,9 @@ int kmmio_handler(struct pt_regs *regs, unsigned long addr)
pr_emerg("kmmio: recursive probe hit on CPU %d, "
"for address 0x%08lx. Ignoring.\n",
smp_processor_id(), addr);
+ pr_emerg("kmmio: previous hit was at 0x%08lx.\n",
+ ctx->addr);
+ disarm_kmmio_fault_page(faultpage->page, NULL);
goto no_kmmio_ctx;
}
ctx->active++;
@@ -322,8 +325,11 @@ static int post_kmmio_handler(unsigned long condition, struct pt_regs *regs)
int ret = 0;
struct kmmio_context *ctx = &get_cpu_var(kmmio_ctx);- if (!ctx->active)
+ if (!ctx->active) {
+ pr_notice("kmmio: spurious debug trap on CPU %d.\n",
+ smp_processor_id());
goto out;+ }
The result is occasional two lines:
kmmio: recursive probe hit on CPU 1, for address 0xffffc20004400140. Ignoring.
kmmio: previous hit was at 0xffffc20004400140.
The addresses vary, but are always the same for a pair of lines. The "spurious debug trap" is never seen, and no kernel oopses. Note, that I (unintentionally) still fall through to do_page_fault() after disarming.
Hypothesis 1:
Something gets to run on this cpu between exiting kmmio_handler() and entering post_kmmio_handler(), and it triggers a new kmmio probe hit. This is unlikely, as there should be a spurious debug trap afterwards.
Hypothesis 2:disarm_kmmio_fault_page() does not work.
But it works most of the time, and on UP it seems to work always.
If hypothesis 2 is true, when the faulted instruction is re-executed, it faults again. This is supported by the fault address being the same at both times.
Could something else (apart from NMI) get to run in between fault and debug handlers?
Is there something wrong in arm/disarm_kmmio_fault_page() functions? Could it be a race between cpus?
Does the fall through to do_page_fault() trigger a proper fix to page tables in case my disarming is bad?
Is the debugging hack an acceptable workaround?
I hope using a binary blob as a test case does not offend anyone, but the main purpose of mmiotrace is to reverse engineer binary blobs.
I would appreciate any insight to the problem.
Thanks,
Pekka.
Signature · 2 lines
Pekka Paalanen http://www.iki.fi/pq/
Re: mmiotrace bug: recursive probe hit
Quoted 6 lines · On Fri, 28 Mar 2008 22:25:00 +0200 Pekka Paalanen <[email protected]> wrote:
A recursive probe hit means that
kmmio_handler()is called twice without a a call topost_kmmio_handler()in between. This situation is explicitly checked for (if (ctx->active)), and the current solution is to ignore the fault and fall through todo_page_fault()triggering an error there. According to experience, this does not happen on a uniprocessor machine.
Quoted 6 lines
However, on an SMP machine this can occasionally occur. I have reproduced it on my Core 2 Duo laptop while tracing the blob. Recursive probe hit is very rare compared to the events logged, I can run two glxgears at the same time for half an hour generating at least millions of events and never hit it. Repeatedly start and stop a single glxgears, and I have a fairly good chance of hitting it. It is random, but reproducible.
It appears this happens:
CPU 0 CPU 1
,---> fault fault | disarm disarm | single step | arm
| single step
'--------'
arm
and the both cpus are faulting on the same page. I guess one cpu is running an nvidia interrupt service.
I see three possible solutions:
A) Like in this patch, just disarm again and hope for the best. Seems to work ok. I also compare the fault address to the saved address ctx->addr. If they are equal, it is a "double probe hit" and harmless. If they are not equal, it is a real "recursive probe hit" and something more is wrong. With these definitions, recursive probe hits are gone in my experiments on Intel Core 2 Duo.
Review int kmmio_handler(struct pt_regs *regs, unsigned long addr) · line 280
Quoted 12 lines
Next, after discussion with Enberg and Nossum, I tried the following patch:
(quoted diff) +3
-0@@ -272,6 +272,9 @@ int kmmio_handler(struct pt_regs *regs, unsigned long addr) pr_emerg("kmmio: recursive probe hit on CPU %d, " "for address 0x%08lx. Ignoring.\n", smp_processor_id(), addr); + pr_emerg("kmmio: previous hit was at 0x%08lx.\n", + ctx->addr); + disarm_kmmio_fault_page(faultpage->page, NULL); goto no_kmmio_ctx; } ctx->active++;
B) Acquire a spinlock in kmmio_handler() and release it in post_kmmio_handler(). I don't like this one since I spent some effort making the fault path spinlockless, but at least this would be a completely separate spinlock. Or we could use per-page spinlocks.
C) Vegard mentioned something about per-cpu page tables for kmemcheck. This would be the ultimate solution, because it would solve two problems:
- recursive probe hits
- missed events due to another cpu disarming the page for single stepping Would it be possible to have a single temporary per-cpu pte?
I understood kmemcheck has similar issues. Of course, one could force the system down to a single running CPU, but that feels nasty.
Which way to go?
I choose A) as the current workaround, keeping in mind that I will loose events on SMP. C) would be the only reliable SMP solution on tracing point of view.
Thanks.
Signature · 2 lines
Pekka Paalanen http://www.iki.fi/pq/
Re: mmiotrace bug: recursive probe hit
Quoted 9 lines · On Sun, 30 Mar 2008 20:26:08 +0300 Pekka Paalanen <[email protected]> wrote:
C) Vegard mentioned something about per-cpu page tables for kmemcheck. This would be the ultimate solution, because it would solve two problems:
- recursive probe hits
- missed events due to another cpu disarming the page for single stepping Would it be possible to have a single temporary per-cpu pte?I understood kmemcheck has similar issues. Of course, one could force the system down to a single running CPU, but that feels nasty.
One more idea:
D) Emulate the faulting instruction.
In __ioremap(), do the mapping, but steal it for mmiotrace's personal use, and return a bogus mapping that is identifiable in #pf handler. When something accesses the bogus mapping, emulate and step over the faulting instruction using the stolen IO memory mapping. This would get rid of the debug trap and single stepping, and also remove the need to disarm the mmio page, which means tracing would work reliably on SMP without any page table kludges. This would also remove the yet another instruction decoding code that mmiotrace has.
The catch is the instruction emulation. I see KVM has some emulation code, but I cannot understand it without a deep study that would take me weeks. Is that general enough to be used, or could it be generalized? Mmiotrace, apart from executing the instruction with a modified address, would need to extract the type of IO memory access, width and the data read/written. And since it is dealing with IO memory, the emulation should be very careful to access the hardware exactly like the original instruction would have.
Maybe also kmemcheck could use this approach, since the current approach is very much like in mmiotrace: #pf, show page, single step, #db trap, hide page.
Are there other x86(_64) instruction emulation facilities in the kernel I might use?
Or, if the emulation cannot be used, what would it take to make at least instruction decoding general enough so that mmiotrace could use that instead of its own decoding?
I fear modifying KVM emulation code is a too heavy job for me personally.
Signature · 2 lines
Pekka Paalanen http://www.iki.fi/pq/
Re: mmiotrace bug: recursive probe hit
Quoted 9 lines · Pekka Paalanen
Quoted 8 lines · Pekka Paalanen
C) Vegard mentioned something about per-cpu page tables for kmemcheck. This would be the ultimate solution, because it would solve two problems:
- recursive probe hits
- missed events due to another cpu disarming the page for single stepping Would it be possible to have a single temporary per-cpu pte?I understood kmemcheck has similar issues. Of course, one could force the system down to a single running CPU, but that feels nasty.
Yes, Ingo Molnar has suggested per-cpu page tables, but that's so far away from what I am capable of, so unless Ingo wants to do it himself, I fear it will never be done ;-) [I also believe the resulting code would be too ugly and too un-useful for the rest of the kernel that it would probably not ever be merged. But that's a different story.] But I do think this is the best solution in terms of reliability.
We do indeed limit maxcpus to 1 at run-time if the kernel is compiled with CONFIG_SMP. kmemcheck is a debugging facility, and as such, actual multiprocessor support is not critical for the purpose of kmemcheck, in my opinion. Doesn't the same hold for mmiotrace?
Quoted 12 lines
One more idea:
D) Emulate the faulting instruction.
In__ioremap(), do the mapping, but steal it for mmiotrace's personal use, and return a bogus mapping that is identifiable in #pf handler. When something accesses the bogus mapping, emulate and step over the faulting instruction using the stolen IO memory mapping. This would get rid of the debug trap and single stepping, and also remove the need to disarm the mmio page, which means tracing would work reliably on SMP without any page table kludges. This would also remove the yet another instruction decoding code that mmiotrace has.
Quoted 8 lines
The catch is the instruction emulation. I see KVM has some emulation code, but I cannot understand it without a deep study that would take me weeks. Is that general enough to be used, or could it be generalized? Mmiotrace, apart from executing the instruction with a modified address, would need to extract the type of IO memory access, width and the data read/written. And since it is dealing with IO memory, the emulation should be very careful to access the hardware exactly like the original instruction would have.
I think that would be extremely difficult to do. I am personally trying to stay as far away from opcode decoding (and recoding! *shudder*) as possible. I do the minimal decoding for operand sizes, etc, which I think you do as well in mmiotrace.
Quoted 3 lines
Maybe also kmemcheck could use this approach, since the current approach is very much like in mmiotrace: #pf, show page, single step, #db trap, hide page.
They are indeed very much the same. I wish somebody had told me about mmiotrace when I first started working on kmemcheck! :-)
I don't think I can be of much more help than that. Just my opinion on things.
Kind regards,
Vegard Nossum
Re: mmiotrace bug: recursive probe hit
Quoted 7 lines · On Thu, 3 Apr 2008 23:40:28 +0200 "Vegard Nossum" <[email protected]>…
Quoted 1 line · Pekka Paalanen
...
We do indeed limit maxcpus to 1 at run-time if the kernel is compiled with
CONFIG_SMP. kmemcheck is a debugging facility, and as such, actual multiprocessor support is not critical for the purpose of kmemcheck, in my opinion. Doesn't the same hold for mmiotrace?
Actually, I think kmemcheck should support SMP even more than mmiotrace. Mmiotrace is just a reverse engineering tool for hardware drivers, but kmemcheck as a debugging tool could be valuable specifically on SMP, think about racing CPUs using and initializing memory. Dropping to UP might hide those problems.
Quoted 21 lines
Quoted 12 lines
One more idea:
D) Emulate the faulting instruction.
In__ioremap(), do the mapping, but steal it for mmiotrace's personal use, and return a bogus mapping that is identifiable in #pf handler. When something accesses the bogus mapping, emulate and step over the faulting instruction using the stolen IO memory mapping. This would get rid of the debug trap and single stepping, and also remove the need to disarm the mmio page, which means tracing would work reliably on SMP without any page table kludges. This would also remove the yet another instruction decoding code that mmiotrace has.Quoted 8 lines
The catch is the instruction emulation. I see KVM has some emulation code, but I cannot understand it without a deep study that would take me weeks. Is that general enough to be used, or could it be generalized? Mmiotrace, apart from executing the instruction with a modified address, would need to extract the type of IO memory access, width and the data read/written. And since it is dealing with IO memory, the emulation should be very careful to access the hardware exactly like the original instruction would have.
Quoted 4 lines
I think that would be extremely difficult to do. I am personally trying to stay as far away from opcode decoding (and recoding! *shudder*) as possible. I do the minimal decoding for operand sizes, etc, which I think you do as well in mmiotrace.
To be honest, I don't know how easy or difficult it is. If there was a general decoding facility, it shouldn't be that hard to use, if someone else makes the facility for us ;-)
Could all relevant instructions be represented as three-address-code or in some other simple form?
This seems to require some experimenting with code.
Signature · 2 lines
Pekka Paalanen http://www.iki.fi/pq/
Re: mmiotrace bug: recursive probe hit
In reply to Pekka PaalanenQuoted 30 lines · Pekka Paalanen
Quoted 9 lines · On Sun, 30 Mar 2008 20:26:08 +0300 Pekka Paalanen <[email protected]> wrote:
C) Vegard mentioned something about per-cpu page tables for kmemcheck. This would be the ultimate solution, because it would solve two problems:
- recursive probe hits
- missed events due to another cpu disarming the page for single stepping Would it be possible to have a single temporary per-cpu pte?I understood kmemcheck has similar issues. Of course, one could force the system down to a single running CPU, but that feels nasty.
One more idea:
The catch is the instruction emulation. I see KVM has some emulation code, but I cannot understand it without a deep study that would take me weeks. Is that general enough to be used, or could it be generalized? Mmiotrace, apart from executing the instruction with a modified address, would need to extract the type of IO memory access, width and the data read/written. And since it is dealing with IO memory, the emulation should be very careful to access the hardware exactly like the original instruction would have.
Maybe also kmemcheck could use this approach, since the current approach is very much like in mmiotrace: #pf, show page, single step, #db trap, hide page.
Quoted 9 lines
Are there other
x86(_64)instruction emulation facilities in the kernel I might use?Or, if the emulation cannot be used, what would it take to make at least instruction decoding general enough so that mmiotrace could use that instead of its own decoding?
I fear modifying KVM emulation code is a too heavy job for me personally.
It should not be too difficult to modify x86_emulate.c to do everything through a function vector. However there is a simpler (for you) solution: run the driver-to-be-reverse-engineered in a kvm guest, and modify kvm userspace to log accesses to mmio regions. This requires the not-yet-merged pci passthrough support. You can reverse engineer Windows drivers with this as well.
This won't work for kmemcheck smp though.
Signature · 1 line
Any sufficiently difficult bug is indistinguishable from a feature.
Re: mmiotrace bug: recursive probe hit
Quoted 8 lines · Avi Kivity
It should not be too difficult to modify
x86_emulate.cto do everything through a function vector. However there is a simpler (for you) solution:
run the driver-to-be-reverse-engineered in a kvm guest, and modify kvm userspace to log accesses to mmio regions. This requires the not-yet-merged pci passthrough support. You can reverse engineer Windows drivers with this as well.This won't work for kmemcheck smp though.
For kmemcheck, I'd prefer the per-CPU page tables suggested by Ingo. I'm having hard time understanding why that's a "ugly hack" compared to using kvm for this...
Re: mmiotrace bug: recursive probe hit
Quoted 9 lines · Pekka Enberg
Quoted 7 lines · Avi Kivity
It should not be too difficult to modify
x86_emulate.cto do everything through a function vector. However there is a simpler (for you) solution:
run the driver-to-be-reverse-engineered in a kvm guest, and modify kvm userspace to log accesses to mmio regions. This requires the not-yet-merged pci passthrough support. You can reverse engineer Windows drivers with this as well.
Quoted 7 lines
Quoted 2 lines
This won't work for kmemcheck smp though.
For kmemcheck, I'd prefer the per-CPU page tables suggested by Ingo. I'm having hard time understanding why that's a "ugly hack" compared to using kvm for this...
It's not an ugly hack, but will be very very difficult. With mmu notifiers it's probably doable though:
- the linux page tables are never loaded into cr3, but rather kept as a reference
- page faults are by instantiating ptes into shadow page tables (which track the linux page tables)
- mmu notifiers are used to drop shadow ptes when the linux ptes change
Signature · 1 line
Any sufficiently difficult bug is indistinguishable from a feature.
Re: mmiotrace bug: recursive probe hit
Quoted 6 lines · Avi Kivity
Quoted 5 lines
For kmemcheck, I'd prefer the per-CPU page tables suggested by Ingo. I'm having hard time understanding why that's a "ugly hack" compared to using kvm for this...
Quoted 8 lines
It's not an ugly hack, but will be very very difficult. With mmu notifiers it's probably doable though:
- the linux page tables are never loaded into cr3, but rather kept as a reference
- page faults are by instantiating ptes into shadow page tables (which track the linux page tables)
- mmu notifiers are used to drop shadow ptes when the linux ptes change
Actually, paravirt_ops is a much better match, as it also provides hooks for setting cr3. I think you can implement per-cpu pagetables using paravirt_ops without modifying core mm code at all.
Signature · 1 line
Do not meddle in the internals of kernels, for they are subtle and quick to panic.
Re: mmiotrace bug: recursive probe hit
In reply to Avi KivityQuoted 5 lines · On Sat, 05 Apr 2008 10:36:50 +0300 Avi Kivity <[email protected]> wrote:
However there is a simpler (for you)
solution: run the driver-to-be-reverse-engineered in a kvm guest, and modify kvm userspace to log accesses to mmio regions. This requires the not-yet-merged pci passthrough support. You can reverse engineer Windows drivers with this as well.
This is a very interesting idea, I didn't know it would be possible. I think this also is a new project and I'd be happy to let someone else take it over. We could still use the log format and tools from mmiotrace, at least for starters.
This puts mmiotrace in a new ligth: there's something better(?) coming in the future. But mmiotrace is here now, and I'd still like to see it in mainline. Within ftrace framework, mmiotrace will be very easy to use even for a Linux newbie. The KVM approach would be targeted to developers, as I suspect setting it up (even when everything has been merged into mainline) is more work than running mmiotrace.
Ingo, what do you think? In my opinion let's make mmiotrace force the system down to UP via CPU hotplugging while MMIO tracing is active. This should guarantee reliable traces in the easiest way possible. The current workaround is not reliable on SMP. "Works enough" is what I'm thinking of.
Thanks.
Signature · 2 lines
Pekka Paalanen http://www.iki.fi/pq/