<?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 Karthik B K on Medium]]></title>
        <description><![CDATA[Stories by Karthik B K on Medium]]></description>
        <link>https://medium.com/@talktokarthikbk?source=rss-3416eb0227e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*50FgDT0TcbKGCZllacCNhg.jpeg</url>
            <title>Stories by Karthik B K on Medium</title>
            <link>https://medium.com/@talktokarthikbk?source=rss-3416eb0227e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:15:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@talktokarthikbk/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[5 Years of Thinking In Rules]]></title>
            <link>https://medium.com/@talktokarthikbk/5-years-of-thinking-in-rules-fc6314a2d786?source=rss-3416eb0227e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc6314a2d786</guid>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[formal-methods]]></category>
            <category><![CDATA[hardware-design]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Karthik B K]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 12:46:41 GMT</pubDate>
            <atom:updated>2026-09-19T14:26:03.890Z</atom:updated>
            <content:encoded><![CDATA[<p>Why am I writing this post and who is it for ?</p><p>I was introduced to Bluespec a little over 5 years ago. I came from a somewhat imperative background of C programming and Verilog. To me, Verilog always felt slightly unintuitive, because the syntax and semantics disagree. In fact, the syntax suggests sequential semantics whereas the standard specifies a concurrent one. Logic synthesis infers a netlist by pattern-matching on the code structure.</p><p>Bluespec is the first [HL]HDL where that discomfort started to go away, but that took some time (evidently, haha!). I think the model is not very intuitive to newcomers; they get the syntax and bounce. It seems to me that is the language’s real problem.</p><p>This post is written for the two audiences that make up most of my network. <strong>Alice</strong> is a hardware engineer who looked at Bluespec and, maybe, dismissed it as “Verilog with Haskell syntax” and <strong>Bob</strong> is a PL/formal-methods guy who wants to know the difference between describing hardware and writing software. The post is written more for Alice, but Bob will find this to be a nice read too, especially towards the end.</p><blockquote>“hardware is software, and software is hardware :D” <br>Nikhil, Bluespec’s CTO.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SUEeaT46Epn1YsG2" /><figcaption>Photo by <a href="https://unsplash.com/@kylejglenn?utm_source=medium&amp;utm_medium=referral">Kyle Glenn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong><em>Disclaimer</em></strong><em>: An important charecteristic of this post is that it does not always tell the truth. To simplify the exposition, some basic but false claims are made about both Verilog and Bluespec. Therefore, the author or his affiliations must not be held responsible for any undesirable outcomes from this post. All thoughts and opinions in this post are my own and do not necessarily reflect the views/positions of either InCore or IIT Madras.</em></p><h3>Alice’s mental model and what to unlearn</h3><p>Alice thinks of hardware as a clocked state machine that includes a bunch of registers, maybe more than one clock edge, and a cloud of combo logic between one edge and the next. Alice’s job is to write all three.</p><p>always @(posedge clk) is Alice’s unit of thought and inside it Alice writes the reset branch and then the state update. Next to it, Alice writes the case on the state register. This could be the FSM, the valid/ready handshakes or the arbiter that picks the winner when multiple folks want the same resouce.</p><p>Now remember, Alice is really only concerned about the datapath because that is the algorithm, and that is also (usually) the easier part. Alice ends up spending a lot of time and effort trying to get the control path “correct” and checks it by looking at waveforms. This is also what “correct” means to Alice, that the trace _looked_ right in simulation and could potentially change for different sitmuli. Datapath bugs, in my little experience writing Verilog/SV, are relatiely rare.</p><p>That change could be anything from a blocking/non-blocking assignment, a race between two blocks, mis-handled (or even worse, not-handled) backpressure, or a missed state transition to name a few.</p><p>Bluespec takes almost all of these away. Do I have your attention now? :’)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nmZBTzl_FMjZiZBo" /><figcaption>Photo by <a href="https://unsplash.com/@miracleday?utm_source=medium&amp;utm_medium=referral">Elena Mozhvilo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>States are terms, designs are term rewriting systems</h3><p>Consider that Alice is trying to write a hardware description for an 8-point fast Fourier transform. Alice has pipelined it to three stages of butterflies, so there is one register before the first, and one after each stage. Here is how she writes it:</p><pre>always @(posedge clk or negedge rst_n) begin<br>  if (!rst_n) begin<br>    isb1      &lt;= 512&#39;d0;<br>    isb2      &lt;= 512&#39;d0;<br>    isb3      &lt;= 512&#39;d0;<br>  end else begin<br>    isb1      &lt;= stage_f(2&#39;d0, isb0);<br>    isb2      &lt;= stage_f(2&#39;d1, isb1);<br>    isb3      &lt;= stage_f(2&#39;d2, isb2);<br>  end<br>end</pre><p>Alice has written all of the book-keeping here so many times that Alice doesn’t see it anymore. Alice also doesn’t see something more interesting.. Alice could permute the three non-blocking assignments or split them into three blocks and nothing would change. They are three independant updates that happen to share a clock/reset edge. The real design is just:</p><pre>rule stage1;<br>  isb1._write(stage_f(0, isb0));<br>endrule<br><br>rule stage2;<br>  isb2._write(stage_f(1, isb1);<br>endrule<br><br>rule stage3;<br>  isb3._write(stage_f(2, isb2);<br>endrule</pre><p>or really just:</p><pre>for (Integer i = 0; i &lt; stages; i = i + 1)<br>  rule stage;<br>    isb[i+1]._write(stage_f(fromInteger(i), isb[i]));<br>  endrule</pre><p>See how the book-keeping is gone? This is not the best example to show the power of Bluespec, Nikhil does that much better in his books, but more importantly the three updates are indeed three separate updates. That is important, if you start adding FIFOs and backpressure and so on. Anyways, moving on..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5C5lbpdgOB6RsPQx" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bluespec gives you the ability to focus on the datapath. You’re still specifying the control path, but you won’t be writing it youself. If were to just take a step back, any meaningful circuit would have a control path and the data path. Unless you’re trying to squeeze the last gate out of your optimization effort, compilers will do a much better job at giving you the control path provided the intent is communicated clearly through your program. I think this applies to more than just hardware descriptions.</p><p>isb[0–3] are state elements here, and the program is really all about rewriting the contents of those states. In this particular case of the FFT and it’s microarchitecture, the ISBs can be updated unconditionally, and correct output will eventually appear at the end of the pipeline after four cycles when meaningful input is fed. If dataflow were to be constrained by some other state element or PI, then they go in to the program as predicates on said rules. For example:</p><pre>for (Integer i = 0; i &lt; stages; i = i + 1)<br>  rule stage if (/* predicate */);<br>    isb[i+1]._write(stage_f(fromInteger(i), isb[i]));<br>  endrule</pre><p>For the longest time, I have considered terms in the predicate to be the control path, and have often been confused when I see wierd interactions between the control and data paths. As it turns out, they were due to poorly written Bluespec programs. The point i’m trying to make is that the Bluespec program that you will write is _only_ the datapath. You’re still specifying the control path, but you won’t be writing it youself. Anything you think is the control path is really just information for the compiler to construct the control path for you.</p><p>A bluespec program is a collection of state elements i.e. _terms_ and a collection of _rules_ that rewrite the said terms. A rule has a guard (predicate) and an action. “When g is true, do a” so to say.. The program described above (is deliberately incomplete, i’ve not specified the interface or defined the types of those state elements) has rules that happen to have no guards, which means they’re always allowed to _fire_, or in some sense always _ready_. The meaning of the whole program is that at any moment, pick any rule whose guard is _true_ and apply it’s action _atomically_ and repeat.</p><blockquote>Atomically.</blockquote><p>The word doing all the work here is “atomically”. Rules are “guarded atomic actions”. Every read inside a rule sees the state as it was before the rule started, and every update is visible _immidiately_ after the rule completes. I do NOT mean at the end of a clock cycle. I mean that the next rule to fire _WILL_ see the updates from the rule(s) that have finished. Nothing else happens in between — not even another rule execution, or a _method_ call — nothing. This is termed as ORAAT, or One-Rule-At-A-Time. So within a rule, there is no such thing as _during_, and there is therefore no such thing as blocking or non-blocking assignment. Bluespec (BSV in particular) does provide the &lt;= shorthand to represent a write, and that symbol is picked for the sake of familiarity. I can therefore write the same program again as:</p><pre>for (Integer i = 0; i &lt; stages; i = i + 1)<br>  rule stage if (/* predicate */);<br>    isb[i+1] &lt;= stage_f(fromInteger(i), isb[i]);<br>  endrule</pre><p>Atoms can not be split further (please don’t go into protons, neutrons, electrons and all the other -ons.)</p><p>You may now ask how this works for a _register_, after all a _flop_ can’t reflect the _DIN_ content in the same _cycle_. Consider these two programs:</p><pre>// Program A<br>rule does_something;<br>  let temp = reg_a._read();<br>  reg_b._write(temp);<br>endrule<br><br>rule does_something_else;<br>  let temp = reg_b._read();<br>  reg_a._write(temp);<br>endrule</pre><p>and</p><pre>// Program B<br>rule does_something;<br>  let temp1 = reg_a._read();<br>  let temp2 = reg_._read();<br>endrule<br><br>rule does_something_else;<br>  reg_a._write(temp);<br>  reg_b._write(temp);<br>endrule</pre><p>Notice how the rules does_something and does_something_else in the first program can never fire in the same _cycle_ (in real hardware) but can fire in the same cycle in program B ? I’ll let that sink in..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j4aSiVmT2xmb3OVS" /><figcaption>Photo by <a href="https://unsplash.com/@art_maltsev?utm_source=medium&amp;utm_medium=referral">Artem Maltsev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>or simply:</p><pre>// A: two rules that cross -- the compiler will never fire these together<br>rule a_to_b;  reg_b &lt;= reg_a;  endrule<br>rule b_to_a;  reg_a &lt;= reg_b;  endrule<br><br>// B: one rule -- an atomic swap, always fine<br>rule swap;<br> reg_a &lt;= reg_b;<br> reg_b &lt;= reg_a;<br>endrule</pre><p>Still unclear? We’ll look at it in section 5 anyways :)</p><p>That brings me to the next, bigger and more interesting part of a Bluespec program. Notice how I call it a program? That is intentional. I’ll come back to that. The program has no notion of a clock or a reset.. atleast not one that you _need_ to worry about, but _can_ if you want to. We’ll get back to this one too, the stuff about clocks and resets, maybe in a different post.</p><p>That’s it.. That is the entire semantics of a Bluespec program. You only describe the datapath and try to convey to the compiler about how you’d like the datapath to be controlled. The compiler does a pretty good job at constructing it for you. “Pretty good” is a very weak statement and that is intentional — you’re welcome to dig deeper into literature to try and understand how good of a job it does. :’)</p><p>For the folks who come here from PL, none of this is new. Hint: Dijkstra’s guarded commands. Some history worth mentioning here would be Chandy and Misra’s UNITY (1988). Hoe and Arvind brought the idea to hardware in the late 90s. A design is a TRS whose terms are the state and whose rewrite rules are, well, the rules.</p><p>Caution, Alice, a rule is not an always block. Neither is it a process or a thread, nor is it a function. This is where Bluespec brings in something new.</p><h3>Rules and methods are the same things</h3><p>isb1 &lt;= stage_f(0, isb0) is the shorthand. The long form is isb1._write(stage_f(0, isb0._read)) and that is a method call. A register in Bluespec is not a simple flop with a D and Q ports (atleast not always); it is a module. Every module _provides_ an interface for external interaction.</p><pre>interface Reg #(type t);<br>  method t _read ();<br>  method Action _write (t x);<br>endinterface</pre><p>This is the Reg interface. There are multiple interfaces, a lot of them are pre-built into the libraries so that you don’t have to go around re-inventing the wheel everytime. A FIFO for instance provides the FIFO interface. There are multiple fifo interfaces. The reader is referred to Bluespec’s LRM for a detailed description. A method is a _piece_ of a rule that lives in another module. When stage1 calls isb1._write , the write becomes part of stage1 ‘s action. If isb1 were not a register but some module whose _write method called three other modules’ methods, those would become part of stage1 ‘s action too. The atomic unit is the rule plus everything it touches, transitively, across every module boundary it crosses. Atomicity doesn’t stop at the hierarchy.</p><p>Alice never had this, since Verilog’s hierarchy is wires. Alice can instantiate a module inside another but there is no notion of “this module touches a fifo and a register and something else so either all of them happen or none do” in Verilog. That notion has to be built by hand, out of valid signals and careful ordering, every time. In Bluespec, this is what a rule is. Simply put, a method’s enable comes from its caller; a rule’s enable is its own guard.</p><p>Now the FFT’s interface:</p><pre>Interface FFT;<br>interface Put request;<br>  method Action put (/*arg list*/);<br>    isb[0] &lt;= bitReverse(x);<br>  endmethod<br>endinterface<br><br>interface Get response = toGet(isb[3]);<br>endinterface</pre><p>On a side note, identifiers starting with uppercase letters are “known variables”. put is a method, a guarded action that some rule/method outside this module will call, and when it does, isb[0]._write becomes part of that rule. response is built from toGet , a function that returns the Get interface and infers the type of the destination (yes Bluespec is strongly typed).</p><h3>Implicit conditions</h3><p>The pipeline in section 2 is inelastic. That is to say that every stage fires every cycle, whether or not there is anything meaningful in it. Alice knows what comes next, because Alice has done it a hundred times. Each stage grows a valid bit and a ready wire; each register update grows an if ; and the ready of every stage depends on the ready of the next.</p><p>Example:</p><pre> reg  isb1_valid;<br> wire isb1_ready = !isb1_valid || isb2_ready;<br> <br> always @(posedge clk or negedge rst_n) begin<br>   if (!rst_n)<br>     isb1_valid &lt;= 1&#39;b0;<br>   else if (isb1_ready) begin<br>     isb1_valid &lt;= isb0_valid;<br>     if (isb0_valid) isb1 &lt;= stage_f(2&#39;d0, isb0);<br>   end<br> end<br> assign isb0_ready = isb1_ready;</pre><p>Three times and then the ends — all of it control — and none of it FFT. Every line is also a place to drop a beat under back-pressure. Here’s the Bluespec version. This is the one I wrote first, in fact, before I swapped the FIFOs for registers to make section 2 cleaner.</p><pre>for (Integer i = 0; i &lt; stages; i = i + 1)<br>  rule stage;<br>    isb[i+1].enq(stage_f(fromInteger(i), isb[i].first));<br>    isb[i].deq;<br>  endrule</pre><p>The registers became FIFOs, _read became first and deq, _write became enq. There is _still_ no guard on the rule, see ? This pipeline, however, has back-pressure. A stage with an empty input doesn’t fire and the same goes for a stage with full output.</p><p>The methods first and deq are guarded by the condition that the FIFO is not empty. enq is guarded by the condition that the fifo is not full. Those guards belong to the FIFO but the compiler simply ANDs the method’s guards into the rule’s guards. If you’re familiar with Bluespec to some extent, the guard post to said ANDing is the CAN_FIRE and the guard post ANDing and conflict resolution is the WILL_FIRE .</p><p>So the guard of stagei really becomes isb[i].notEmpty &amp;&amp; isb[i+1].notFull . I never had to think of this, let alone write it. These are called implicit conditions. These are primarily what enable the freedom “you only need to write the datapath” that the compiler gives you. Every piece of control that Alice writes by hand in Verilog is simply a consequence of a guard that some library module declared once.</p><p>There are some nuances when it comes to FIFO depth there, a regular FIFO as you may know it will not let you enqueue when full or dequeue when empty, and a single-depth fifo will therefore drop your throughput by half. There are mitigations — 2-deep fifos, PipelineFIFOs, unguarded FIFOs are to name some.</p><h3>A cycle is a linearisation</h3><p>Let’s go back to when I said “the next rule to fire sees the update”. This defines how the control path is constructed. Every cycle, the control path should determine a set of rules to fire and a total order on that set such that firing them all at once (in a single cycle) in hardware will appear as though they all fire in the legal sequence of execution that is the total order determined by the scheduler. If the scheduler can’t find such an order, a subset of the rules may not fire in the same clock cycle. The clock cycle is simply the compiler’s unit of linearisation.</p><p>Now, when can two rules share a cycle? It comes down to their action-sets. The compiler/scheduler basically constructs a conflict matrix based on the actions every rule performs. An action can contain more actions, an action needs to be performed/executed atomically.</p><p>Consider the same case where you have two rules, one that reads the register r and another that writes the same register r . In order for these two rules to share a cycle, reads must be scheduled-before, or more precisely, sequenced-before (SB) writes. The reader therefore sees the old value and the writer’s update being immidiately visible doesn’t matter because there will be no rule in the total order on the selected rule-set that fires _after_ the rule that performs the write.</p><p>If we now apply this learning to the pipeline:</p><pre>Logical execution order: response_get, stage3, stage2, stage1, request_put</pre><p>This is part of the compiler’s output if you used the -show-schedule flag during compilation. The pipeline, however, seems to run backwards ? Nope. Nopity-nope. The order is just a proof that the compiler could produce about the ORAAT steps.</p><p>If you go back to the swap example from earlier, you’ll end up with a warning:</p><pre> Warning: &quot;swap.bsv&quot;, line 12, column 8: (G0010)<br>   Rule &quot;a_to_b&quot; was treated as more urgent than &quot;b_to_a&quot;. Conflicts:<br>     &quot;a_to_b&quot; cannot fire before &quot;b_to_a&quot;: calls to b._write vs. b._read<br>     &quot;b_to_a&quot; cannot fire before &quot;a_to_b&quot;: calls to a._write vs. a._read</pre><p>The fog is slowly starting to clear up, huh ? It’s okay, the elevator took a while to reach the top floor for me too, in the beginning :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OrtEWtkxJMZkPZF9" /><figcaption>Photo by <a href="https://unsplash.com/@rgaleriacom?utm_source=medium&amp;utm_medium=referral">Ricardo Gomez Angel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Just execution order ?</h3><p>We just discussed the execution order. However, when you have two rules that can’t share a cycle, you need to pick one. More like the compiler needs to pick one. This order is a second, separate relation called urgency. If left lose, the compiler will make these decisions for you. Said decisions may be unintended. Example:</p><pre> Warning: &quot;Swap.bsv&quot;, line 3, column 8: (G0010)<br>   Rule &quot;a_to_b&quot; was treated as more urgent than &quot;b_to_a&quot;. Conflicts:<br>     &quot;a_to_b&quot; cannot fire before &quot;b_to_a&quot;: calls to b.write vs. b.read<br>     &quot;b_to_a&quot; cannot fire before &quot;a_to_b&quot;: calls to a.write vs. a.read<br> Warning: &quot;Swap.bsv&quot;, line 8, column 8: (G0021)<br>   According to the generated schedule, rule `b_to_a&#39; can never fire.</pre><p>Read that second warning again. Both rules are always_ready but a_to_b wins. You might ask why..</p><p>Without more information, the compiler just picks the rule that appears before the other in the source code (i.e. the one written above/before the other is treated as more urgent).</p><h3>Scheduling is a programmable relation</h3><p>So far, we’ve only considered the case where we’re not explicitly giving the compiler more information to help with the scheduling.. while that is a good rule of thumb to stick to (write your program well enough that the compiler infers the right schedule), this can sometimes become impractical. Let’s first see how rewriting (or some would call this refactoring) the program can alter the schedule.</p><p>Consider the following modification to the standard mkReg (register) module:</p><pre> module mkReg#(t reset_val)(Reg#(t)) provisos (Bits#(t, tSz));<br>   Reg#(t) _r &lt;- Prelude::mkReg(reset_val);<br>   Reg#(Bool) double_write_error &lt;- mkRevertingVirtualReg(True);<br><br>   method t _read = _r._read;<br><br>   method Action _write(t x) if (double_write_error);<br>     double_write_error &lt;= False;<br>     _r &lt;= x;<br>   endmethod<br> endmodule</pre><p>_write now reads double_write_error (in its guard) and writes it (in its body). Two calls to _write in the same cycle would put the second call’s read after the first call’s write (because ORAAT). This is a RAW hazard on a register. The conflict table forbids this — we’ve seen this earlier in this post.</p><p>The mkRevertingVirtualReg here is a trick. It is a register that resets itself at the end of every cycle, so every read of it returns true. It is therefore _not_ a register, but just a logic constant true :). It only exists here to have an _read and an _write for the scheduler to reason about. Give it a second to sink in..</p><p>There are more such tricks. One very popular trick is a CReg, traditionally called an EHR. Look at the circuit diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*S0EwbDqrhoovzxwCndI6iA.png" /><figcaption>Dan Rosenband [MEMOCODE ‘04]</figcaption></figure><p>Writes at port 0 will be available for reads at port 1 within the same cycle. write_0 is therefore SBR read_1. The consequency of doing fancy things like this in your program is troubles with timing closure — if not used carefully, this can result in large blocks combo-combining.</p><h3>Clocks and Resets</h3><p>I know.. I know.. I said we can completely forget this. I take that back. Any realistic design would have domain crossings.</p><p>Every module, obviously, has a default clock and reset signal. Every state element you define under that module’s context takes this default clock and reset unless specified otherwise. For example, mkReg(0) is a register with a synchronous reset to 0 , mkRegU is the same with no reset, mkRegA is also the same but with an asynchronous reset. So the clock/reset is there. But where does the compiler deal with it ?</p><p>Once in the beginning and once again towards the end of the compilation process. At the very start i.e. elaboration — before any rule is scheduled and before the word “cycle” has any meaning at all — every method call is tagged with a clock domain. Here, any rule that touches two domains is an error:</p><pre> Error: &quot;Cdc.bsv&quot;, line 9, column 8: (G0007)<br>   Reference across clock domain in rule `crossing&#39;.<br>   Method calls by clock domain:<br>     Clock domain 1:  default_clock:  fast.read<br>     Clock domain 2:  c2.gen_clk:     slow.write</pre><p>The clock/reset is part of a method’s identity. Clock and Reset are also known types!</p><pre> Clock c2 &lt;- mkAbsoluteClock(0, 7);<br> Reset r2 &lt;- mkAsyncResetFromCR(0, c2);<br> Reg#(UInt#(8)) slow &lt;- mkReg(0, clocked_by c2, reset_by r2);<br> SyncFIFOIfc#(UInt#(8)) q &lt;- mkSyncFIFOToCC(2, c2, r2);</pre><p>Clock gating is as simple as using a mkGatedClock and the gate signal is therefore data. Alice’s clock is everywhere but checked nowhere, only at lint :)</p><p>Towards the end of the compilation process, bsc simply retro-fits an always @(posedge clk) . This is what turns every inlined rgister into an edge-triggered assignment.</p><h3>The other language</h3><p>There are two “languages” in a Bluespec file and they both share a syntax. One of them is that of syntheiszable hardware and the other is used for static elaboration.</p><pre>function ComplexSample getTwiddle(Integer stage, Integer index, Integer points);<br>  Integer i = ((2*index)/(2 ** (log2(points)-stage))) * (2 ** (log2(points)-stage));<br>  return cmplx(fromReal(cos(fromInteger(i)*pi/fromInteger(points))),<br>               fromReal(-1*sin(fromInteger(i)*pi/fromInteger(points))));<br>endfunction</pre><p>Notice how this uses the known types Integer , Real , and some functions like cos and log2 . Alice would read this as a floating-point unit in the FFT hardware i’ve been describing throughout this post. There is a way to get trigonometry and logarithms into hardware, but that is obviously not what happens here. The compiler elaborates these functions statically and propagates the results into the program that is synthesized into hardware. Or maybe I should say “into a hardware description”, because the output of the Bluespec compiler is either SystemC or Verilog. You’re obviously welcome to add a compiler hook and emit your own backend, there are multiple places to fork off the bsc compiler, but amod_final is what goes to Verilog.</p><p>The scope of this post will blow up if I get into details about these unbounded types, like Integer and Real . I will therefore refer the reader to the Bluespec LRM. A quick note, Integer and Int #(n) are both representing integers. The former is not synthesizable into hardware because it is unbounded. The latter is bounded to a hardware representation in n bits and therefore derives the Bits typeclass. Again, I’m not going to get into typeclasses in this post, maybe in a different one :)</p><h3>Rules, modules and interfaces are values too!</h3><p>The more surprising thing about the elaboration language is what else is a value in it. Verilog has values i.e. bits and structures i.e. modules, always blocks, wires and so on. The structures in Verilog are _not_ values. That is to say you can’t put a module in an array, pass an always block to a function, or return an interface. In Bluespec however, all of these are values. In fact, we’ve already seen a very nice example:</p><pre>for (Integer i = 0; i &lt; stages; i = i + 1)                                 <br>  rule stage;<br>    isb[i+1] &lt;= stage_f(fromInteger(i), isb[i]);<br>  endrule</pre><p>The for-loop here is in the elaboration language and the rule here therefore elaborates into multiple rules. Each of those rules post elaboration are in the synthesizable subset of Bluespec. Here, isb[i] is a register interface that is being passed into a function stage_f and the function returns a value that is written into the isb[i+1] interface that is provided by yet another register. Confusing much?</p><p>Let me make it worse.. Actions are values too. The body of a rule is an Action, and an Action therefore can be named, passed and shared:</p><pre>function Action advance(Reg#(Bit#(2)) ctr) = action<br>  ctr &lt;= ctr + 1;<br>endaction;</pre><p>Two rules can most definitely call the same action function, and each gets it spliced into it’s own atomic step! This is how I write Bluespec now — one action per rule with shared logic in action functions.</p><p>Wait, I’m not done :D</p><p>Modules are values too! mkReg(0) is a value of the type Module #(Reg #(t) ! One would be tempted to consider this an instantiation and call it a day, but oh well. replicateM is the general “run this recipie n times and collect the results” combinator. This is the same one Bob would have seen in Haskell.</p><p>Bob saw what I did there, and subtly smiled. Bob knows Alice is about to be even more confused now. Yes, Module is a monad. &lt;- is bind, instantiation is the effect and the module _hierarchy_ is monadic composition. For Alice, think of a module as a constructor that, when run, both gives you back an interface and tells the compiler “there’s a register here now”.</p><p>Interfaces are also values! There is a Connectable typeclass that knows how a Get meets a Put .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uE0N2eGUZj0fmskA" /><figcaption>Photo by <a href="https://unsplash.com/@helloimnik?utm_source=medium&amp;utm_medium=referral">Nik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Monads, for Alice</h3><p>Sorry Bob, I’m going to try to quickly tell Alice what a monad is. I understood this well quite recently, thanks to the hitchhiker’s guide to logic verification. This explanation is borrowed directly from that book.</p><p>In general, Alice, a monad is a unary type constructor m : Type -&gt; Type equipped with two distinguished operations:</p><pre>pure { a : Type } : a -&gt; m a<br>bind {a b : Type } : m a -&gt; (a -&gt; m b) -&gt; m b</pre><p>This syntax is “Lean 4”. The curly braces denote implicit arguments. We cna think of a monad as a box containing some data. The box captures some special effects (here, it could be the presence of a register). The pure operation puts data into the box, whereas bind allows you to access the data in the box and modify it. It is possible to change a datum’s type when you bind . There is however, no general way to extract the data from the box i.e. to obtain a from m a . There might not be any value in the box, or there might be several.</p><p>To summarize, pure ais a box containing the value a , with no effects whereas bind ma f (here written as a &lt;- ma, f a ) executes ma then executes f with the unboxed result a of ma . Monads are an abstract concept with many applications. Monads need to follow three laws to be considered lawful monads.</p><p>Another nice analogy is to think of the box as a swiss bank account.. with a := money . The first law means that if you put some money in the account, you can take it out. The second law means that nobody will notice if you take out some money and put it back afterwards. The third law means that performing two bank operations together followed by a third one is the same as performing the first one alone followed by the other two. Given the swiss bank’s reputaiton for secrecy, all theee laws seem plausible :)</p><p>Why did I get into this ungodly concept that is a monad? Bluespec defines six monadic types. They are:<br>(1) Module: the elaboration monad. The effect is instantiation.<br>(2) ActionValue #(t) : the effect monad. The effect is a state update inside an atomic step.<br>(3) StmtM : The StmtFSM monad. The effect is appending a statement to a sequence; This is perhaps one of the best examples to illustrate that control flow is sugar over rules.<br>(4) ModuleContext #(c) : Module with a context threaded through the hierarchy. This is how the library implements things that have to be collected or distributed across every level. Clock and Reset are good examples.<br>(5) Maybe #(t) : same as the Option monad Bob might be aware of — Bind on it’s “if Valid continue with the value else stay Invalid ”. It simply throws a valid bit at the MSB side and therefore increases bit-width by one. A chain of binds will elaborate into a chain of muxes in hardware!<br>(6) List #(t) : elaboration-time lists. This is part of Bluespec’s elaboration language. It has no Bits representation and therefore can never become hardware.</p><p>Bluespec (BSV) spells all their binds as &lt;- and which monad you’re in is decided by which block you’re inside. The same symbol can therefore mean “instantiate a register”, “perform an action and take it’s result”, or “add a step to a sequence”. BH on the other hand, has the ordinary do notation for all 6.</p><h3>Types that do work</h3><p>The last piece of the elaboration langauge is the type system. Alice is seriously missing out on this! Verilog’s type system is, to a first approximation, bit-widths. It doesn’t even enforce those!</p><p>assign a = b; with an 8-bit a and a 9-bit b silently truncates and shows up as lint trouble later, closer to the backend flow. Bluespec’s type-system is basically that of Haskell’s but wiht numbers in it.</p><p>Provisos are a constraint on any type-level number that a defnition needs in order to make sense.</p><pre>module mkRegularReg#(t reset_val)(Reg#(t)) provisos (Bits#(t, tSz));</pre><p>This is basically saying “for any type t, as long as t can be turned into some tSz bits”. Provisos are just that really.. I’ve seen people make a huge deal out of it. Add #(a, b, c) says a + b = c . Log #(n, k) says that k = log n . Bits #(t, n) says that t is n bits wide. These provisos are how the compiler proves that zeroExtend(), truncate(), pack(), split() and the rest of size operations use consistent widths. When they fail, the error is ugly and quite evident. This is also known to cause a lot of scalability problems if a module was written with a lot of provisos keeping some implicit or wrong assumption in mind and that was not explicitly stated.</p><p>Hint: Bit #(0) is a valid, synthesizable data type. What does it transform to in Verilog? I’ll leave that as an exercise for the reader :D</p><h3>Functions are curried</h3><p>This is Bob’s word for something alice never had a reason to want. Basically, a function of three arguments, given one, is a function of two. That is to say that if you have a function written in Bluespec, you could pass one argument in one module, pass the curried function through a Value method provided it is a pure function, else through an ActionValue method and pass the second argument in another module!</p><h3>Don’t use wires!</h3><p>I am not going to talk about Wires at all, it is recommended that you don’t use them. Use CRegs instead. In my experience, using wires is a very easy way to end up with combinational loops that are painful to debug/fix.</p><h3>Bluecheck is somewhat beautiful!</h3><p>Bluecheck is inspired from Haskell’s QuickCheck. It just has a PRNG and some tooling around it, to put naively. It is however, a very nice way to try and verify some of your programs written in Bluespec.</p><p>First of all, it is synthesizable. So you can put it on an FPGA and get much faster testing. For example, put it on a board with a 50MHz clock and leave it running for a month — it will greatly increase the chances in finding counterexamples to properties you’ve stated. This is nice to do in case the module is too large to take through some of the traditional formal verification techniques for hardware i.e. miter circuit construction, Tseitin transformation, followed by SAT solving on the gate-level netlist’s CNF representation.</p><p>It also supports counterexample shrinking and iterative deepening. Bluecheck, I think, is also the most concrete meaning of “hardware is software”. The techniques of property-based testing transferred over to hardware essentially unchanged. The reason I said that it is somewhat beautiful is that it is testing the design with random stimulus and not proving the absence of bugs.</p><p>I will refer the reader to the Bluecheck paper from CHERI at Cambridge.</p><h4>An open question for Bob</h4><p>A rule is guard -&gt; action , and action is a parallel assignment. An action always terminates. A rule, to me, looks a lot like the thing Hoare triples were invented for, with the guard playing precondition, the action playing program, and an assertion playing postcondition. I think the logic applies, but what do you do with it ?</p><p>I also think a guard is not a precondition here. A rule can’t fire without the guard being true. So i think that the assertion itself would be the precondition. Given that the weakest precondition of a rule is a substitution, and that in Bluespec strengthening a guard is cheap i.e. the rule simply declines to fire, what if you take a postcondition, compute it’s weakest precondition and make it the guard? The rule becomes incapable of violating the precondition.. Additionally, how far can a Bluespec tool derive useful guards from properties while preserving progress and keeping hardware cost acceptable ? I have opinions and i think it can be a post of it’s own, but Bob, if you get there first, I’d like to read it.</p><h3>Closing</h3><p>Alice, I hope this post motivates you to give Bluespec another shot. Bob, you knew most of what I’ve described here, and I hope the rest gave you a sense of what it is like to design in Bluespec. I also have an open question that I’ve mentioned above, if you’re interested.</p><h3>About Me</h3><p>I am Karthik. I am an engineer, deep sea diver, and a fitness enthusiast amongst many other things.</p><p>I am currently with <a href="https://www.incoresemi.com/">InCore</a> as a Senior Design Engineer. It has been about <strong>5 years</strong>. I am also a research scholar with the <a href="https://www.ee.iitm.ac.in/vlsi/start">Integrated Circuits and Systems group</a> at <a href="https://www.iitm.ac.in/">IIT Madras</a>. Prior to this, I was with the <a href="https://chips.pes.edu/">Centre for Heterogeneous and Intelligent Processing Systems</a> at <a href="https://www.pes.edu/">PES</a>. Prior to that, I was a mentee at the Linux Foundation.</p><p>My research interests lie in Formal Methods for Logic Verification, Electronic Design Automation and Computer Architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc6314a2d786" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RISC-V Memory Protection: Diving Deep into the Complexities]]></title>
            <link>https://medium.com/@talktokarthikbk/risc-v-memory-protection-diving-deep-into-the-complexities-9d751212be6b?source=rss-3416eb0227e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d751212be6b</guid>
            <category><![CDATA[memories]]></category>
            <category><![CDATA[protection]]></category>
            <category><![CDATA[risc-v]]></category>
            <category><![CDATA[scuba-diving]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <dc:creator><![CDATA[Karthik B K]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 17:56:46 GMT</pubDate>
            <atom:updated>2023-11-23T18:17:26.815Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prologue</h3><p>Hi there! I spent a couple months designing and implementing PMPs on one of our RISC-V CPU core-generators, and I want to share my experience. I want to talk about the architecture as I found it interesting.</p><p><em>This article goes pretty deep (quite literally) into the Physical Memory Protection Architecture (section 3.7) of the RISC-V Privileged Specification (release 20231012). Understanding this article to the fullest might require a decent understanding of computer architecture principles.</em></p><p><em>This text has been written purely in my personal capacity and it does not definitively reflect the views of my employer. My employer will not take responsibility for any mistakes that may have crept into this text. This is going to be a long read.</em></p><p><em>That being said, grab your oxygen tank and fins, deflate your buoyancy compensator, and let’s take a deep dive into what I was doing the last couple of months!</em></p><p><em>(*clears face mask*)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MfFHjBMOgUUFfECV" /><figcaption>Photo by <a href="https://unsplash.com/@jeremybishop?utm_source=medium&amp;utm_medium=referral">Jeremy Bishop</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Surface to 10 meters (0 to 1 Bar)</h3><h4>Introduction to PMPs</h4><p>Simply put, PMPs are just a bunch of registers and gates. They’re an optional hardware unit, that allow you regulate memory access privileges such as read, write, and execute, over the physical address space.</p><p>Typically, these are used to regulate accesses whose effective privilege mode is Supervisor or User. However, they may also be used to regulate accesses to the Machine mode, but in this case the PMP registers themselves are locked and even M-mode software can’t change them until the hart is reset.</p><blockquote>From the spec: At any time, a RISC-V hardware thread (hart) is running at some privilege level encoded as a mode in one or more CSRs (control and status registers). Three RISC-V privilege levels are currently defined in the increasing order of privilege as: User (U), Supervisor (S) and Machine (M).</blockquote><p>Wait a minute, I said “PMP registers”. Let’s talk about them for a minute ?</p><p>(*equalizes*)</p><h4>PMP Registers</h4><p>In order to protect a certain region of physical memory, we need to define the start/end addresses, and the permissions that apply on them. The RISC-V architecture specifies a set of dedicated CSRs for encoding the address space, and another for encoding the permissions. The former being called <em>pmpaddr</em> and the latter, <em>pmpcfg</em>. There can be a maximum of 64 PMP entries. Hence, 64 <em>pmpaddr</em> and 16 <em>pmpcfg</em> registers.</p><p>You can simply use 2 entries to denote the base/bound addresses (TOR). The spec defines a smart technique to encode the base address and the size of the region in a single 32-bit register, if your region is an aligned natural power of 2. Given that the minimum region size is 4 bytes, we can already ignore the lower 2 bits of an address. Then, you can simply set all the bits with lower significance to indicate the size of the region. Confused? here’s an example [1]:</p><pre>/* encode PMP address */<br>if (log2len == PMP_SHIFT) {<br>    pmpaddr = (addr &gt;&gt; PMP_SHIFT);<br>} else {<br>    if (log2len == __riscv_xlen) {<br>        pmpaddr = -1UL;<br>    } else {<br>        addrmask = (1UL &lt;&lt; (log2len - PMP_SHIFT)) - 1;<br>        pmpaddr  = ((addr &gt;&gt; PMP_SHIFT) &amp; ~addrmask);<br>        pmpaddr |= (addrmask &gt;&gt; 1);<br>    }<br>}</pre><p>The <em>pmpcfg</em> registers, are even smaller. Just 3 bits to indicate the “<em>rwx”</em> permissions, a couple of bits to indicate the address matching mode, and another bit to indicate a locked state. Aligning this number to a power of 2, we say we need 8 bits to define a <em>pmpcfg</em> entry.</p><p><em>We’re at about 6 to 8 meters below the sea level. Exciting, right ? By the way, here’s some marine life at this depth.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKbiL-sXh9riYOOTxplleA.jpeg" /><figcaption>This is a Titan Trigger Fish. I did not click this picture, but I wish I had. I did get chased by one though.</figcaption></figure><p><em>Let’s dive a little deeper, shall we?<br></em>(*equalizes*)<br>(*clears face mask*)</p><h3>10 to 18 meters (1 to 2 Bar)</h3><h4>Address Matching Modes</h4><p>Let’s talk a little more about this. We said that we need 2 bits to encode the address matching mode. As it happens, the spec defines 4 modes to match addresses. They are: <em>(0) Off, (1) TOR — Top of range, (2) NA4 — Naturally aligned four-byte region, (3) NAPOT — Naturally aligned power-of-two region, ≥ 8 bytes.</em></p><p>Each <em>pmpcfg</em> register holds 4 PMP entries. In case of a 64-bit machine, the odd-numbered indices act in continuity of the even-numbered indices.</p><p>In the TOR mode, there is no restriction on the alignment of the base/bound addresses. In the NAPOT mode however, both the base address must be aligned to the power of two which the size of the region is. This must also be a multiple of the granularity. For example, if your granularity is <em>32 bytes</em>, then protecting a region starting at <em>0x80000010</em> is <em>illegal</em> in the NAPOT mode.</p><h4>Setting permissions</h4><p>In order to protect a <em>32-byte region starting at 0x80000000 against fetches in S/U modes</em>, and set this to be of the <strong><em>first priority</em></strong> while matching addresses, you would write the value <em>0x2000000F</em> into the <em>pmpaddr0</em><strong> </strong>register. Before you do that, you would set the <em>pmpcfg0</em> register to contain the value <em>0x0000001B</em>. In order to apply these permissions to <em>machine mode (M)</em> as well, you would now lock this PMP entry by setting the <strong><em>pmpcfg0</em></strong> register to contain the value <em>0x0000009B</em>. Alas, now you can never fetch the first 32 bytes starting at <em>0x80000000</em>, Unless that’s your debug module’s progbuf, for whatever reason. You also can’t change this value until you reset your hart. Haha :)</p><p>Now wait, I mentioned priority. Where did that come from ?</p><p><em>Check your oxygen tanks, we’re going deeper. Heads up, my dive computer says we’re at about 17 meters. If we go any deeper, we may have to perform a decompression stop. We’ll make a safety-stop at 5 meters anyways :)</em></p><p><em>By the way, here’s some marine life at this depth.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SuDFxOWLu-e75fqS" /><figcaption>This is a Cuttle Fish. Spotted one at “Slope” in Havelock Island, AN IND. Photo by <a href="https://unsplash.com/@emilesch?utm_source=medium&amp;utm_medium=referral">Emile Schilders</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>(*equalizes*)<br>(*clears face mask*)</em></p><h3>18 to 20 meters (2 to 3 Bar)</h3><h4>Priority and Matching Logic</h4><p>This is some complex stuff. Let’s slow down our finning, and explore the reef better. The spec says that a lower-numbered PMP entry will always take priority even if your access matches multiple PMP entries. Makes sense, right?</p><p>But wait, what if a memory access is not fully protected by a PMP entry with a higher priority ? In that case, we say that it’s an access fault.</p><p>What if it partially matches a higher priority entry, and fully matches a lower priority entry ? You guessed it right, it’s still an access fault :)</p><p>What if I want to protect a certain region against reads only, and allow writes ? Well, that’s not allowed :)</p><p>What if my access does not match any PMP entry ? It’s still an access fault :)</p><p>What if PMP registers exist on my hart but all the cfg.A fields are set to <em>Off</em> ? It’s still an access fault :)</p><p>What if I have a machine-mode access that is partially protected by a (higher priority) PMP entry that is not locked ? It’s an access fault :)</p><p>What if I have an instruction that performs a read-modify-write atomically ? What happens if the target memory address it protected against writes and not reads ? It’s an access fault :)</p><p>What if the atomic instruction operates on a region that is protected against both reads and writes ? What kind of an exception will that generate ? It’s always a store access fault, because that is indeed the last operation :)</p><p>What if this doesn’t happen atomically ? This might make changes to my architectural states, as a side-effect ? Even though the instruction didn’t commit ? Possible. side-effects are OK. Although, this is still going to take an access fault.</p><p>What if I have hardware support for misaligned memory accesses ? Do we still have to match the entire access region ? Aha! Now since your region needs to be aligned to a power of 2, a misaligned access may read/write to/from the bytes that are allowing access. In case of reads, it doesn’t matter because you can generate an access fault before writing to the register file, but in case of writes, a partial-write may go through :)</p><p>What if my write is wider than XLEN ? Like the FSD instruction in RV32D ? The same applies here. Even if the store address is aligned, a partial write may go through :)</p><p>(*equalizes*)<br>(*giggles*)</p><p>Confused? Same here. My dive computer says that we need to ascend ASAP, or we might have to make a compulsory decompression stop. Let’s take good deep breaths and not panic. Shall we start ascending ?</p><h3>Safety Stop (3 to 5 meters)</h3><p>What did I learn the last couple months ? The entire PMP spec (excluding Smepmp) is just 4 pages long. I’ve indeed lost count of the number of times I’ve had to go back and forth to understand it well. All be it, I was able to get these to work to the best of my understanding. This was a lot of fun :)</p><p>I’ve listed the version of the spec that I used as a reference[2].</p><h3>Epilogue</h3><p>If you made it through the entire article, thank you so much for reading! Did you notice that this article has a scuba-diving theme? That’s because I’m now an SSI certified open-water diver! I had to log 6 dives with a maximum depth of 18 to 20 meters, and pass a written exam in order to complete this certification.</p><p>I got my certification from <strong><em>“Seahawks Scuba”</em></strong>. It’s a diving school on Havelock Island (Swaraj Dweep) in the Andaman and Nicobar Islands in India. If you want to go diving, check them out! Read more about diving in India [3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*Bixx028TbBwgpkwt4SbzKg.jpeg" /><figcaption>This is me, performing my safety stop before the end of my 6th dive!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*DwPi2C4oGsJkQenhArfUyw.png" /><figcaption>This is my SSI Diving Certificate as an Open Water Diver!</figcaption></figure><h4>About Me</h4><p>My name is Karthik, and I’m an Engineer and Photographer, both by passion and profession. I am currently with InCore Semiconductors as a CPU Micro-Architect. Prior to this, I was with the Centre for Heterogeneous and Intelligent Processing Systems working on Energy Efficient Computing Techniques. Prior to that, I was a mentee at the Linux Foundation.</p><p>I have about a year of research experience and another 2 years of industry experience. My research interests lie in CPU micro-architecture for high-performance and secure computing. I plan to pursue a PhD. I also have a newly developed interest in law and psychology :)</p><p>I am a certified open-water diver. I am also a photographer. You can check out some of my work on Unsplash :) ( <a href="https://unsplash.com/@thatbangaloreanguy">https://unsplash.com/@thatbangaloreanguy</a> ) ❤</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fabj76oXtjOTw1P30P0kA.jpeg" /><figcaption>This is a picture I clicked in December last year. I like it a little too much :)</figcaption></figure><p>If you want to chat about RISC-V or Computer Architecture in general, feel free to write to me at karthik.bk@incoresemi.com !</p><p>If you are interested in working in this domain, check out my employer, <a href="http://incoresemi.com/"><strong>InCore Semiconductors (incoresemi.com).</strong></a></p><p>Thanks once again for reading! Talk to you next time, bye bye!</p><h3>References</h3><p>[1] <a href="https://github.com/riscv-software-src/opensbi/blob/ec0559eb315bd11a5ef8865a8a8fa91ab6888250/lib/sbi/riscv_asm.c#L333">https://github.com/riscv-software-src/opensbi/blob/ec0559eb315bd11a5ef8865a8a8fa91ab6888250/lib/sbi/riscv_asm.c#L333</a></p><p>[2] <a href="https://github.com/riscv/riscv-isa-manual/releases/download/riscv-isa-release-056b6ff-2023-10-02/priv-isa-asciidoc.pdf">https://github.com/riscv/riscv-isa-manual/releases/download/riscv-isa-release-056b6ff-2023-10-02/priv-isa-asciidoc.pdf</a></p><p>[3] <a href="https://www.divessi.com/en/mydiveguide/destination/india-9749332">https://www.divessi.com/en/mydiveguide/destination/india-9749332</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d751212be6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the hidden wonders: CPU Micro-Architecture]]></title>
            <link>https://medium.com/@talktokarthikbk/exploring-the-hidden-wonders-cpu-micro-architecture-b8bb680738b7?source=rss-3416eb0227e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8bb680738b7</guid>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[microarchitecture]]></category>
            <category><![CDATA[risc-v]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <dc:creator><![CDATA[Karthik B K]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 13:41:50 GMT</pubDate>
            <atom:updated>2023-07-03T18:40:13.160Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prologue</h3><p>Hello, curious soul! This is going to be a long read. Maybe you want to quickly go grab a cup of coffee?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jeuS4MBne1PO6MxS" /><figcaption>Photo by <a href="https://unsplash.com/de/@jckbck?utm_source=medium&amp;utm_medium=referral">Jakub Dziubak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bienvenue to the tour of my fascinating realm, where mystique and fascination intertwine with the inner workings of the digital world. I know that everyone has always wondered how a computer works, but the answer you got, was probably vanilla. Allow me to take a shot at it :’)</p><p><em>In this article, you can expect to understand what it takes to design (partially) a CPU, who does it, who tells them what to do and what not to do, and what their day-to-day tasks may look like.</em></p><p>*sips coffee*</p><h3>The Surface</h3><p>So, you want to boot Linux on your own “chip” ? Well, the truth is, there’s a lot on that chip. I’m only going to talk about the “hart” of it. See what I did there :’)</p><blockquote>A “<strong>hart</strong>” or a “<strong>har</strong>dware <strong>t</strong>hread” is a physical CPU or core.</blockquote><p>The reality is, one hardware thread can only do one thing <strong>at a time</strong>. One hardware thread, can run multiple software threads. But wait, let’s take a step back. How do you think Linux talks to your “chip” ? What’s the language they both speak? Well, obviously binary, but what are the rules of speaking binary? Well, that’s where your <strong>ISA</strong> comes into the picture.</p><blockquote>ISA stands for instruction set architecture, and it’s the standard that both hardware and (system) software designers have to adhere to.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*LPBOSSXoNdNBhGWR5qLXJg.png" /><figcaption>Instruction Sets from the Textbook - Computer Architecture: A Quantitative Approach, authored by Hennessy and Patter</figcaption></figure><p>You’ve probably heard of some of them a lot. x86, ARM64, RISC-V ? No? Well, Intel’s i3, i5, i7, i9 CPUs are based on the x86 architecture, Apple’s M1 series of CPUs are based on the ARM64 (also called AArch64) architecture. RISC-V is an open-source ISA. Some like to say that RISC-V is to hardware what Linux is to software. Upto a cetain extent, it is true.</p><blockquote><strong>RISC-V</strong> (pronounced “risk-five”) is an <a href="https://en.wikipedia.org/wiki/Open_standard">open standard</a> <a href="https://en.wikipedia.org/wiki/Instruction_set_architecture">instruction set architecture</a> (ISA) based on established <a href="https://en.wikipedia.org/wiki/RISC">reduced instruction set computer</a> (RISC) principles. Unlike most other ISA designs, RISC-V is provided under <a href="https://en.wikipedia.org/wiki/Royalty-free">royalty-free</a> <a href="https://en.wikipedia.org/wiki/Open-source_license">open-source licenses</a>. It was designed by the University of California in Berkeley back in 2015; 8 years ago. Prof. Krste Asanović and graduate students Yunsup Lee and Andrew Waterman started the RISC-V instruction set in May 2010 as part of the Parallel Computing Laboratory (Par Lab) at UC Berkeley, of which Prof. David Patterson was Director.</blockquote><p>The ISA defines the set of instructions and their binary encodings that your linker (last step out of 4, in compilation) should generate. This file is what is called as the executable (binary) file.</p><blockquote>Fun fact: Did you know that the extension of your files have nothing to do with what the file is intended for ? Yes, Windows just likes to the save some executable files with the <em>.exe </em>extension.</blockquote><p>These instructions, are what hardware designers — wait, let’s call them CPU Architects from here. These instructions are what CPU architects are supposed to design for. The spec (ISA) tells a little more about how to design the hardware, and places some restrictions on the way things are done, but the fact is, most of the implementation is left to the wild ideas of the architect. These guys write some code (yes, code) which eventually becomes hardware that can be fabricated. Programming languages are not designed for this purpose, and can not be used to generate hardware. There exist (HDLs) <strong>H</strong>ardware <strong>D</strong>escription <strong>L</strong>anguages, and their <strong>H</strong>igh <strong>L</strong>evel counterparts (HLHDLs). But wait, you’ve probably heard of these too. Verilog, System Verilog, VHDL, Bluespec, Chisel? No?</p><p>*sips coffee*</p><h3>The Allure</h3><p>Now this is where it starts to get a lot more fun. Since the architecture only defines what needs to be done, and the ‘how’ is left to us, we can start to get wild. It may not be very intuitive how, but let me walk you through an example. Here’s a snippet from the latest draft (2023–05–23) of the RISC-V Unprivileged Specification:</p><pre>Shifts by a constant are encoded as a specialization of the I-type format. The operand to be shifted is in<br>rs1, and the shift amount is encoded in the lower 5 bits of the I-immediate field. The right shift type is<br>encoded in bit 30. SLLI is a logical left shift (zeros are shifted into the lower bits); SRLI is a logical<br>right shift (zeros are shifted into the upper bits); and SRAI is an arithmetic right shift (the original sign<br>bit is copied into the vacated upper bits).</pre><p>Here’s the encoding of these instructions, as per the specification:</p><pre>slli   rd rs1 31..26=0  shamtd 14..12=1 6..2=0x04 1..0=3<br>srli   rd rs1 31..26=0  shamtd 14..12=5 6..2=0x04 1..0=3<br>srai   rd rs1 31..26=16 shamtd 14..12=5 6..2=0x04 1..0=3</pre><blockquote>Links to the spec, and the encodings (opcodes) repositories have been listed under ‘References’ at the end of this article.</blockquote><p>If you look carefully, the encoding differentiates between right shifts and left shifts in the 15th bit (zero-based indexing, obviously). Which means, I (as the micro-architect) now have the freedom to design whatever hardware I want, as long as it’s compliant to these constraints defined by the spec.</p><blockquote>Take this as an exercise — what’s the most efficient way to design hardware for this?</blockquote><p>*sips coffee*</p><p>Well, if you ask me, I might say that it’s a left shifter. Wait, how would you right shift with a left shifter ? For starters, you could simply reverse the inputs/outputs to/from the left shifter. Confused ? Here’s some pseudo-code:</p><pre>..note:: assume there&#39;s a 4-wide left shifter available.<br><br>a = 5 &lt;&lt; 2<br>b = 5 &gt;&gt; 2<br><br>..note:: &#39;b&#39; can be implemented as follows<br><br>b = reverse(reverse(5) &lt;&lt; 2)<br><br>..note:: here&#39;s the binary representations<br><br>a = 0101 &lt;&lt; 2 = 0100<br>b = 0101 &gt;&gt; 2 = 0001<br><br>b&#39;:<br>  reverse(0101) = 1010<br>  1010 &lt;&lt; 2 = 1000<br>  reverse(1000) = 0001</pre><p>*sips coffee*</p><p>So we could do two things with just a few more wires (for reversing). Fascinating, isn’t it? It’s not just this. The entire core pipeline, all the stages, the dispatch and bypass logic, branch prediction, cache subsystems, co-processor interfaces, tightly integrated memories, CSR hooks, and not to mention the trapping mechanism. There’s so much to play around with!</p><p>*sips coffee*</p><p><em>(…the cup is empty)</em> *refills coffee cup*</p><p>*sips coffee*</p><p>I could give you more examples, but my supervisors would probably fire me if I revealed any serious micro-architecture :’(</p><p>The truth is, RISC-V is a modular ISA, and expects to grow in a modular fashion. This, and the coming decades are going to demonstrate a larger demand for compute than ever. Especially with Artificial Intelligence, and the end of Moore’s law (?)</p><p>By the way, check out <a href="https://raniyer07.medium.com/introduction-to-generative-ai-28ef4bd2a3b5">my friend’s article on Generative AI</a>.</p><h3>Next Steps</h3><p>Right.. we were building a core. We micro-architects are expected to document the hardware designs extremely well, and write a lot of docs mentioning all the potential pitfalls we can foresee, and describing what kind of performance improvements and overheads our changes/additions are expected to bring.</p><p>Once this is done, we start to make the changes in code, and smoke-test the new hardware, before it’s handed off to the verification team. Now, it’s their problem. If the ‘chip’ is taped-out and someone finds a bug (in hardware) later, then their asses would be on fire, because they were the last ones to sign-off on the design.</p><blockquote>Did you know? Intel had to recall some of it’s CPUs? Read more about the Pentium FDIV bug on Wikipedia.</blockquote><p>*sips coffee*</p><p>Once that’s done, you would have to go make something like an RPi, but only now, the CPU would be hand-crafted by you. All the best booting Linux on your own CPU! If you stick around long enough, you might be able to play CSGO on it :)</p><h3>More thoughts</h3><p>Consider the example of Apple’s M series of CPUs. They’re the latest proof of how much impact the ISA can have on the Performance and Energy Efficiency of the hardware. Something like RISC-V can be pivotal in the hardware industry. A country like India, is very well capable of supplying the talent to meet the demands of the future, that is only if not every single student wants to become a web developer. Yes that was an exaggeration.</p><p>Anyways. Do you think whatever you’ve read so far has sparked an interest in computer architecture ? Then you should go explore!</p><p>But wait, do you have any of <strong>these</strong> questions?</p><ol><li>I’m using an Intel CPU, those are so good! Why do I have to use your ‘chips’ at all?</li><li>You’re trying to enter a market that’s dominated by giants like Intel and AMD. Do you think you can stand your ground ?</li><li>Apple made their own chips, true, but they also had (have) a lot of money. Can you match the effort that they put into their M series of CPUs ?</li><li>Does this field have any money ?</li><li>Are domain specific accelerators going to be a thing in the future ?</li><li>Can/will the demand for micro-architects shoot up sometime soon ?</li><li>…</li><li>Are we “re-inventing the wheel” ?</li></ol><p>Well, I only want to take a shot at answering the last one. I don’t think that we’re re-inventing the “wheel”. We’re only making it better.</p><p>If you find all of this to be interesting, then you should check out my employer, <a href="https://www.incoresemi.com/">InCore Semiconductors</a>, backed by Sequoia Capital. We’re actively hiring right now. They have great leadership, and provide immense amounts of guidance. The learning curve is steep, true, but I like climbing :D</p><h3>Epilogue</h3><p>This article begins with defining a hart and transitions to ISAs and RISC-V micro-architecture, and ends with some thoughts on careers in the semiconductor industry. This article was written with the intention to share what I do at work, more or less on a daily basis, because it excited me.</p><p><em>That being said, all these are my personal thoughts and opinions, and none of them, in any manner, definitively reflect of the views of my employer.</em></p><h3>About Me</h3><p>Hi there! My name is <a href="https://about.me/bkkarthik">Karthik</a>, and I’m an Engineer and Photographer, both by passion and profession. I am currently with <a href="https://incoresemi.com/">InCore Semiconductors</a> as a CPU Micro-Architect. Prior to this, I was with the <a href="https://www.chips.pes.edu/about">Centre for Heterogeneous and Intelligent Processing Systems</a> working on Energy Efficient Computing Techniques. Prior to that, I was a mentee at the <a href="https://training.linuxfoundation.org/?SSAID=3481415&amp;sscid=61k7_17foha&amp;utm_source=shareasale&amp;utm_medium=affiliate&amp;utm_campaign=affiliate">Linux Foundation</a>.</p><p>I have about a year of research experience and close to another 1.5 years of industry experience. My research interests lie in micro-architecture for high-performance and secure computing. I plan to pursue a PhD. I also have a newly developed interest in law and psychology :)</p><p>Here’s a picture I clicked back in December 2022 !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a5YG8WyeDvevtzcV" /><figcaption>Photo by <a href="https://unsplash.com/@thatbangaloreanguy?utm_source=medium&amp;utm_medium=referral">Karthik B K</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You can check out the other pictures that I have published on <a href="https://unsplash.com/@thatbangaloreanguy">unsplash</a> ❤</p><p>It was nice talking to you :) See you again next time !</p><p>*goes to get more coffee for self*</p><h3>References</h3><ol><li>RISC-V ISA Manual — <a href="https://github.com/riscv/riscv-isa-manual">https://github.com/riscv/riscv-isa-manual</a></li><li>RISC-V Instruction Encodings — <a href="https://github.com/riscv/riscv-opcodes">https://github.com/riscv/riscv-opcodes</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8bb680738b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>