<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
   <title>Aaron&apos;s Sandbox</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/" />
   <link rel="self" type="application/atom+xml" href="http://www.antfarm.org/blog/aaronf/atom.xml" />
   <id>tag:www.antfarm.org,2010:/blog/aaronf//8</id>
   <updated>2008-03-06T05:06:23Z</updated>
   <subtitle>what I&apos;m working on these days.</subtitle>
   <generator uri="http://www.sixapart.com/movabletype/">Movable Type 3.31</generator>

<entry>
   <title>MyHDL example: Avalon-ST Error Adapter</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2008/03/myhdl_example_avalonst_error_a.html" />
   <id>tag:www.antfarm.org,2008:/blog/aaronf//8.54</id>
   
   <published>2008-03-06T04:21:44Z</published>
   <updated>2008-03-06T05:06:23Z</updated>
   
   <summary> Another MyHDL experiment: the amazing Avalon-ST error adapter. I&apos;ve mentioned this component before; here&apos;s a quick recap: The component has a single Avalon-ST sink and an single Avalon-ST source. &quot;ordinary&quot; inputs of the sink (e.g. roles data, valid) wire...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="MyHDL" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
Another MyHDL experiment: the amazing Avalon-ST error adapter.  I've mentioned this component before; here's a quick recap:
<p>
<UL>
<LI>The component has a single Avalon-ST sink and an single Avalon-ST source.</LI>
<LI>"ordinary" inputs of the sink (e.g. roles <strong>data</strong>, <strong>valid</strong>) wire directly, combinationally, to outputs of the source. (Sink and source data widths must match.)</LI>
<LI>"ordinary" inputs of the source (role <strong>ready</strong>) wire directly, combinationally, to outputs of the sink.</LI>
<LI>The sink (and source) have an input (and output) of role <strong>error</strong>.  Each individual sink and source error bit has an associated error type, which is a string.  The sink and source error types need not match, nor must they have matching widths, thus some connection rules are required:
<OL>
<LI>matching (string match) error types are wired directly.</LI>
<LI>if present, an output error bit of type "other" is driven from the logical OR of any otherwise non-matching input error bits</LI>
<LI>any unmatched output error bits are driven with logical 0</LI>
</OL>
</LI>
<p>
</UL>
<p>
As I showed in a previous article,
<a href="http://www.antfarm.org/blog/aaronf/2007/11/xvg_avalon_st_error_adapter.html">avalon_st_error_adapter</a>, this component, though simple to describe, is not so easy to generate.  The Europa implementation turns out to be acceptable, by dint of some object overloading.
<p>
So - how does a MyHDL implementation of this component turn out?
<p>
<strong>Finding #1: It is possible!</strong>... but I certainly struggled with the implementation.
<p>
Two aspects of this component were difficult - not because it would be hard to code the logic in Python; rather, because it was hard to code the problem using the limited subset of Python which is convertible to Verilog.
<OL>
<LI> the wiring-together of matching error bits, wherever they appeared in the error ports (component <strong>permute</strong> from the previous article was this problem, in disguise): 
<p>
In MyHDL, I created a mapping tuple, <strong>outputMapping</strong>, whose element of index 'i' gave the index of the input error signal which drove output error bit i.  Then I loop over all matching output bits, assign the proper index bit to a variable (which becomes a signal in Verilog), and drive the output from the given input bit, something like this:
<pre>
# (j is large enough to hold any index into intermediate.)
j = intbv(0, min=0, max=2 + len(i_err))
for i in range(len(outputMapping)):
  j[:] = outputMapping[i]
  o_err.next[i] = intermediate[int(j)]
</pre>
<p>
Notice that I use an intermediate signal, rather than assigning directly from the input error signal.  The intermediate signal is 2 bits wider than the input error signal.  One "extra" bit is driven with 0 (for otherwise undriven outputs); the other is driven with the logical OR of any "other" input bits.  This way, I know the index value from which to drive every output error bit, whether it's a direct-map bit, an "other" bit or an output which must be driven with 0.
</LI>
<LI> forming the logical OR of all otherwise unconnected error inputs to drive the 'other' error output.  The way I solved the puzzle was to create another tuple, <strong>otherList</strong>, containing indices of input error bits which are to be OR'ed into the output "other" bit.  In another for loop, I loop over all the elements of the tuple, iteratively OR'ing in each bit into the correct bit of the intermediate signal, like this:
<p>
<pre>
# (k is large enough to hold any index into intermediate.)
k = intbv(0, min=0, max=2 + len(i_err))
for i in range(len(otherList)):
  k[:] = otherList[i]
  intermediate[otherIndex] = \
    intermediate[otherIndex] | intermediate[int(k)]
</pre>
</LI>
</OL>
<p>
The implementation code looks very very unlike the conceptual picture in one's brain - it should be more like straight bit assignments, and an OR gate.  The violent disagreement between concept and implementation is the sort of thing that makes my spider-sense tingle.
<p>

<strong>Finding #2: Unit testing is swell.</strong>
<p>
My design flow here was to add a feature, add a test for it, add another feature, add another test, ...  This worked great: I found lots of bugs quickly as I went, and the need to write tests forced me to carefully consider interface/API issues.  <p>
Here's what one of my tests looks like: it tests the function of a the simplest possible error adapter, with a single input and output error bit of matching type:
<pre>
def testA(self):
  """
    Simple case: data, valid, ready, one-bit matching input and output error.
    (Arguably this shouldn't be a valid error adapter - there's nothing to
    adapt!  Philosophical issue whether or not this should be supported. I'm
    going to allow it, because to make a special case of it to exclude it
    would be more work.)
  """
  # Direct mapping.
  def error_map(i_err):
    return i_err

  self.doATest( \
    "testA", \
    8, \
    { 'o_err': { 'a' : 0, }, 'i_err': { 'a' : 0, }, }, \
    error_map = error_map, \
  )
</pre>
<p>
In this test I define the mapping from input error to output error, the data width, and the hash which defines the error bit mapping.  Utility routines do the rest of the work of creating the actual adapter, running the simulation, verifying the outputs vs. the inputs, and running toVerilog on the adapter.  Other tests have a similar framework - only the error mapping routine, the data width and the parameterization hash are varied.  See <em>test_avalon_st_error_adapter.py</em> for the rest of the tests, and the definition of test utility routine <em>doATest</em>.
<p>
<strong>Finding #3: That Verilog is nigh-unreadable!</strong>
<p>
Perhaps as a natural result of the fact that the implementation relies on special MyHDL "tricks", the Verilog output appears to have been written by an evil genius.  For example, if the input and output error bits are defined as follows:
<pre>
{
  'o_err': { 'nomatch' : 0, 'other' : 1, 'a' : 2, 'c' : 3, },
  'i_err': { 'a' : 1, 'b' : 2, 'c' : 0, 'd' : 3, 'e' : 4, 'f' : 5, },
},
</pre>
<p>
you might hope that the output error bit assignment would look something like this:
<pre>
assign other = i_err[5] | i_err[4] | i_err[3] | i_err[2];
assign o_err = {i_err[0], i_err[1], other, 1'b0};
</pre>
<p>
rather than this:
<pre>
always @(i_err) begin: _testG_mapOutputErrorBits
    integer i;
    reg [3-1:0] k;
    reg [8-1:0] intermediate;
    reg [3-1:0] j;
    intermediate = {1'h0, 1'h0, i_err};
    k = 0;
    for (i=0; i<4; i=i+1) begin
        // synthesis parallel_case full_case
        case (i)
            0: k = 2;
            1: k = 3;
            2: k = 4;
            default: k = 5;
        endcase
        intermediate[6] = (intermediate[6] | intermediate[k]);
    end
    j = 0;
    for (i=0; i<4; i=i+1) begin
        // synthesis parallel_case full_case
        case (i)
            0: j = 7;
            1: j = 6;
            2: j = 1;
            default: j = 0;
        endcase
        o_err[i] <= intermediate[j];
    end
end
</pre>
<p>
So it goes.  The illegibility of the Verilog output may not matter so much in practice, if 1) the unit test facilities lead to well-verified logic, so that the Verilog doesn't need to be studied for bugs (when was the last time you looked for bugs in an assembler listing of your C code?), and 2) the <strong>toVerilog</strong> function is reliable.
<p>
I think that'll be it for now.  As usual, I include a full archive of the code: 
<p>
<a href="http://www.antfarm.org/blog/aaronf/avalon_st_error_adapter.rar">avalon_st_error_adapter.rar</a>


]]>
      
   </content>
</entry>
<entry>
   <title>MyHDL example: permute</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2008/02/myhdl_example_permute.html" />
   <id>tag:www.antfarm.org,2008:/blog/aaronf//8.52</id>
   
   <published>2008-02-13T14:40:24Z</published>
   <updated>2008-02-14T04:51:03Z</updated>
   
   <summary> Consider a very simple parameterized module, permute, with a single input and output of equal width. Output bits are driven from input bits according to a single generation parameter, mapping, which is a list of integers from 0 to...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="MyHDL" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
Consider a very simple parameterized module, <strong>permute</strong>, with a single input and output of equal width.  Output bits are driven from input bits according to a single generation parameter, <string>mapping</strong>, which is a list of integers from 0 to (width - 1) in any order.
<p>
For example: mapping = (1, 2, 0) would generate a module containing these assignments:

<pre>
  assign x[0] = a[1];
  assign x[1] = a[2];
  assign x[2] = a[0];
</pre>
<p>
Making parameterized assignments like this is in europa straightforward (assume @mapping contains the particular permutation to generate):
<pre>
for my $i (0 .. -1 + @mapping)
{
  $module->add_contents(
    e_assign->new({
      lhs => "x\[$i\]",
      rhs => "a\[$mapping[$i]\]",
    }),
  );
}
</pre>
<p>
<a href="http://www.antfarm.org/blog/aaronf/permute.pm.html">(europa generator, derived from europa_module_factory)</a>
<p>
<a href="http://www.antfarm.org/blog/aaronf/run1.v.html">(complete Verilog listing, as generated)</a>
<p>
A similar implementation in MyHDL turns out to be pretty clean:
<pre>
  @always_comb
  def logic():
    for i in mapping:
      x.next[i] = a[mapping[i]]
</pre>
<p>
<a href="http://www.antfarm.org/blog/aaronf/permute.py0.html">(initial attempt in its entirety)</a>
<p>
Using the above, I wrote some <a href="http://www.antfarm.org/blog/aaronf/testPermute.py.html">simple unit tests</a> which try a variety of permutation mappings of various widths, driving a bunch of input values and verify the resulting output values.  This works great!  But trouble loomed when I tried to generate some Verilog.  My innocent-looking code apparently angers <strong>toVerilog</strong>, and elicits a giant stack dump.  Here's the final part of the stack dump, which I think is the actual error:
<pre>
(lots of lines of stack trace deleted)
myhdl.ToVerilogError: in file .../permute.py, line 15:
    Requirement violation: Expected (down)range call
</pre>
<p>
<a href="http://www.antfarm.org/blog/aaronf/error.txt.html">(complete stack dump)</a>
<p>
So... it is documented that <a href="http://www.jandecaluwe.com/Tools/MyHDL/manual/conv-subset-intro.html"><strong>toVerilog</strong> does not support everything you can write in python</a>; in fact, you're limited to a pretty small subset of the language in code which will be translated to HDL.  This might be what I've run into, here, but sadly I don't know what a "(down)range call" is, nor who was expecting it.
<p>
I asked Stefaan, who originally pointed me toward MyHDL, about this, and he mentioned a discussion of an issue in a <a href="http://sourceforge.net/mailarchive/forum.php?thread_name=flibei%24vp%241%40ger.gmane.org&forum_name=myhdl-list">forum posting</a>.  In that thread, someone attempted a different implementation of a permuting module, and ran into trouble.  Mr. MyHDL himself, Jan Decaluwe, came to the rescue with a method.  The solution is to loop through the mapping not directly by element, but instead by index number, and to use a temp variable to index into the mapping list.  (I think this is leveraging off of the same special case which allows inferred RAMs to work.)  Here's what the modified generator function looks like:
<p>
<pre>
  @always_comb
  def logic():
    tmp = intbv(0, min=0, max=len(mapping))
    for i in range(len(mapping)):
      index[:] = mapping[i]
      x.next[i] = a[int(index)]
</pre>
<p>
<a href="http://www.antfarm.org/blog/aaronf/permute.py1.html">(final MyHDL generator)</a>
<p>
I think it's pretty clear that the above version of the generator does the same thing as the initial version (though it's a bit more cluttered), and, since my unit tests pass just fine with this version, I'm pretty happy with it.  And, <strong>toVerilog</strong> runs without error.  So what does the generated Verilog look like?
<p>
<pre>
always @(a) begin: _permute_logic
    reg [2-1:0] tmp;
    integer i;
    tmp = 0;
    for (i=0; i<3; i=i+1) begin
        // synthesis parallel_case full_case
        case (i)
            0: tmp = 1;
            1: tmp = 2;
            default: tmp = 0;
        endcase
        x[i] <= a[tmp];
    end
end
</pre>
<p>
<a href="http://www.antfarm.org/blog/aaronf/permute.v.myhdl.html">(complete Verilog listing, as generated)</a>
<p>
This is a lot more complex than the simple list of assignments I was hoping for.
<p>
So, the tradeoffs: with MyHDL, it's easy to write unit tests with the full power of python, and the tested behavior can then be written out as Verilog.  If the conversion process is successful, the resulting generated Verilog can be regarded (though warily) as tested.  But, the generated Verilog may not be so readable, and confirming that it matches the original design intent requires work (via PLI, you can run your unit tests against the generated Verilog in a simulator - haven't tried this yet).
<p>
Writing the behavioral definition can be a struggle, since it may not be clear which aspects of the language <strong>toVerilog</strong> will accept (though that's probably just my lack of experience with the tool showing through).
<p>
On the whole I think the tradeoff is worth it: MyHDL should make a strong foundation for building up a library of tested functional building blocks.
<p>
<em>As usual, I'm attaching <a href="http://www.antfarm.org/blog/aaronf/permute.rar">the various files</a> associated with this article.  At the top level are the MyHDL generator script, with its test script, verilog generator script and output file.  One level down in subdirectory permute, you'll find the Europa generator, associated scripts and output file.
<p>
<UL>
<LI>To run the MyHDL unit tests: </em>python testPermute.py<em></LI>
<LI>To generate Verilog using the MyHDL generarator: </em>python vPermute.py<em></LI>
<LI>To generate Verilog using the europa generator: 
<OL>
<LI>in a bash shell, cd to subdirectory </em>permute<em></LI>
<LI>run the script </em>run1.sh<em></LI>
</OL
</LI>
</UL>
<p>
Say, do people prefer winzip files over rar files?  Let me know.</em>
<p>
<em>20080213 20:50: Edit: for no good reason I posted used one parameterization (mapping) for the europa example, and a different one for MyHDL example.  That doesn't help to make things clear!   I fixed it... sorry if you were confused by the original version.</em>
<p>]]>
      
   </content>
</entry>
<entry>
   <title>MyHDL: a brief discussion</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2008/02/myhdl_a_brief_discussion_2.html" />
   <id>tag:www.antfarm.org,2008:/blog/aaronf//8.50</id>
   
   <published>2008-02-06T14:32:30Z</published>
   <updated>2008-02-07T21:10:39Z</updated>
   
   <summary> A reader pointed me at another HDL generation solution, MyHDL. According to the MyHDL manual, The goal of the MyHDL project is to empower hardware designers with the elegance and simplicity of the Python language. Sounds good to me!...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="MyHDL" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
A reader pointed me at another HDL generation solution, <b>MyHDL</b>.  According to the <a href="http://www.jandecaluwe.com/Tools/MyHDL/manual/MyHDL.html">MyHDL manual</a>,
<p>
<blockquote>The goal of the MyHDL project is to empower hardware designers with the elegance and simplicity of the Python language.</blockquote>
<p>
Sounds good to me!  In the interest of science, I decided to check it out.  After reading the manual and tinkering with it for a while, I'm ready to talk about my experience with MyHDL.
<p>
<b>MyHDL Features</b>
<p>
<UL>
<LI>Documentation: I was able to install and use MyHDL by following the excellent on-line documentation. Full marks for this!</LI>
<LI>Language: MyHDL is a Python package.  Python is a decent and usable programming language.  It seems about equivalent to Perl, but I get the impression that readable code might flow a little more naturally in Python.</LI>
<LI>Built-in verification: this is a big deal.  You can code your design in MyHDL and run unit tests against it, all within pure Python. Execution is very fast, and the unit tests have all the power of a modern, "free", high-level language. (Europa has nothing like this.)</LI>
<LI>Verilog generation: the <b>toVerilog</b> method converts your design to Verilog.  (Right, well, without this feature, MyHDL would be useless.)</LI>
<LI>Co-simulation flow (via PLI).  I haven't used this yet, but it looks like a well-thought-out story for testing the generated Verilog against the same set of unit tests which were created during the pure-Python design phase.  If this works well, it sounds like an extremely useful feature.</LI>
<LI>Hierarchy.  It should be possible to create a complete, deeply hierarchical design composed of well-defined functional blocks, as I've been demonstrating in Europa.</LI>
<LI>Synthesizable subset: it's possible to create a design in MyHDL, and a body of unit tests, only to be informed (by <b>toVerilog</b>) that unsupported language features were used in the design. I don't know that the supported subset will grow as MyHDL is developed - the architecture may prevent this.</LI>
<LI>Flat Verilog: <b>toVerilog </b>delivers a single Verilog file with no hierarchy.  This is fine for small designs, but I foresee that this flat output structure will be inadequate for large, complex designs. Of course, you could verify an entire system in one step, then generate each system sub-module's Verilog file as a separate step, but then the top-level instance that stitches all the sub-modules together will not have been verified.</LI>
</UL>
<p>
<b>Simple example: switchable inverter</b>
<p>
I'll start off with the simplest imaginable example: a purely combinational module with one input and one output. The output is either the same as the input, or its logical inverse, according to a generation parameter.  Don't close your browser window - even this simple example demonstrates interesting facets of MyHDL.
<p>
Here's the implementation:
<p>
<pre>
from myhdl import always_comb
def inv_or_buf(mode, a, x):
  @always_comb
  def buffer():
    x.next = a

  @always_comb
  def inverter():
    x.next = not a

  if (mode == 0):
    logic = buffer
  else:
    logic = inverter
    
  return logic
</pre>
<p>
A few things to note:
<UL>
<LI><strong>inv_or_buf</strong> is a function which returns a locally-defined function (in this case, either <strong>buffer</strong> or <strong>inverter</strong>, depending on the generation parameter <strong>mode</strong>)</LI>
<LI>Regular python operators are used to model the logic (either python's <strong>not</strong> operator, or a simple assignment)</LI>
<LI>Suppose <strong>mode</strong> were used within a single local function to determine whether to buffer or invert the input? Then I'd have a 2-input combinational function, which may seem familiar - in fact, it's a 2-input XOR gate.  So, input parameters are either treated as HDL module ports or as generation-time parameters - which it is depends on how the parameters are used.</LI>
<LI>Two local functions are created, but only one is returned.  This is a MyHDL idiom for creating parameterized logic.  (Many thanks to reader Stefaan for his hints on this - It's alien enough to my usual way of thinking that I don't think I would have hit upon it.)   </LI>
<LI><strong>always_comb</strong> is a <em>decorator</em> on the locally-defined functions, which are <em>generator</em> functions.  For more info on these topics, you'll want to refer to the MyHDL and python documentation.
</UL>
<p>
Here's something that stands out for me about MyHDL: the low-level routines which define behavior are very simple, with not much more expressive power than the HDL they will eventually be transformed to.  If you want to define behavior which depends on a parameter, then for all but the simplest of behaviors, you must declare logic for all possible parameter values, and then conditionally return only the logic which corresponds to the particular parameterization.  There is a special case which allows for building ROM-like logic (anything where an output doesn't depend on inputs in an easily-computable way); fortunately, you can make any combinational logic function in ROM-like logic.  I rely on this in my implementation of the Avalon-ST error adapter, which I'll get to later.
<p>
<strong>Generating some Verilog</strong>
<p>
Here's some code to invoke <strong>inv_or_buf</strong>, and produce Verilog:
<p>
<pre>
from myhdl import toVerilog, Signal, intbv
from inv_or_buf import inv_or_buf

def make_some_verilog(mode, name):

  a = Signal(intbv(0)[1:])
  x = Signal(intbv(0)[1:])

  toVerilog.name = name
  toVerilog(inv_or_buf, mode, a, x)

make_some_verilog(0, "buffer")
make_some_verilog(1, "inverter")
</pre>
<p>
The resulting Verilog output shows up in two files:
<p>
<strong>buffer.v</strong>:
<p>
<pre>
module buffer (
    a,
    x
);

input [0:0] a;
output [0:0] x;
wire [0:0] x;

assign x = a;

endmodule
</pre>

<p>
<strong>inverter.v</strong>:
<p>
<pre>
module inverter (
    a,
    x
);

input [0:0] a;
output [0:0] x;
wire [0:0] x;

assign x = (!a);

endmodule
</pre>
<p>
The output is not the most readable code you've ever seen, but it does appear to be correct.
<p>
<strong>Leaving some for later</strong>
<p>
That's it for now.  I haven't touched on MyHDL unit testing, which is one of its major strengths - I'll leave that for a future article.
]]>
      
   </content>
</entry>
<entry>
   <title>vji_component</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/12/xvia_vji_component.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.48</id>
   
   <published>2007-12-24T18:17:17Z</published>
   <updated>2008-02-01T14:34:50Z</updated>
   
   <summary> To continue! I&apos;ve created a new component, vji_component. In the planned pulse measurement testbench, this component will be the bridge between the host system and the pulse generator logic. The general purpose of vji_component is to provide one or...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="XBox Remote Project" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
To continue!
<p>I've created a new component, <strong>vji_component</strong>.  In the planned pulse measurement testbench, this component will be the bridge between the host system and the pulse generator logic.  The general purpose of vji_component is to provide one or more host-accessible input or output signals, while hiding all the complexity of using the <strong>sld_virtual_instance</strong>.
<p>
For components I've written previously, I've provided a handful of test cases.  These test cases were simple: each one generates a particular instance of the component, and then compares the generated HDL against a "known good" reference HDL file.  One problem with this approach is that my "known good" files have not actually been verified for correct function.  Still, this method lets me proceed confidently with component changes which should not result in changed output.  
<strong>vji_component</strong> follows the same basic flow that I've established with previous components, but with one additional test feature: a system test.
<p>
In the system test, a vji_component instance is configured to have an input and output signal of width 24 (by default; the width is configurable).  The output signal wires to the input signal through inverters.  A tcl script drives random numbers into the writedata port, reads back the inverted signal on the readdata port, and verifies the value.  The block diagram shows what's going on (sorry about that "inv" block - my attempt at an ASCII inverter symbol ended in failure).
<p>
<img alt="vji_component_system_test_block.gif" src="http://www.antfarm.org/blog/aaronf/vji_component_system_test_block.gif" width="363" height="214" />
<p>
With this new system test, I'm taking the opportunity to create the entire system from as few source files as possible, under control of a Makefile. The system top-level is generated by a europa_module_factory-derived perl module and looks exactly like any other component. (I have come to realize that my use of the word "component" is not standard.  When I say "component" I just mean some logic with optional sub-instances.  Just about any HDL hierarchy is a "component", so maybe I need a different word.)
<p>
The test system source files are as follows:

<UL>
<LI>make_quartus_project.tcl: creates the quartus project, makes pin assignments, etc.</LI>
<LI>vji_test_system/vji_test_system.pm: perl module for the system "component".  One parameter is provided, "datawidth"</LI>
<LI>compile_quartus_project.tcl: compiles the project in quartus</LI>
<LI>test.tcl: functional test: a script to write, read and verify</LI>
<LI>Makefile: targets are:</LI>
<UL>
<LI>qp: call a tcl script to create the quartus project</LI>
<LI>hdl: create the HDL</LI>
<LI>sof: compile to bitstream (sof)</LI>
<LI>pgm: program the FPGA</LI>
<LI>test: test the system by writing, reading and verifying</LI>
<LI>clean: destroy the evidence</LI>
</UL>
</UL>
<p>
The upshot of all this: 5 source files encode the system and test scripts.  Typing "make" runs everything and reports any errors.
<p>
<a href="http://www.antfarm.org/blog/aaronf/vji_component_20071224.zip">Zip archive</a> of the vji_component and associated tests.]]>
      
   </content>
</entry>
<entry>
   <title>Pulse Measurement Testbench</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/11/xvi_pulse_measurement_testbenc_1.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.47</id>
   
   <published>2007-11-26T00:05:51Z</published>
   <updated>2008-02-01T14:34:36Z</updated>
   
   <summary> The heart of an IR receive circuit is the pulse measurement circuit. A single-bit signal goes in, and the length of each input pulse goes out. IR-protocol-specific logic to decode the actual data values being transmitted would work off...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="XBox Remote Project" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
The heart of an IR receive circuit is the pulse measurement circuit.  A single-bit signal goes in, and the length of each input pulse goes out.  IR-protocol-specific logic to decode the actual data values being transmitted would work off the sequence of length values coming out of the pulse measurement block.  The pulse-measurement circuit itself, though, is protocol-agnostic.
<p>
Now, I'm planning to build this pulse-measurement circuit (and later on, the follow-on data decode circuit) in firmware in the f2013.  I could drive pulses into the f2013 by aiming an IR remote control at the IR transceiver (as seen in <a href="http://www.antfarm.org/blog/aaronf/2007/07/viii_my_little_gp1ue267xk.html">VIII. My Little GP1UE267XK</a>) and pushing various buttons on the remote.  That sounds pretty annoying - I'd have to pick up and put down the remote all the time, in between typing, and the resulting pulses would vary in length according to factors beyond my control (as I documented in <a href="http://www.antfarm.org/blog/aaronf/2007/08/xiii_wwasd_1.html">XIII. WWASD?</a>).  
<p>
Here's a better idea: I'll build logic in the FPGA to generate precise, reproducible pulse sequences, under control of the host PC.  Without moving my hands from the keyboard, I'll download various pulse sequences to the hardware, which in turn will drive the device-under-test (f2013 firmware in active development).  If I equip the f2013 and testbench logic with a SPI-to-JTAG bridge (as seen in <a href="http://www.antfarm.org/blog/aaronf/2007/09/xiv_hello_world_1.html">XIV. Hello, world!</a>), then the f2013 can send its interpretation of the pulse sequence back to the host.  A script can compare the f2013's report with what was sent - so - a regression test system is possible.
<p>
Here's a top-level block diagram of the system:
<p>
<img alt="block.gif" src="http://www.antfarm.org/blog/aaronf/block.gif" width="451" height="108" />
<p>
You can see three basic sub-blocks:
<OL>
<LI><strong>VJI</strong>: A virtual-JTAG-interface which provides a FIFO-write interface ("source") and an additional signal, "go".</LI>
<LI><strong>Pulse Gen</strong>: The pulse generator proper.  The idea here is that the VJI writes a sequence of values into the pulse generator's internal FIFO (data rate limited by the JTAG interface), then asserts the "go" signal, which initiates processing on the FIFO data at top speed.  Data read from the internal FIFO specifies the level and pulse duration on the single-bit output, "out".</LI>
<LI><strong>f2013</strong>: The f2013 hardware/software block, which is the real device-under-test here, y'all. The f2013 will measure successive pulse durations and (at least for test purposes) transmit the pulse length values via SPI back to the host.</LI>
</OL>
<p>
Notice symmetry: the testbench in <a href="http://www.antfarm.org/blog/aaronf/2007/08/xii_gathering_the_xbox_dvd_rem.html">XII. Gathering the XBox DVD Remote Codes: Method</a> transformed sequences of pulses from the IR remote into sequences of pulse durations.  The new testbench will do the inverse transformation, durations to pulses. I have a big pile of labeled sample data which I collected during the IR remote protocol analysis; I can "play back" the samples to the f2013 firmware as I develop it.
<p>
Alright then.  For the implementation, I'll generate the entire FPGA system (quartus project, pinout declarations and HDL) via script, relying heavily on europa_module_factory.  The next step will be to flesh out the sub-sub-blocks within the <strong>VJI</strong> and <strong>Pulse Gen</strong> sub-blocks.


]]>
      
   </content>
</entry>
<entry>
   <title>avalon_st_error_adapter</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/11/xvg_avalon_st_error_adapter.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.46</id>
   
   <published>2007-11-15T05:09:55Z</published>
   <updated>2008-02-01T14:34:23Z</updated>
   
   <summary> An unexpected puzzle came up - a component which seems simple, but turns out to be rather annoying to implement. A good test case, I say. I&apos;ll make this quick and brief - the new component files are attached...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="Europa" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
An unexpected puzzle came up - a component which seems simple, but turns out to be rather annoying to implement.  A good test case, I say.  I'll make this quick and brief - the new component files are attached below if you want to dig deeper.
<p>
The component's Family/Genus/Species is Adapter/Avalon-ST adapter/Avalon-ST Error Adapter.
<p>
<strong>Adapter</strong><p>
An adapter, generally speaking, is a simple component which is inserted in between a pair of components of a particular type, to accomplish some sort of conversion.  A typical example is the  data-width adapter (to allow connection of, say, an Avalon-MM master and slave, or an Avalon-ST source and sink, which happen to have different data widths).  A good adapter is fairly simple, does only one thing, and is completely parameterized according to information from the interfaces it connects to. 
<p>
<strong>Avalon-ST Adapter</strong><p>
Adapters of this description are tailored to the particular set of signals supported by Avalon-ST. These adapters understand the specific direction of Avalon-ST signals (e.g. the "data" signal is an output from a source, and an input to a sink; the "ready" signal is an input to a source, and an output from a sink).
<p>
<strong>Avalon-ST Error Adapter</strong><p>
This adapter does straight-through wiring on all Avalon-ST signals except for one, the "error" signal.  All signals other than "error" are required to have the same bit width on both the source and sink which the adapter is connects to.  And that's where the regularity ends: the "error" signal is wonderfully free to vary.  The source may have no error signal, or a multiple-bit one; likewise on the sink.  With mismatched widths, how can the adapter do its job?  Well, one more thing about the error signal: each individual bit of the error signal has a "type", which is an arbitrary string, or the special string "other".  Given a "type map" for all the source and sink error bits, there are some simple rules for error signal adaptation:
<p>
<OL>
<LI>Like-type error bits are directly connected</LI>
<LI>If the sink has an error bit of type "other", it's driven by the logical OR of any as-yet unconnected source error bits (type "other" or otherwise).</LI>
<LI>If any undriven sink error bits remain, they are driven with 0.</LI>
<LI>Any remaining unconnected source error bits are ignored.</LI>
</OL>
<p>
<strong>Huzzah, a new base class</strong><p>
Since any Avalon-ST adapter will have a mess of same-width signals which wire straight through, and then maybe one signal which needs some special treatment, it makes sense to derive a base class (avalon_st_adapter) from europa_module_factory, from which all Avalon-ST adapters will further derive.  This base class calls into a derived class method for doing any special signal handling, then does straight-through wiring on any remaining (non-special) signals.  The derived class is concerned only with doing its special job on its special signal(s), and managing any options relevant to the special signal(s).
<p>
<strong>Command-line args - limited to simple numerals and strings thus far</strong><p>
But that's far too limiting.  Here's why: avalon_st_adapter is a component in its own right, though really a silly one.  Its generation parameters are a set of signal descriptions (name, width and type) on its "in" (driven by the source) and "out" (driving the sink) interfaces.  It's natural to think of these input parameters as a simple pair of hashes, keyed on signal type.  But I want to retain the guideline of pure command-line specification of parameters.  I could encode those hashes as comma-separated lists of things, to be massaged and processed by a script into proper perl data structures, but that seems like a lot of work.  What to do?  No problem, I simply pass my hashes in perl syntax on the command line, appropriately escaped, and "eval" does the parsing for me.  Validation of these non-scalar fields presents a bit of a nuisance, but nothing that can't be dealt with.  For now, I simply validate against the field "type" (HASH, ARRAY, CODE, undef-for-scalar), but nothing stops me from (in the future) defining nested parameter data structures which encode the same sorts of value sets and ranges that I already use for scalar parameters.
<p>
To the basic set of port declarations which form avalon_st_adapter's generation parameters, avalon_st_error_adapter adds two more hashes, in which the "in" and "out" interface error bit types are described.
<p>
<strong>Testing, testing...</strong><p>
Once I had the basic avalon_st_adapter class working, and a skeleton implementation of avalon_st_error_adapter, I found myself doing lots of exploratory refactoring.  I worried that I'd break the functionality, which I was happy with.  Solution: unit tests.  In my case, this means, for each component, a handful of test-case scripts, each of which produces an HDL module, and a top-level test script, "test.sh".  After making a change, I run ". test.sh", which runs all the test cases and diffs the output HDL against a set of "known-good" files in a subdirectory.  Occasionally, a change is made which does change the output HDL, and for those cases, I carefully examine the new and old files to convince myself that the new HDL file can replace the old known-good one (or note that I've created a new bug, and fix it).
<p>
<strong>Avalon-ST signal type "error": wonderfully free form</strong><p>
Actually, this is rather an annoying adapter, due to the unconstrained nature of the "error" signal.  You'll note that all of the nuisance is concentrated in avalon_st_error_adapter::make_special_assignments().
<p>
<strong>HDL comments</strong><p>
I went a bit out of my way to produce comments on the adapter assignments, to label the signals and error bit types.  Here's a nice ascii block diagram of error adapter test case "3":
<p>
<img alt="avalon_st_error_adapter3.gif" src="http://www.antfarm.org/blog/aaronf/avalon_st_error_adapter3.gif" width="482" height="148" />
<p>
... and here's a snippet of of test case 3's HDL implementation, showing handy assignment comments:<p>
<img alt="avalon_st_error_adapter3.v.gif" src="http://www.antfarm.org/blog/aaronf/avalon_st_error_adapter3.v.gif" width="287" height="248" />
<p>
That's it for now. For all my most ardent fans, I'm attaching the new avalon_st_adapter and avalon_st_error_adapter components, along with their test scripts and known-good HDL files.  I'm also including the latest version of europa_module_factory, which changed slightly to support the new command-line processing.
<p>
<a href="http://www.antfarm.org/blog/aaronf/components20071114.zip">components20071114.zip</a>

]]>
      
   </content>
</entry>
<entry>
   <title>europa_module_factory unveiled</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/11/xvf_europa_module_factory_unve_2.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.45</id>
   
   <published>2007-11-08T06:05:40Z</published>
   <updated>2008-02-01T14:34:08Z</updated>
   
   <summary> Some results. I&apos;ve been working up a new framework for authoring HDL modules in Europa, using a simple example component (SPI Slave) as an anchoring point. To present the results, I&apos;ll first do a top-down traversal, then dig a...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="Europa" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
Some results.  I've been working up a new framework for authoring HDL modules in Europa, using a simple example component (SPI Slave) as an anchoring point.  To present the results, I'll first do a top-down traversal, then dig a bit into the details.<p>
<strong>From the top</strong><p>
From the user's point of view, the top level is a simple script, "mk.pl",  which invokes the top-level package.  This script is not truly a part of the architecture, but it's an easy place to start.  Here's the basic call-and-response, at your friendly neighborhood cygwin shell:
<p>
<pre>
<font color="BLUE">[SOPC Builder]$ perl -I common mk.pl</font>

<font color="RED">mk.pl:
Missing required parameter 'component'
Missing required parameter 'top'
Missing required parameter 'name'

Usage:
mk.pl [--help]
(Print this help message)

mk.pl --component=&lt;component name&gt; \
        --top=&lt;top level module&gt; \
        --help
(Print sub-package-specific (component::top) help)

mk.pl --component=&lt;component name&gt; \
        --top=&lt;top level module&gt; \
        --name=&lt;top level module name&gt; \
        &lt;component-specific options&gt;
(Create a module of type component::top, with the given name
and options)</font>
</pre>
<p>
A few notes here:
<UL>
<LI>"common" is a subdirectory where I've stashed infrastructure perl modules:
<UL>
<LI><strong>europa_module_factory.pm</strong>: All HDL-module-producing packages derive from this base class. </LI>
<LI><strong>component_utils.pm</strong>: You always need one of these.  Today it just contains a routine for command-line processing.  I expect to throw more stuff in here later.</LI>
</UL></LI>
<LI>"component" is the overall name of a component (in my example, "spi_slave").  All perl packages for a component are installed in a directory named the same as the component (directory "spi_slave"); all packages are one level down in the hierarchy from the component name (e.g. perl package "spi_slave::control", or "spi_slave/control.pm" in the file system).</LI>
<LI>"top" is the package to invoke as the component top-level.  Any sub-package within a component is suitable for top-level invocation, which is handy during development.  During ordinary use, there may be several sub-packages which are invoked as the top level.</LI>
</UL>
<p>
<strong>sub-package-specific help</strong><p>
Here's something cool: component sub-packages must declare their required fields and valid values for those fields.  Wouldn't it be handy if sub-package-specific help text were built from that same set of declared required fields?  Yes, very handy. Example:
<pre>
<font color="BLUE">[SOPC Builder]$ perl -I common mk.pl --component=spi_slave \
> --top=spi_slave_mm --help</font>

<font color="RED">Allowed fields in package 'spi_slave::spi_slave_mm':
datawidth:
        Data width
        range: [1 .. maxint]
lsbfirst:
        data direction (0: msb first; 1: lsb first)
        range: [0 .. 1]</font>
</pre>
<p>
(By the way, sub-package "spi_slave_mm" is one of the expected top-level packages - it's the SPI Slave component with an Avalon-MM flowcontrol interface.)
<p>
How about some help for a less top-level sub-package?
<p>
<pre>
<font color="BLUE">[SOPC Builder]$ perl -I common mk.pl --component=spi_slave \
> --top=fifo --help</font>

<font color="RED">Allowed fields in package 'spi_slave::fifo':
datawidth:
        range: [1 .. maxint]
depth:
        allowed values: 1</font>
</pre>
<p>
You can see that this help is less verbose - that's simply because sub-package "fifo" didn't happen to provide descriptions for its fields.
<p>
<strong>Building an SPI Slave</strong><p>
Help text is swell, but what does a successful component build look like?  A few more -I includes are required; a Makefile helps keep things tidy:
<p>
<pre>
<font color="BLUE">[SOPC Builder]$ make
perl \
  -I $QUARTUS_ROOTDIR/sopc_builder/bin \
  -I $QUARTUS_ROOTDIR/sopc_builder/bin/europa \
  -I $QUARTUS_ROOTDIR/sopc_builder/bin/perl_lib \
  -I ./common \
  mk.pl \
          --component=spi_slave \
          --top=spi_slave_mm \
          --name=spi_0 \
          --target_dir=. \
          --lsbfirst=0 --datawidth=8</font>
</pre>
<p>
I've set a name for the top-level HDL file (spi_0), and specified a target directory in which to generate.  Parameters "lsbfirst" and "datawidth" are passed along to the chosen subpackage, "spi_slave::spi_slave_mm".
<p>
<strong>Generator Innards</strong><p>
The basic inner loop of a generator sub-package looks something like this:
<pre>
# construct an instance of a sub-package module-factory, for example:
my $tx = spi_slave::tx->new({
  lsbfirst => 0,
  datawidth => 13,
});
# ask the module-factory for an HDL instance, and it to the module: 
$module->add_contents(
  $tx->make_instance({
    name => "the_tx",
  }),
);
</pre>
<p>
Besides factory-generated instances, the sub-package will add simple logic of its own to the module.
<p>
<strong>SPI Slave Results</strong><p>
The new SPI Slave component occupies 32 LEs in my example system (tb_8a), and functions just as the old SPI component did (the old component occupied 40 LEs).  The new component is heavily modularized; individual module tend to be very simple.  The module hierarchy of the component is in 3 levels:

<UL>
  <LI><strong>spi_slave_mm</strong></LI>
  <UL>
    <LI><strong>spi_slave_st</strong></LI>
    <UL>
      <LI><strong>av_st_source</strong></LI>
      <LI><strong>av_st_sink</strong></LI>
      <LI><strong>control</strong></LI>
      <LI><strong>fifo (rx_fifo)</strong></LI>
      <LI><strong>fifo (tx_fifo)</strong></LI>
      <LI><strong>sync</strong></LI>
      <LI><strong>rx</strong></LI>
      <LI><strong>tx</strong></LI>
    </UL>
  </UL>
</UL>
<p>
The simplicity of this component hides some of the power of the europa_module_factory architecture.  It turns out that only a single factory instance is created by each sub-package of the SPI Slave, and in only one case (sub-package "fifo") does an factory deliver more than one HDL instance; in general, though, a single sub-package will create multiple factory instances, which in turn will deliver multiple HDL instances.
<p>
By the way, that middle level, <strong>spi_slave_st</strong>, is a perfectly viable top-level component all on its own, assuming you'd like an Avalon-ST sink and source, rather than an Avalon-MM slave with flow control.  This highlights what I believe is a major feature of the architecture: hierarchy comes "for free".  Any perl package (and likewise, HDL module) can be instantiated within another.  The way is clear to create deeply-nested design hierarchies composed of reusable blocks.  It's also possible to build complete systems of components and interconnect, all within a single running perl process.  But possibly the most common use of hierarchy will be to add a small amount of functionality to an existing component, by wrapping that component in another layer.
<p>
<a href="http://www.antfarm.org/blog/aaronf/components.zip">Here's</a> an archive of the component factory modules, spi slave modules and Makefile/build script.]]>
      
   </content>
</entry>
<entry>
   <title>Ground Rules</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/10/xve_ground_rules.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.43</id>
   
   <published>2007-10-06T20:21:18Z</published>
   <updated>2008-02-01T14:33:52Z</updated>
   
   <summary> Some rules! So, I&apos;ll be writing perl scripts which will generate HDL for me. Perl is wonderfully flexible, which means there are an unwonderfully infinite numbers of ways to proceed from here. Let&apos;s see if I can trim down...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="Europa" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
<strong>Some rules!</strong>
<p>
So, I'll be writing perl scripts which will generate HDL for me.  Perl is wonderfully flexible, which means there are an unwonderfully infinite numbers of ways to proceed from here.  Let's see if I can trim down the possibilities a bit with some goals...
<UL>
<LI>Goal: components are generated from the command line by a top-level script, "mk.pl"</LI>
<LI>Goal: any point in the HDL hierarchy is a valid entry point for generation, so that sub-trees of the HDL hierarchy can be generated in isolation</LI>
</UL>
<p>
... and guidelines:
<p>
<UL>
<LI>Guideline: make one top-level perl package per component</LI>
<LI>Guideline: the top-level perl package creates the top-level module.  HDL submodules are created by subpackages. All packages define and manage their particular HDL module (or family of closely-related modules) and deliver instances of modules</LI>
<LI>Guideline: sub-package API should be the same as top-level package API, so that submodules can be generated in isolation</LI>
<LI>Guideline: hide as much Europa or other clutter away in base classes; as much as possible, perl modules should consist primarily of code related to their own modules and any sub-instances</LI>
</UL>
<p>
<strong>... but I don't mean...</strong>
<p>
It might sound like I'm saying that the perl package hierarchy should reflect the HDL hierarchy.  Not so; in fact, this is not possible in general.  To understand why, consider the fact that instances of a particular module may appear at various places within the HDL hierarchy.  I'll just place all of my subpackages one level down from the top-level package in the package hierarchy; in the file system, package <code>foo</code> (foo.pm) and subpackage <code>foo::bar</code> (bar.pm) will reside in subdirectory <code>foo</code>.
<p>
<strong>I expect a payoff!</strong>
<p>
Related note: why bother with all these subpackages?  I see these potential payoffs for the added complexity:
<UL>
<LI>Code reuse.  Occasionally, a sub-entity (package/module) of general utility will appear.  This sub-entity can be promoted to a common repository, where it can be shared among all components</LI>
<LI>Separate name-spaces.  An immediate payoff here: every package, top-level or sub-level, implements the same API for delivering modules and instances.</LI>
</UL>
<p>
<strong>With sadness, a confession</strong>
<p>
For my Europa-generated modules, I would like to think in terms of two possible forms of parametrization:
<p>
<OL>
<LI>Generation-time parameters: these parameters modulate the form of the HDL module definition. Each differently-parametrized module is defined as a separate HDL module.  There is no limit to the degree of parametrization available, so the challenge is to keep parametrization scope within reasonable bounds.  (If a parameter's value results in radically different HDL, it probably makes sense to split into multi subpackages, perhaps sharing a common utility library.)</LI>
<LI>Instantiation-time parameters: HDL parameters are declared within a module, with a default value; each instance of the module can override the parameter value.  This form of parametrization is limited to very simple features, such as port width.  It's probably a good idea to use this form when possible, to reduce the total number of modules and improve human readability.</LI>
</OL>
<p>
The two types of parametrization are orthogonal: a module may have no parametrization, generation-time parametrization only, instantiation-time parametrization only, or both types of parametrization.  
<p>
Unfortunately, Europa (as it stands today) does not handle instance-time parametrization very well.  In particular, the most obviously-useful form of instance-time parameterization, parameterizable port widths, is not supported.  So, I'm forced to fall back upon generation-time parametrization even for simple port width parameters.
<p>
<strong>So what does it look like?</strong>
<p>
The nucleus of the implementation is a perl package, <code>europa_module_factory</code>, which defines the base class.  Subclasses of europa_module_factory are responsible for producing families of modules grouped by generation-time parametrization.  Each subclass implements the following methods:
<OL>
<LI><strong>get_fields</strong>: a static method which returns a data structure listing the module's generation options and their legal values.  Values are verified against the specified legal range in the  (autoloaded) setter methods in the base class. (I expect to add a few more validation types beyond the initial offering, "range".  <em>List of allowed values</em> and <em>code reference</em> are natural candidates).</LI>
<LI><strong>add_contents_to_module</strong>: the real meat of the generator: adds all the logic that implements the module's function.</LI>
</OL>
<p>
This is sounding much more abstract than it actually is, so it's time for a simple example.  The sub-block of the SPI slave, "rx", is a simple shift register with serial input, parallel output and a couple of control signals.  There are two generation options, "lsbfirst" and "datawidth".  Here's its perl module, rx.pm:
<p>
<pre>
<font color="blue">
package spi_slave::rx;
use europa_module_factory;
@ISA = qw(europa_module_factory);

use strict;

sub add_contents_to_module
{
  my $this = shift;
  my $module = $this->module();

  my $dw = $this->datawidth();

  $module->add_contents(
    e_register->new({
      out => "rxbit",
      in => "sync_MOSI",
      enable => "sample",
    }),
  );

  my $rxshift_expression;
  if ($this->lsbfirst())
  {
    my $msb = $dw - 1;
    $rxshift_expression = "{rxbit, rxshift[$msb : 1]}";
  }
  else
  {
    my $msb2 = $dw - 2;
    $rxshift_expression = "{rxshift[$msb2 : 0], rxbit}";
  }

  $module->add_contents(
    e_register->new({
      out => {name => "rxshift", width => $dw, export => 1,},
      in => $rxshift_expression,
      enable => "shift",
    }),
  );
}

sub get_fields
{
  my $class = shift;

  my %fields = (
    datawidth => {range => [1, undef]},
    lsbfirst => {range => [0, 1]},
  );

  return \%fields;
}

1;
</font>
</pre>
<p>
How to invoke that perl module?  A simple Makefile and top-level generation script (mk.pl) handle the grunt work.  The command line is:
<p>
<pre>
<font color="blue">
make COMPONENT=spi_slave FACTORY=rx NAME=rx_0 \
  OPTIONS="--lsbfirst=1 --datawidth=8"
</font>
</pre>
<p>
And the resulting HDL (with a bit of boilerplate removed) is:
<p>
<pre>
<font color="blue">
//Module class: spi_slave::rx
//Module options:
//datawidth: 8
//lsbfirst: 1
//name: rx_0

module rx_0 (
              // inputs:
               clk,
               reset_n,
               sample,
               shift,
               sync_MOSI,

              // outputs:
               rxshift
            )
;
  output  [  7: 0] rxshift;
  input            clk;
  input            reset_n;
  input            sample;
  input            shift;
  input            sync_MOSI;
  reg              rxbit;
  reg     [  7: 0] rxshift;
  always @(posedge clk or negedge reset_n)
    begin
      if (reset_n == 0)
          rxbit <= 0;
      else if (sample)
          rxbit <= sync_MOSI;
    end

  always @(posedge clk or negedge reset_n)
    begin
      if (reset_n == 0)
          rxshift <= 0;
      else if (shift)
          rxshift <= {rxbit, rxshift[7 : 1]};
    end
endmodule
</font>
</pre>
<p>
A nearly-identical invocation generates the SPI component top-level:
<p>
<pre>
<font color="blue">
make COMPONENT=spi_slave FACTORY=spi_slave NAME=spi_0 \
  OPTIONS="--lsbfirst=1 --datawidth=8"
</font>
</pre>
<p>
<strong>Save some for later</strong>
<p>
Thoughts for future work:
<UL>
<LI>
The perl modules I've produced form a thin, porous layer on top of the europa library.  "Thin", because they don't provide a lot of complex functionality; "porous", because clients of my perl modules still work with europa objects (e_project, e_module, e_register, e_assign, et al ) directly.  It might be worthwhile to try to make an opaque layer on top of europa, for simplicity and possible future reimplementation of the underlying europa code.</LI>
<LI>I have a framework for generated-module-specific validation, with the module options as input.  This is good and useful, as it guards against bogus input at the earliest possible time.  I'd like to think about how to guard against bogus output (basic sanity tests on the instantiated logic), as well.  For example, a module could declare (in some way) its expected input and output ports, and after contents are added, the module could be tested against the expectation.  Or, the generated HDL could be parsed by some external tool, from within the generator - this would probably need to be a default-off option, in the interest of speedy generation time.</LI>
<LI>I need to think more carefully about module names.  In the current implementation, if multiple instances of the spi_slave component are created, each will have its own (not-necessarily-identical) module called "spi_slave_fifo".  One way out of this is to decorate module names with the (unique) name of the top-level instance; this can lead to multiple module declarations identical except for name, but it may be the only practical solution.</LI>
</UL>
<p>
For the curious, I attach the <a href="http://www.antfarm.org/blog/aaronf/spi_slave_20071019.zip">complete set of files</a> for the spi_slave and underlying europa_module_factory, as of this moment.  The SPI slave is not yet complete, but has a top-level module and two sub-modules for illustration.
<p>

]]>
      
   </content>
</entry>
<entry>
   <title>A Little Chat about Verilog &amp; Europa</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/10/xvd_a_little_chat_about_verilo_1.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.42</id>
   
   <published>2007-10-04T04:44:03Z</published>
   <updated>2008-02-01T14:33:38Z</updated>
   
   <summary> Say, what&apos;s in my FPGA? Just a sea of configurable wires, registers, and logic. Without a configuration bitstream, the FPGA does nothing (well, it eagerly awaits a bitstream. It does almost nothing.) How do I create that bitstream? Assuming...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="Europa" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
Say, what's in my FPGA?  Just a sea of configurable wires, registers, and logic.  Without a configuration bitstream, the FPGA does nothing (well, it eagerly awaits a bitstream.  It does <em>almost</em> nothing.)   How do I create that bitstream?  Assuming I have some digital logic function in mind, I have only to translate my design intent into one of a handful of gratuitously cryptic hardware-description "languages" and throw it in Quartus' lap.  Among my choices are: 
<UL>
<LI>block diagrams full of little schematic symbols</LI>
<LI>Verilog</LI>
<LI>VHDL</LI>
<LI>an Altera-created hardware description called <a href="http://en.wikipedia.org/wiki/AHDL">AHDL</a></LI>
</UL>
<p>
But I eschew all that for a different Altera creation: a collection of perl modules called Europa.
<p>
First, the history.  Long ago, some clever engineers needed to wire a little soft-core CPU to its UART, onchip memory, PIOs and other peripherals.  They could have just banged out a Verilog description of the interconnections and called it a day, but that was too easy. Also, what if someone wanted eleven UARTs?  What if they somehow thought VHDL was better?  Then what?  Clearly, automatic generation of the interconnect bus was indicated, and while we're at it, go ahead and generate the HDL for the UART and PIO as well. What better language in which to write a generator program than Perl?  Case closed.
<p>Time for a simple example. 
Consider the following logic, displayed in a format which still, for me, resonates deeply:
<p>
<img alt="simple_circuit.gif" src="http://www.antfarm.org/blog/aaronf/simple_circuit.gif" width="440" height="165" />

<p>
(I hope the notation is clear: the diagram shows a module named <strong>simple</strong>, which has some inputs, an OR gate, a D-flip-flop, and an output.)
<p>
Module <strong>simple</strong> translates fairly readily to Verilog:
<p>
<pre>
<font color="BLUE">module</font> simple(
  clk,
  reset_n,
  a,
  b,
  x
);
  <font color="BLUE">input</font> clk;
  <font color="BLUE">input</font> reset_n;
  <font color="BLUE">input</font> a;
  <font color="BLUE">input</font> b;
  <font color="BLUE">output</font> x;

  <font color="BLUE">wire</font> tmp;
  <font color="BLUE">assign</font> tmp = a | b;
  <font color="BLUE">reg</font> x;

  <font color="BLUE">always</font> @(<font color="BLUE">posedge</font> clk <font color="BLUE">or</font> <font color="BLUE">negedge</font> reset_n)
    <font color="BLUE">if</font> (~reset_n) x <= 1'b0;
    <font color="BLUE">else</font> x <= tmp;

<font color="BLUE">endmodule</font>
</pre>
<p>
Even in this extremely simple example, you can see Verilog's flaws.  The module's inputs and output are listed twice: once in the module port list and again as input and output declarations within the module.  A different sort of redundancy exists between a given signal's direction (as input, output or neither - internal) and its role in the described logic (signal with no source, signal with no sink or signal with both source and sink).  Here's the Europa equivalent of the above Verilog, which solves those problems:
<p>
<pre>
<font color="blue">use</font> europa_all;

<font color="blue">my</font> <font color="cyan">$project</font> = e_project-><font color="blue">new</font>({
  <font color="brown">do_write_ptf</font> => <font color="brown">0</font>,
});

<font color="blue">my</font> <font color="cyan">$module</font> = e_module-><font color="blue">new</font>({<font color="brown">name</font> => <font color="brown">"simple"</font>});
<font color="cyan">$module</font>->add_contents(
  e_assign-><font color="blue">new</font>({
    <font color="brown">lhs</font> => <font color="brown">"tmp"</font>,
    <font color="brown">rhs</font> => <font color="brown">"a | b"</font>,
  }),
  e_register-><font color="blue">new</font>({
    <font color="brown">out</font> => <font color="brown">"x"</font>,
    <font color="brown">in</font> => <font color="brown">"tmp"</font>,
    <font color="brown">enable</font> => <font color="brown">"1'b1"</font>,
  }),
);

<font color="cyan">$project</font>-><font color="blue">top</font>(<font color="cyan">$module</font>);
<font color="cyan">$project</font>->output();
</pre>
<p>
The benefits are clear:
<UL>
<LI>redundancy is eliminated</LI>
<LI>Perl is a real programming language, and fun besides</LI>
<LI>Even in this simple example, fewer bytes/keystrokes are required to encode the design</LI>
<LI>I didn't show it here, but VHDL output is available (controlled by an e_project setting)</LI>
</UL>
<p>
So there you have it.  I can merrily go off and build my SPI slave component in Europa, and generate to the HDL of my choice.  Great!
<p>
However! I couldn't very well count myself among the top 1 billion software architects on the planet if I just went off and coded my component as pages and pages of formless Perl/Europa.  No, no, no.  I must first make class hierarchy diagrams, invent some directory structure guidelines, and worry about names of API methods.  That's the key to success in this business.

<p>
<em>Side-note/tangent/rant: there is an alternate Verilog style for coding combinational logic which would prefer the following for the <strong>tmp</strong> assignment:</em>
<p>
<pre>
  <font color="BLUE">reg</font> tmp;
  <font color="BLUE">always</font> @(a <font color="BLUE">or</font> b)
    tmp = a | b;
</pre>
<p>
<em>I think most programmers would report a long list of flaws in this style.  For myself, I find that:
<UL>
<LI>It doesn't do what it says: tmp is declared as a "reg", but is purely combinational</LI>
<LI>It's redundant: inputs to the expression must be declared in the "sensitivity list" (a <font color="BLUE">or</font> b), and appear again in the actual assignment (tmp = a | b)</LI>
<LI>It's too big: the superfluous 'always' block consumes more screen area, and requires more typing</LI>
<LI>It reveres historical baggage: Verilog began life as a simulation language; the construct above appears to be informed by that history, to the detriment of the goal at hand (to concisely define digital logic on a programmable chip)</LI>
</UL>
<p>
That said, I admit (to my astonishment) that the above is a preferred coding style in the industry.
Not a problem: in the end, the precise style of Verilog coding is irrelevant, because (in my so-humble opinion), if you're coding in Verilog, you've already made the wrong choice.  So let's not fight this fight: we can leave Verilog style issues to the language lawyers, the guardians of legacy code bases, and those evil-doers with a vested interest in seeing that HDL coding remains a black art.</em>

]]>
      
   </content>
</entry>
<entry>
   <title>Block Diagrams?  Well, Block Descriptions.</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/09/xvc_block_diagrams_well_block_1.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.41</id>
   
   <published>2007-09-30T19:03:19Z</published>
   <updated>2008-02-01T14:33:22Z</updated>
   
   <summary>I don&apos;t have a usable block diagram editor. I tried Microsoft Paint, but it&apos;s too bitmap-oriented. I have used Quartus successfully for simple diagrams, but it&apos;s not very flexible. I think I achieved the limit of the ASCII block diagrams...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="Europa" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<em>I don't have a usable block diagram editor.  I tried Microsoft Paint, but it's too bitmap-oriented.  I have used Quartus successfully for simple diagrams, but it's not very flexible.  I think I achieved the limit of the ASCII  block diagrams <a href="http://www.antfarm.org/blog/aaronf/2007/09/xiv_hello_world_1.html">a while back</a>.  So, for now, I'll describe my blocks in words.  If anyone has a suggestion for a free and decent block diagram editor, please let me know!</em>
<p>
Here are the sub-blocks of the SPI Slave implementation, which will map directly to HDL modules:
<p>
<UL>
<LI><strong>sync</strong>: this block synchronizes the SPI input signals to the system clock domain.  Nothing fancy here; just the traditional chain of 2 flip flops, which I use as a magic talisman to ward off <a href="http://en.wikipedia.org/wiki/Metastability_in_electronics">metastability</a>.</LI>
<LI><strong>sequencer</strong>: From the synchronized <strong>SCLK</strong> signal (<strong>sync_SCLK</strong>), this block produces two active-high event triggers:
<OL>
<LI><strong>shift</strong>: enable a shift on the outgoing data shift register</LI>
<LI><strong>sample</strong>: enable a sample of the incoming data</LI>
</OL>
(If I wanted to create a CPOL- and CPHA-configurable slave, this block is the only one that would change.)
</LI>
<LI><strong>bit_counter: </strong>for a n-bit SPI slave, this block counts from 0 to n-1, incrementing once for each <strong>shift</strong>.  Its outputs control some FIFOs (see below). Inactive level (high) on <strong>SS_n</strong> resets this counter to 0.</LI>
<LI><strong>rx</strong>: <strong>MOSI</strong> feeds an n-bit shift-register chain, enabled by <strong>shift</strong>.</LI>
<LI><strong>rx_fifo</strong>: A basic FIFO with clk, write, writedata, read, readdata, full and empty signals.  When not empty, readdata is valid. For this FIFO, writedata is the rx shift-register chain. For now, this FIFO has a single storage element - call it a receive holding register, if you like. In the future, more FIFO locations may be useful; if so, this block's interface need not change.</LI>
<LI><strong>av_st_source</strong>: input is the rx_fifo outputs; output is a standard set of signals implementing an Avalon ST source.  This block is just wires.</LI>
<LI><strong>tx</strong>: a parallel-loadable shift register.  The shift-register output drives <strong>MISO</strong> directly.</LI>
<LI><strong>tx_fifo</strong>: Another FIFO.  This one drives the parallel-load input on <strong>tx</strong>, and accepts data from the Avalon-ST sink or Avalon-MM interface.</LI>
<LI><strong>av_st_sink</strong>: another just-wires block.  Avalon-ST is pretty much designed to bolt up directly to FIFOs, and this one connects to <strong>tx_fifo</strong>.</LI>
<LI><strong>av_mm_slave</strong>: this optional block funnels the Avalon-ST interfaces into a single Avalon-MM slave interface with flow control (<strong>readyfordata</strong>, <strong>dataavailable</strong>).  It'll take some careful thought to avoid deadlock on this interface.  The lock-step full-duplex nature of SPI will be a key factor in this.</LI>
</UL>
<p>
That seems like a lot of blocks!  Fortunately, though, most of them are very very simple.
<p>
Next, I'll get to dig into the implementation.  I'll probably need to say some introductory words about Europa, first.
<p>
<em>A Note on Clock-Domain Crossing</em>
<p>
<em>
I've made the choice to synchronize the SPI input signals as they enter the FPGA; all logic in the SPI slave will be in the system clock domain.  Delaying the SPI signals like this implies an upper bound on the SCLK frequency, relative to the system clock rate (I think the max SCLK will be something like 1/4 the system clock frequency).  There is another option: SCLK could drive a subsection of the SPI slave, all the way from serial input to parallel output.  The parallel output would connect to proper clock-crossing FIFOs.  This solution would be more complex, but should be able to run at a higher clk/SCLK ratio.   I won't implement this solution for now, but it's worth keeping in mind if higher bandwidth is needed.
</em>]]>
      
   </content>
</entry>
<entry>
   <title>A Flash of Inspiration: Useless Features are Bad</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/09/xvb_a_flash_of_inspiration_use.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.40</id>
   
   <published>2007-09-29T19:49:18Z</published>
   <updated>2008-02-01T14:33:08Z</updated>
   
   <summary> The Altera-provided SPI slave component is configurable in several ways: Data format: MSB-first or LSB-first Data width: 1 to 16 bits Clock polarity (CPOL): non-inverted or inverted Clock phase (CPHA): leading or trailing edge sample (The data-related stuff is...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="Europa" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
The Altera-provided SPI slave component is configurable in several ways:
<UL>
<LI>Data format: MSB-first or LSB-first</LI>
<LI>Data width: 1 to 16 bits</LI>
<LI>Clock polarity (CPOL): non-inverted or inverted</LI>
<LI>Clock phase (CPHA): leading or trailing edge sample</LI>
</UL>
<p>
(The data-related stuff is obvious; see <a href="http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus">Wikipedia</a> for a decent explanation of CPOL and CPHA.)
<p>
I see a way to make my task easier: drop configurable CPOL and CPHA. That sort of configurability in an SPI slave is a useless feature, and I can prove it.  First, consider this fact: most existing SPI slaves lack CPHA and CPOL configurability. (Imagine a cheap SPI-equipped ADC chip.  If it were configurable, how would you configure it?  By tying pins high or low?  Too expensive.  By init-time communication via secret codes from the SPI master?  Well, I'm sure you see the problem with that idea.)  Because there are exist non-configurable SPI slaves, SPI masters (like the one in the f20123) must pick up the slack and provide variable CPHA and CPOL.  There's no value in making both ends of the link configurable, so I'll drop that bit of needless complexity and choose CPOL=0, CPHA=0 for my new SPI slave.
<p>
That's a relief.  Fewer features means less complexity, fewer bugs, easier testing.  So, what features do I deem useful enough to implement?
<UL>
<LI>Data width: 1 up to some huge number, why not.</LI>
<LI>MSB-first or LSB-first data</LI>
<LI>Proper operation if SS_n is tied low (in other words, don't rely on SS_n falling or rising edges). But do resynchronize on inactive SS_n, if it occurs.</LI>
<LI>Double-buffered transmit and receive registers</LI>
<LI>Avalon-ST source and sink interfaces, or Avalon-MM slave interface with flow control</LI>
<LI>Verilog or VHDL implementation, which must be at least barely human-readable</LI> 
</UL>
<p>
That'll do.  Next time: some block diagrams.
]]>
      
   </content>
</entry>
<entry>
   <title>SPI Makeover: Mission Statement</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/09/xva_spi_makeover_mission_state_1.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.39</id>
   
   <published>2007-09-28T02:10:24Z</published>
   <updated>2008-02-01T14:32:54Z</updated>
   
   <summary> Time for another distracting tangent. The tb_8 system consists of: a JTAG UART (104 LEs) my little custom byte-pipe (9 LEs) an 8-bit SPI slave (40 LEs) The first two components are beyond reproach: the JTAG UART because I...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="Europa" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
Time for another distracting tangent.  The tb_8 system consists of:
<OL>
<LI>a JTAG UART (104 LEs)</LI>
<LI>my little custom byte-pipe (9 LEs)</LI>
<LI>an 8-bit SPI slave (40 LEs)</LI>
</OL>
<p>
The first two components are beyond reproach: the JTAG UART because I have no idea how it works, but it works, and my little byte-pipe because it's so cute and tiny. 
<p>
But the SPI slave; that's another matter.  My feeling upon reading the HDL implementation, <strong>spi.v</strong>, is that its designer was not only criminally incompetent, but also completely disinterested in producing legible code.  And maybe 40 LEs is not so much, but I believe I can do better.  Also, in the process of doing this reimplementation, I can write a few words on my favorite hardware design methodology, "Europa".
<p>
To wrap up, here are the metrics by which I'll judge the existing <strong>spi.v</strong> versus my new implementation, in priority order:
<UL>
<LI>Proper function</LI>
<LI>HDL readability</LI>
<LI>Configurability.  I'm thinking I need to support both flavors of clock polarity and clock phase, and also various data widths.</LI>
<LI>FPGA resource consumption</LI
</UL>
<p>
There you have it.  The challenge is on!]]>
      
   </content>
</entry>
<entry>
   <title>Hello, world!</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/09/xiv_hello_world_1.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.38</id>
   
   <published>2007-09-13T14:54:37Z</published>
   <updated>2008-02-01T14:32:40Z</updated>
   
   <summary> It&apos;s finally time to work on some firmware! But, since I seem to be compelled to develop a design environment rather than actually work on a design (what was I working on? Something about turning something on, or off......</summary>
   <author>
      <name></name>
      
   </author>
         <category term="XBox Remote Project" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
It's finally time to work on some firmware! 
<p>
But, since I seem to be compelled to develop a design environment rather than actually work on a design (what was I working on?  Something about turning something on, or off... something like that), let's talk about debugging tools.  Well.  Let's talk about bugs, first.
<p>
Bugs that, say, the compiler fails on, are simple: they're right there in red text.  Those bugs die quickly.  (Are these even bugs?  Perhaps not.  But I'll assume they are, for the sake of my point.)  On the other end of the spectrum are those extremely intermittent bugs which seem to occur only when we're not looking.  We know these bugs through stale logfile tracings, collections of disproven hypotheses, and a body of murky, often contradictory and superstitious lore which grows throughout the long, long lifespan of the bug.
<p>
Bugs elude us by hiding.  So, what do I want from a debugging tool?  I wouldn't ask for too much - just something which:
<UL>
<LI>is no more difficult to use than it ought to be</LI>
<LI>lets me see everywhere</LI>
<LI>has no effect on the normal operation of the system</LI>
<LI>lets me gather trace data on the workings of the system, in its actual working environment</LI>
<LI>provides a way to inject artificial stimulus into the system, for testing purposes</LI>
</UL> 
<p>
I do have a few debugging tools handy.  How do they rate?
<p>
<UL>
<LI><strong>LEDs</strong>.  These are very easy to use: write a value, look at the blinky lights.  LEDs can answer questions like:
<UL>
<LI>Is it on?</LI>
<LI>Is it the correct version (like my testbench id on the 7-segment display)?</LI>
<LI>Is it toggling?  (At human-perceptible rate, at least.)</LI>
</UL>
But the amount of information you can transmit to a human via LED is limited, and you very quickly yearn for more.
</LI>
<LI><strong>The IAR IDE debugger</strong>.  Single-stepping through your program is a great way to find dumb errors.  Breakpoints are available too.  This is a very user-interface-intensive debugging methodology, though, and can dramatically affect program execution time, leading to the dreaded <a href="http://en.wikipedia.org/wiki/Heisenbug#Heisenbugs">Heisenbug</a>.</LI>
<LI><strong>Signaltap(tm)</strong>.  Signaltap can show me anything happening inside the FPGA (so, in my little rig, anything on the f2013 pins), and can capture a trace of that data, sampled on any clock I choose.  This is great stuff! But, it's kind of a pain in the neck to set up, and the penalty for the frequent "I just want to see one more thing" moments in debugging is usually a hardware recompile.  Signaltap is not suited to a pure scripted flow, since trace data is stowed in an undocumented file format. The amount of data that can be captured is limited to what fits in the onchip memory.</LI>
<LI><strong>Custom logic using the <em>sld_virtual_jtag</em></strong>.  Think of this as a hand-crafted signaltap, accessible via tcl script.  This answers the scripting flow problem of signaltap.  Captured data size is unlimited, as long as the bandwidth out of the jtag link is sufficient to keep up with the data generation rate. The information flow can go the other way, too: the system-under-observation's inputs can be driven from the custom logic, ultimately from a script running on the host, which opens up an interesting world of test possibilities. Naturally this more powerful debugging tool is even more work to set up than signaltap, since you have to design the custom logic and write scripts to access the link.</LI>
</UL>
<p>
So, it looks like I'm a little heavy on the powerful-but-hard-to-use side.  What I'm missing is something simple and quick to iterate on, which can give me lots of data without burdening the system too much.  What I need is something like... printf.
<p>

<strong>Something like printf</strong>
<p>
Most microcontrollers have some form of built-in serial communications module.  The f2013 is a bit odd: rather than a plain-ol' UART, its communications module speaks SPI or I2C. But that's ok - my laptop doesn't have a UART either.  Fortunately, to assist me in the simple goal of streaming bytes from the f2013 to my laptop under firmware control, I have a giant heap of programmable logic right next to my f2013, which I can use to bridge the gap between the f2013 and the laptop. Think of the solution as an "SPI-to-JTAG bridge".  Here's a block diagram showing the path of a byte from f2013 to laptop:
<p>
<img alt="block_tb8.gif" src="http://www.antfarm.org/blog/aaronf/block_tb8.gif" width="460" height="152" />
<p>
The components of the system are:
<UL>
<LI>The f2013, configured with an 8-bit SPI master</LI>
<LI>The 1c20, configured with
<UL>
<LI>An 8-bit SPI slave</LI>
<LI>A DMA component, configured to (forever) read bytes from the SPI slave and write them to...</LI>
<LI>A "JTAG UART"</LI>
</UL>
<LI>The USB Blaster (the same device that I use for downloading sofs, running signaltap, etc.</LI>
<LI>The terminal program <em>nios2-terminal</em>, running on the host computer</LI>
</UL>
<p>
Say, not to pull a fast one: I realize that this is the first time I'm using a system which consists of other than hand-typed Verilog and the odd megafunction module.  I designed this system using Altera's <a href="http://www.altera.com/products/software/products/sopc/sop-index.html">SOPC Builder</a>, which you can think of as a heap of useful hardware components and an automatic bus generator.  The system consumes 303 logic elements - pretty small.  For reference, tb_6, my most complex system so far, consumed 312 LEs. SOPC Builder generation and Quartus compilation complete in about 2.5 minutes.
<p>
For anyone reading who happens to be familiar with SOPC Builder, I used these tricks to optimize the system for low logic consumption and fast generation:
<UL>
<LI>The DMA's registers are reset to an actively-running state, so that I don't need a complicated master to configure the DMA at run-time.  I used an undocumented feature of the DMA for this trick, which, sadly, requires running in "--classic" mode</LI>
<LI>I set the DMA's internal FIFO depth to 1 location (another undocumented feature)</LI>
<LI>I limited the DMA to performing 8-bit transactions</LI>
<LI>I reduced the JTAG UART FIFO transmit and receive FIFO depths to minimal values</LI>
</UL>
<p>
<strong>f2013 firmware</strong>
This is a pretty simple firmware project: all I'm doing is sending a string of bytes, over and over, so I can see it in the terminal program.  It took a bit of research to hit upon the correct combination of control register values; see utility routines <em>init_spi</em> and <em>send_spi</em> in the attached project archive.
<p>
By the way, I have to create my own SPI chipselect (SS_n), using a generic f2013 pin, since the built-in SPI master doesn't provide that automatically.  Also notice that <em>send_spi</em> is a polling transmit routine: clearly the next step is to create an IRQ-based transmitter.  
<p>
<strong>Hello, world!</strong>
<p>
Here's a screen capture of the spi test firmware in action:
<p>
<img alt="nios2-terminal.gif" src="http://www.antfarm.org/blog/aaronf/nios2-terminal.gif" width="668" height="331" />
<p>
<strong>P.S. The bug is in the pin assignments</strong>
<p>
For my own reference, mostly, here's a table of pin names and functions for this little test bench:
<p>
<TABLE BORDER>
<TR ALIGN="RIGHT">
<TH>f2013 function</TH>
<TH>f2013 SPI function</TH>
<TH>1c20 pin</TH>
<TH>J15 pin</TH>
</TR>
<TR ALIGN="RIGHT">
<TD>P1.4</TD>
<TD>&lt;none&gt;</TD>
<TD>U11</TD>
<TD>J15-12</TD>
</TR>

<TR ALIGN="RIGHT">
<TD>P1.5</TD>
<TD>SCLK</TD>
<TD>Y11</TD>
<TD>J15-14</TD>
</TR>

<TR ALIGN="RIGHT">
<TD>P1.6</TD>
<TD>MOSI</TD>
<TD>W11</TD>
<TD>J15-13</TD>
</TR>

<TR ALIGN="RIGHT">
<TD>P1.7</TD>
<TD>MISO</TD>
<TD>V11</TD>
<TD>J15-11</TD>
</TR>

</TABLE>
<p>
Here's the <a href="http://www.antfarm.org/blog/aaronf/tb_8.zip">tb_8 archive.</a>
<p>
<em>20070922: a small optimization: SOPC Builder's DMA is a bit overpowered for the simple task of moving bytes from one place to another.  Also, needing to use undocumented features annoys me. It was about a half hour's work to create a new component (simple_byte_pipe) that does the same job, wiith less logic.  The new system (files attached as tb_8a.zip) uses only 248 LEs, and builds in 1.5 minutes.
</em>
<p>
<a href="http://www.antfarm.org/blog/aaronf/tb_8a.zip">tb_8a archive.</a>]]>
      
   </content>
</entry>
<entry>
   <title>WWASD?</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/08/xiii_wwasd_1.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.37</id>
   
   <published>2007-08-26T18:14:48Z</published>
   <updated>2008-02-01T14:32:23Z</updated>
   
   <summary> I&apos;ve got the data from hundreds of remote-control transmissions in a handy file format. What would a statistician do? Analyze it, of course! Remember that the XBox remote transmits in the RCA protocol; that protocol allows for 5 different...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="XBox Remote Project" scheme="http://www.sixapart.com/ns/types#category" />
   
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
I've got the data from hundreds of remote-control transmissions in a handy file format.  What would a statistician do?  Analyze it, of course!
<p>
Remember that the XBox remote transmits in the <a href="http://www.sbprojects.com/knowledge/ir/rca.htm">RCA protocol</a>; that protocol allows for 5 different sorts of pulses:
<p>
<UL>
<LI>mark_4ms: nominal 4 ms "mark" (active IR transmission)</LI>
<LI>space_4ms: nominal 4ms "space" (no IR transmission)</LI>
<LI>mark_500us: nominal 500&mu;s mark</LI>
<LI>space_1ms: nominal 1ms space (logic 0)</LI>
<LI>space_2ms: nominal 2ms space (logic 1)</LI>
</UL>
<p>
The real world is usually a bit messy - in this particular case, the data I measured coming out of the IR receiver module diverges from those nice values.  So,
by trial and error, I determined an upper and lower bound for each pulse type.  
I bin the data into the 5 types according to these thresholds (a value falls in a bin if it is in the range <strong>(min-bin-value, max-bin-value)</strong>, where the parens represent noninclusive boundaries):
<p>
<TABLE BORDER>
<TR ALIGN="CENTER">
<TH>bin</TH>
<TH>min-bin-value</TH>
<TH>max-bin-value</TH>
</TR>
<TR>
<TD>mark_4ms</TD>
<TD>4.01</TD>
<TD>4.07</TD>
</TR>
<TR>
<TD>space_4ms</TD>
<TD>3.9</TD>
<TD>4.0</TD>
</TR>
<TR>
<TD>mark_500us</TD>
<TD>0.5</TD>
<TD>0.56</TD>
</TR>
<TR>
<TD>space_1ms</TD>
<TD>0.9</TD>
<TD>1.0</TD>
</TR>
<TR>
<TD>space_2ms</TD>
<TD>1.94</TD>
<TD>2.0</TD>
</TR>
</TABLE>
<p>

Notice that the "mark" bins have larger than nominal values, while the "space" bins have smaller than nominal values. (By the way, by design, every duration value I collected falls into one of the 5 bins.) <p>
Here are some statistics on the collected data, grouped by bin:
<p>
<TABLE BORDER>
<TR ALIGN="CENTER">
<TH>bin</TH>
<TH>average value</TH>
<TH>min value</TH>
<TH>max value</TH>
<TH>deviation from nominal (%)</TH>
<TH>number of samples</TH>
</TR>
<TR ALIGN="RIGHT">
<TD>mark_4ms</TD>
<TD>4.046216011</TD>
<TD>4.02744</TD>
<TD>4.06724</TD>
<TD>+1.155%</TD>
<TD>1514</TD>
</TR>
<TR ALIGN="RIGHT">
<TD>space_4ms</TD>
<TD>3.979702576</TD>
<TD>3.96054</TD>
<TD>3.99844</TD>
<TD>-0.507%</TD>
<TD>1514</TD>
</TR>
<TR ALIGN="RIGHT">
<TD>mark_500us</TD>
<TD>0.539785722</TD>
<TD>0.51732</TD>
<TD>0.55442</TD>
<TD>+7.957%</TD>
<TD>37850</TD>
</TR>
<TR ALIGN="RIGHT">
<TD>space_1ms</TD>
<TD>0.95811015</TD>
<TD>0.94466</TD>
<TD>0.98132</TD>
<TD>-4.189%</TD>
<TD>18168</TD>
</TR>
<TR ALIGN="RIGHT">
<TD>space_2ms</TD>
<TD>1.965947435</TD>
<TD>1.94998</TD>
<TD>1.98714</TD>
<TD>-1.703%</TD>
<TD>18168</TD>
</TR>
</TABLE>
<p>
Average, min and max are useful, and reveal basic facts, but also hide other things.  For a full picture, there's nothing like... a picture.  I discovered something interesting when I plotted each bin's data as a histogram.  Click on a chart thumbnail to see the full-size version:
<p>
<strong>IR Receiver Output</strong>
<p>
<TABLE BORDER>
<TR ALIGN="CENTER">
<TH>Bin</TH>
<TH>Histogram</TH>
</TR>
<TD>mark_4ms</TD>
<TD><a href="http://www.antfarm.org/blog/aaronf/mark_4ms4.html" onclick="window.open('http://www.antfarm.org/blog/aaronf/mark_4ms4.html','popup','width=881,height=585,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://www.antfarm.org/blog/aaronf/mark_4ms-thumb.gif" width="100" height="66" alt="" /></a>
</TD>
</TR>
<TR>
<TD>space_4ms</TD>
<TD><a href="http://www.antfarm.org/blog/aaronf/space_4ms2.html" onclick="window.open('http://www.antfarm.org/blog/aaronf/space_4ms2.html','popup','width=879,height=585,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://www.antfarm.org/blog/aaronf/space_4ms-thumb.gif" width="100" height="66" alt="" /></a>
</TD>
</TR>
<TR>
<TD>mark_500us</TD>
<TD>
<a href="http://www.antfarm.org/blog/aaronf/mark_500us2.html" onclick="window.open('http://www.antfarm.org/blog/aaronf/mark_500us2.html','popup','width=880,height=585,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://www.antfarm.org/blog/aaronf/mark_500us-thumb.gif" width="100" height="66" alt="" /></a>
</TD>
</TR>
<TR>
<TD>space_1ms</TD>
<TD><a href="http://www.antfarm.org/blog/aaronf/space_1ms2.html" onclick="window.open('http://www.antfarm.org/blog/aaronf/space_1ms2.html','popup','width=879,height=585,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://www.antfarm.org/blog/aaronf/space_1ms-thumb.gif" width="100" height="66" alt="" /></a>
</TD>
</TR>
<TR>
<TD>space_2ms</TD>
<TD><a href="http://www.antfarm.org/blog/aaronf/space_2ms2.html" onclick="window.open('http://www.antfarm.org/blog/aaronf/space_2ms2.html','popup','width=879,height=584,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://www.antfarm.org/blog/aaronf/space_2ms-thumb.gif" width="100" height="66" alt="" /></a>
</TD>
</TR>
</TABLE>
<p>
Isn't that peculiar?  The data for each bin is clustered into groups rather than being a nice <a href="http://en.wikipedia.org/wiki/Normal_distribution">normal distribution</a>.
<p>
Well.  The measurement is made on the output of the IR receiver; could that receiver be distorting my nice clean data?  Moving upstream a bit, I took apart the Xbox remote control, and found a very simple circuit driving the IR LED.  (The box labled "micro" is an integrated circuit whose markings were pretty much indecipherable - presumably some simple microcontroller.) 
<p>
<img alt="measurement3.jpg" src="http://www.antfarm.org/blog/aaronf/measurement3.jpg" width="489" height="362" />
<p>
I've taken a new set of measurements between the cathode of the IR LED and ground.

<p>
<strong>Internal-toXBox-Remote, IR cathode-to-ground</strong>
<p>
<TABLE BORDER>
<TR ALIGN="CENTER">
<TH>Bin</TH>
<TH>Histogram</TH>
</TR>
<TD>mark_4ms</TD>
<TD><a href="http://www.antfarm.org/blog/aaronf/mark_4ms_int.html" onclick="window.open('http://www.antfarm.org/blog/aaronf/mark_4ms_int.html','popup','width=879,height=585,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://www.antfarm.org/blog/aaronf/mark_4ms_int-thumb.gif" width="100" height="66" alt="" /></a>
</TD>
</TR>
<TR>
<TD>space_4ms</TD>
<TD><a href="http://www.antfarm.org/blog/aaronf/space_4ms_int.html" onclick="window.open('http://www.antfarm.org/blog/aaronf/space_4ms_int.html','popup','width=879,height=585,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://www.antfarm.org/blog/aaronf/space_4ms_int-thumb.gif" width="100" height="66" alt="" /></a>
</TD>
</TR>
<TR>
<TD>mark_500us</TD>
<TD><a href="http://www.antfarm.org/blog/aaronf/mark_500us_int.html" onclick="window.open('http://www.antfarm.org/blog/aaronf/mark_500us_int.html','popup','width=880,height=581,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://www.antfarm.org/blog/aaronf/mark_500us_int-thumb.gif" width="100" height="66" alt="" /></a>
</TD>
</TR>
<TR>
<TD>space_1ms</TD>
<TD><a href="http://www.antfarm.org/blog/aaronf/space_1ms_int.html" onclick="window.open('http://www.antfarm.org/blog/aaronf/space_1ms_int.html','popup','width=879,height=585,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://www.antfarm.org/blog/aaronf/space_1ms_int-thumb.gif" width="100" height="66" alt="" /></a>
</TD>
</TR>
<TR>
<TD>space_2ms</TD>
<TD><a href="http://www.antfarm.org/blog/aaronf/space_2ms_int1.html" onclick="window.open('http://www.antfarm.org/blog/aaronf/space_2ms_int1.html','popup','width=878,height=583,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://www.antfarm.org/blog/aaronf/space_2ms_int-thumb.gif" width="100" height="66" alt="" /></a>
</TD>
</TR>
</TABLE>
<p>
These histograms show that the XBox remote itself is emitting pulse durations which tend to cluster into sub-bins separated by about 20&mu;s.  The histograms have higher peaks than those measured at the IR output - perhaps the IR receiver circuit has a "smearing" effect (I can imagine that the automatic gain-control part of the receiver would have this effect).
<p>
<strong>Move forward!</strong>
<p>
This measurement and analysis is fun laboratory work, but I'm anxious to get started on some firmware.  Were I to continue in this vein, I'd work on some of these tasks:
<UL>
<LI>Investigate the effect of transmitter-to-receiver distance on pulse durations</LI>
<LI>Get at least one more Xbox remote, and compare pulse duration statistics</LI>
<LI>Try to find a datasheet for the alleged microcontroller in the Xbox remote</LI>
<LI>Probe more pins on the alleged microcontroller - try to correlate pulse duration with power supply, incoming clock frequency, ...</LI>
</UL>
<p>
But instead, now it's time to get back to my long-neglected f2013.  As a preliminary step, I plan to<del> learn about the f2013's clock source options</del> think about the problem of debugging visibility in embedded systems. 
<p>
<em>Oh, right.  Here are the up-to-date <a href="http://www.antfarm.org/blog/aaronf/tb_6.zip">tb_6</a> (IR receiver measurement) and <a href="http://www.antfarm.org/blog/aaronf/tb_7.zip">tb_7</a> (IR LED cathode measurement) files.</em>]]>
      
   </content>
</entry>
<entry>
   <title>Gathering the XBox DVD Remote Codes: Method</title>
   <link rel="alternate" type="text/html" href="http://www.antfarm.org/blog/aaronf/2007/08/xii_gathering_the_xbox_dvd_rem.html" />
   <id>tag:www.antfarm.org,2007:/blog/aaronf//8.36</id>
   
   <published>2007-08-21T05:41:58Z</published>
   <updated>2008-02-01T14:32:08Z</updated>
   
   <summary> Last time I presented a table of address and command codes, one for each of the XBox DVD Remote&apos;s 27 buttons. How did I come up with the table? First, a recap: back in X. Start Making Sense, I...</summary>
   <author>
      <name></name>
      
   </author>
         <category term="XBox Remote Project" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="26" label="xbox remote codes virtual jtag instance" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://www.antfarm.org/blog/aaronf/">
      <![CDATA[<p>
Last time I presented a table of address and command codes, one for each of the XBox DVD Remote's 27 buttons.  How did I come up with the table?
<p>
First, a recap: back in <a href="http://www.antfarm.org/blog/aaronf/2007/07/x_start_making_sense.html">X. Start Making Sense</a>, I displayed disappointment at Signaltap's partial scriptability, and resigned myself to manually processing the data, in heavy interaction with Signaltap's GUI and Excel.  This solution, though workable, didn't sit well with me, and fortunately I found a better method.
<p>
<strong>The Virtual JTAG Interface To The Rescue!</strong>
<p>
The <strong>sld_virtual_jtag</strong> megafunction, aka the Virtual JTAG interface (VJI), provides access to the same on-chip hardware resources that signaltap makes use of, but in a far more user-configurable form.
Here's what the Mighty Altera Corporation says:
<p>
<em>
The megafunction can be used to diagnose, sample, and update the
values of internal parts of your logic. With this megafunction, you
can easily sample and update the values of the internal counters and
state machines in your hardware device.
<p>
You can build your own custom software debugging IP using the Tcl
commands listed above to debug your hardware. This IP
communicates with the instances of the sld_virtual_jtag
megafunction inside your design.
</em>
<p>
I used the VJI, suitably wrapped in glue logic, to gather data under control of a tcl script.
I'll give a brief textual description of the method I used; check out the attached design files for more details.
<p>
Remember that my goal is to measure the durations of the mark and space values emitted by the remote control.  The measurement circuit consists of these functional blocks:
<UL>
<LI>An edge detector, which provides a 1-cycle pulse on each rising or falling edge of the incoming IR signal</LI>
<LI>A 20-bit counter, which increments on each clock pulse, and synchronously resets to 0 on each IR edge</LI>
<LI>A 20-bit FIFO, which is written with the counter value on each IR edge</LI>
</UL>
<p>
Those simple circuit elements, running at 50MHz, write the sequence of IR duration values into the FIFO. The read side of the FIFO is controlled by the VJI, which exposes two values to the outside world:
<UL>
<LI>rdempty: is the FIFO empty?</LI>
<LI>readdata: data from the FIFO</LI>
</UL>
<p>
A tcl script (pseudo code, here - the actual script is get_data.tcl) running on the host gathers the FIFO data: 
<p>
<pre>
while (FIFO nonempty)
  read FIFO
  print FIFO readdata
end while
</pre>
<p>
The script <code>process_data.bat</code> transforms data from all raw data files into a single summary file and one processed data file per raw data file.

So, that's the basic operation of the data-acquisition logic.  Next time I'll do some analysis on the gathered data.
<p>
<em>Postscript:
The testbench for this data acquisition fiesta is "tb_6"; <a href="http://www.antfarm.org/blog/aaronf/tb_6a.zip">here</a> are the files.  This testbench could actually be useful to anyone trying to analyze a serial protocol, so it's worthwhile to give a bit of an overview.  The zip file contains these files:</em>
<p>

<UL>
<LI>go.sh: Build bash script.  Creates the quartus project, compiles the design and configures the FPGA.</LI>
<LI>pgm.sh, make_tb.tcl, compile_tb.tcl: Lower-level build tcl scripts.</LI>
<LI>top.v: Design top-level.  Synchronizes the incoming IR signal to the system clock, instantiates module "sys".</LI>
<LI>sys.v: The real guts of the design.  Implements the edge detector, the counter and the FIFO.  Instantiates the virtual jtag wrapper module (vj_rw).  Drives the test bench code ("06.") onto the seven-segment display.</LI>
<LI>fifo.v: A dual-clock FIFO, delivered by the FIFO megawizard.</LI>
<LI>vj_rw.v: Assorted logic to provide a clean interface to the virtual-jtag-interface, from the outside world.  Instantiates the virtual-jtag-interface itself (vj).</LI>
<LI>vj.v: The actual virtual-jtag-interface, as delivered by the virtual jtag interface megawizard.</LI>
<LI>get_data.tcl: The data acquisition script, as described above.  Reads the FIFO, writes the values to the console, slightly formatted (newlines are inserted for "long" durations, which are supposed to be IR transmission boundaries</LI>
<LI>process_data.bat: A perl script which transforms the raw data (as delivered by get_data.tcl) into "cooked" data files, a summary file of IR codes, and an html table for pasting here.  This file is very XBox-remote-specific.</LI>
</UL>
]]>
      
   </content>
</entry>

</feed>

