Five EmbedDev logo Five EmbedDev

An Embedded RISC-V Blog

Intro

Example Code

The quick reference on this blog is generated from a YAML description (csr.yaml). Using that with a web template engine script (generators/yaml_jinja.py) and a template (templates/riscv-csr.h) code can be easily generated.

The C is code is include/riscv-csr.h, and there is an example examples/test_csr.c.

Accessing CSRs

The instructions to modifiy CSRs are listed here Some examples are shown below.

   uint32_t vendorid;
   __asm__ volatile ("csrr    %0, mvendorid" 
                      : "=r" (vendorid)  /* output : register */
                      : /* input : none */
                      : /* clobbers: none */);
   uint32_t new_mtvec = 0x10000000;
   __asm__ volatile ("csrw    mtvec, %0" 
                      : /* output: none */ 
                      : "r" (new_mtvec) /* input : from register */
                      : /* clobbers: none */);
   uint32_t value = 0x80; /* timer interrupt mtie */
   __asm__ volatile ("csrrs    zero, mie, %0"  
                     : /* output: none */ 
                     : "r" (value)  /* input : register */
                     : /* clobbers: none */);
   uint32_t prev_enabled;
   uint32_t new_enable = 0x880;  /* timer and external */
   __asm__ volatile ("csrrs    %0, mie, %1"  /* read and write atomically */
                     : "=r" (prev_enabled) /* output: register %0 */
                     : "r" (new_enable)  /* input: register %1 */
                     : /* clobbers: none */);
#define MASK 0x08
   __asm__ volatile ("    csrsi mstatus, %0" 
                     : /* output: none */ 
                     : "i" (MASK)  /* input : constant immediate MASK */
                     : /* clobbers: none */);
#define MASK 0x08
   __asm__ volatile ("    csrci mstatus, %0" 
                     : /* output: none */ 
                     : "i" (MASK)  /* input : constant immediate MASK */
                     : /* clobbers: none */);