paulpeng
    • 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 No publishing access yet

      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.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      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 No publishing access yet

    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.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    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
    # Assignment3: Single-cycle RISC-V CPU contributed by < [`paulpeng-popo`](https://github.com/paulpeng-popo/ca2023-lab3) > ## Prerequisites In order to avoid affecting the original computer environment, a container is set up to provide the experimental environment for [Assignment 3](https://hackmd.io/@sysprog/2023-arch-homework3). Here, I use Docker for building container. ```Dockerfile FROM arm64v8/ubuntu:22.04 # set the working directory WORKDIR /root # set the environment variable ENV DEBIAN_FRONTEND=noninteractive # update the repository sources list RUN apt update # install sudo RUN apt install sudo -y # create a new user as popo RUN useradd -ms /bin/bash popo # add the user to sudo group RUN usermod -aG sudo popo # set user popo as sudoer without password RUN echo "popo ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers # change the user to popo USER popo # change the working directory to home WORKDIR /home/popo # set the environment variable ENV HOME /home/popo ENV USER popo ENV PATH $PATH:/home/popo/.local/bin # install packages RUN sudo apt install git wget curl xauth dbus-x11 -y ENTRYPOINT ["/bin/bash"] ``` Then, following the instructions provided in [Lab3: Construct a single-cycle RISC-V CPU with Chisel](https://hackmd.io/@sysprog/r1mlr3I7p#Prerequisites) to install necessary dependency packages and tools. ```sh $ sudo apt install build-essential verilator gtkwave $ curl -s "https://get.sdkman.io" | bash $ sdk install java 11.0.21-tem $ sdk install sbt ``` ```sh # install scala on aarch64 linux $ curl -fL https://github.com/VirtusLab/coursier-m1/releases/latest/download/cs-aarch64-pc-linux.gz | gzip -d > cs && chmod +x cs && ./cs setup # change to scala 2 $ cs install scala:2.13.12 scalac:2.13.12 ``` ## Hello World in Chisel ```scala // Hello.scala class Hello extends Module { val io = IO(new Bundle { val led = Output(UInt(1.W)) }) val CNT_MAX = (50000000 / 2 - 1).U; val cntReg = RegInit(0.U(32.W)) val blkReg = RegInit(0.U(1.W)) cntReg := cntReg + 1.U when(cntReg === CNT_MAX) { cntReg := 0.U blkReg := ~blkReg } io.led := blkReg } ``` The module has two registers, `cntReg` and `blkReg`, both initialized with zero values. `cntReg` is a 32-bit counter that increments by 1 in each clock cycle. When `cntReg` reaches a certain value (CNT_MAX), it resets to zero, and `blkReg` toggles its value. I test [`Hello.scala`](https://hackmd.io/@sysprog/r1mlr3I7p#Hello-World-in-Chisel) on [chisel-template](https://github.com/freechipsproject/chisel-template) For testing convenience, I have reduced the number from 50,000,000 to 10, making it easier to observe the differences in the output. The updated `CNT_MAX` value is now set to 4 Then create `HelloSpec.scala` in `scr/test/scala/example` ```scala // HelloSpec.scala class HelloSpec extends AnyFreeSpec with ChiselScalatestTester { "Hello" in { test(new Hello) { hello => for (clk <- 0 until 10) { hello.clock.step(1) val led = hello.io.led.peek() println(s"clk: $clk, led: $led") } } } } ``` It checks whether the module correctly simulates by stepping the simulation forward for 10 clock cycles and printing the values of the `clk` and `led` signals at each step. ```sh $ sbt "testOnly example.HelloSpec" ``` The output would look like: ``` clk: 0, led: UInt<1>(0) clk: 1, led: UInt<1>(0) clk: 2, led: UInt<1>(0) clk: 3, led: UInt<1>(0) clk: 4, led: UInt<1>(1) clk: 5, led: UInt<1>(1) clk: 6, led: UInt<1>(1) clk: 7, led: UInt<1>(1) clk: 8, led: UInt<1>(1) clk: 9, led: UInt<1>(0) ``` ### Enhancement > Using `when` blocks in Hardware Description Language (HDL) designs is not necessarily something that should be avoided in all cases. However, in some situations, particularly when dealing with simple state machines or conditional assignments, it might be more readable and synthesizable to use multiplexers (muxes) instead of `when` blocks. > > The primary reason for preferring `muxes` in some cases is that they directly map to hardware multiplexing structures, which synthesis tools can often recognize and implement more efficiently. This is especially true for simple conditions or state machines where a `mux` can directly represent the selection of one value from several inputs. > > --- From ChatGPT --- ```diff= - cntReg := cntReg + 1.U - when(cntReg === CNT_MAX) { - cntReg := 0.U - blkReg := ~blkReg - } + cntReg := Mux(cntReg === CNT_MAX, 0.U, cntReg + 1.U) + blkReg := blkReg ^ (cntReg === CNT_MAX) ``` Here, a multiplexer is employed to determine whether the counter should increment or reset to zero. Simultaneously, a logical `XOR` operation is utilized to toggle the state of blkReg. The `XOR` operation ensures that blkReg changes its state whenever the counter is reset, providing the desired functionality without using a `when` block. ## Single Cycle RISC-V CPU (MyCPU) ### Overview of Implementation ![full_diagram](https://hackmd.io/_uploads/Byls_puBT.png) ![overview](https://hackmd.io/_uploads/BygcZK_B6.png) 1. Instruction Fetch: Fetching the instruction data from memory. 2. Decode: Understanding the meaning of the instruction and reading register data. 3. Execute: Calculating the result using the ALU. 4. Memory Access (load/store instructions): Reading from and writing to memory. 5. Write-back (for all instructions except store): Writing the result back to registers. ### Check waveform by [GTKWave](https://gtkwave.sourceforge.net/) ```sh $ WRITE_VCD=1 sbt test $ gtkwave test_run_dir/<xxx>/<xxx>.vcd ``` ### Instruction Fetch ![InstructionFetch](https://hackmd.io/_uploads/SyImGF_BT.png) Instruction fetch stage does: - Fetch the instruction from memory based on the current address in the PC register. - Modify the value of the PC register to point to the next instruction. The PC register is initially set to the entry address of the program. Upon encountering a valid instruction, the CPU fetches the instruction located at the address specified by the PC. If a jump is necessary, the CPU checks the `jump_flag_id` to determine whether a jump should be taken. If a jump is required, the PC is then updated with the address specified by `jump_address_id`. Otherwise, the PC is incremented by 4 to move to the next sequential instruction. ![instruction_fetch_wave](https://hackmd.io/_uploads/SJWnaFOHa.png) PC initiates at address `0x1000`. In the first test case, where no jump occurs, the PC advances to fetch the next instruction by incrementing to PC + 4. Subsequently, in the second test case, a jump to address `0x1000` is executed, causing the PC to update its value to `0x1000` during the next clock cycle. ### Instruction Decode ![instruction_fields](https://hackmd.io/_uploads/BkgOeiOSa.png) Decode stage does: - Read the opcode to determine instruction type and field lengths - Read in data from all necessary registers - for `add`, read two registers - for `addi`, read one register - for `jal`, no reads are necessary - Output control signals ![control_signals](https://hackmd.io/_uploads/ryRE8jdra.png) At this stage, 8 signals need to be generated, and the remaining two outputs, namely `memory_read_enable` and `memory_write_enable`, have not been implemented yet. These two signals appear to be associated with load and store instructions. To finalize their implementation, we can easily configure `memory_read_enable` to be `true.B` when processing L type instructions, and set `memory_write_enable` to `true.B` for S type instructions; otherwise, the default value remains `false.B`. :::warning A warning occurs during compilation: > method apply in object **MuxLookup is deprecated** (since Chisel 3.6): Use **MuxLookup(key, default)(mapping)** instead To address this warning, simply relocate the mapping sequence section to eliminate the deprecation message. ```scala val immediate = MuxLookup( opcode, Cat(..., ...) ) { IndexedSeq( ..., ... ) } ``` ::: ![control_signals_wave](https://hackmd.io/_uploads/B1TcVpOST.png) Three test cases: - 0x00a02223 (S-type) - 0x000022b7 (lui) - 0x002081b3 (add) ```scala object InstructionTypes { val L = "b0000011".U // 0x3 val I = "b0010011".U val S = "b0100011".U // 0x23 val RM = "b0110011".U val B = "b1100011".U } ``` According to our design specification, when the opcode is `0x3`, the signal `memory_read_enable` should be set to `true.B`, and when the opcode is `0x23`, the signal `memory_write_enable` should be set to `true.B`. The waveform chart above conveniently validates this behavior. ### Execution ![execution](https://hackmd.io/_uploads/HkZu_TuS6.png) Execution stage does: - Perform ALU computation. - Determine if there is a branch. The control line for the ALU, denoted as `alu.io.func`, is derived from the output of the ALU control module, specifically `alu_ctrl.io.alu_funct`. Additionally, the two inputs of the ALU are determined by the control lines `aluop1_source` and `aluop2_source`. These control lines drive the corresponding inputs through two Muxes. ![execution_wave](https://hackmd.io/_uploads/Hyf5ZAuBp.png) Initially, there are some test cases that involve the **ADD** instruction, aiming to evaluate the normal functioning of the ALU. The final two tests involve the **BEQ** instruction, assessing both jump and non-jump scenarios. In the case where the jump is taken, the program counter advances to PC + 2, equivalent to `0x4`. ### Combining into a CPU With the completion of modules for each stage, the subsequent phase involves connecting the inputs and outputs of these stages. Once this integration is accomplished, the single-cycle RISC-V CPU will be considered complete. ``` [info] Run completed in 10 seconds, 938 milliseconds. [info] Total number of tests run: 9 [info] Suites: completed 7, aborted 0 [info] Tests: succeeded 9, failed 0, canceled 0, ignored 0, pending 0 [info] All tests passed. [success] Total time: 12 s, completed Dec 3, 2023, 12:05:01 AM ``` ## Make handwritten RISC-V assembly code functions correctly on "MyCPU"

    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
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    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