# Linux Kernel Module Cheat

#### 24.8.2. m5ops instructions

There are few different possible instructions that can be used to implement identical m5ops:

- magic instructions reserved in the encoding space

- magic addresses: m5ops magic addresses

- unused Semihosting addresses space on ARM platforms

All of those those methods are exposed through the gem5 m5 executable in-tree executable. You can select which method to use when calling the executable, e.g.:

    m5 exit
    # Same as the above.
    m5 --inst exit
    # The address is mandatory if not configured at build time.
    m5 --addr 0x10010000 exit
    m5 --semi exit

To make things simpler to understand, you can play around with our own minimized educational `m5` subset:

- userland/c/m5ops.c

- userland/cpp/m5ops.cpp

The instructions used by `./c/m5ops.out` are present in lkmc/m5ops.h in a very simple to understand and reuse inline assembly form.

To use that file, first rebuild `m5ops.out` with the m5ops instructions enabled and install it on the root filesystem:

    ./build-userland \
      --arch aarch64 \
      --force-rebuild \
      userland/c/m5ops.c \
    ;
    ./build-buildroot --arch aarch64

We don’t enable `-DLKMC_M5OPS_ENABLE=1` by default on userland executables because we try to use a single image for both gem5, QEMU and native, and those instructions would break the latter two. We enable it in the Baremetal setup by default since we already have different images for QEMU and gem5 there.

Then, from inside gem5 Buildroot setup, test it out with:

    # checkpoint
    ./c/m5ops.out c

    # dumpstats
    ./c/m5ops.out d

    # exit
    ./c/m5ops.out e

    # dump resetstats
    ./c/m5ops.out r

In theory, the cleanest way to add m5ops to your benchmarks would be to do exactly what the `m5` tool does:

- include `include/gem5/asm/generic/m5ops.h`

- link with the `.o` file under `util/m5` for the correct arch, e.g. `m5op_arm_A64.o` for aarch64.

However, I think it is usually not worth the trouble of hacking up the build system of the benchmark to do this, and I recommend just hardcoding in a few raw instructions here and there, and managing it with version control + `sed`.

Bibliography:

- https://stackoverflow.com/questions/63488050/what-are-pseudo-instructions-for-in-gem5/63489417#63489417

- https://stackoverflow.com/questions/62757008/how-to-use-m5-in-gem5-20/62759204#62759204

- https://stackoverflow.com/questions/56506154/how-to-analyze-only-interest-area-in-source-code-by-using-gem5/56506419#56506419

- https://www.mail-archive.com/gem5-users@gem5.org/msg15418.html

- m5ops magic addresses

- m5ops instructions interface

- m5op annotations