← All writing

QEMU

QEMU Camp 2026 notes and solutions.

QEMU

Usage

Really useful help.

Code
qemu-system-riscv64 --help
qemu-system-riscv64 -machine help
qemu-system-riscv64 -cpu help 					#list all supported cpu
qemu-system-riscv64 -device help
qemu-system-riscv64 -device virtio-blk-device,help

A example

Code
qemu-system-riscv64 \
    -M g233 -cpu saber -smp 1 \
    -m 128M -bios none -S \
    -display none -serial none -monitor stdio

-M specifies the mother board.

-cpu specifies the cpu model.

-smp specifies the number of hart.

-m sepcifies the size of memory.

Advanced C

In qemu or system programming, there are a lot of grammars of c which is hard to see in normal programs.

initializer

c
#include <stdio.h>

typedef struct saber {
    char *name;
    int age;
} Saber;



int main(void) {
    // positional initializer (the order should match)
    Saber s = {"love", 16};
    printf("%s", s.name);
    
    // designated initializer
    Saber a = {.name = "I", .age = 16};
    printf("%s", a.name);
    return 0;
}

marco

A macro gives the C preprocessor a rule for rewriting code before compilation.

function-like macro

c
#define GPGPU_STATUS_BUSY (1 << 1)
// function-like macro
#define BIT(nr)           (1UL << (nr))

unsigned long mask = BIT(1 + 2);

_VA_ARGS_

``VA_ARGS` is a placeholder for the extra arguments in a macro.

c
#define VALUES(first, ...) { (first), __VA_ARGS__ }

int nums[] = VALUES(10, 20, 30);

token-pasting operator

## is the C preprocessor’s token-pasting operator. It takes the token on each side and joins them into one token. A token is a piece of C syntax, such as an identifier like status, a number like 42, or an operator like +.

c
#define JOIN_RAW(a, b) a ## b

// Expands to: int reg_3 = 7;
int JOIN_RAW(reg_, 3) = 7;

_attribute_

__attribute__((...)) is GNU C syntax for attaching extra information to a declaration.

__attribute__((constructor)) tells GCC to run a function automatically before main() when the function is linked into the executable

c
static void __attribute__((constructor)) setup(void)
{
    puts("setup");
}

Inline assembly (RISC-V)

c
static unsigned long add_rv64(unsigned long a, unsigned long b)
{
    unsigned long sum;


    __asm__("add %0, %1, %2"
            : "=r"(sum)
            : "r"(a), "r"(b));

    return sum;
}

NOTE: this is for RISC-V.

In GCC inline assembly, : separates the instruction string from the lists of outputs, inputs, and clobbers.

  1. Instruction. RISC-V writes add destination, left, right. %0, %1, and %2 are placeholders for registers GCC chooses.
  2. Output after the first colon. "=r"(sum) means the instruction writes a register and GCC uses that value for sum. = means write-only, and r means a CPU register. This is operand %0.
  3. Inputs after the second colon. "r"(a), "r"(b) means GCC puts a and b in registers before the instruction runs. Outputs are numbered first, so these are %1 and %2.

QOM

QOM means QEMU Object Model. It implements object-oriented features in C:

  • Named types and inheritance.
  • Objects created from those types.
  • Methods implemented through function pointers.
  • Properties that can be inspected or configured.

In QOM, TypeInfo describes a type infomation of class.

And TypeImpl then is used to convert a internal type record (like a wrapper).

Then it will be initialization as runtime class ObjectClass.

And Object is the instance of that ObjectClass.

Code
TypeInfo                 Developer-written description
    ↓ registration
TypeImpl                 QOM’s internal type record
    ↓ class initialization
ObjectClass              Runtime class shared by its instances
    ↑              ↑
 Object         Object   Individual instances

TypeInfo Registration

c
struct TypeInfo
{
    const char *name;
    const char *parent;

    size_t instance_size;
    size_t instance_align;
    // This function is called to initialize an object.
    void (*instance_init)(Object *obj); 
    void (*instance_post_init)(Object *obj);
    // This function is called during object destruction.
    void (*instance_finalize)(Object *obj);
	
    //If this field is true, then the class is considered abstract and cannot be directly instantiated.
    bool abstract;
    size_t class_size;

    void (*class_init)(ObjectClass *klass, const void *data);
    void (*class_base_init)(ObjectClass *klass, const void *data);
    const void *class_data;

    // The list of interfaces associated with this type.
    const InterfaceInfo *interfaces;
};

At very beginning, QEMU register the type. Usually, it call

c
static TypeImpl *type_register_internal(const TypeInfo *info)
{
    TypeImpl *ti;

    if (!type_name_is_valid(info->name)) {
        fprintf(stderr, "Registering '%s' with illegal type name\n", info->name);
        abort();
    }

    ti = type_new(info);

    type_table_add(ti);
    return ti;
}

whose type_new converts the TypeInfo into a internal wrapper TypeImpl.

QOM maintain a hash table which store all these TypeImpl. And type_table_add() just add that TypeImpl into that hash table. The hash table is implemented by GLib, a C utility library.

Class Initialization

Next, QEMU initializes the type’s class when something requests it.

For example, object_class_by_name() looks up the type and initializes its class:

c
ObjectClass *object_class_by_name(const char *typename)
{
    TypeImpl *type = type_get_by_name_noload(typename);

    if (!type) {
        return NULL;
    }

    type_initialize(type);

    return type->class;
}

Code is self-explained. Let's look the type_initialize().

Each TypeImpl contains a fields ObjectClass *class; which points the runtime ObjectClass. And this is also what TypeInof doesn't contain.

c
struct ObjectClass
{
    /* private: */
    Type type;
    GSList *interfaces;

    const char *object_cast_cache[OBJECT_CLASS_CAST_CACHE];
    const char *class_cast_cache[OBJECT_CLASS_CAST_CACHE];

    ObjectUnparent *unparent;

    GHashTable *properties;
};

c
static void type_initialize(TypeImpl *ti) {
    TypeImpl *parent;
    // Check if the ObjectClass is already existing.
    if (ti->class) {
        return;
    }
	...
    // Here create that ObjectClass *class
    ti->class = g_malloc0(ti->class_size);
	
    // First initialize parent class recursively.
    parent = type_get_parent(ti);
    if (parent) {
        type_initialize(parent);
        ...
        // copy parent's ObjectClass *class
       	memcpy(ti->class, parent->class, parent->class_size);
		...
    }
    
    ....
        
    while (parent) {
        if (parent->class_base_init) {
            parent->class_base_init(ti->class, ti->class_data);
        }
        parent = type_get_parent(parent);
    }
       
    // This calls the type’s class initialization callback
    if (ti->class_init) {
        ti->class_init(ti->class, ti->class_data);
    }
}

And what is intersting is like Object class in java, there is a root class TYPE_OBJECT that every class is its descendant.

In the these stage, it will call the callback functions void (*class_base_init)(ObjectClass *klass, const void *data); and void (*class_init)(ObjectClass *klass, const void *data); in TypeImpl which is copyed from TypeInfo.

Object Instance

c
Object *object_new(const char *typename)
{
    TypeImpl *ti = type_get_or_load_by_name(typename, &error_fatal);

    return object_new_with_type(ti);
}

First create a object from that TypeImpl.

c
static Object *object_new_with_type(Type type)
{
    Object *obj;
	....
    // Class Initialization
    type_initialize(type);

    // Do the memory allocation
	....
    
    // Here is the instance ininitalization.
    object_initialize_with_type(obj, size, type);

    return obj;
}

Then let's look into it deeply:

c
static void object_initialize_with_type(Object *obj, size_t size, TypeImpl *type)
{
	...
   
    object_ref(obj);
    object_class_property_init_all(obj);
    obj->properties = g_hash_table_new_full(g_str_hash, g_str_equal,
                                            NULL, object_property_free);
    object_init_with_type(obj, type);
    object_post_init_with_type(obj, type);
}

object_ref(obj) This is a interesting thing. Object contains a reference counter:uint32_t ref;

After zeroing, it is 0. This call increments it to 1. Reference counting helps QOM manage the object’s lifetime: code holding a reference can keep it alive.

And the object_init_with_type(obj, type) and object_post_init_with_type(obj, type) will call the registered callback function in TypeImpl which is copyed from TypeInfo void (*instance_init)(Object *obj); and void (*instance_post_init)(Object *obj); .

CPU Model

First define the name marco of our cpu in target/riscv/cpu-qom.h

c
#define TYPE_RISCV_CPU_MAX              RISCV_CPU_TYPE_NAME("max")
#define TYPE_RISCV_CPU_MAX32            RISCV_CPU_TYPE_NAME("max32")
#define TYPE_RISCV_CPU_BASE32           RISCV_CPU_TYPE_NAME("rv32")
#define TYPE_RISCV_CPU_BASE64           RISCV_CPU_TYPE_NAME("rv64")
...
// our definition
#define TYPE_RISCV_CPU_SABER            RISCV_CPU_TYPE_NAME("saber")

Then we use add a item of our cpu type into riscv_cpu_type_infos:

c
// target/riscv/cpu.c
static const TypeInfo riscv_cpu_type_infos[] = {
	...
    DEFINE_RISCV_CPU(TYPE_RISCV_CPU_SABER, TYPE_RISCV_CPU_GEVICO_CV1
    ),
}

The DEFINE_RISCV_CPU will construct a instance of TypeInfo with parent cpu definition TYPE_RISCV_CPU_GEVICO_CV1.

So our current DEFINE_RISCV_CPU(...) just defines a TypeInfo i.e., defines a class in OPP

The type chain:

Code
TYPE_OBJECT
    └── TYPE_DEVICE
         └── TYPE_CPU
              └── TYPE_RISCV_CPU          ← Base for RISC-V CPUs
                   └── TYPE_RISCV_VENDOR_CPU
                        └── TYPE_RISCV_CPU_GEVICO_CV1
                             └── TYPE_RISCV_CPU_SABER

TYPE_RISCV_CPU

So let's first see the TYPE_RISCV_CPU

c
static const TypeInfo riscv_cpu_type_infos[] = {
    {
        .name = TYPE_RISCV_CPU,
        .parent = TYPE_CPU,
        .instance_size = sizeof(RISCVCPU),
        .instance_align = __alignof(RISCVCPU),
        .instance_init = riscv_cpu_init,
        .abstract = true,
        .class_size = sizeof(RISCVCPUClass),
        .class_init = riscv_cpu_common_class_init,
        .class_base_init = riscv_cpu_class_base_init,
    },
    ...
}

So the instance_init function is riscv_cpu_init and will be called in the object initialization.

And also note these two functions: .class_init = riscv_cpu_common_class_init and .class_base_init = riscv_cpu_class_base_init which are called when ClassObject is initialized.

riscv_cpu_class_base_init is used for implementing inheritance.

test 1

Purpose

RISC-V is an Instruction Set Architecture (ISA): it defines instructions, their binary encodings, registers, and execution rules.

RISC-V also reserves encoding spaces for custom instructions. This lab uses one of those spaces.

Preliminary

Think of the combination as the instruction’s identification code. We will teach QEMU to recognize it.

c
    asm volatile(
        ".insn r 0x7b, 6, 6, %0, %1, %2"
        :
        : "r"(dst), "r"(src), "r"(grain)
        : "memory" // tells the compiler the assembly may read or modify memory.
    );

Normally, assembly uses instruction names:add a0, a1, a2

The assembler knows how to encode add into binary.

Our custom instruction has no built-in assembler name, so we use .insn to specify its encoding directly:

Code
.insn r opcode, funct3, funct7, rd, rs1, rs2

Here r selects the R-type instruction format.

R-type is a layout for a 32-bit RISC-V instruction. It divides those 32 bits into fields.

Code
Bit: 31       25 24     20 19     15 14    12 11      7 6         0
     ┌──────────┬─────────┬─────────┬────────┬─────────┬───────────┐
     │ funct7   │ rs2     │ rs1     │ funct3 │ rd      │ opcode    │
     └──────────┴─────────┴─────────┴────────┴─────────┴───────────┘
Size:  7 bits     5 bits    5 bits    3 bits   5 bits    7 bits

FieldUsual meaning
opcodeIdentifies a broad instruction group
funct3, funct7Identify the operation within that group
rs1First source register number
rs2Second source register number
rdDestination register number

For a standard addition, its encoding is

Code
add x10, x11, x12

funct7   rs2    rs1    funct3  rd     opcode
0000000  01100  01011  000     01010  0110011
         x12    x11            x10

So the opcode, funct7 and funct3 together identify what our operation is.

And the lab’s specification already defines the encoding and behavior; we implement them in QEMU.

  1. Decode: recognize opcode=0x7b, funct3=6, funct7=6, and extract the register numbers.
  2. Translate: generate code that will perform this instruction’s behavior.
  3. Execute: when that generated code runs, read the register values and transpose the matrix in guest memory.

Solution

In target/riscv/insn32.decode contains RISC-V translation routines for the RVXI Base Integer Instruction Set.

we add our instruction

Code
# Xg233ai matrix transpose
xg233_dma  0000110 ..... ..... 110 ..... 1111011 @r

we supply only opcode=0x7b, funct3=6, funct7=6 and the ..... leaves a bit unconstrained, allowing different register numbers.

@r reuses the file’s existing R-type format, which extracts rd, rs1, and rs2.

since there are other formats like @i.

Code
@r       .......   ..... ..... ... ..... ....... &r                %rs2 %rs1 %rd
@i       ............    ..... ... ..... ....... &i      imm=%imm_i     %rs1 %rd
@b       .......   ..... ..... ... ..... ....... &b      imm=%imm_b %rs2 %rs1
....

Then we should handle the translation of that instruction.

First we need to add a helper function marco in target/riscv/helper.c

c
/* Xg233ai */
// tl means a target-sized integer—64 bits for this CPU.
// xg233_dma, Helper name
//  void for No return value 
// env, CPU architectural state pointer
DEF_HELPER_4(xg233_dma, void, env, tl, tl, tl)

It will be expand twice (THIS IS A deliberately but insteresting design)

One is

c
gen_helper_xg233_dma()

and the other is

Code
TCGHelperInfo helper_info_xg233_dma = {                          \
    .func = helper_xg233_dma, .name = xg233_dma,                 \
    .flags = FLAGS | dh_callflag(RET),                           \
    .typemask = dh_typemask(RET, 0)                              \
};

Frirst add the a function to target/riscv/translate.c

c
// arg_xg233_dma *a contains our extracted arguments
// ctx holds information about the translation currently
// in progress, including CPU configuration and instruction location.

static bool trans_xg233_dma(DisasContext *ctx, arg_xg233_dma *a)
{
    // Check the CPU width
    // If the current execution width is not RV64, 
    // this macro returns false, rejecting this translation.
    REQUIRE_64BIT(ctx);

    // getting register values
    TCGv dst = get_gpr(ctx, a->rd, EXT_NONE);
    TCGv src = get_gpr(ctx, a->rs1, EXT_NONE);
    TCGv grain = get_gpr(ctx, a->rs2, EXT_NONE);

    // This records the instruction encoding and supporting
    // metadata so QEMU can report the correct guest instruction 
    // if execution encounters a fault.
    decode_save_opc(ctx, 0);

    // This emits a TCG operation that calls our C helper during execution.
    gen_helper_xg233_dma(tcg_env, dst, src, grain);

    return true;
}

gen_helper_xg233_dma() will finially register our callback functionhelper_xg233_dma() into a list which will be called later.

So helper_xg233_dma() is the function do the exact work. we define it in target/riscv/op_helper.c

c
// src address of matrix, destination address of matrix and the grain stands for the 
// scale of matrix 0: 8x8, 1: 16x16, 2: 32x32. 
void helper_xg233_dma(CPURISCVState *env, target_ulong dst,
                       target_ulong src, target_ulong grain)
{
    // undefined behavior
    if (grain > 2) {
        return;
    }
    unsigned int n = 8U << grain;
    // Gets the host return address of the current helper.
    uintptr_t ra = GETPC();

    for(unsigned int i = 0; i < n; i++)
        for(unsigned int j = 0; j < n; j++){
            // note: 4 stands for 4 bytes, since we reads the raw FP32
            // bits, and the store writes those same bits to the transposed position.
            target_ulong src_addr = src + 4 * (i * n + j);
            target_ulong dst_addr = dst + 4 * (j * n + i);

            // c code:
            // dst[j * n + i] = src[i * n + j]

            // load
            uint32_t bits = cpu_ldl_le_data_ra(env, src_addr, ra);
            // store
            cpu_stl_le_data_ra(env, dst_addr, bits, ra);
        }
}

Done.

There are a lot of things worthy exploring. We leave them later tests.

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.