<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vivek on Medium]]></title>
        <description><![CDATA[Stories by Vivek on Medium]]></description>
        <link>https://medium.com/@viveksgt?source=rss-383741476adf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Vivek on Medium</title>
            <link>https://medium.com/@viveksgt?source=rss-383741476adf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:14:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@viveksgt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding RISCV Virtual Memory [Part 2]: Virtual Memory Schemes]]></title>
            <link>https://medium.com/@viveksgt/understanding-riscv-virtual-memory-part-2-virtual-memory-schemes-c36c4309d374?source=rss-383741476adf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c36c4309d374</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[virtual-memory]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[risc-v]]></category>
            <category><![CDATA[processors]]></category>
            <dc:creator><![CDATA[Vivek]]></dc:creator>
            <pubDate>Thu, 23 May 2024 12:37:08 GMT</pubDate>
            <atom:updated>2024-05-23T18:10:06.378Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Link to the previous part</strong><br>(<a href="https://medium.com/@viveksgt/understanding-risc-v-virtual-memory-part-0-0bc2ce3318cf">https://medium.com/@viveksgt/understanding-risc-v-virtual-memory-part-0-0bc2ce3318cf</a> )</p><p>RISCV specification defines the following 32-bit and 64-bit virtual memory schemes.</p><h4><strong>RV32 Virtual Memory Schemes:</strong></h4><ol><li><strong>Bare Scheme</strong>: In this mode the virtual address is mapped to the same physical address and no address translation is done. It is used in some embedded systems.</li><li><strong>SV32 Scheme: </strong>A 2-level page table mechanism that maps 4GB virtual address space to 16 GB Physical address space. The page table consists of two levels. And have support for Megapages in addition to normal 4KB pages.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*AEe_t5hTygUjPQbx2yKyNA.png" /><figcaption>Credit: RISCV specification doc v1.10</figcaption></figure><h4><strong>RV64 Virtual Memory Schemes:</strong></h4><ol><li><strong>Bare Scheme</strong>: Same as 32-bit Bare Scheme, no address translation is carried out, and the virtual address is mapped to the same physical address</li><li><strong>SV39</strong> <strong>Scheme</strong>: A 3-level page table mechanism that maps 512 Gigabytes of virtual address space to 64 Petabytes of physical address space. The page level consists of three levels. And have support for Megapages, And Giga-pages in addition to normal 4KB pages.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*AEe_t5hTygUjPQbx2yKyNA.png" /><figcaption>Credit: RISCV specification doc v1.10</figcaption></figure><p><strong>3. SV48 Scheme</strong>: A 4-level page table mechanism that maps 256 Terabytes of virtual address space to 64 Petabytes of Physical address space. The page Table consists of four levels. And have support for Megapages, Gigapages, And Terapages in addition to normal 4KB pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*-6ufv8aQF762mwGVOFdHhg.png" /><figcaption>Credit: RISCV specification doc v1.10</figcaption></figure><h4><strong>SATP (Superviser Address Translation and Protection ) Register:</strong></h4><p>The SATP register is the page table base register used in address translation. The SATP register has three fields</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*1lSplCpANM8b3SUpsKacSg.png" /><figcaption><strong>SATP REGISTER</strong></figcaption></figure><p>SATP register can be of 32 and 64 bits depending on the processor (32-bit or 64-bit).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*JiTmbEhXqPfJuJ5YPK0xdQ.png" /></figure><p>Mode: Mode bits are used to determine the mode or scheme of the virtual memory system. <br>a. For a 32-bit system, the mode is represented by MSB (bit 31) and if this value is 0 then the virtual memory mode is 32-bit bare, and if this value is 1 then the virtual memory mode is <strong>SV32 Scheme</strong></p><p>b. For a 64-bit system, the mode is represented By four bits[63–60] of SATP register. If these bits are &lt;0000&gt; the virtual memory mode is BARE. If these bits are &lt;1000&gt;, then the virtual memory mode is <strong>SV39 Scheme</strong>, <br>And if these bits are &lt;1001&gt;, then the virtual memory mode is <strong>SV48 Scheme</strong>.</p><p><strong>ASID</strong>: ASID bit is related to the Translation lookaside buffer. Since the address translation process is costly, So the page table address mappings are cached in a small memory connected to the processor. The processor references the TLB before doing virtual memory-based address translation to resolve the address.</p><p>ASID stands for <strong>ADDRESS SPACE IDENTIFIER</strong>. Each user process on RISCV systems is supposed to be running on a unique address space and the Address space identifier for the current process is stored in ASID bits of the SATP register.</p><p>For RV32 ASID is a 9 bit value from Bits[30–22], and for RV64 ASID is 16 bit value from Bits[ 59–44]</p><p><strong>PPN</strong>: <strong>Physical Page Number, is the physical address</strong> of the base of the page table. For RV32 this value is 22 bits [0–21] and for RV64 this value is 44 bits [0–43]</p><h4><strong>Page Table Entries:</strong></h4><p>Each page table entry consists of two types of information <strong>Physical Page Number</strong> related information and <strong>Page Flags.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*ncwh97auCp9ox8SPyl3KWg.png" /><figcaption>General Page Table Entry Format</figcaption></figure><p>In the page table entry of any virtual memory scheme, the first nine bits are for page flags. Page Flag bits are interpreted in the following manner.</p><p><strong>Valid Bit (Bit 0): </strong>This bit tells whether the page table entry is valid. If this bit is 0 then the page table entry is invalid and the memory management system will report an access fault.</p><p><strong>Permissions Bits (XWR, Bits[3–1]): </strong>Bits [3–1] of the page table entry are interpreted as permission bits. Bit 3 is the <strong>execute</strong> permission bit, Bit 2 is the <strong>write</strong> permission bit, and Bit 1 is the <strong>read </strong>permission bit. The summarized interpretation of permission bits is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*EIYABwrU0jX6bMBSKoJRIw.png" /><figcaption><strong>Credit: RISCV specification doc v1.10</strong></figcaption></figure><p>If bits XWR is NOT 000 the,en the corresponding page of the page table entry is considered as <strong>Leaf Page</strong>. That is no further traversing is required, and permission bits are to be used accordingly. But If the XWR bits are 000 the page table entry is considered a <strong>Non-Leaf Page table entry, and address translation requires traversing at next level.</strong></p><p><strong>User mode bit or U [Bit 4]: </strong>The User mode tells whether the page can be accessed by user mode software. If this bit is 1 then user mode software can access the page. If the SUM bit of status control register of the processor is set to 1 and U bit is 1 then the page can be accessed in supervisor mode. (The address space can viewed as a division in two halves, the top half and the bottom half. The bottom half can only be accessed by software running in user mode)</p><p><strong>Global Bit(Bit 5): </strong>The Global bit tells whether the page can be shared among all address spaces. If this bit is set to 1 then the corresponding mappings can be used by all address spaces. And ASID check while memory translation can be suppressed.</p><p><strong>Accessed bit(Bit 6): </strong>This bit is set to 1 whenever a byte from the corresponding page undergoes read, write, execute operation.</p><p><strong>Dirty Bit (Bit 7): </strong>This bit is set to 1 whenever a byte from the corresponding page undergoes a write, operation.</p><p>(Note: The Access and Dirty bits are only relevant for leaf page table entries)</p><p><strong>Reserve Bits (Bits[9–8]): </strong>These bits are not used by hardware and can be used by the supervisor mode software.</p><h4>Concept of Megapages, Gigapages, Terapages:</h4><p>Suppose you want to map a whole program on a single page, but the program’s address space is greater than 4KB, For example, <strong>you want to run software with low TLB miss, or you are running a database management system or you are running a virtual machine. In all these cases page faults will affect the performance of the software. So memory management hardware has support for large pages.</strong></p><p>In SV32 we can have a leaf page table entry in the first-level page table. That page table entry can point to a page of size 2²² bytes of 4MB and such a page is called a <strong>Megapage</strong></p><p>In SV39 we can have a leaf page table entry in the first-level page table. That page table entry can point to a page of size 2³⁰ bytes of 1GB and such a page is called a <strong>Gigapage. </strong>Similarly, a leaf entry on the second level of the page table can support a <strong>Megapage</strong> as well.</p><p>In SV48 we can have a leaf page table entry in the first-level page table. That page table entry can point to a page of size 2⁴⁰ bytes of 1TB and such a page is called a <strong>Terapage. </strong>Similarly, a leaf entry on the second level of page table can support a <strong>Gigapage </strong>and a leaf entry on the third level can support a <strong>Megapage </strong>as well.</p><p>This concludes the second article in this blog series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c36c4309d374" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding RISC-V Virtual Memory [Part 1]]]></title>
            <link>https://medium.com/@viveksgt/understanding-risc-v-virtual-memory-part-0-0bc2ce3318cf?source=rss-383741476adf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bc2ce3318cf</guid>
            <category><![CDATA[virtual-memory]]></category>
            <category><![CDATA[risc-v]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[processors]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Vivek]]></dc:creator>
            <pubDate>Tue, 07 May 2024 08:42:23 GMT</pubDate>
            <atom:updated>2024-05-23T12:37:37.748Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The Necessity of Virtual Memory:</strong></p><p>When an operating system loads a program, it utilizes a loader to interpret the executable file (elf, exe). These files contain not only machine code but also crucial address information dictating where the program should reside in memory. This address allocation is determined by the compiler.</p><p>However, issues arise when multiple programs are assigned the same or overlapping address spaces. For instance, Program A might be designated for loading at address 0x0000c000–0x00040000, while Program B is slated for 0x0000d000–0x00041000. Moreover, with a finite main memory capacity, loading numerous programs can exhaust available space, hindering the addition of new programs. This is where the concept of virtual memory proves indispensable.</p><p><strong>Understanding Virtual Memory</strong>:</p><p>Virtual memory functions as a facade, providing a perception of vast memory space to individual processes. It achieves this through a translation mechanism known as a Page Table. Each entry in the page table maps an address from the executable to its corresponding physical address in the main memory.</p><p>Although the page table is intricate, its basic function can be comprehended. The operating system allocates a page table for each process. Consequently, if two programs, A and B, share the same address for their initial instruction (e.g., 0xc000), their respective page table entries differentiate the physical memory locations. For instance, the page table entry for Program A might be &lt;0xc000,0x0001c000&gt;, while for Program B it could be &lt;0xc000, 0x0002c000&gt;. This ensures that despite sharing the same virtual address, each program accesses distinct physical memory locations.</p><p>The presence of a page table facilitates the partial loading of a program into memory. Address space is divided into uniform segments known as <strong>pages</strong>, which can be allocated to processes. When the address space reaches capacity, the operating system employs a technique called <strong>page replacement</strong>, where pages belonging to inactive processes are removed and reallocated to the active process. This dynamic allocation optimizes memory usage. If a running process attempts to access an unmapped address, triggering a <strong>page faul</strong>t, the entire page containing that address is loaded into memory to resolve the issue</p><p><strong>Summary of Process execution and memory accesses</strong></p><ol><li>When an operating system has to load a program, It parses its executable (elf,exe). Detects program’s load address, allocates memory and then loads the program’s <strong>machine instructions </strong>to its corresponding address in memory. At this point, the program is referred to as aConcept of TLB (Translation look aside buffer) <strong>Process Control Block (PCB).</strong></li><li>Each process is represented as a data structure called Process control block, which contains information like the next instruction’s address, page table base address, etc</li><li>The process is marked as runnable and its entry containing process info<br>is added to the scheduler’s queue.</li><li>When the process is scheduled to be executed by the processor. The OS parses its PCB and sets up the necessary registers. Like program counters, segment registers, etc.</li><li>When a program, is assigned with a processor, the processor’s program counter PC is loaded with the current instruction’s address. The processor <strong>accesses instruction memory, </strong>to fetch the current instruction to be executed. The processor decodes the instruction and executes it.</li><li>During execution, the processor may need to fetch operands from memory and save it to the processor’s registers. Or after execution processor may need to save the results from register back to memory.</li><li>When the paging mechanism is activated, each of the memory access goes through the address translation mechanism, discussed below. Concept of TLB (Translation look aside buffer</li></ol><p><strong>Page table architecture:</strong></p><p>In the next few paragraphs the term <strong>Virtual address space</strong> will be used to represent how the process will view the memory and the term <strong>Physical address space</strong> will be used to represent the actual physical (main) memory address space. The term<strong> Level(s)</strong> will represent the number of page table Look-ups between the virtual address and physical address</p><p>The page tables are maintained by OS in main memory.</p><p><strong>To describe page table organization we’ll take an example of 4 GB byte-addressable memory. Also to access a single-byte 32-bit address will be Used. A single page/chunk of memory will contain 4 kilobytes. <br>So physical address space will consist of 2³²/2¹² = 2²⁰ pages.<br>So 20 bits will be required to access a page and 12 bits will be required <br>To access a byte with a page</strong></p><p><strong>Single-level page table:</strong></p><p>In Single-level page table design, every address translation involves going through a single-page table. Every entry in the page table contains the base address of one of 2²⁰ pages, along with flags (providing useful information about the page like permissions, access mode,</p><p>etc). So the Single-level page table for the example presented above will have 2²⁰ entries. As already discussed Each physical page will be of size 4KB, That is 2¹² bytes, so to access a byte in physical address space we need two pieces of information</p><p>a. The 20-bit physical address of the page containing that byte.<br>b. The 12-bit byte offset of that byte within the page.</p><p>Every address access involves taking the first 20 MSBs (most significant bits) and adding that value to the base address of the page table, in the <strong>Page table base register. </strong>The result then leads to an entry in the page table, The page table entry contains the base address of the physical address of the page containing the byte.</p><p>The byte offset is added with the physical page address (obtained during page table access) and the full physical address is obtained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcxhZOR1U6DBIqd__llpaA.png" /><figcaption>SIngle Level Page table</figcaption></figure><p>[Image Credit: <a href="https://web.cs.ucla.edu/classes/winter16/cs111/scribe/15d/index.html">https://web.cs.ucla.edu/classes/winter16/cs111/scribe/15d/index.html</a>]</p><p><strong>Multi-level page table:</strong></p><p>One drawback to single-level page table is that the size of page table is large. Considering each page table entry of size 32 bits and total 2²⁰ entries<br>The page table of a single process will be of size 2²² bytes that is 4MB.</p><p>So the idea is to have multiple levels of page tables between virtual and physical address and allocate the memory for higher levels as required.<br>In a way page table itself got paged.</p><p>A diagram of two level page table is shown below.</p><p>For the example case discussed above, the first level of the page table will have 2¹⁰, 1024 entries. Each of these entries will point to a <strong>second-level </strong>page table. The second level page table itself will contain 2¹⁰, 1024 entries<br>And each of these entries points to a 4KB physical page.</p><p>Each virtual address is split into 3 parts, and translation takes place in <br>Following manner.</p><ol><li>Bits [31–22] of the virtual address are added with value in the page table base register to get an entry in the first level of the page table.</li><li>The entry obtained in step 1, is the base address for the second level page table. This value is added with Bits [21–12] of the virtual address. To get the address of the physical page containing the byte.</li><li>The address of the physical page is added with Bits[11–0] of the physical address to get the address of the byte.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHRdrDdRIKZCDOyztvV47g.png" /><figcaption>Multi-level Page Table</figcaption></figure><p>[Image Credit: <a href="https://web.cs.ucla.edu/classes/winter16/cs111/scribe/15d/index.html">https://web.cs.ucla.edu/classes/winter16/cs111/scribe/15d/index.html</a>]</p><p>In the next article of this series, we’ll explore Virtual memory models specific to RISCV (sv32,sv39,sv48).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bc2ce3318cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding custom instructions compilation support, to RISCV toolchain.]]></title>
            <link>https://medium.com/@viveksgt/adding-custom-instructions-compilation-support-to-riscv-toolchain-78ce1b6efcf4?source=rss-383741476adf------2</link>
            <guid isPermaLink="false">https://medium.com/p/78ce1b6efcf4</guid>
            <category><![CDATA[risc-v]]></category>
            <dc:creator><![CDATA[Vivek]]></dc:creator>
            <pubDate>Sat, 15 Jan 2022 20:23:01 GMT</pubDate>
            <atom:updated>2022-01-18T11:44:35.767Z</atom:updated>
            <content:encoded><![CDATA[<p>RISCV ISA provides a robust set of instructions to fulfill most of the computing needs. But in some cases, The hardware designers may need to modify the core to carry out some additional operations.<br>And this ends up in the addition of new instructions in the existing ISA.</p><p>In such cases, the RISC-V toolchain is needed to be modified to provide compilation support for newly added instructions. In the next few sections, we’ll see how to do that.</p><p>In short, the process involves modifying gnu assembler(gas), such that the cross compiler generated from the toolchain<br>is able to recognize the newly added instructions.</p><p>Let&#39;s assume we add two new instructions</p><p>1. gcd rd,rs1,rs2<br> Which computes the gcd of integers stored in source registers rs1 and rs2.<br> And store the result in destination register rd</p><p>2. fact rd, &lt;immediate&gt;<br> <br>Which divides the value of immediate by 2 and then computes the factorial of result, and store it in memory address pointed<br> by the address specified in rd. (It can be assumed that only even values are allowed in immediate)</p><p>[Note: GCD and factorial computations can be carried out sufficiently in existing RISCV ISA,<br>Both of these custom instructions are for illustration purposes only]</p><p><strong>Brief Encoding Overview:</strong></p><p>Let&#39;s assume that the target ISA is for 32 bits (non-compressed).<br>So each instruction is 32 bits long.<br>The encoding rules specify where the identifiers of source and destination registers, Immediate values, and opcode are placed in those 32 bits.</p><p>Just to revise there are 32 general-purpose registers in rv32 ISA,<br>So log32 = 5 bits are required to uniquely identify each register.<br>Also, the rv32 ISA supports 12 and 20-bit immediate values.</p><ol><li>Every 32-bit instruction should have the first two LSBs set to 1<br>That means last two bits of every 32 bit instruction are 11; Bits[0,1] = 11</li><li>Bits [2–4], tell whether the instruction is long instruction (64 bit).<br> So for 32-bit instructions Bits[2–4] should never be 111.</li><li>The gcd instruction is an R- type instruction, <br> For R- type instruction<br> The destination register is defined in bits from, bit 7 to bit 11, Bits[7,11]<br> The first source register is defined in bits from, bit 15 to bit 19, Bits[15,19]<br> second source register is defined in bits from, bit 20 to bit 24, Bits[20,24]<br> Bits[0,1] = 11 (to specify that instruction is a 32 bit instruction)<br> The rest of the Bits are used to store the opcode, such that Bits[2,4] should NOT be 111</li><li>The fact instruction is a J-type instruction.<br> For J-type instruction<br> The destination register is defined in bits from, bit 7 to bit 11, Bits[7,11]<br> Bit 12 to Bit 31 are used to store the 20-bit immediate value.<br> The rest of the Bits are used to store the opcode, such that Bits[2,4] should NOT be 111</li></ol><p>[The processors are designed to load the instruction and decode it by opcode<br>Identifying the type of instruction and location of the source and destination operands, And then generating suitable control signals to activate the circuits required to execute the instruction and store the results.]</p><p><strong>Toolchain changes:</strong></p><p>In order to add two new instructions the first step is to modify <br><a href="https://github.com/riscv-collab/riscv-binutils-gdb/blob/116a737f438d03a1bd6aa706b6ea0b4022f3b7e2/opcodes/riscv-opc.c">riscv-gnu-toolchain/riscv-binutils/opcodes/riscv-opc.c</a> file.<br>This file contains all opcode or instruction definitions in an array riscv_opcodes, which is an array of riscv_opcode structure.</p><pre>const struct riscv_opcode riscv_opcodes[]</pre><p>For adding a new instruction we need to add an entry in this array.</p><p>Before that let&#39;s take a look at riscv_opcode structure</p><pre>struct riscv_opcode<br>{<br> /* The name of the instruction. */<br> const char *name;<br> /* The requirement of xlen for the instruction, 0 if no requirement. */<br> unsigned xlen_requirement;<br> /* Class to which this instruction belongs. Used to decide whether or<br> not this instruction is legal in the current -march context. */<br> enum riscv_insn_class insn_class;<br> /* A string describing the arguments for this instruction. */<br> const char *args;<br> /* The basic opcode for the instruction. When assembling, this<br> opcode is modified by the arguments to produce the actual opcode<br> that is used. If pinfo is INSN_MACRO, then this is 0. */<br> insn_t match;<br> /* If pinfo is not INSN_MACRO, then this is a bit mask for the<br> relevant portions of the opcode when disassembling. If the<br> actual opcode anded with the match field equals the opcode field,<br> then we have found the correct instruction. If pinfo is<br> INSN_MACRO, then this field is the macro identifier. */<br> insn_t mask;<br> /* A function to determine if a word corresponds to this instruction.<br> Usually, this computes ((word &amp; mask) == match). */<br> int (*match_func) (const struct riscv_opcode *op, insn_t word);<br> /* For a macro, this is INSN_MACRO. Otherwise, it is a collection<br> of bits describing the instruction, notably any relevant hazard<br> information. */<br> unsigned long pinfo;<br>};</pre><p>So the entries added to riscv_opcode arrays for the new instructions will be as follows</p><pre>{&quot;gcd&quot;, 0,  INSN_CLASS_I,&quot;d,s,t&quot;,MATCH_GCD,MASK_GCD,match_opcode,0}</pre><pre>{&quot;fact&quot;,0,  INSN_CLASS_I,&quot;d,a&quot;,MATCH_FACT,MASK_FACT,match_opcode,0}</pre><p>A brief description of each value is given below.</p><ol><li>name will be “gcd” and “fact” for the gcd and factorial instructions respectively.</li><li>xlen can have values 0,32 or 64. <br> It is used to specify whether the instruction is targeted for only 32 or 64-bit RISCV variants. It seems if this value is set to 32 the instruction will work with only 32-bit variant, And if the value is 64 the instruction will work only on 64-bit version. And if the xlen value is set to 0 then the instruction will work on both 32 and 64-bit variants. For both instructions, this value will be 0</li><li>insn_class: Described the class of instruction, whether it is an integer, atomic, compressed.</li><li>*args: Is string to specify the operands/register involved in the instruction.<br> For gcd instruction args = “d,s,t”<br> for fact instruction args = “d,a”<br> “d” is for destination<br> “s” is for source register 1<br> “t” is for source register 2<br> “a” is for 20 bit immediate<br> How these characters will be utilized will become more clear in the Validation section.</li><li>match: It is the basic instruction opcode provided Initially. This opcode is later modified during assembling. The modification involves the placement of identifiers for operand registers and other information in the opcode.</li><li>mask: Mask is used to identify the position of operand bits in the instruction, ith bit in Mask is 1 if it is not used as an operand in the instruction, Otherwise it is 0.</li><li>The instruction opcode specification struct also requires a pointer to function, which will be used to detect if any instruction matches with given instruction. The function is given below.</li></ol><pre>static int<br> match_opcode (const struct riscv_opcode *op, insn_t insn)<br> {<br> return ((insn ^ op-&gt;match) &amp; op-&gt;mask) == 0;<br> }<br> [from<a href="https://github.com/riscv-collab/riscv-binutils-gdb/blob/116a737f438d03a1bd6aa706b6ea0b4022f3b7e2/opcodes/riscv-opc.c"> riscv-binutils/opcodes/riscv-opc.c</a>]</pre><p>8. pinfo is used to describe the instruction by binary codes. Like there are codes for conditional, jump type, data movement instructions. <br> We wont be describing the instruction so this will be 0</p><p>In File riscv-gnu-toolchain/riscv-binutils/include/opcode/riscv-opc.h match and mask codes for the instruction are added<br>Using the rules described above</p><pre>#define MATCH_GCD 0x6027<br>#define MASK_GCD 0xfe00707f<br>#define MATCH_FACT 0x27<br>#define MASK_FACT 0x7f</pre><pre>DECLARE_INSN(gcd, MATCH_GCD,MASK_GCD)<br>DECLARE_INSN(fact, MATCH_FACT,MASK_FACT)</pre><p>optinally same changes can be done in <br>riscv-gnu-toolchain/riscv-gdb/opcodes/riscv-opc.c<br>riscv-gnu-toolchain/riscv-gdb/include/opcode/riscv-opc.h</p><p><strong>Instruction Validation Summary:</strong></p><p>Instruction defined in the riscv-opc.c are validated during assembler building process. Instruction validation logic can be found in “<a href="https://github.com/riscv-collab/riscv-binutils-gdb/blob/116a737f438d03a1bd6aa706b6ea0b4022f3b7e2/gas/config/tc-riscv.c#L1010">validate_riscv_insn</a>” function in file riscv-gnu-toolchain/riscv-binutils/gas/config/tc-riscv.c</p><p>1. The validation process starts with detecting the size of the instruction <br> be checking the last two bits defined in opc-&gt;match</p><p>2. Based on the size of bits total number of required bits is computed<br> For these instruction it will be 2³¹ -1 or 0xFFFFFFFF;</p><p>3. Variable used_bits is set to the initial mask code of the instruction<br> Defined in opc-&gt;mask. So used bits initially have all the operand bits<br> set to 0 and all then non-operand bits set to 1.</p><p>4. After instruction size validation is done. <br> The args string (opc-&gt;args, which is stored in variable p), is parsed.<br> Every character in args string corresponds to an operand.<br> For each character and shift and mask value is defined and the bits in the Variable “used_bits” are set for the given mask and shift value as follows</p><pre>used_bits |= ((insn_t)(mask) &lt;&lt; (shift))<br> <br>Example if the instruction uses a destination register, then its args string will have character “d”, for “d”, mask is 1xf and shift is 7. So this will set bits 7 to 11 of used bits.</pre><p>5. Step 4 is repeated for all the characters in the args string.<br>6. If the final results have all the bits in used_bits equal to 1, i.e <br> used_bits = required_bits<br>Then the instruction definition is considered valid.</p><p>After making the toolchain changes specified above, the toolchain can be rebuilt to support newly added instructions</p><p><strong>A test program</strong></p><pre>#include &lt;stdint.h&gt;<br>#define FACT_DIGITS 10000<br>int main(void)<br>{<br>uint32_t num1 = 2321, num2 = 1771731, gcd = 0;<br>uint32_t fact_test_val = 10;<br>uint32_t fact_result_ptr; <br>uint8_t fact_result[FACT_DIGITS];<br>fact_result_ptr = (uint32_t)fact_result;<br>asm volatile(&quot;gcd %0, %1,%2\n&quot;:&quot;=r&quot;(gcd):&quot;r&quot;(num1),&quot;r&quot;(num2):);<br>//suppose we want to compute the factorial of 125 so immediate=250<br>asm volatile(&quot;fact %0, %1\n&quot;:&quot;=r&quot;(fact_result_ptr):&quot;i&quot;(250):); <br>return 0;<br>}<br></pre><p><strong>Generated assembly code from the output elf file</strong></p><pre>0001013c &lt;main&gt;:<br>   1013c: 8c010113           addi sp,sp,-1856<br>   10140: 72812e23           sw s0,1852(sp)<br>   10144: 74010413           addi s0,sp,1856<br>   10148: ffffe2b7           lui t0,0xffffe<br>   1014c: 00510133           add sp,sp,t0<br>   10150: 000017b7           lui a5,0x1<br>   10154: 91178793           addi a5,a5,-1775 # 911 &lt;register_fini-0xf763&gt;<br>   10158: fef42623           sw a5,-20(s0)<br>   1015c: 001b17b7           lui a5,0x1b1<br>   10160: 8d378793           addi a5,a5,-1837 # 1b08d3 &lt;__global_pointer$+0x19eafb&gt;<br>   10164: fef42423           sw a5,-24(s0)<br>   10168: fe042223           sw zero,-28(s0)<br>   1016c: 00a00793           li a5,10<br>   10170: fef42023           sw a5,-32(s0)<br>   10174: ffffe7b7           lui a5,0xffffe<br>   10178: 8dc78793           addi a5,a5,-1828 # ffffd8dc &lt;__global_pointer$+0xfffebb04&gt;<br>   1017c: ff078793           addi a5,a5,-16<br>   10180: 008787b3           add a5,a5,s0<br>   10184: fcf42e23           sw a5,-36(s0)<br>   10188: fec42783           lw a5,-20(s0)<br>   1018c: fe842703           lw a4,-24(s0)<br>   10190: 00e7e7a7           gcd a5,a5,a4<br>   10194: fef42223           sw a5,-28(s0)<br>   10198: f63ef7a7           fact a5,fa &lt;register_fini-0xff7a&gt;<br>   1019c: fcf42e23           sw a5,-36(s0)<br>   101a0: 00000793           li a5,0<br>   101a4: 00078513           mv a0,a5<br>   101a8: 000022b7           lui t0,0x2<br>   101ac: 00510133           add sp,sp,t0<br>   101b0: 73c12403           lw s0,1852(sp)<br>   101b4: 74010113           addi sp,sp,1856<br>   101b8: 00008067           ret</pre><p>Instructions at address 0x10190 and 0x10198 contains newly added custom instructions</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78ce1b6efcf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>