Re: [RFC 5/7] arm64: pmu: Add hook to handle pmu-related undefined instructions

From: Peter Zijlstra
Date: Wed May 29 2019 - 05:49:27 EST


On Tue, May 28, 2019 at 04:03:18PM +0100, Raphael Gault wrote:
> +static int emulate_pmu(struct pt_regs *regs, u32 insn)
> +{
> + u32 sys_reg, rt;
> + u32 pmuserenr;
> +
> + sys_reg = (u32)aarch64_insn_decode_immediate(AARCH64_INSN_IMM_16, insn) << 5;
> + rt = aarch64_insn_decode_register(AARCH64_INSN_REGTYPE_RT, insn);
> + pmuserenr = read_sysreg(pmuserenr_el0);
> +
> + if ((pmuserenr & (ARMV8_PMU_USERENR_ER|ARMV8_PMU_USERENR_CR)) !=
> + (ARMV8_PMU_USERENR_ER|ARMV8_PMU_USERENR_CR))
> + return -EINVAL;
> +

I would really prefer there to be a comment here that explain how the
'0' value works. Maybe something like:

/*
* Userspace is expected to only use this in the context of the
* scheme described in the struct perf_event_mmap_page comments.
*
* Given that context, we can only get here if we got migrated
* between getting the register index and doing the MSR read.
* This in turn implies we'll fail the sequence and retry, so
* any value returned is 'good', all we need is to be non-fatal.
*/

> + pt_regs_write_reg(regs, rt, 0);

And given the above, we don't even need to do this, we can simply
preserve whatever garbage was in the register and return to userspace.

The only thing we really need is for the trap to be non-fatal.

> +
> + arm64_skip_faulting_instruction(regs, 4);
> + return 0;
> +}
> +
> +/*
> + * This hook will only be triggered by mrs
> + * instructions on PMU registers. This is mandatory
> + * in order to have a consistent behaviour even on
> + * big.LITTLE systems.
> + */
> +static struct undef_hook pmu_hook = {
> + .instr_mask = 0xffff8800,
> + .instr_val = 0xd53b8800,
> + .fn = emulate_pmu,
> +};
> +
> +static int __init enable_pmu_emulation(void)
> +{
> + register_undef_hook(&pmu_hook);
> + return 0;
> +}
> +
> +core_initcall(enable_pmu_emulation);