洪佑杭
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Term Project: Improve RISC-V System Emulation of [semu](https://github.com/sysprog21/semu) contributed by < [`hungyuhang`](https://github.com/hungyuhang), [`RayChen`](https://github.com/padaray) > ## Introduction System emulation provides a virtual model of a machine (CPU, memory and emulated devices) to run a guest OS. In integrated circuit (IC) design, system emulation plays a significant role during the initial design phase of the chip. And among those system emulators, [semu](https://github.com/sysprog21/semu) is a minimalist RISC-V system emulator capable of running Linux the kernel and corresponding userland. But as the term "minimalist" implies, semu does not include some essential peripherals, such as the RTC module. To improve the system emulation of semu, we add a simple RTC module. The implementations are in the following repositories: - [hungyuhang/semu](https://github.com/hungyuhang/semu) - [hungyuhang/linux_for_semu](https://github.com/hungyuhang/linux_for_semu) For repository [hungyuhang/semu](https://github.com/hungyuhang/semu), the code is implemented in the `rtc_feature` branch. And the precompiled image of our custom Linux is provided below: - [Image_rtc_feature.bz2](https://github.com/hungyuhang/semu/raw/blob/Image_rtc_feature.bz2) </br> ## Implementation We choose [LupIO real-time clock (RTC)](https://gitlab.com/luplab/lupio/lupio-specs/-/blob/main/lupio-rtc.md) as the RTC module to emulate, since it is easy for software/hardware adaptation because there are already implementations of the LupIO RTC in [lupV](https://gitlab.com/luplab/lupv) and [lupio/linux](https://gitlab.com/luplab/lupio/linux). ### **Hardware** ### 1. Real-time Clock Device We chose to port the real-time clock to **`semu`** due to its limited functions, minimizing dependencies and reducing the likelihood of encountering bugs during the porting process. #### **`lupV` Implementation - rtc.c** Below is the code for the `real-time clock(RTC)` in **`lupV`**: ```cpp #include <assert.h> #include <inttypes.h> #include <time.h> #include <devices/rtc.h> #define DBG_ITEM DBG_RTC #include <lib/debug.h> #include <platform/iomem.h> /* * Frontend: LupIO-RTC virtual device implementation */ enum { LUPIO_RTC_SECD = 0x0, LUPIO_RTC_MINT, LUPIO_RTC_HOUR, LUPIO_RTC_DYMO, LUPIO_RTC_MNTH, LUPIO_RTC_YEAR, LUPIO_RTC_CENT, LUPIO_RTC_DYWK, LUPIO_RTC_DYYR, /* Top offset in register map */ LUPIO_RTC_OFFSET_MAX, }; static uint64_t lupio_rtc_read(void *dev, phys_addr_t offset, enum iomem_size_log2 size_log2) { uint32_t val = 0; time_t time_sec; struct tm time_bd; char buffer[256]; /* Get real time in seconds */ time_sec = time(NULL); /* Break down time representation */ gmtime_r(&time_sec, &time_bd); strftime(buffer, 256, "%c", &time_bd); dbg_more("%s: read time = %s", __func__, buffer); switch(offset) { case LUPIO_RTC_SECD: val = time_bd.tm_sec; /* 0-60 (for leap seconds) */ break; case LUPIO_RTC_MINT: val = time_bd.tm_min; /* 0-59 */ break; case LUPIO_RTC_HOUR: val = time_bd.tm_hour; /* 0-23 */ break; case LUPIO_RTC_DYMO: val = time_bd.tm_mday; /* 1-31 */ break; case LUPIO_RTC_MNTH: val = time_bd.tm_mon + 1; /* 1-12 */ break; case LUPIO_RTC_YEAR: val = (time_bd.tm_year + 1900) % 100; /* 0-99 */ break; case LUPIO_RTC_CENT: val = (time_bd.tm_year + 1900) / 100; /* 0-99 */ break; case LUPIO_RTC_DYWK: val = 1 + (time_bd.tm_wday + 6) % 7; /* 1-7 (Monday is 1) */ break; case LUPIO_RTC_DYYR: val = time_bd.tm_yday + 1; /* 1-366 (for leap years) */ break; default: dbg_core("%s: invalid read access at offset=0x%" PRIxpa, __func__, offset); break; } return val; } static void lupio_rtc_write(void *dev, phys_addr_t offset, uint64_t val, enum iomem_size_log2 size_log2) { dbg_core("%s: invalid write access at offset=0x%" PRIxpa, __func__, offset); } static struct iomem_dev_ops lupio_rtc_ops = { .read = lupio_rtc_read, .write = lupio_rtc_write, .flags = IOMEM_DEV_SIZE8, }; void lupio_rtc_init(phys_addr_t base, phys_addr_t size) { assert(size >= LUPIO_RTC_OFFSET_MAX); iomem_register_device(base, size, NULL, &lupio_rtc_ops); } ``` </br> #### **`semu` Implementation - rtc.c** To align with the architecture of **`semu`**, we have designated `lupio_rtc_read` as the entry point, with the implementation details housed in `lupio_rtc_reg_read`. In this [document](https://gitlab.com/luplab/lupio/lupio-specs/-/blob/main/lupio-rtc.md), the register size is specified as 8 bits, thus the entry point's width is set to RV_MEM_LBU. Below is the implementation of the `lupio_rtc_read` function in **`semu`**. ```cpp void lupio_rtc_read(vm_t *vm, rtc_states *rtcState, uint32_t addr, uint8_t width, uint32_t *value) { uint8_t u8value; int32_t i32value; switch (width) { case RV_MEM_LBU: lupio_rtc_reg_read(rtcState, addr, &u8value); *value = (uint32_t) u8value; break; case RV_MEM_LB: lupio_rtc_reg_read(rtcState, addr, &u8value); i32value = (int32_t) (*((int8_t *) &u8value)); // do sign-extension *value = *((uint32_t *) &i32value); break; case RV_MEM_LW: case RV_MEM_LHU: case RV_MEM_LH: vm_set_exception(vm, RV_EXC_LOAD_MISALIGN, vm->exc_val); return; default: vm_set_exception(vm, RV_EXC_ILLEGAL_INSTR, 0); return; } } uint64_t lupio_rtc_reg_read(rtc_states *rtcState, uint32_t offset, uint8_t *value) { // uint32_t val = 0; time_t time_sec; struct tm time_bd; char buffer[256]; /* Get real time in seconds */ time_sec = time(NULL); /* Break down time representation */ gmtime_r(&time_sec, &time_bd); strftime(buffer, 256, "%c", &time_bd); // dbg_more("%s: read time = %s", __func__, buffer); switch(offset) { case LUPIO_RTC_SECD: *value = time_bd.tm_sec; /* 0-60 (for leap seconds) */ return true; case LUPIO_RTC_MINT: *value = time_bd.tm_min; /* 0-59 */ return true; case LUPIO_RTC_HOUR: *value = time_bd.tm_hour; /* 0-23 */ return true; case LUPIO_RTC_DYMO: *value = time_bd.tm_mday; /* 1-31 */ return true; case LUPIO_RTC_MNTH: *value = time_bd.tm_mon + 1; /* 1-12 */ return true; case LUPIO_RTC_YEAR: *value = (time_bd.tm_year + 1900) % 100; /* 0-99 */ return true; case LUPIO_RTC_CENT: *value = (time_bd.tm_year + 1900) / 100; /* 0-99 */ return true; case LUPIO_RTC_DYWK: *value = 1 + (time_bd.tm_wday + 6) % 7; /* 1-7 (Monday is 1) */ return true; case LUPIO_RTC_DYYR: *value = time_bd.tm_yday + 1; /* 1-366 (for leap years) */ return true; default: printf("%d: invalid read access at offset = " , offset); return true; } return true; } ``` </br> The modification to `lupio_rtc_write` involves adding the entry point `lupio_rtc_write`, while the implementation remains printing text in the original **`lupV`** code. Therefore, in **`semu`**, we opted to return void.The `lupio_rtc_write` code is as follows: ```cpp void lupio_rtc_write(vm_t *vm, rtc_states *rtcState, uint32_t addr, uint8_t width, uint32_t value) { switch (width) { case RV_MEM_SB: lupio_rtc_reg_write(rtcState, addr, value); return; case RV_MEM_SW: case RV_MEM_SH: vm_set_exception(vm, RV_EXC_STORE_MISALIGN, vm->exc_val); return; default: vm_set_exception(vm, RV_EXC_ILLEGAL_INSTR, 0); return; } } void lupio_rtc_reg_write(rtc_states *rtcState, uint32_t offset, uint8_t value) { return; } ``` </br> #### **`semu` Implementation - main.c** `main.c` file has four sections that need to be modified, including interrupt handling and memory read/write. The code is as follows: ```cpp static void emu_update_rtc_interrupts(vm_t *vm) { emu_state_t *data = (emu_state_t *) vm->priv; if (data->lrtc.InterruptStatus) data->plic.active |= IRQ_RTC_BIT; else data->plic.active &= ~IRQ_RTC_BIT; plic_update_interrupts(vm, &data->plic); } ``` ```cpp static void mem_load(vm_t *vm, uint32_t addr, uint8_t width, uint32_t *value) { ... ... case 0x43: /* rtc */ lupio_rtc_read(vm, &data->lrtc, addr & 0xFFFFF, width, value); emu_update_rtc_interrupts(vm); return; ... ... } ``` ```cpp static void mem_store(vm_t *vm, uint32_t addr, uint8_t width, uint32_t value) { ... ... case 0x43: /* realtime-clock */ lupio_rtc_write(vm, &data->lrtc, addr & 0xFFFFF, width, value); emu_update_rtc_interrupts(vm); return; ... ... } ``` ```cpp static int semu_start(int argc, char **argv) { ... ... if (emu.lrtc.InterruptStatus) emu_update_rtc_interrupts(&vm); ... ... } ``` </br> ### 2. Device Tree #### `lupV` Implementation - machine.c In **`lupV`**, the dynamic generation of the device tree is implemented by `generate_dtb` function as shown below: ```cpp static void generate_dtb(uint8_t *dst, phys_addr_t kernel_entry) { fdt_t fdt; enum { CPU_PHANDLE = 1, CLK_PHANDLE, PIC_PHANDLE, SYS_PHANDLE, }; int size; /* Build FDT */ fdt = fdt_create(); ... ... /* /soc/rtc@0x... */ fdt_begin_node_num(fdt, "rtc", memmap[RTC].base); fdt_prop_str(fdt, "compatible", "lupio,rtc"); fdt_prop_u64n(fdt, "reg", 2, memmap[RTC].base, memmap[RTC].size); fdt_end_node(fdt); /* } /soc/rtc */ ... ... } ``` #### `semu` Implementation - minimal.dts In **`semu`**, we write a DTS (Device Tree Source) file, and the code is as follows: ``` { ... ... rtc@4300000 { compatible = "lupio,rtc"; reg = <0x4300000 0x1000>; interrupts = <4>; }; ... ... } ``` </br> ### **Softwate** ### 1. Building the Linux Kernel with Custom RTC Driver For Linux to use the RTC module we implemented, we need to add a corresponding driver into the Linux kernel. In order to add the custom RTC driver, I create a custom Linux source code repository [linux_for_semu](https://github.com/hungyuhang/linux_for_semu/tree/main), and replace the Linux repository in `build-image.sh` by [linux_for_semu](https://github.com/hungyuhang/linux_for_semu/tree/main). This script will run when using `$ make build-image` to build the image. In [linux_for_semu](https://github.com/hungyuhang/linux_for_semu/tree/main), I apply the following modifications to add the RTC module: 1. Create a directory `lupio` inside `drivers`(which is in the Linux source code) for the RTC driver and put `rtc.c` inside this directory. 2. Create one Makefile inside the directory `drivers/lupio` and inside it put the line `obj-$(CONFIG_LUPIO_RTC) += rtc.o` and save this file. 3. Create one Kconfig file inside the directory `drivers/lupio` and inside it put: ``` if LUPIO config LUPIO_RTC tristate "LupIO-rtc driver" depends on LUPIO select RTC_CLASS help This driver supports a simple real-time clock (RTC) virtual device. endif ``` 4. Save the file in step 3. 5. Add both Makefile and Kconfig file in the Linux source drivers Makefile and Kconfig file which are at `drivers/Makefile` and `drivers/Kconfig` 6. In the Makefile add below: `obj-$(CONFIG_LUPIO) += lupio/` 7. In Kconfig file add below: `source "drivers/lupio/Kconfig"` 8. In `arch/riscv/Kconfig.socs` add below: ``` config SOC_LUPV bool "LupV Machine" select POWER_RESET select POWER_RESET_SYSCON select POWER_RESET_SYSCON_POWEROFF select LUPIO select LUPIO_RTC help This enables support for LupV Machine. ``` 9. Finally in `linux.config`, which is in the `semu` repository, modify the settings below: ``` ... CONFIG_SOC_LUPV=y ... CONFIG_RTC_LIB=y CONFIG_RTC_CLASS=y CONFIG_RTC_HCTOSYS=y CONFIG_RTC_HCTOSYS_DEVICE="rtc0" CONFIG_RTC_SYSTOHC=y CONFIG_RTC_SYSTOHC_DEVICE="rtc0" # CONFIG_RTC_DEBUG is not set CONFIG_RTC_NVMEM=y # # RTC interfaces # CONFIG_RTC_INTF_SYSFS=y CONFIG_RTC_INTF_PROC=y CONFIG_RTC_INTF_DEV=y ... CONFIG_LUPIO=y CONFIG_LUPIO_RTC=y ... ``` ### 2. Check if Linux Kernel Can Use RTC Module We will use `date` command to validate the RTC module. Use `$ date` to read the current time. Use `$ date YYYY.MM.DD-hh:mm:ss` to write the time. > Since writing data to RTC module is not implemented, we will only test read time function. When using the `date` command on [lupV](https://gitlab.com/luplab/lupv), the system returns the current time: ``` # date Wed Jan 10 11:31:33 UTC 2024 ``` But when using the `date` command on the original [semu](https://github.com/sysprog21/semu), the system only returns the default time: ``` # date Thu Jan 1 00:00:12 UTC 1970 ``` ## Issues Encountered After writing the RTC code, we run the emulator, but the emulator did not run properly. Below is the error message: ``` hungyuhang@hungyuhang-VirtualBox:~/semu$ make check 600+0 records in 600+0 records out 2457600 bytes (2.5 MB, 2.3 MiB) copied, 0.00384572 s, 639 MB/s mke2fs 1.46.5 (30-Dec-2021) Filesystem too small for a journal Discarding device blocks: done Creating filesystem with 600 4k blocks and 304 inodes Allocating group tables: done Writing inode tables: done Writing superblocks and filesystem accounting information: done Ready to launch Linux kernel. Please be patient. failed to allocate TAP device: Operation not permitted No virtio-net functioned [ 0.000000] Linux version 6.1.71-g1db6e9ae68da (hungyuhang@hungyuhang-VirtualBox) (riscv32-buildroot-linux-gnu-gcc.br_real (Buildroot 2023.05.1) 12.3.0, GNU ld (GNU Binutils) 2.39) #1 Thu Jan 11 15:21:01 CST 2024 [ 0.000000] Machine model: semu [ 0.000000] earlycon: ns16550 at MMIO 0xf4000000 (options '') [ 0.000000] printk: bootconsole [ns16550] enabled [ 0.000000] Zone ranges: [ 0.000000] Normal [mem 0x0000000000000000-0x000000001fffffff] [ 0.000000] Movable zone start for each node [ 0.000000] Early memory node ranges [ 0.000000] node 0: [mem 0x0000000000000000-0x000000001fffffff] [ 0.000000] Initmem setup node 0 [mem 0x0000000000000000-0x000000001fffffff] [ 0.000000] SBI specification v0.3 detected [ 0.000000] SBI implementation ID=0x999 Version=0x1 [ 0.000000] SBI TIME extension detected [ 0.000000] SBI SRST extension detected [ 0.000000] riscv: base ISA extensions ai [ 0.000000] riscv: ELF capabilities aim [ 0.000000] Built 1 zonelists, mobility grouping on. Total pages: 130048 [ 0.000000] Kernel command line: earlycon console=ttyS0 [ 0.000000] Dentry cache hash table entries: 65536 (order: 6, 262144 bytes, linear) [ 0.000000] Inode-cache hash table entries: 32768 (order: 5, 131072 bytes, linear) [ 0.000000] mem auto-init: stack:off, heap alloc:off, heap free:off [ 0.000000] Memory: 506884K/524288K available (3221K kernel code, 332K rwdata, 827K rodata, 158K init, 136K bss, 17404K reserved, 0K cma-reserved) [ 0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1 [ 0.000000] NR_IRQS: 64, nr_irqs: 64, preallocated irqs: 0 [ 0.000000] riscv-intc: 32 local interrupts mapped [ 0.000000] plic: interrupt-controller@0: mapped 31 interrupts with 1 handlers for 1 contexts. [ 0.000000] riscv-timer: riscv_timer_init_dt: Registering clocksource cpuid [0] hartid [0] [ 0.000000] clocksource: riscv_clocksource: mask: 0xffffffffffffffff max_cycles: 0xefdb196da, max_idle_ns: 440795204367 ns [ 0.000006] sched_clock: 64 bits at 65MHz, resolution 15ns, wraps every 2199023255550ns [ 0.001242] Console: colour dummy device 80x25 [ 0.001509] Calibrating delay loop (skipped), value calculated using timer frequency.. 130.00 BogoMIPS (lpj=260000) [ 0.001813] pid_max: default: 32768 minimum: 301 [ 0.003071] Mount-cache hash table entries: 1024 (order: 0, 4096 bytes, linear) [ 0.003333] Mountpoint-cache hash table entries: 1024 (order: 0, 4096 bytes, linear) [ 0.009246] ASID allocator disabled (0 bits) [ 0.011333] devtmpfs: initialized [ 0.017629] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 7645041785100000 ns [ 0.017930] futex hash table entries: 256 (order: -1, 3072 bytes, linear) [ 0.027105] NET: Registered PF_NETLINK/PF_ROUTE protocol family [ 0.032324] platform soc: Fixed dependency cycle(s) with /soc/interrupt-controller@0 [ 0.059010] clocksource: Switched to clocksource riscv_clocksource [ 0.118973] NET: Registered PF_INET protocol famil [ 0.121172] IP idents hash table entries: 8192 (order: 4, 65536 bytes, linear) [ 0.143229] tcp_listen_portaddr_hash hash table entries: 1024 (order: 0, 4096 bytes, linear) [ 0.143664] Table-perturb hash table entries: 65536 (order: 6, 262144 bytes, linear) [ 0.143950] TCP established hash table entries: 4096 (order: 2, 16384 bytes, linear) [ 0.144766] TCP bind hash table entries: 4096 (order: 3, 32768 bytes, linear) [ 0.145692] TCP: Hash tables configured (established 4096 bind 4096) [ 0.146194] UDP hash table entries: 256 (order: 0, 4096 bytes, linear) [ 0.146508] UDP-Lite hash table entries: 256 (order: 0, 4096 bytes, linear) [ 0.147710] NET: Registered PF_UNIX/PF_LOCAL protocol family [ 0.152664] Unpacking initramfs... [ 0.187390] workingset: timestamp_bits=30 max_order=17 bucket_order=0 [ 3.045763] Freeing initrd memory: 8188K [ 3.114188] Serial: 8250/16550 driver, 4 ports, IRQ sharing disabled [ 3.122704] printk: console [ttyS0] disabled [ 3.123089] f4000000.serial: ttyS0 at MMIO 0xf4000000 (irq = 1, base_baud = 312500) is a 16550 [ 3.123435] printk: console [ttyS0] enabled [ 3.123435] printk: console [ttyS0] enabled [ 3.123734] printk: bootconsole [ns16550] disabled [ 3.123734] printk: bootconsole [ns16550] disabled [ 3.126348] Oops - Oops - load address misaligned [#1] [ 3.126576] Modules linked in: [ 3.126756] CPU: 0 PID: 1 Comm: swapper Not tainted 6.1.71-g1db6e9ae68da #1 [ 3.127094] Hardware name: semu (DT) [ 3.127270] epc : lupio_rtc_read_time+0x14/0xf8 [ 3.127552] ra : __rtc_read_time+0x5c/0xa4 [ 3.127828] epc : c01f549c ra : c021a9d0 sp : c0861c50 [ 3.128100] gp : c046ff78 tp : c0844000 t0 : c0861cbc [ 3.128372] t1 : 00000023 t2 : ae000000 s0 : c0861c60 [ 3.128637] s1 : c08b2000 a0 : c083b210 a1 : c0861c98 [ 3.128909] a2 : 00000000 a3 : c0861cbc a4 : 0000005c [ 3.129164] a5 : a4001000 a6 : 00000030 a7 : 00000020 [ 3.129422] s2 : c0861c98 s3 : c08b2000 s4 : c08b20fc [ 3.129694] s5 : 00000000 s6 : c09953f4 s7 : c034782c [ 3.129956] s8 : 00000008 s9 : c03267b4 s10: 00000000 [ 3.130209] s11: 00000000 t3 : 91922286 t4 : 4199e48b [ 3.130471] t5 : 673ae5a1 t6 : c0a710ab [ 3.130686] status: 00000120 badaddr: a4001000 cause: 00000004 [ 3.130965] [<c01f549c>] lupio_rtc_read_time+0x14/0xf8 [ 3.131363] ---[ end trace 0000000000000000 ]--- [ 3.131583] Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000000b [ 3.131901] ---[ end Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000000b ]--- ``` From the message above, we can see that the emulator issues a `Load address misaligned` error. And the instruction which causes the issue is at address `0xc01f549c` To check the issue, I use the following command to dump the disassembly of the Linux image: ``` $ export PATH="path/to/buildroot/output/host/bin:$PATH" $ iscv32-buildroot-linux-gnu-objdump -b binary -D Image -m riscv > image_objdump.txt ``` > `path/to/buildroot` is the directory of the toolchain which builds the Linux kernel. In the disassembly code, there is no address `0xc01f549c`, but the instruction at `0x1f549c` is the compiled instruction in function `lupio_rtc_read_time()`. So I assumed that `0x1f549c` is the address that `epc` stored. And below are the instructions around `0x1f549c`: ``` ... 1f5488: ff010113 addi sp,sp,-16 1f548c: 00812623 sw s0,12(sp) 1f5490: 01010413 addi s0,sp,16 1f5494: 04052783 lw a5,64(a0) 1f5498: 0007a783 lw a5,0(a5) 1f549c: 00078703 lb a4,0(a5) 1f54a0: 0ff77713 zext.b a4,a4 1f54a4: 08a0000f fence i,ir 1f54a8: 00e5a023 sw a4,0(a1) # 0xa00000 1f54ac: 00178713 addi a4,a5,1 1f54b0: 00070703 lb a4,0(a4) 1f54b4: 0ff77713 zext.b a4,a4 1f54b8: 08a0000f fence i,ir ... ``` From the disassembly, we can see that `0x1f549c` is a `lb` instruction. And this instruction causes the exception. By tracing the code of `semu`, we find the root cause. Below is the original code of `lupio_rtc_read()` in `rtc.c`: ```ctype void lupio_rtc_read(vm_t *vm, rtc_states *rtcState, uint32_t addr, uint8_t width, uint32_t *value) { uint8_t u8value; switch (width) { case RV_MEM_LW: case RV_MEM_LBU: lupio_rtc_reg_read(rtcState, addr, &u8value); *value = (uint32_t) u8value; break; case RV_MEM_LB: case RV_MEM_LHU: case RV_MEM_LH: vm_set_exception(vm, RV_EXC_LOAD_MISALIGN, vm->exc_val); return; default: vm_set_exception(vm, RV_EXC_ILLEGAL_INSTR, 0); return; } } ``` We can see when using `lb` instruction to access the RTC module, the `width` variable in the code above will equals to `RV_MEM_LB`, which will cause an exception. And here is the code after modification: ```ctype void lupio_rtc_read(vm_t *vm, rtc_states *rtcState, uint32_t addr, uint8_t width, uint32_t *value) { uint8_t u8value; int32_t i32value; switch (width) { case RV_MEM_LBU: lupio_rtc_reg_read(rtcState, addr, &u8value); *value = (uint32_t) u8value; break; case RV_MEM_LB: lupio_rtc_reg_read(rtcState, addr, &u8value); i32value = (int32_t) (*((int8_t *) &u8value)); // do sign-extension *value = *((uint32_t *) &i32value); break; case RV_MEM_LW: case RV_MEM_LHU: case RV_MEM_LH: vm_set_exception(vm, RV_EXC_LOAD_MISALIGN, vm->exc_val); return; default: vm_set_exception(vm, RV_EXC_ILLEGAL_INSTR, 0); return; } } ``` After this modification, the RTC emulation code can handle both `lb` and `lbu` instruction access. </br> ## Result After solving the issue above, I run the `date` command to check the time, and below is the result: ``` # date Sat Jan 13 03:11:39 UTC 2024 ``` The Linux OS get the date from the RTC module successfully. If you want run [hungyuhang/semu](https://github.com/hungyuhang/semu) to see the result, you can simply run the same commands as the original [semu](https://github.com/sysprog21/semu)(`$ make` and `$ make check`). The Makefile script will download the correct prebuild Linux image file with the RTC driver in it. </br> ## Reference - [System Emulation](https://www.cadence.com/zh_TW/home/explore/system-emulation.html) - [LupV: an education-friendly RISC-V based system emulator](https://gitlab.com/luplab/lupv) - [Device Tree](https://elinux.org/Device_Tree_Usage) - [Linux Booting Process](https://linux.vbird.org/linux_basic/centos7/0510osloader.php#startup_intro) - [RTC Driver on Linux](https://docs.kernel.org/admin-guide/rtc.html) - [The /dev Directory in Linux](https://tldp.org/LDP/Linux-Filesystem-Hierarchy/html/dev.html) - [User Guide for some RTC device driver](https://www.analog.com/media/en/technical-documentation/user-guides/rtc-device-driver-user-guide.pdf) - [Adding new driver code to Linux source code](https://stackoverflow.com/questions/11710022/adding-new-driver-code-to-linux-source-code)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully