Skip to contentSkip to conversation

ras-tools: hardware validation for arm64 MC-safe memory error recovery

PATCH In review Ruidong Tian 2 participants 6 messages Jun 17 Kbuild

lore
Share & tools
lore
#0 lore raw

cover ras-tools: hardware validation for arm64 MC-safe memory error recovery

From: Ruidong Tian <[email protected]>

This series adds tooling to ras-tools for end-to-end validation of the arm64 "MC-safe" memory error recovery work on real hardware.

Recent arm64 patches teach the kernel to survive an uncorrectable (poison) memory error consumed during a kernel copy, instead of taking the whole machine down. Two broad families of copy paths are covered:

- kernel-side page copies (copy_mc_highpage / copy_mc_user_highpage /

    folio_mc_copy) used by COW, khugepaged, page migration and hugetlb;

- user-access copies (copy_from_user / copyin) driven by syscalls.

This series adds validation test cases and observability tooling for these recovery scenarios.

Ruidong Tian (4):
ras-tools: add bpftrace verification and opcode decode helpers
ras-tools: verify MC-safe recovery for hwpoison copy-on-write patches
einj_mem_uc_uaccess: exercise copy_from_user hwpoison recovery via
syscalls
einj_mem_uc: add copy_mc_to_kernel() case

 Makefile              |   4 +-
 decode_opcode.py      | 274 +++++++++++++++++
 einj_mem_uc.c         | 155 +++++++---
 einj_mem_uc.h         |  72 +++++
 einj_mem_uc_mm.c      | 682 ++++++++++++++++++++++++++++++++++++++++++
 einj_mem_uc_uaccess.c | 369 +++++++++++++++++++++++
 einj_mem_uc_verify.bt | 108 +++++++
 7 files changed, 1628 insertions(+), 36 deletions(-)
 create mode 100644 decode_opcode.py
 create mode 100644 einj_mem_uc.h
 create mode 100644 einj_mem_uc_mm.c
 create mode 100644 einj_mem_uc_uaccess.c
 create mode 100644 einj_mem_uc_verify.bt
Signature · 1 line
2.39.3
#1 lore raw

PATCH 1/4 ras-tools: add bpftrace verification and opcode decode helpers

From: Ruidong Tian <[email protected]>

einj_mem_uc_verify.bt:
arm64-focused bpftrace script that observes key facts during MC-safe fault injection tests:
- Fault PC and call stack from do_sea's pt_regs
- Extable entry type (UACCESS_ERR_ZERO, UACCESS_CPY, etc.)
- Fixup/recovery address from search_exception_tables

decode_opcode.py:
Post-processing filter for the bpftrace output that:
- Calculates KASLR offset from /proc/kallsyms vs vmlinux _text
- Disassembles fault PC instructions via capstone (arm64)
- Appends source file:line via addr2line when DWARF is available
- Supports --context N to show surrounding instructions

Together they form the runtime verification pipeline:
bpftrace einj_mem_uc_verify.bt | sudo python3 decode_opcode.py

example
=========================================
input: sudo bpftrace einj_mem_uc_verify.bt -c './einj_mem_uc copyin -f' | sudo python3 decode_opcode.py

  [do_sea   ] Fault PC (faulting insn):  <__arch_copy_from_user> ffffb45742beb300  linux/arch/arm64/lib/copy_template.S:165
  [do_sea   ] Call stack:
  [do_sea   ]   <copy_folio_from_iter_atomic>
  [do_sea   ]   <generic_perform_write>
  [do_sea   ]   <shmem_file_write_iter>
  [do_sea   ]   <new_sync_write>
  [do_sea   ]   <vfs_write>
  [do_sea   ]   <ksys_write>
  [extable  ] Fault type:                UACCESS_ERR_ZERO
  [extable  ] Recovery addr (fixup):     <__arch_copy_from_user> ffffb45742beb3a0  linux/arch/arm64/lib/copy_from_user.S:75
  [do_sea   ] Fault PC (faulting insn):  <__arch_copy_from_user> ffffb45742beb3a8  linux/arch/arm64/lib/copy_from_user.S:78
  [do_sea   ] Call stack:
  [do_sea   ]   <copy_folio_from_iter_atomic>
  [do_sea   ]   <generic_perform_write>
  [do_sea   ]   <shmem_file_write_iter>
  [do_sea   ]   <new_sync_write>
  [do_sea   ]   <vfs_write>
  [do_sea   ]   <ksys_write>
  [extable  ] Fault type:                UACCESS_ERR_ZERO
  [extable  ] Recovery addr (fixup):     <__arch_copy_from_user> ffffb45742beb3b0  linux/arch/arm64/lib/copy_from_user.S:80
---
 decode_opcode.py      | 274 ++++++++++++++++++++++++++++++++++++++++++
 einj_mem_uc_verify.bt | 108 +++++++++++++++++
 2 files changed, 382 insertions(+)
 create mode 100644 decode_opcode.py
 create mode 100644 einj_mem_uc_verify.bt
decode_opcode.py new file +274 -0
new file mode 100644
index 0000000..0b7d4ae
@@ -0,0 +1,274 @@
+#!/usr/bin/env python3
+"""
+decode_opcode.py - Parse bpftrace output from einj_mem_uc_verify.bt in real time,
+                   disassemble instructions near the fault PC using KASLR offset.
+
+Usage:
+    sudo bpftrace einj_mem_uc_verify.bt -c './einj_mem_uc pwrite_uc' \
+        | sudo python3 decode_opcode.py [--vmlinux /path/to/vmlinux] [--context 5]
+
+Default vmlinux path: ../vmlinux relative to this script.
+
+Dependencies:
+    pip install capstone pyelftools
+"""
+
+import sys
+import re
+import os
+import argparse
+
+# ---------- dependency check ----------
+try:
+    from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM
+    HAS_CAPSTONE = True
+except ImportError:
+    HAS_CAPSTONE = False
+
+try:
+    from elftools.elf.elffile import ELFFile
+    HAS_ELFTOOLS = True
+except ImportError:
+    HAS_ELFTOOLS = False
+
+import subprocess
+
+HAS_DWARF = False   # lazy detection, checked on first use
+_dwarf_checked = False
+
+def check_dwarf(vmlinux_path):
+    global HAS_DWARF, _dwarf_checked
+    if _dwarf_checked:
+        return HAS_DWARF
+    _dwarf_checked = True
+    try:
+        with open(vmlinux_path, 'rb') as f:
+            elf = ELFFile(f)
+            HAS_DWARF = elf.get_section_by_name('.debug_info') is not None
+    except Exception:
+        HAS_DWARF = False
+    if HAS_DWARF:
+        pass  # silently available
+    else:
+        print(f'[decode    ] vmlinux has no DWARF (CONFIG_DEBUG_INFO not enabled), source location unavailable', flush=True)
+    return HAS_DWARF
+
+# ---------- command-line arguments ----------
+parser = argparse.ArgumentParser(description='decode bpftrace arm64 opcode with KASLR')
+parser.add_argument('--vmlinux',
+                    default=os.path.join(os.path.dirname(__file__), '..', 'vmlinux'),
+                    help='path to vmlinux (default: ../vmlinux)')
+parser.add_argument('--context', type=int, default=0,
+                    help='number of context instructions to show (default: 0, target only)')
+args, _ = parser.parse_known_args()
+
+VMLINUX = os.path.realpath(args.vmlinux)
+CTX     = args.context
+
+# ---------- compute KASLR offset ----------
+def get_kaslr_offset(vmlinux_path):
+    """Return (kaslr_offset, runtime_text, compiled_text). Requires root to read /proc/kallsyms."""
+    # runtime _text
+    runtime_text = None
+    try:
+        with open('/proc/kallsyms') as f:
+            for line in f:
+                parts = line.split()
+                if len(parts) >= 3 and parts[2] == '_text':
+                    runtime_text = int(parts[0], 16)
+                    break
+    except PermissionError:
+        print('[decode    ] ERROR: cannot read /proc/kallsyms, run as root', flush=True)
+        return None, None, None
+
+    if runtime_text is None:
+        print('[decode    ] ERROR: _text not found in /proc/kallsyms', flush=True)
+        return None, None, None
+
+    if runtime_text == 0:
+        print('[decode    ] ERROR: /proc/kallsyms returns 0 for _text -- run as root', flush=True)
+        print('[decode    ]   hint: sudo python3 decode_opcode.py', flush=True)
+        return None, None, None
+
+    # compile-time _text (from vmlinux ELF symbol table)
+    compiled_text = None
+    if HAS_ELFTOOLS:
+        try:
+            with open(vmlinux_path, 'rb') as f:
+                elf = ELFFile(f)
+                for sec_name in ('.symtab', '.dynsym'):
+                    sym_tab = elf.get_section_by_name(sec_name)
+                    if sym_tab:
+                        for sym in sym_tab.iter_symbols():
+                            if sym.name == '_text':
+                                compiled_text = sym['st_value']
+                                break
+                    if compiled_text is not None:
+                        break
+        except Exception as e:
+            print(f'[decode    ] WARNING: elftools error: {e}', flush=True)
+
+    if compiled_text is None:
+        # fallback: nm
+        import subprocess
+        try:
+            out = subprocess.check_output(['nm', '-n', vmlinux_path],
+                                          stderr=subprocess.DEVNULL, text=True)
+            for line in out.splitlines():
+                parts = line.split()
+                if len(parts) >= 3 and parts[2] == '_text':
+                    compiled_text = int(parts[0], 16)
+                    break
+        except Exception as e:
+            print(f'[decode    ] WARNING: nm fallback failed: {e}', flush=True)
+
+    if compiled_text is None:
+        print('[decode    ] ERROR: cannot determine compiled _text from vmlinux', flush=True)
+        return None, None, None
+
+    offset = runtime_text - compiled_text
+    print(f'[decode    ] KASLR offset={offset:#x}  '
+          f'_text(runtime={runtime_text:#x} compiled={compiled_text:#x})', flush=True)
+    return offset, runtime_text, compiled_text
+
+
+# ---------- read raw bytes from vmlinux (by compile-time virtual address) ----------
+def read_vmlinux_bytes(vmlinux_path, compiled_addr, n_bytes):
+    if not HAS_ELFTOOLS:
+        return None
+    try:
+        with open(vmlinux_path, 'rb') as f:
+            elf = ELFFile(f)
+            for seg in elf.iter_segments():
+                vaddr  = seg['p_vaddr']
+                filesz = seg['p_filesz']
+                if vaddr <= compiled_addr < vaddr + filesz:
+                    file_off = seg['p_offset'] + (compiled_addr - vaddr)
+                    # do not exceed segment boundary
+                    avail = vaddr + filesz - compiled_addr
+                    f.seek(file_off)
+                    return f.read(min(n_bytes, avail))
+    except Exception as e:
+        print(f'[decode    ] read_vmlinux_bytes error: {e}', flush=True)
+    return None
+
+
+# ---------- disassemble a single instruction (for OPCODE and fixup) ----------
+def disasm_one(runtime_pc, kaslr_offset, vmlinux_path, label='>>>'):
+    """Disassemble one instruction; output format matches context display."""
+    if kaslr_offset is None or not HAS_CAPSTONE or not os.path.exists(vmlinux_path):
+        return
+    compiled_pc = runtime_pc - kaslr_offset
+    raw = read_vmlinux_bytes(vmlinux_path, compiled_pc, 4)
+    if not raw or len(raw) < 4:
+        print(f'[decode    ]   {label} {runtime_pc:#x}:  <cannot read bytes>', flush=True)
+        return
+    cs = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
+    insns = list(cs.disasm(raw, runtime_pc))
+    if insns:
+        ins = insns[0]
+        print(f'[decode    ]   {label} {ins.address:#x}:  {ins.mnemonic:<8} {ins.op_str}', flush=True)
+    else:
+        print(f'[decode    ]   {label} {runtime_pc:#x}:  <capstone failed to decode>', flush=True)
+
+
+# ---------- disassemble with surrounding context ----------
+def disasm_context(runtime_pc, kaslr_offset, vmlinux_path, ctx=0):
+    if kaslr_offset is None:
+        print('[decode    ]   cannot compute KASLR offset, skipping disassembly', flush=True)
+        return
+    if not HAS_CAPSTONE:
+        print('[decode    ]   capstone not installed, skipping disassembly (pip install capstone)', flush=True)
+        return
+    if not os.path.exists(vmlinux_path):
+        print(f'[decode    ]   vmlinux not found: {vmlinux_path}', flush=True)
+        return
+
+    compiled_pc    = runtime_pc - kaslr_offset
+    start_compiled = compiled_pc - ctx * 4
+    total_bytes    = (ctx * 2 + 1) * 4
+
+    raw = read_vmlinux_bytes(vmlinux_path, start_compiled, total_bytes)
+    if not raw or len(raw) < 4:
+        print(f'[decode    ]   cannot read bytes from vmlinux, skipping disassembly', flush=True)
+        return
+
+    cs    = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
+    # use runtime addresses so output matches bpftrace directly
+    start_runtime = start_compiled + kaslr_offset
+    insns = list(cs.disasm(raw, start_runtime))
+
+    print(f'[decode    ]   --- context (pc={runtime_pc:#x}, +/-{ctx} insns) ---', flush=True)
+    for ins in insns:
+        marker = '>>>' if ins.address == runtime_pc else '   '
+        print(f'[decode    ]   {marker} {ins.address:#x}:  {ins.mnemonic:<8} {ins.op_str}',
+              flush=True)
+    print(f'[decode    ]   ---', flush=True)
+
+
+# ---------- source location (brief, returns file:line string) ----------
+def get_source_brief(runtime_pc, kaslr_offset, vmlinux_path):
+    """Return absolute 'path:line' string, or None."""
+    if kaslr_offset is None or not check_dwarf(vmlinux_path):
+        return None
+    compiled_pc = runtime_pc - kaslr_offset
+    try:
+        out = subprocess.check_output(
+            ['addr2line', '-e', vmlinux_path, '-f', '-C',
+             hex(compiled_pc)],
+            stderr=subprocess.DEVNULL, universal_newlines=True
+        ).strip()
+        if out and '??' not in out:
+            # addr2line -f outputs: function\nfile:line
+            for ln in out.splitlines():
+                if '/' in ln or ':' in ln:
+                    return ln.strip()
+        return None
+    except Exception:
+        return None
+
+
+# ---------- initialization ----------
+if not HAS_CAPSTONE:
+    print('[decode    ] WARNING: capstone not installed  ->  pip install capstone', flush=True)
+if not HAS_ELFTOOLS:
+    print('[decode    ] WARNING: pyelftools not installed -> pip install pyelftools', flush=True)
+
+if not os.path.exists(VMLINUX):
+    print(f'[decode    ] WARNING: vmlinux not found at {VMLINUX}', flush=True)
+    KASLR_OFFSET = None
+else:
+    KASLR_OFFSET, _, _ = get_kaslr_offset(VMLINUX)
+
+# ---------- main loop: pass through all lines, trigger disasm on key lines ----------
+# do_sea Fault PC (with <ksym>)
+DOSEA_PC_RE  = re.compile(r'\[do_sea\s+\].*Fault PC \(faulting insn\):.*?([0-9a-f]{8,})\s*$')
+# Recovery addr (fixup)
+FIXUP_RE     = re.compile(r'Recovery addr \(fixup\):.*?([0-9a-f]{8,})\s*$')
+
+for line in sys.stdin:
+    # ---- do_sea Fault PC: append source location at end of line ----
+    m = DOSEA_PC_RE.search(line)
+    if m:
+        pc = int(m.group(1), 16)
+        src = get_source_brief(pc, KASLR_OFFSET, VMLINUX)
+        if src:
+            line = line.rstrip('\n') + '  ' + src + '\n'
+        sys.stdout.write(line)
+        sys.stdout.flush()
+        continue
+
+    # ---- Recovery addr: append source location at end of line ----
+    mf = FIXUP_RE.search(line)
+    if mf:
+        fixup_pc = int(mf.group(1), 16)
+        src = get_source_brief(fixup_pc, KASLR_OFFSET, VMLINUX)
+        if src:
+            line = line.rstrip('\n') + '  ' + src + '\n'
+        sys.stdout.write(line)
+        sys.stdout.flush()
+        continue
+
+    # ---- pass through other lines unchanged ----
+    sys.stdout.write(line)
+    sys.stdout.flush()
einj_mem_uc_verify.bt new file +108 -0

108 lines not on this page · raw message

Signature · 1 line
2.39.3
#2 lore raw

PATCH 2/4 ras-tools: verify MC-safe recovery for hwpoison copy-on-write patches

In reply to Ruidong Tian

From: Ruidong Tian <[email protected]>

Use EINJ hardware error injection with bpftrace to verify that each MC-safe page copy path correctly recovers from uncorrectable memory errors. Each test case targets a specific upstream commit.

== cow_anon -> d302c2398ba2 ("mm, hwpoison: when copy-on-write hits poison, take page offline") ==

[do_sea   ] Fault PC (faulting insn):  <copy_mc_page> ffffc4d88625b3ec
[do_sea   ] Call stack:
[do_sea   ]   <copy_mc_highpage>
[do_sea   ]   <copy_mc_user_highpage>
[do_sea   ]   <__wp_page_copy_user>
[do_sea   ]   <wp_page_copy>
[do_sea   ]   <do_wp_page>
[do_sea   ]   <handle_pte_fault>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <copy_mc_page> ffffc4d88625b45c

== cow_hugetlb -> 1cb9dc4b475c ("mm: hwpoison: support recovery from HugePage copy-on-write faults") ==

[do_sea   ] Fault PC (faulting insn):  <copy_mc_page> ffffc4d88625b3bc
[do_sea   ] Call stack:
[do_sea   ]   <copy_mc_highpage>
[do_sea   ]   <copy_mc_user_highpage>
[do_sea   ]   <copy_user_large_folio>
[do_sea   ]   <hugetlb_wp>
[do_sea   ]   <hugetlb_fault>
[do_sea   ]   <handle_mm_fault>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <copy_mc_page> ffffc4d88625b45c

== khugepaged_anon -> 98c76c9f1ef7 ("mm/khugepaged: recover from poisoned anonymous memory") ==

[do_sea   ] Fault PC (faulting insn):  <copy_mc_page> ffffc4d88625b3ec
[do_sea   ] Call stack:
[do_sea   ]   <copy_mc_highpage>
[do_sea   ]   <copy_mc_user_highpage>
[do_sea   ]   <__collapse_huge_page_copy>
[do_sea   ]   <collapse_huge_page>
[do_sea   ]   <collapse_scan_pmd>
[do_sea   ]   <collapse_single_pmd>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <copy_mc_page> ffffc4d88625b45c

== khugepaged_file -> 12904d953364 ("mm/khugepaged: recover from poisoned file-backed memory") ==

[do_sea   ] Fault PC (faulting insn):  <__pi_copy_mc_page> ffffa3447405b3ec
[do_sea   ] Call stack:
[do_sea   ]   <copy_mc_highpage>
[do_sea   ]   <collapse_file>
[do_sea   ]   <collapse_scan_file>
[do_sea   ]   <collapse_single_pmd>
[do_sea   ]   <madvise_collapse>
[do_sea   ]   <madvise_vma_behavior>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <__pi_copy_mc_page> ffffa3447405b45c

== cow_anon_pinned -> 658be46520ce ("mm: support poison recovery from copy_present_page()") ==

[do_sea   ] Fault PC (faulting insn):  <copy_mc_page> ffffc4d88625b3ec
[do_sea   ] Call stack:
[do_sea   ]   <copy_mc_highpage>
[do_sea   ]   <copy_mc_user_highpage>
[do_sea   ]   <copy_present_page>
[do_sea   ]   <copy_present_ptes>
[do_sea   ]   <copy_pte_range>
[do_sea   ]   <copy_pmd_range>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <copy_mc_page> ffffc4d88625b45c

== cow_private_filemap -> aa549f923f5e ("mm: support poison recovery from do_cow_fault()") ==

[do_sea   ] Fault PC (faulting insn):  <copy_mc_page> ffffc4d88625b3ec
[do_sea   ] Call stack:
[do_sea   ]   <copy_mc_highpage>
[do_sea   ]   <copy_mc_user_highpage>
[do_sea   ]   <do_cow_fault>
[do_sea   ]   <do_fault>
[do_sea   ]   <handle_pte_fault>
[do_sea   ]   <__handle_mm_fault>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <copy_mc_page> ffffc4d88625b45c

== migrate_hugetlb -> f00b295b9b61 ("fs: hugetlbfs: support poisoned recover from hugetlbfs_migrate_folio()") ==

[do_sea   ] Fault PC (faulting insn):  <copy_mc_page> ffffb45742beb3bc
[do_sea   ] Call stack:
[do_sea   ]   <copy_mc_highpage>
[do_sea   ]   <folio_mc_copy>
[do_sea   ]   <migrate_huge_page_move_mapping>
[do_sea   ]   <hugetlbfs_migrate_folio>
[do_sea   ]   <move_to_new_folio>
[do_sea   ]   <unmap_and_move_huge_page>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <copy_mc_page> ffffb45742beb45c

== move_pages_numa -> 060913999d7a ("mm: migrate: support poisoned recover from migrate folio") ==

[do_sea   ] Fault PC (faulting insn):  <__pi_copy_mc_page> ffffa3447405b3ec
[do_sea   ] Call stack:
[do_sea   ]   <copy_mc_highpage>
[do_sea   ]   <folio_mc_copy>
[do_sea   ]   <__migrate_folio.constprop.0>
[do_sea   ]   <migrate_folio>
[do_sea   ]   <move_to_new_folio>
[do_sea   ]   <migrate_folio_move>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <__pi_copy_mc_page> ffffa3447405b45c

== migrate_pages_numa -> 060913999d7a (same patch, different syscall entry) ==

[do_sea   ] Fault PC (faulting insn):  <copy_mc_page> ffffb45742beb3ec
[do_sea   ] Call stack:
[do_sea   ]   <copy_mc_highpage>
[do_sea   ]   <folio_mc_copy>
[do_sea   ]   <__migrate_folio.constprop.0>
[do_sea   ]   <migrate_folio>
[do_sea   ]   <move_to_new_folio>
[do_sea   ]   <migrate_folio_move>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <copy_mc_page> ffffb45742beb45c

== mbind_move -> 060913999d7a (same patch, different syscall entry) ==

[do_sea   ] Fault PC (faulting insn):  <copy_mc_page> ffffb45742beb3ec
[do_sea   ] Call stack:
[do_sea   ]   <copy_mc_highpage>
[do_sea   ]   <folio_mc_copy>
[do_sea   ]   <__migrate_folio.constprop.0>
[do_sea   ]   <migrate_folio>
[do_sea   ]   <move_to_new_folio>
[do_sea   ]   <migrate_folio_move>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <copy_mc_page> ffffb45742beb45c
---
 Makefile         |   4 +-
 einj_mem_uc.c    | 141 ++++++++---
 einj_mem_uc.h    |  69 +++++
 einj_mem_uc_mm.c | 637 +++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 815 insertions(+), 36 deletions(-)
 create mode 100644 einj_mem_uc.h
 create mode 100644 einj_mem_uc_mm.c
Makefile +2 -2
index 59c281c..2b5b78d 100644
@@ -34,8 +34,8 @@ rep_ce_page: rep_ce_page.o proc_pagemap.o einj.o
 hornet: hornet.o einj.o
 	$(CC) -o hornet $(CFLAGS) hornet.o einj.o
 
-einj_mem_uc: einj_mem_uc.o proc_cpuinfo.o proc_interrupt.o proc_pagemap.o do_memcpy.o einj.o
-	$(CC) -o einj_mem_uc $(CFLAGS) einj_mem_uc.o proc_cpuinfo.o proc_interrupt.o proc_pagemap.o do_memcpy.o einj.o -pthread
+einj_mem_uc: einj_mem_uc.o einj_mem_uc_mm.o proc_cpuinfo.o proc_interrupt.o proc_pagemap.o do_memcpy.o einj.o
+	$(CC) -o einj_mem_uc $(CFLAGS) einj_mem_uc.o einj_mem_uc_mm.o proc_cpuinfo.o proc_interrupt.o proc_pagemap.o do_memcpy.o einj.o -pthread
 
 lmce: proc_pagemap.o lmce.o
 	$(CC) -o lmce $(CFLAGS) proc_pagemap.o lmce.o -pthread
einj_mem_uc.c +107 -34

202 lines not on this page · raw message

einj_mem_uc.h new file +69 -0

69 lines not on this page · raw message

einj_mem_uc_mm.c new file +637 -0

637 lines not on this page · raw message

Signature · 1 line
2.39.3
#3 lore raw

PATCH 3/4 einj_mem_uc_uaccess: exercise copy_from_user hwpoison recovery via syscalls

In reply to Ruidong Tian

From: Ruidong Tian <[email protected]>

The MC-safe copy_from_user (copyin) path has already been validated to recover from a poisoned source page: the consumed hardware memory error is contained and reported rather than crashing the kernel. That baseline, however, only proves the mechanism works on a single code path.

These tests add cases that reach copy_from_user / get_user through a range of syscall entry points. The goal is not to re-validate copyin itself, but to demonstrate that the same recovery holds regardless of which syscall drives the copy -- i.e. the fix applies broadly across the kernel's uaccess call sites rather than in one isolated path.

Each test poisons a user page and then issues one syscall whose kernel side copies FROM that page, expecting either SIGBUS delivery or an -EFAULT return instead of a fatal fault.

Test cases by subsystem:

  File I/O:  pwrite_uc, writev_uc
  Network:   send_uc, sendmsg_uc, setsockopt_uc, netlink_send_uc
  IPC/sync:  msgsnd_uc, mq_send_uc, semop_uc
  Memory:    process_vm_writev_uc
---
 Makefile              |   4 +-
 einj_mem_uc.c         |  16 +-
 einj_mem_uc.h         |   3 +
 einj_mem_uc_uaccess.c | 369 ++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 389 insertions(+), 3 deletions(-)
 create mode 100644 einj_mem_uc_uaccess.c
Makefile +2 -2
index 2b5b78d..03d7673 100644
@@ -34,8 +34,8 @@ rep_ce_page: rep_ce_page.o proc_pagemap.o einj.o
 hornet: hornet.o einj.o
 	$(CC) -o hornet $(CFLAGS) hornet.o einj.o
 
-einj_mem_uc: einj_mem_uc.o einj_mem_uc_mm.o proc_cpuinfo.o proc_interrupt.o proc_pagemap.o do_memcpy.o einj.o
-	$(CC) -o einj_mem_uc $(CFLAGS) einj_mem_uc.o einj_mem_uc_mm.o proc_cpuinfo.o proc_interrupt.o proc_pagemap.o do_memcpy.o einj.o -pthread
+einj_mem_uc: einj_mem_uc.o einj_mem_uc_mm.o einj_mem_uc_uaccess.o proc_cpuinfo.o proc_interrupt.o proc_pagemap.o do_memcpy.o einj.o
+	$(CC) -o einj_mem_uc $(CFLAGS) einj_mem_uc.o einj_mem_uc_mm.o einj_mem_uc_uaccess.o proc_cpuinfo.o proc_interrupt.o proc_pagemap.o do_memcpy.o einj.o -pthread -lrt
 
 lmce: proc_pagemap.o lmce.o
 	$(CC) -o lmce $(CFLAGS) proc_pagemap.o lmce.o -pthread
einj_mem_uc.c +15 -1
index a6471af..aea795c 100644
@@ -1079,6 +1079,7 @@ static void show_help(void)
 	printf("  %-24s %-5s %s\n", "Testname", "Fatal", "Description");
 	show_test_array(tests, 0, NULL);
 	show_test_array(mm_tests, mm_tests_count, "MM subsystem (hwpoison recovery)");
+	show_test_array(uaccess_tests, uaccess_tests_count, "uaccess (copy_from_user direction)");
 	exit(0);
 }
 
@@ -1108,6 +1109,9 @@ static struct test *lookup_test(char *s)
 	if (t)
 		return t;
 	t = lookup_in(mm_tests, mm_tests_count, s);
+	if (t)
+		return t;
+	t = lookup_in(uaccess_tests, uaccess_tests_count, s);
 	if (t)
 		return t;
 	fprintf(stderr, "%s: unknown test '%s'\n", progname, s);
@@ -1118,7 +1122,7 @@ static struct test *next_test(struct test *t)
 {
 	/*
 	 * Walk: tests[] (NULL-terminated) -> mm_tests[] (counted) ->
-	 * wrap to tests[].
+	 * uaccess_tests[] (counted) -> wrap to tests[].
 	 */
 	if (t >= tests && (!t->testname || t[1].testname)) {
 		t++;
@@ -1126,12 +1130,22 @@ static struct test *next_test(struct test *t)
 			return t;
 		if (mm_tests_count)
 			return &mm_tests[0];
+		if (uaccess_tests_count)
+			return &uaccess_tests[0];
 		return tests;
 	}
 	if (mm_tests_count && t >= mm_tests && t < mm_tests + mm_tests_count) {
 		t++;
 		if (t < mm_tests + mm_tests_count)
 			return t;
+		if (uaccess_tests_count)
+			return &uaccess_tests[0];
+		return tests;
+	}
+	if (uaccess_tests_count && t >= uaccess_tests && t < uaccess_tests + uaccess_tests_count) {
+		t++;
+		if (t < uaccess_tests + uaccess_tests_count)
+			return t;
 		return tests;
 	}
 	return tests;
einj_mem_uc.h +3 -0
index c2d6c32..1f0487a 100644
@@ -66,4 +66,7 @@ void skip_test(const char *msg) __attribute__((noreturn));
 extern struct test mm_tests[];
 extern int mm_tests_count;
 
+extern struct test uaccess_tests[];
+extern int uaccess_tests_count;
+
 #endif /* EINJ_MEM_UC_H */
einj_mem_uc_uaccess.c new file +369 -0

369 lines not on this page · raw message

Signature · 1 line
2.39.3
#4 lore raw

PATCH 4/4 einj_mem_uc: add copy_mc_to_kernel() case

In reply to Ruidong Tian

From: Ruidong Tian <[email protected]>

add a coredump case to test copy_mc_to_kernel, call stack as follow:

[do_sea   ] Fault PC (faulting insn):  <__memcpy_mc> ffffb45742bee24c
[do_sea   ] Call stack:
[do_sea   ]   <dump_user_range>
[do_sea   ]   <elf_core_dump>
[do_sea   ]   <coredump_write>
[do_sea   ]   <do_coredump>
[do_sea   ]   <vfs_coredump>
[do_sea   ]   <get_signal>
[extable  ] Fault type:                unknown(5)
[extable  ] Recovery addr (fixup):     <__memcpy_mc> ffffb45742bee328
---
 einj_mem_uc_mm.c | 51 +++++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 48 insertions(+), 3 deletions(-)
einj_mem_uc_mm.c +48 -3
index 3e23593..b495c22 100644
@@ -2,12 +2,14 @@
 
 /*
  * einj_mem_uc_mm.c - tests that exercise the kernel's MC-safe page
- * copy primitives: copy_mc_user_highpage (COW / khugepaged / ksm) and
- * copy_mc_highpage (page migration).
+ * copy primitives: copy_mc_user_highpage (COW / khugepaged / ksm),
+ * copy_mc_highpage (page migration) and copy_mc_to_kernel (the ELF core
+ * dumper's dump_page_copy()).
  *
  * Each test allocates a page in a way that lets the kernel reach one of
  * those primitives, and its trigger drives the operation synchronously
- * whenever possible (MADV_COLLAPSE, move_pages, mbind MOVE, MADV_PAGEOUT).
+ * whenever possible (MADV_COLLAPSE, move_pages, mbind MOVE, MADV_PAGEOUT,
+ * or a core dump).
  */
 
 #define _GNU_SOURCE 1
@@ -26,6 +28,8 @@
 #include <sys/syscall.h>
 #include <sys/stat.h>
 #include <sys/ioctl.h>
+#include <sys/resource.h>
+#include <sys/prctl.h>
 
 #include <sys/uio.h>
 
@@ -602,6 +606,45 @@ static int trigger_cow_anon_pinned(char *addr)
 }
 
 
+/* ---------- core dump (copy_mc_to_kernel) ---------- */
+
+/*
+ * trigger_coredump - exercise copy_mc_to_kernel() via the ELF core dumper.
+ */
+static int trigger_coredump(char *addr)
+{
+	pid_t pid;
+
+	PRINT_TRIGGERING;
+	pid = fork();
+	if (pid == 0) {
+		struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
+
+		child_process = 1;
+		/* Allow a core dump regardless of inherited limits. */
+		setrlimit(RLIMIT_CORE, &rl);
+		prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
+		/*
+		 * Do NOT touch *addr ourselves: the poisoned page must be
+		 * consumed by the kernel core dumper (dump_user_range ->
+		 * dump_page_copy -> copy_mc_to_kernel), not by a user read.
+		 */
+		(void)addr;
+		abort();		/* SIGABRT -> core dump */
+		_exit(0);		/* not reached */
+	}
+	if (pid > 0) {
+		int st;
+
+		waitpid(pid, &st, 0);
+		if (WIFSIGNALED(st))
+			printf("child killed by signal %d%s\n", WTERMSIG(st),
+			       WCOREDUMP(st) ? " (core dumped)" : "");
+	}
+	return 0;
+}
+
+
 /* ---------- test table ---------- */
 
 #define MM(name, help, alloc_fn, trig_fn, fl) \
@@ -631,6 +674,8 @@ struct test mm_tests[] = {
 	MM("migrate_hugetlb", "move_pages(2) hugetlb file cross-node -> hugetlbfs_migrate_folio",
 	   mm_hugetlb_file_alloc, trigger_move_pages_hugetlb, F_MCE|F_CMCI|F_SIGBUS|F_FATAL),
 
+	MM("coredump", "Core dump of a poisoned page -> dump_page_copy -> copy_mc_to_kernel",
+	   mm_anon_private_alloc, trigger_coredump, F_MCE|F_CMCI|F_FATAL),
 
 };
 
Signature · 1 line
2.39.3
#5 lore raw
In reply to Ruidong Tian

Ruidong,

Thanks for sending this series. It looks like a very useful addition to test cases for ras-tools.

Quoted 10 lines

This series adds tooling to ras-tools for end-to-end validation of the arm64 "MC-safe" memory error recovery work on real hardware.

Recent arm64 patches teach the kernel to survive an uncorrectable (poison) memory error consumed during a kernel copy, instead of taking the whole machine down. Two broad families of copy paths are covered:

- kernel-side page copies (copy_mc_highpage / copy_mc_user_highpage /

    folio_mc_copy) used by COW, khugepaged, page migration and hugetlb;

- user-access copies (copy_from_user / copyin) driven by syscalls.

Does x86 also handle all those cases?

Quoted 2 lines

This series adds validation test cases and observability tooling for these recovery scenarios.

I didn't look closely at how this series works, but I did notice it provides code to disassemble binary code ... is that the ARM specific part of this series? What would need to be changed to support x86 too?

Please add a patch to update the README file with step by step instructions or examples of using this new capability.

-Tony