From 90546fd8117f3270afd2202e2662528df71c8a2b Mon Sep 17 00:00:00 2001 From: Sebastien Bourdeauducq Date: Fri, 9 Mar 2012 17:08:38 +0100 Subject: [PATCH] doc: switch to sphinx --- .gitignore | 1 + doc/Makefile | 130 +++++++++++ doc/_build/.keep_me | 0 doc/_static/.keep_me | 0 doc/_templates/.keep_me | 0 doc/asmi.txt | 170 -------------- doc/conf.py | 216 ++++++++++++++++++ doc/index.rst | 428 +++++++++++++++++++++++++++++++++++ doc/migen.txt | 481 ---------------------------------------- 9 files changed, 775 insertions(+), 651 deletions(-) create mode 100644 doc/Makefile create mode 100644 doc/_build/.keep_me create mode 100644 doc/_static/.keep_me create mode 100644 doc/_templates/.keep_me delete mode 100644 doc/asmi.txt create mode 100644 doc/conf.py create mode 100644 doc/index.rst delete mode 100644 doc/migen.txt diff --git a/.gitignore b/.gitignore index 77b68122..cec18e71 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ __pycache__ vpi/*.o vpi/migensim.vpi examples/*.vcd +doc/_build diff --git a/doc/Makefile b/doc/Makefile new file mode 100644 index 00000000..d6a5924b --- /dev/null +++ b/doc/Makefile @@ -0,0 +1,130 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Migen.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Migen.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/Migen" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Migen" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + make -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/doc/_build/.keep_me b/doc/_build/.keep_me new file mode 100644 index 00000000..e69de29b diff --git a/doc/_static/.keep_me b/doc/_static/.keep_me new file mode 100644 index 00000000..e69de29b diff --git a/doc/_templates/.keep_me b/doc/_templates/.keep_me new file mode 100644 index 00000000..e69de29b diff --git a/doc/asmi.txt b/doc/asmi.txt deleted file mode 100644 index f50293d3..00000000 --- a/doc/asmi.txt +++ /dev/null @@ -1,170 +0,0 @@ - Advanced System Memory Infrastructure (ASMI) -============================================== - -Rationale -========= -The lagging of the DRAM semiconductor processes behind the logic -processes has led the industry into a subtle way of ever increasing -memory performance. - -Modern devices feature a DRAM core running at a fraction of the logic -frequency, whose wide data bus is serialized and deserialized to and -from the faster clock domain. Further, the presence of more banks -increases page hit rate and provides opportunities for parallel -execution of commands to different banks. - -A first-generation SDR-133 SDRAM chip runs both DRAM, I/O and logic at -133MHz and features 4 banks. A 16-bit chip has a 16-bit DRAM core. - -A newer DDR3-1066 chip still runs the DRAM core at 133MHz, but the logic -at 533MHz (4 times the DRAM frequency) and the I/O at 1066Mt/s (8 times -the DRAM frequency). A 16-bit chip has a 128-bit internal DRAM core. -Such a device features 8 banks. Note that the serialization also -introduces multiplied delays (e.g. CAS latency) when measured in number -of cycles of the logic clock. - -To take full advantage of these new architectures, the memory controller -should be able to peek ahead at the incoming requests and service -several of them in parallel, while respecting the various timing -specifications of each DRAM bank and avoiding conflicts for the shared -data lines. Going further in this direction, a controller able to -complete transfers out of order can provide even more performance by: -(1) grouping requests by DRAM row, in order to minimize time spent on - precharging and activating banks. -(2) grouping requests by direction (read or write) in order to minimize - delays introduced by bus turnaround and write recovery times. -(3) being able to complete a request that hits a page earlier than a - concurrent one which requires the cycling of another bank. - -The first two techniques are explained with more details in [1]. - -To enable the efficient implementation of these mechanisms, a new -communication protocol with the memory controller must be devised. Migen -and Milkymist SoC (-NG) implement their own bus, called ASMIbus, based -on the split-transaction principle. - -Topology -======== -The ASMI consists of a memory controller (e.g. ASMIcon) containing a hub -that connects the multiple masters, handles transaction tags, and -presents a view of the pending requests to the rest of the memory -controller. - -Links between the masters and the hub are using the same ASMIbus protocol -described below. - -It is suggested that memory controllers use an interface to a PHY -compatible with DFI [2]. The DFI clock can be the same as the ASMIbus -clock, with optional serialization and deserialization happening across -the PHY, as specified in the DFI standard. - -+-------+ +---+ -|Master1|<==>| | +----------+ -+-------+ | +-------+ +-------+ | Off-chip | - |Hub|ASMIcon|<-->|DDR PHY|<<====>>| SDRAM | -+-------+ | +-------+ +-------+ |device(s) | -|Master2|<==>| | +----------+ -+-------+ +---+ - -<====> ASMIbus links -<----> DFI (or similar) links -<<==>> PCB traces to external SDRAM chips - -Signals -======= -The ASMIbus consists of two parts: the control signals, and the data -signals. - -The control signals are used to issue requests. - * Master->Hub: - - ADR communicates the memory address to be accessed. The unit is - the word width of the particular implementation of ASMIbus. - - WE is the write enable signal. - - STB qualifies the transaction request, and should be asserted - until ACK goes high. - * Hub->Master - - TAG_ISSUE is an integer representing the transaction ("tag") - attributed by the hub. The width of this signal is determined by - the maximum number of in-flight transactions that the hub port - can handle. - - ACK is asserted when TAG_ISSUE is valid and the transaction has - been registered by the hub. A hub may assert ACK even when STB is - low, which means it is ready to accept any new transaction and - will do as soon as STB goes high. - -The data signals are used to complete requests. - * Hub->Master - - TAG_CALL is used to identify the transaction for which the data - is "called". It takes the tag value that has been previously - attributed by the hub to that transaction during the issue - phase. - - CALL qualifies TAG_CALL. - - DATA_R returns data from the DRAM in the case of a read - transaction. It is valid for one cycle after CALL has been - asserted and TAG_CALL has identified the transaction. - The value of this signal is undefined for the cycle after a write - transaction data have been called. - * Master->Hub - - DATA_W must supply data to the controller from the appropriate - write transaction, on the cycle after they have been called using - CALL and TAG_CALL. - - DATA_WM are the byte-granular write data masks. They are used in - combination with DATA_W to identify the bytes that should be - modified in the memory. The DATA_WM bit should be high for its - corresponding DATA_W byte to be written. - -In order to avoid duplicating the tag matching and tracking logic, the -master->hub data signals must be driven low when they are not in use, so -that they can be simply ORed together inside the memory controller. This -way, only masters have to track (their own) transactions for arbitrating -the data lines. - -Tags represent in-flight transactions. The hub can reissue a tag as soon -as the cycle when it appears on TAG_CALL. - -SDRAM burst length and clock ratios -=================================== -A system using ASMI must set the SDRAM burst length B, the ASMIbus word -width W and the ratio between the ASMIbus clock frequency Fa and the -SDRAM I/O frequency Fi so that all data transfers last for exactly one -ASMIbus cycle. - -More explicitly, these relations must be verified: -B = Fi/Fa -W = B*[number of SDRAM I/O pins] - -For DDR memories, the I/O frequency is twice the logic frequency. - -Example transactions -==================== - -Basic transaction: -CTL ------------------ -ISSUE< T1 >------------------ -CALL ------------< T1 >------ -DAT_R------------------ -DAT_W------------------------ - -Two simple transactions: -CTL ------------------------------ -ISSUE< T1 >------< T2 >------------------------ -CALL ------------------< T1 >------< T2 >------ -DAT_R------------------------------ -DAT_W------------------------------------------ - -Interleaved transactions: -CTL ------------------------------ -ISSUE< T1 >------< T1 >< T2 >< T1 >< T1 >------------------------ -CALL ------------< T1 >------< T1 >< T1 >------< T1 >< T2 >------ -DAT_R------------------------------------------ -DAT_W------------------------------------------------ - - Read address x - Write address x -< Tn > Tag n - Data to/from address x - - -[1] http://www.xilinx.com/txpatches/pub/documentation/misc/ - improving%20ddr%20sdram%20efficiency.pdf -[2] http://www.ddr-phy.org/ diff --git a/doc/conf.py b/doc/conf.py new file mode 100644 index 00000000..9cb6d423 --- /dev/null +++ b/doc/conf.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- +# +# Migen documentation build configuration file, created by +# sphinx-quickstart on Fri Mar 9 14:11:54 2012. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.pngmath'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'Migen' +copyright = u'2012, Sebastien Bourdeauducq' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = 'X' +# The full version, including alpha/beta/rc tags. +release = 'X' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'Migendoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +# The paper size ('letter' or 'a4'). +#latex_paper_size = 'letter' + +# The font size ('10pt', '11pt' or '12pt'). +#latex_font_size = '10pt' + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'Migen.tex', u'Migen manual', + u'Sebastien Bourdeauducq', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Additional stuff for the LaTeX preamble. +latex_preamble = '\setcounter{tocdepth}{3}' + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'migen', u'Migen manual', + [u'Sebastien Bourdeauducq'], 1) +] diff --git a/doc/index.rst b/doc/index.rst new file mode 100644 index 00000000..7ff6273f --- /dev/null +++ b/doc/index.rst @@ -0,0 +1,428 @@ +Migen manual +############ + +.. _introduction: + +Introduction +############ +Migen is a Python-based tool that aims at automating further the VLSI design process. + +Migen makes it possible to apply modern software concepts such as object-oriented programming and metaprogramming to design hardware. This results in more elegant and easily maintained designs and reduces the incidence of human errors. + +Even though the Milkymist system-on-chip [mm]_ is technically successful, it suffers from several limitations stemming from its implementation in manually written Verilog HDL: + +.. [mm] http://www.milkymist.org + +#. The "event-driven" paradigm of today's dominant hardware descriptions languages (Verilog and VHDL, collectively referred to as "V*HDL" in the rest of this document) is often too general. Today's FPGA architectures are optimized for the implementation of fully synchronous circuits. This means that the bulk of the code for an efficient FPGA design falls into three categories: + + #. Combinatorial statements + #. Synchronous statements + #. Initialization of registers at reset + + V*HDL do not follow this organization. This means that a lot of repetitive manual coding is needed, which brings sources of human errors, petty issues, and confusion for beginners: + + #. wire vs. reg in Verilog + #. forgetting to initialize a register at reset + #. deciding whether a combinatorial statement must go into a process/always block or not + #. simulation mismatches with combinatorial processes/always blocks + #. and more... + + A little-known fact about FPGAs is that many of them have to ability to initialize their registers from the bitstream contents. This can be done in a portable and standard way using an "initial" block in Verilog, and by affecting a value at the signal declaration in VHDL. This renders an explicit reset signal unnecessary in practice in some cases, which opens the way for further design optimization. However, this form of initialization is entirely not synthesizable for ASIC targets, and it is not easy to switch between the two forms of reset using V*HDL. + +#. V*HDL support for composite types is very limited. Signals having a record type in VHDL are unidirectional, which makes them clumsy to use e.g. in bus interfaces. There is no record type support in Verilog, which means that a lot of copy-and-paste has to be done when forwarding grouped signals. + +#. V*HDL support for procedurally generated logic is extremely limited. The most advanced forms of procedural generation of synthesizable logic that V*HDL offers are CPP-style directives in Verilog, combinatorial functions, and generate statements. Nothing really fancy, and it shows. To give a few examples: + + #. Building highly flexible bus interconnect is not possible. Even arbitrating any given number of bus masters for commonplace protocols such as Wishbone is difficult with the tools at V*HDL puts at our disposal. + #. Building a memory infrastructure (including bus interconnect, bridges and caches) that can automatically adapt itself at compile-time to any word size of the SDRAM is clumsy and tedious. + #. Building register banks for control, status and interrupt management of cores can also largely benefit from automation. + #. Many hardware acceleration problems can fit into the dataflow programming model. Manual dataflow implementation in V*HDL has, again, a lot of redundancy and potential for human errors. See the Milkymist texture mapping unit [mthesis]_ [mxcell]_ for an example of this. The amount of detail to deal with manually also makes the design space exploration difficult, and therefore hinders the design of efficient architectures. + #. Pre-computation of values, such as filter coefficients for DSP or even simply trigonometric tables, must often be done using external tools whose results are copy-and-pasted (in the best cases, automatically) into the V*HDL source. + +.. [mthesis] http://milkymist.org/thesis/thesis.pdf +.. [mxcell] http://www.xilinx.com/publications/archives/xcell/Xcell77.pdf p30-35 + +Enter Migen, a Python toolbox for building complex digital hardware. We could have designed a brand new programming language, but that would have been reinventing the wheel instead of being able to benefit from Python's rich features and immense library. The price to pay is a slightly cluttered syntax at times when writing descriptions in FHDL, but we believe this is totally acceptable, particularly when compared to VHDL ;-) + +Migen is made up of several related components, which are described in this manual. + +The FHDL layer +############## + +The Fragmented Hardware Description Language (FHDL) is the lowest layer of Migen. It consists of a formal system to describe signals, and combinatorial and synchronous statements operating on them. The formal system itself is low level and close to the synthesizable subset of Verilog, and we then rely on Python algorithms to build complex structures by combining FHDL elements and encapsulating them in "fragments". +The FHDL module also contains a back-end to produce synthesizable Verilog, and some basic analysis functions. It would be possible to develop a VHDL back-end as well, though more difficult than for Verilog - we are "cheating" a bit now as Verilog provides most of the FHDL semantics. + +FHDL differs from MyHDL [myhdl]_ in fundamental ways. MyHDL follows the event-driven paradigm of traditional HDLs (see :ref:`introduction`) while FHDL separates the code into combinatorial statements, synchronous statements, and reset values. In MyHDL, the logic is described directly in the Python AST. The converter to Verilog or VHDL then examines the Python AST and recognizes a subset of Python that it translates into V*HDL statements. This seriously impedes the capability of MyHDL to generate logic procedurally. With FHDL, you manipulate a custom AST from Python, and you can more easily design algorithms that operate on it. + +.. [myhdl] http://www.myhdl.org + +FHDL is made of several elements, which are briefly explained below. + +Expressions +*********** + +Bit vector (BV) +=============== +The bit vector (BV) object defines if a constant or signal is signed or unsigned, and how many bits it has. This is useful e.g. to: + +* determine when to perform sign extension (FHDL uses the same rules as Verilog). +* determine the size of registers. +* determine how many bits should be used by each value in concatenations. + +Constant +======== +This object should be self-explanatory. All constant objects contain a BV object and a value. If no BV object is specified, one will be made up using the following rules: + +* If the value is positive, the BV is unsigned and has the minimum number of bits needed to represent the constant's value in the canonical base-2 system. +* If the value is negative, the BV is signed, and has the minimum number of bits needed to represent the constant's value in the canonical two's complement, base-2 system. + +Signal +====== +The signal object represents a value that is expected to change in the circuit. It does exactly what Verilog's "wire" and "reg" and VHDL's "signal" and "variable" do. + +The main point of the signal object is that it is identified by its Python ID (as returned by the :py:func:`id` function), and nothing else. It is the responsibility of the V*HDL back-end to establish an injective mapping between Python IDs and the V*HDL namespace. It should perform name mangling to ensure this. The consequence of this is that signal objects can safely become members of arbitrary Python classes, or be passed as parameters to functions or methods that generate logic involving them. + +The properties of a signal object are: + +* a bit vector description +* a name, used as a hint for the V*HDL back-end name mangler. +* a boolean "variable". If true, the signal will behave like a VHDL variable, or a Verilog reg that uses blocking assignment. This parameter only has an effect when the signal's value is modified in a synchronous statement. +* the signal's reset value. It must be an integer, and defaults to 0. When the signal's value is modified with a synchronous statement, the reset value is the initialization value of the associated register. When the signal is assigned to in a conditional combinatorial statement (If or Case), the reset value is the value that the signal has when no condition that causes the signal to be driven is verified. This enforces the absence of latches in designs. If the signal is permanently driven using a combinatorial statement, the reset value has no effect. + +The sole purpose of the name property is to make the generated V*HDL code easier to understand and debug. From a purely functional point of view, it is perfectly OK to have several signals with the same name property. The back-end will generate a unique name for each object. If no name property is specified, Migen will analyze the code that created the signal object, and try to extract the variable or member name from there. For example, the following statements will create one or several signal named "bar": :: + + bar = Signal() + self.bar = Signal() + self.baz.bar = Signal() + bar = [Signal() for x in range(42)] + +In case of conflicts, Migen tries first to resolve the situation by prefixing the identifiers with names from the class and module hierarchy that created them. If the conflict persists (which can be the case if two signal objects are created with the same name in the same context), it will ultimately add number suffixes. + +Operators +========= +Operators are represented by the _Operator object, which generally should not be used directly. Instead, most FHDL objects overload the usual Python logic and arithmetic operators, which allows a much lighter syntax to be used. For example, the expression: :: + + a * b + c + +is equivalent to:: + + _Operator("+", [_Operator("*", [a, b]), c]) + +Slices +====== +Likewise, slices are represented by the _Slice object, which often should not be used in favor of the Python slice operation [x:y]. Implicit indices using the forms [x], [x:] and [:y] are supported. Beware! Slices work like Python slices, not like VHDL or Verilog slices. The first bound is the index of the LSB and is inclusive. The second bound is the index of MSB and is exclusive. In V*HDL, bounds are MSB:LSB and both are inclusive. + +Concatenations +============== +Concatenations are done using the Cat object. To make the syntax lighter, its constructor takes a variable number of arguments, which are the signals to be concatenated together (you can use the Python "*" operator to pass a list instead). +To be consistent with slices, the first signal is connected to the bits with the lowest indices in the result. This is the opposite of the way the "{}" construct works in Verilog. + +Replications +============ +The Replicate object represents the equivalent of {count{expression}} in Verilog. + +Statements +********** + +Assignment +========== +Assignments are represented with the _Assign object. Since using it directly would result in a cluttered syntax, the preferred technique for assignments is to use the eq() method provided by objects that can have a value assigned to them. They are signals, and their combinations with the slice and concatenation operators. +As an example, the statement: :: + + a[0].eq(b) + +is equivalent to: :: + + _Assign(_Slice(a, 0, 1), b) + +If +== +The If object takes a first parameter which must be an expression (combination of the Constant, Signal, _Operator, _Slice, etc. objects) representing the condition, then a variable number of parameters representing the statements (_Assign, If, Case, etc. objects) to be executed when the condition is verified. + +The If object defines a Else() method, which when called defines the statements to be executed when the condition is not true. Those statements are passed as parameters to the variadic method. + +For convenience, there is also a Elif() method. + +Example: :: + + If(tx_count16 == 0, + tx_bitcount.eq(tx_bitcount + 1), + If(tx_bitcount == 8, + self.tx.eq(1) + ).Elif(tx_bitcount == 9, + self.tx.eq(1), + tx_busy.eq(0) + ).Else( + self.tx.eq(tx_reg[0]), + tx_reg.eq(Cat(tx_reg[1:], 0)) + ) + ) + +Case +==== +The Case object constructor takes as first parameter the expression to be tested, then a variable number of lists describing the various cases. + +Each list contains an expression (typically a constant) describing the value to be matched, followed by the statements to be executed when there is a match. The head of the list can be the an instance of the Default object. + +Special elements +**************** + +Instances +========= +Instance objects represent the parametrized instantiation of a V*HDL module, and the connection of its ports to FHDL signals. They are useful in a number of cases: + +* reusing legacy or third-party V*HDL code. +* using special FPGA features (DCM, ICAP, ...). +* implementing logic that cannot be expressed with FHDL (asynchronous circuits, ...). +* breaking down a Migen system into multiple sub-systems, possibly using different clock domains. + +The properties of the instance object are: + +* the type of the instance (i.e. name of the instantiated module). +* a list of output ports of the instantiated module. Each element of the list is a pair containing a string, which is the name of the module's port, and either an existing signal (on which the port will be connected to) or a BV (which will cause the creation of a new signal). +* a list of input ports (likewise). +* a list of (name, value) pairs for the parameters ("generics" in VHDL) of the module. +* the name of the clock port of the module (if any). If this is specified, the port will be connected to the system clock. +* the name of the reset port of the module (likewise). +* the name of the instance (can be mangled like signal names). + +Memories +======== +Memories (on-chip SRAM) are supported using a mechanism similar to instances. + +A memory object has the following parameters: + +* the width, which is the number of bits in each word. +* the depth, which represents the number of words in the memory. +* an optional list of integers used to initialize the memory. +* a list of port descriptions. + +Each port description contains: + +* the address signal (mandatory). +* the data read signal (mandatory). +* the write enable signal (optional). If the port is using masked writes, the width of the write enable signal should match the number of sub-words. +* the data write signal (iff there is a write enable signal). +* whether reads are synchronous (default) or asynchronous. +* the read enable port (optional, ignored for asynchronous ports). +* the write granularity (default 0), which defines the number of bits in each sub-word. If it is set to 0, the port is using whole-word writes only and the width of the write enable signal must be 1. This parameter is ignored if there is no write enable signal. +* the mode of the port (default ``WRITE_FIRST``, ignored for asynchronous ports). It can be: + + * ``READ_FIRST``: during a write, the previous value is read. + * ``WRITE_FIRST``: the written value is returned. + * ``NO_CHANGE``: the data read signal keeps its previous value on a write. + +Migen generates behavioural V*HDL code that should be compatible with all simulators and, if the number of ports is <= 2, most FPGA synthesizers. If a specific code is needed, the memory generator function can be overriden using the memory_handler parameter of the conversion function. + +Fragments +********* +A "fragment" is a unit of logic, which is composed of: + +* a list of combinatorial statements. +* a list of synchronous statements. +* a list of instances. +* a list of memories. +* a set of pads, which are signals intended to be connected to off-chip devices. +* a list of simulation functions (see :ref:`simulating`). + +Fragments can reference arbitrary signals, including signals that are referenced in other fragments. Fragments can be combined using the "+" operator, which returns a new fragment containing the concatenation of each pair of lists. + +Fragments can be passed to the back-end for conversion to Verilog. + +By convention, classes that generate logic implement a method called ``get_fragment``. When called, this method builds a new fragment implementing the desired functionality of the class, and returns it. This convention allows fragments to be built automatically by combining the fragments from all relevant objects in the local scope, by using the autofragment module. + +Conversion for synthesis +************************ + +Any FHDL fragment (except, of course, its simulation functions) can be converted into synthesizable Verilog HDL. This is accomplished by using the ``convert`` function in the ``verilog`` module. + +Migen does not provide support for any specific synthesis tools or ASIC/FPGA technologies. Users must run themselves the generated code through the appropriate tool flow for hardware implementation. + +Bus support +########### +Migen Bus contains classes providing a common structure for master and slave interfaces of the following buses: + +* Wishbone [wishbone]_, the general purpose bus recommended by Opencores. +* CSR-2 (see :ref:`csr2`), a low-bandwidth, resource-sensitive bus designed for accessing the configuration and status registers of cores from software. +* ASMIbus (see :ref:`asmi`), a split-transaction bus optimized for use with a high-performance, out-of-order SDRAM controller. +* DFI [dfi]_ (partial), a standard interface protocol between memory controller logic and PHY interfaces. + +.. [wishbone] http://cdn.opencores.org/downloads/wbspec_b4.pdf +.. [dfi] http://www.ddr-phy.org/ + +It also provides interconnect components for these buses, such as arbiters and address decoders. The strength of the Migen procedurally generated logic can be illustrated by the following example: :: + + wbcon = wishbone.InterconnectShared( + [cpu.ibus, cpu.dbus, ethernet.dma, audio.dma], + [(0, norflash.bus), (1, wishbone2asmi.wishbone), + (3, wishbone2csr.wishbone)]) + +In this example, the interconnect component generates a 4-way round-robin arbiter, multiplexes the master bus signals into a shared bus, determines that the address decoding must occur on 2 bits, and connects all slave interfaces to the shared bus, inserting the address decoder logic in the bus cycle qualification signals and multiplexing the data return path. It can recognize the signals in each core's bus interface thanks to the common structure mandated by Migen Bus. All this happens automatically, using only that much user code. The resulting interconnect logic can be retrieved using ``wbcon.get_fragment()``, and combined with the fragments from the rest of the system. + + +Configuration and Status Registers +********************************** + +.. _csr2: + +CSR-2 bus +========= +The CSR-2 bus, is a low-bandwidth, resource-sensitive bus designed for accessing the configuration and status registers of cores from software. + +It is the successor of the CSR bus used in Milkymist SoC 1.x, with two modifications: + +* Up to 32 slave devices (instead of 16) +* Data words are 8 bits (instead of 32) + +Generating register banks +========================= +Migen Bank is a system comparable to wishbone-gen [wbgen]_, which automates the creation of configuration and status register banks and interrupt/event managers implemented in cores. + +.. [wbgen] http://www.ohwr.org/projects/wishbone-gen + +Bank takes a description made up of a list of registers and generates logic implementing it with a slave interface compatible with Migen Bus. + +A register can be "raw", which means that the core has direct access to it. It also means that the register width must be less or equal to the bus word width. In that case, the register object provides the following signals: + +* ``r``, which contains the data written from the bus interface. +* ``re``, which is the strobe signal for ``r``. It is active for one cycle, after or during a write from the bus. r is only valid when re is high. +* ``w``, which must provide at all times the value to be read from the bus. + +Registers that are not raw are managed by Bank and contain fields. If the sum of the widths of all fields attached to a register exceeds the bus word width, the register will automatically be sliced into words of the maximum size and implemented at consecutive bus addresses, MSB first. Field objects have two parameters, ``access_bus`` and ``access_dev``, determining respectively the access policies for the bus and core sides. They can take the values ``READ_ONLY``, ``WRITE_ONLY`` and ``READ_WRITE``. +If the device can read, the field object provides the r signal, which contains at all times the current value of the field (kept by the logic generated by Bank). +If the device can write, the field object provides the following signals: + +* ``w``, which provides the value to be written into the field. +* ``we``, which strobes the value into the field. + +As a special exception, fields that are read-only from the bus and write-only for the device do not use the ``we`` signal. Instead, the device must permanently drive valid data on the ``w`` signal. + +Generating interrupt controllers +================================ +TODO: please document me! + +.. _asmi: + +Advanced System Memory Infrastructure +************************************* + +Rationale +========= +The lagging of the DRAM semiconductor processes behind the logic processes has led the industry into a subtle way of ever increasing memory performance. + +Modern devices feature a DRAM core running at a fraction of the logic frequency, whose wide data bus is serialized and deserialized to and from the faster clock domain. Further, the presence of more banks increases page hit rate and provides opportunities for parallel execution of commands to different banks. + +A first-generation SDR-133 SDRAM chip runs both DRAM, I/O and logic at 133MHz and features 4 banks. A 16-bit chip has a 16-bit DRAM core. + +A newer DDR3-1066 chip still runs the DRAM core at 133MHz, but the logic at 533MHz (4 times the DRAM frequency) and the I/O at 1066Mt/s (8 times the DRAM frequency). A 16-bit chip has a 128-bit internal DRAM core. Such a device features 8 banks. Note that the serialization also introduces multiplied delays (e.g. CAS latency) when measured in number of cycles of the logic clock. + +To take full advantage of these new architectures, the memory controller should be able to peek ahead at the incoming requests and service several of them in parallel, while respecting the various timing specifications of each DRAM bank and avoiding conflicts for the shared data lines. Going further in this direction, a controller able to complete transfers out of order can provide even more performance by: + +#. grouping requests by DRAM row, in order to minimize time spent on precharging and activating banks. +#. grouping requests by direction (read or write) in order to minimize delays introduced by bus turnaround and write recovery times. +#. being able to complete a request that hits a page earlier than a concurrent one which requires the cycling of another bank. + +The first two techniques are explained with more details in [drreorder]_. + +.. [drreorder] http://www.xilinx.com/txpatches/pub/documentation/misc/improving%20ddr%20sdram%20efficiency.pdf + +To enable the efficient implementation of these mechanisms, a new communication protocol with the memory controller must be devised. Migen and Milkymist SoC (-NG) implement their own bus, called ASMIbus, based on the split-transaction principle. + +Topology +======== +The ASMI consists of a memory controller (e.g. ASMIcon) containing a hub that connects the multiple masters, handles transaction tags, and presents a view of the pending requests to the rest of the memory controller. + +Links between the masters and the hub are using the same ASMIbus protocol described below. + +It is suggested that memory controllers use an interface to a PHY compatible with DFI [dfi]_. The DFI clock can be the same as the ASMIbus clock, with optional serialization and deserialization happening across the PHY, as specified in the DFI standard. + +TODO: figure + +Signals +======= +The ASMIbus consists of two parts: the control signals, and the data signals. + +The control signals are used to issue requests. + +* Master-to-Hub: + + * ``adr`` communicates the memory address to be accessed. The unit is the word width of the particular implementation of ASMIbus. + * ``we`` is the write enable signal. + * ``stb`` qualifies the transaction request, and should be asserted until ``ack`` goes high. + +* Hub-to-Master + + * ``tag_issue`` is an integer representing the transaction ("tag") attributed by the hub. The width of this signal is determined by the maximum number of in-flight transactions that the hub port can handle. + * ``ack`` is asserted when ``tag_issue`` is valid and the transaction has been registered by the hub. A hub may assert ACK even when ``stb`` is low, which means it is ready to accept any new transaction and will do as soon as ``stb`` goes high. + +The data signals are used to complete requests. + +* Hub-to-Master + + * ``tag_call`` is used to identify the transaction for which the data is "called". It takes the tag value that has been previously attributed by the hub to that transaction during the issue phase. + * ``call`` qualifies ``tag_call``. + * ``data_r`` returns data from the DRAM in the case of a read transaction. It is valid for one cycle after CALL has been asserted and ``tag_call`` has identified the transaction. The value of this signal is undefined for the cycle after a write transaction data have been called. + +* Master-to-Hub + + * ``data_w`` must supply data to the controller from the appropriate write transaction, on the cycle after they have been called using ``call`` and ``tag_call``. + * ``data_wm`` are the byte-granular write data masks. They are used in combination with ``data_w`` to identify the bytes that should be modified in the memory. The ``data_wm`` bit should be high for its corresponding ``data_w`` byte to be written. + +In order to avoid duplicating the tag matching and tracking logic, the master-to-hub data signals must be driven low when they are not in use, so that they can be simply ORed together inside the memory controller. This way, only masters have to track (their own) transactions for arbitrating the data lines. + +Tags represent in-flight transactions. The hub can reissue a tag as soon as the cycle when it appears on ``tag_call``. + +SDRAM burst length and clock ratios +=================================== +A system using ASMI must set the SDRAM burst length B, the ASMIbus word width W and the ratio between the ASMIbus clock frequency Fa and the SDRAM I/O frequency Fi so that all data transfers last for exactly one ASMIbus cycle. + +More explicitly, these relations must be verified: + +B = Fi/Fa + +W = B*[number of SDRAM I/O pins] + +For DDR memories, the I/O frequency is twice the logic frequency. + +Example transactions +==================== +TODO: please document me! + +Using ASMI with Migen +===================== +TODO: please document me! + +Dataflow high-level synthesis +############################# +.. WARNING:: + This is experimental and incomplete. + +Many hardware acceleration problems can be expressed in the dataflow paradigm, that is, using a directed graph representing the flow of data between actors. + +Actors in Migen are written directly in FHDL. This maximizes the flexibility: for example, an actor can implement a DMA master to read data from system memory. It is conceivable that a CAL [cal]_ to FHDL compiler be implemented at some point, to support higher level descriptions of some actors and reuse of third-party RVC-CAL applications. [orcc]_ [orcapps]_ [opendf]_ + +.. [cal] http://opendf.svn.sourceforge.net/viewvc/opendf/trunk/doc/GentleIntro/GentleIntro.pdf +.. [orcc] http://orcc.sourceforge.net/ +.. [orcapps] http://orc-apps.sourceforge.net/ +.. [opendf] http://opendf.sourceforge.net/ + +Actors communicate by exchanging tokens, whose flow is typically controlled using handshake signals (strobe/ack). + +Each actor has a "scheduling model". It can be: + +* N-sequential: the actor fires when tokens are available at all its inputs, and it produces one output token after N cycles. It cannot accept new input tokens until it has produced its output. A multicycle integer divider would use this model. +* N-pipelined: similar to the sequential model, but the actor can always accept new input tokens. It produces an output token N cycles of latency after accepting input tokens. A pipelined multiplier would use this model. +* Dynamic: the general case, when no simple hypothesis can be made on the token flow behaviour of the actor. An actor accessing system memory on a shared bus would use this model. + +Migen Flow automatically generates handshake logic for the first two scheduling models. In the third case, the FHDL descriptions for the logic driving the handshake signals must be provided by the actor. + +An actor can be a composition of other actors. + +Actor graphs are managed using the NetworkX [networkx]_ library. + +.. [networkx] http://networkx.lanl.gov/ + +.. _simulating: + +Simulating a Migen design +######################### diff --git a/doc/migen.txt b/doc/migen.txt deleted file mode 100644 index b50bf9e6..00000000 --- a/doc/migen.txt +++ /dev/null @@ -1,481 +0,0 @@ - Migen (Milkymist Generator) -a Python toolbox for building complex digital hardware -====================================================== - -Background -========== -Even though the Milkymist system-on-chip [1] is technically successful, -it suffers from several limitations stemming from its implementation in -manually written Verilog HDL: - -(1) The "event-driven" paradigm of today's dominant hardware descriptions -languages (Verilog and VHDL, collectively referred to as "V*HDL" in the -rest of this document) is often too general. Today's FPGA architectures -are optimized for the implementation of fully synchronous circuits. This -means that the bulk of the code for an efficient FPGA design falls into -three categories: - (a) Combinatorial statements - (b) Synchronous statements - (c) Initialization of registers at reset -V*HDL do not follow this organization. This means that a lot of -repetitive manual coding is needed, which brings sources of human errors, -petty issues, and confusion for beginners: - - wire vs. reg in Verilog - - forgetting to initialize a register at reset - - deciding whether a combinatorial statement must go into a - process/always block or not - - simulation mismatches with combinatorial processes/always blocks - - and more... -A little-known fact about FPGAs is that many of them have to ability to -initialize their registers from the bitstream contents. This can be done -in a portable and standard way using an "initial" block in Verilog, and -by affecting a value at the signal declaration in VHDL. This renders an -explicit reset signal unnecessary in practice in some cases, which opens -the way for further design optimization. However, this form of -initialization is entirely not synthesizable for ASIC targets, and it is -not easy to switch between the two forms of reset using V*HDL. - -(2) V*HDL support for composite types is very limited. Signals having a -record type in VHDL are unidirectional, which makes them clumsy to use -e.g. in bus interfaces. There is no record type support in Verilog, which -means that a lot of copy-and-paste has to be done when forwarding grouped -signals. - -(3) V*HDL support for procedurally generated logic is extremely limited. -The most advanced forms of procedural generation of synthesizable logic -that V*HDL offers are CPP-style directives in Verilog, combinatorial -functions, and generate statements. Nothing really fancy, and it shows. -To give a few examples: - - Building highly flexible bus interconnect is not possible. Even -arbitrating any given number of bus masters for commonplace protocols -such as Wishbone cannot be done with the tools at V*HDL puts at our -disposal. This requires manual recoding of parts of the arbiter to add or -remove a master, which is tedious and often cause frustrating errors. -Each occurence of the latter can easily cause one or two hours of lost -productivity when combined with the long compilation times of moderately -complex system-on-chip designs. - - Building a memory infrastructure (including bus interconnect, bridges -and caches) that can automatically adapt itself at compile-time to any -word size of the SDRAM is clumsy and tedious. - - Building register banks for control, status and interrupt management -of cores can also largely benefit from automation. - - Many hardware acceleration problems can fit into the dataflow -programming model. Manual dataflow implementation in V*HDL has, again, a -lot of redundancy and potential for human errors. See the Milkymist -texture mapping unit [3][4] for an example of this. The amount of detail -to deal with manually also makes the design space exploration difficult, -and therefore hinders the design of efficient architectures. - - Pre-computation of values, such as filter coefficients for DSP or -even simply trigonometric tables, must often be done using external tools -whose results are copy-and-pasted (in the best cases, automatically) into -the V*HDL source. - -Enter Migen, a Python toolbox for building complex digital hardware. We -could have designed a brand new programming language, but that would have -been reinventing the wheel instead of being able to benefit from Python's -rich features and immense library. The price to pay is a slightly -cluttered syntax at times when writing descriptions in FHDL, but we -believe this is totally acceptable, particularly when compared to VHDL -;-) - -Migen is made up of several related components, which are briefly -described below. - -Migen FHDL -========== -The Fragmented Hardware Description Language (FHDL) is the lowest layer -of Migen. It consists of a formal system to describe signals, and -combinatorial and synchronous statements operating on them. The formal -system itself is low level and close to the synthesizable subset of -Verilog, and we then rely on Python algorithms to build complex -structures by combining FHDL elements and encapsulating them in -"fragments". -The FHDL module also contains a back-end to produce synthesizable -Verilog, and some basic analysis functions. It would be possible to -develop a VHDL back-end as well, though more difficult than for Verilog - -we are "cheating" a bit now as Verilog provides most of the FHDL -semantics. - -FHDL differs from MyHDL [2] in fundamental ways. MyHDL follows the -event-driven paradigm of traditional HDLs (see Background, #1) while FHDL -separates the code into combinatorial statements, synchronous statements, -and reset values. In MyHDL, the logic is described directly in the Python -AST. The converter to Verilog or VHDL then examines the Python AST and -recognizes a subset of Python that it translates into V*HDL statements. -This seriously impedes the capability of MyHDL to generate logic -procedurally. With FHDL, you manipulate a custom AST from Python, and you -can more easily design algorithms that operate on it. - -FHDL is made of several elements, which are briefly explained below. - -BV --- -The bit vector (BV) object defines if a constant or signal is signed or -unsigned, and how many bits it has. This is useful e.g. to: - - determine when to perform sign extension (FHDL uses the same rules as -Verilog). - - determine the size of registers. - - determine how many bits should be used by each value in -concatenations. - -Constant --------- -This object should be self-explanatory. All constant objects contain a BV -object and a value. If no BV object is specified, one will be made up -using the following rules: - - If the value is positive, the BV is unsigned and has the minimum -number of bits needed to represent the constant's value in the canonical -base-2 system. - - If the value is negative, the BV is signed, and has the minimum -number of bits needed to represent the constant's value in the canonical -two's complement, base-2 system. - -Signal ------- -The signal object represents a value that is expected to change in the -circuit. It does exactly what Verilog's "wire" and "reg" and VHDL's -"signal" and "variable" do. - -The main point of the signal object is that it is identified by its -Python ID (as returned by the id() function), and nothing else. It is the -responsibility of the V*HDL back-end to establish an injective mapping -between Python IDs and the V*HDL namespace. It should perform name -mangling to ensure this. The consequence of this is that signal objects -can safely become members of arbitrary Python classes, or be passed as -parameters to functions or methods that generate logic involving them. - -The properties of a signal object are: - - a bit vector description - - a name, used as a hint for the V*HDL back-end name mangler. - - a boolean "variable". If true, the signal will behave like a VHDL -variable, or a Verilog reg that uses blocking assignment. This parameter -only has an effect when the signal's value is modified in a synchronous -statement. - - the signal's reset value. It must be an integer, and defaults to 0. -When the signal's value is modified with a synchronous statement, the -reset value is the initialization value of the associated register. -When the signal is assigned to in a conditional combinatorial statement -(If or Case), the reset value is the value that the signal has when no -condition that causes the signal to be driven is verified. This enforces -the absence of latches in designs. If the signal is permanently driven -using a combinatorial statement, the reset value has no effect. - -The sole purpose of the name property is to make the generated V*HDL code -easier to understand and debug. From a purely functional point of view, -it is perfectly OK to have several signals with the same name property. -The back-end will generate a unique name for each object. If no name -property is specified, Migen will analyze the code that created the -signal object, and try to extract the variable or member name from there. -It then uses the module name that created the signal, a underscore, and -the variable name. For example, if we are in module "foo", the following -statements will create one or several signal(s) named "foo_bar": - bar = Signal() - self.bar = Signal() - self.baz.bar = Signal() - bar = [Signal() for x in range(42)] - -Operators ---------- -Operators are represented by the _Operator object, which generally should -not be used directly. Instead, most FHDL objects overload the usual -Python logic and arithmetic operators, which allows a much lighter syntax -to be used. For example, the expression: - a * b + c -is equivalent to: - _Operator('+', [_Operator('*', [a, b]), c]) - -Slices ------- -Likewise, slices are represented by the _Slice object, which often should -not be used in favor of the Python slice operation [x:y]. -Implicit indices using the forms [x], [x:] and [:y] are supported. -Beware! Slices work like Python slices, not like VHDL or Verilog slices. -The first bound is the index of the LSB and is inclusive. The second -bound is the index of MSB and is exclusive. In V*HDL, bounds are MSB:LSB -and both are inclusive. - -Concatenations --------------- -Concatenations are done using the Cat object. To make the syntax lighter, -its constructor takes a variable number of arguments, which are the -signals to be concatenated together (you can use the Python '*' operator -to pass a list instead). -To be consistent with slices, the first signal is connected to the bits -with the lowest indices in the result. This is the opposite of the way -the '{}' construct works in Verilog. - -Replications ------------- -The Replicate object represents the equivalent of {count{expression}} in -Verilog. - -Assignments ------------ -Assignments are represented with the _Assign object. Since using it -directly would result in a cluttered syntax, the preferred technique for -assignments is to use the eq() method provided by objects that can have a -value assigned to them. They are signals, and their combinations with the -slice and concatenation operators. -As an example, the statement: - a[0].eq(b) -is equivalent to: - _Assign(_Slice(a, 0, 1), b) - -If statement ------------- -The If object takes a first parameter which must be an expression -(combination of the Constant, Signal, _Operator, _Slice, etc. objects) -representing the condition, then a variable number of parameters -representing the statements (_Assign, If, Case, etc. objects) to be -executed when the condition is verified. - -The If object defines a Else() method, which when called defines the -statements to be executed when the condition is not true. Those -statements are passed as parameters to the variadic method. - -For convenience, there is also a Elif() method. - -Example: -If(tx_count16 == 0, - tx_bitcount.eq(tx_bitcount + 1), - If(tx_bitcount == 8, - self.tx.eq(1) - ).Elif(tx_bitcount == 9, - self.tx.eq(1), - tx_busy.eq(0) - ).Else( - self.tx.eq(tx_reg[0]), - tx_reg.eq(Cat(tx_reg[1:], 0)) - ) -) - -Case statement --------------- -The Case object constructor takes as first parameter the expression to be -tested, then a variable number of lists describing the various cases. - -Each list contains an expression (typically a constant) describing the -value to be matched, followed by the statements to be executed when there -is a match. The head of the list can be the an instance of the Default -object. - -Instances ---------- -Instance objects represent the parametrized instantiation of a V*HDL -module, and the connection of its ports to FHDL signals. They are useful -in a number of cases: - - reusing legacy or third-party V*HDL code. - - using special FPGA features (DCM, ICAP, ...). - - implementing logic that cannot be expressed with FHDL (asynchronous - circuits, ...). - - breaking down a Migen system into multiple sub-systems, possibly - using different clock domains. - -The properties of the instance object are: - - the type of the instance (i.e. name of the instantiated module). - - a list of output ports of the instantiated module. Each element of - the list is a pair containing a string, which is the name of the - module's port, and either an existing signal (on which the port will - be connected to) or a BV (which will cause the creation of a new - signal). - - a list of input ports (likewise). - - a list of (name, value) pairs for the parameters ("generics" in VHDL) - of the module. - - the name of the clock port of the module (if any). If this is - specified, the port will be connected to the system clock. - - the name of the reset port of the module (likewise). - - the name of the instance (can be mangled like signal names). - -Memories --------- -Memories (on-chip SRAM) are supported using a mechanism similar to -instances. - -A memory object has the following parameters: - - the width, which is the number of bits in each word. - - the depth, which represents the number of words in the memory. - - an optional list of integers used to initialize the memory. - - a list of port descriptions. - -Each port description contains: - - the address signal (mandatory). - - the data read signal (mandatory). - - the write enable signal (optional). If the port is using masked - writes, the width of the write enable signal should match the number - of sub-words. - - the data write signal (iff there is a write enable signal). - - whether reads are synchronous (default) or asynchronous. - - the read enable port (optional, ignored for asynchronous ports). - - the write granularity (default 0), which defines the number of bits - in each sub-word. If it is set to 0, the port is using whole-word - writes only and the width of the write enable signal must be 1. This - parameter is ignored if there is no write enable signal. - - the mode of the port (default WRITE_FIRST, ignored for asynchronous - ports). It can be: - * READ_FIRST: during a write, the previous value is read. - * WRITE_FIRST: the written value is returned. - * NO_CHANGE: the data read signal keeps its previous value on a - write. - -Migen generates behavioural V*HDL code that should be compatible with all -simulators and, if the number of ports is <= 2, most FPGA synthesizers. -If a specific code is needed, the memory generator function can be -overriden using the memory_handler parameter of the conversion function. - -Fragments ---------- -A "fragment" is a unit of logic, which is composed of: - - a list of combinatorial statements. - - a list of synchronous statements. - - a list of instances. - - a list of memories. - - a set of pads, which are signals intended to be connected to - off-chip devices. - -Fragments can reference arbitrary signals, including signals that are -referenced in other fragments. Fragments can be combined using the "+" -operator, which returns a new fragment containing the concatenation of -each pair of lists. - -Fragments can be passed to the back-end for conversion to Verilog. - -By convention, classes that generate logic implement a method called -"get_fragment". When called, this method builds a new fragment -implementing the desired functionality of the class, and returns it. This -convention allows fragments to be built automatically by combining the -fragments from all relevant objects in the local scope, by using the -autofragment module. - -Migen Core Logic -================ -Migen Core Logic is a convenience library of common logic circuits -implemented using FHDL: - - a multi-cycle integer divider. - - a round-robin arbiter, useful to build bus arbiters. - - a multiplexer bank (multimux), useful to multiplex composite - (grouped) signals. - - a condition-triggered static scheduler of FHDL synchronous statements - (timeline). - -Migen Bus -========= -Migen Bus contains classes providing a common structure for master and -slave interfaces of the following buses: - - Wishbone [5], the general purpose bus recommended by Opencores. - - CSR-2, a low-bandwidth, resource-sensitive bus designed for - accessing the configuration and status registers of cores from - software. - - ASMIbus, a split-transaction bus optimized for use with a - high-performance, out-of-order SDRAM controller. - - DFI [12] (partial), a standard interface protocol between memory - controller logic and PHY interfaces. - -It also provides interconnect components for these buses, such as -arbiters and address decoders. The strength of the Migen procedurally -generated logic can be illustrated by the following example: - wbcon = wishbone.InterconnectShared( - [cpu.ibus, cpu.dbus, ethernet.dma, audio.dma], - [(0, norflash.bus), (1, wishbone2asmi.wishbone), - (3, wishbone2csr.wishbone)]) -In this example, the interconnect component generates a 4-way round-robin -arbiter, multiplexes the master bus signals into a shared bus, determines -that the address decoding must occur on 2 bits, and connects all slave -interfaces to the shared bus, inserting the address decoder logic in the -bus cycle qualification signals and multiplexing the data return path. It -can recognize the signals in each core's bus interface thanks to the -common structure mandated by Migen Bus. All this happens automatically, -using only that much user code. The resulting interconnect logic can be -retrieved using wbcon.get_fragment(), and combined with the fragments -from the rest of the system. - -Migen Bank -========== -Migen Bank is a system comparable to wishbone-gen [6], which automates -the creation of configuration and status register banks and -interrupt/event managers implemented in cores. - -Bank takes a description made up of a list of registers and generates -logic implementing it with a slave interface compatible with Migen Bus. - -A register can be "raw", which means that the core has direct access to -it. It also means that the register width must be less or equal to the -bus word width. In that case, the register object provides the following -signals: - - r, which contains the data written from the bus interface. - - re, which is the strobe signal for r. It is active for one cycle, - after or during a write from the bus. r is only valid when re is - high. - - w, which must provide at all times the value to be read from the - bus. - -Registers that are not raw are managed by Bank and contain fields. If the -sum of the widths of all fields attached to a register exceeds the bus -word width, the register will automatically be sliced into words of the -maximum size and implemented at consecutive bus addresses, MSB first. -Field objects have two parameters, access_bus and access_dev, determining -respectively the access policies for the bus and core sides. They can -take the values READ_ONLY, WRITE_ONLY and READ_WRITE. -If the device can read, the field object provides the r signal, which -contains at all times the current value of the field (kept by the logic -generated by Bank). -If the device can write, the field object provides the following signals: - - w, which provides the value to be written into the field. - - we, which strobes the value into the field. - -Migen Flow (Work in progress) -========== -Many hardware acceleration problems can be expressed in the dataflow -paradigm, that is, using a directed graph representing the flow of data -between actors. - -Actors in Migen are written directly in FHDL. This maximizes the -flexibility: for example, an actor can implement a DMA master to read -data from system memory. It is conceivable that a CAL [7] to FHDL -compiler be implemented at some point, to support higher level -descriptions of some actors and reuse of third-party RVC-CAL -applications. [8] [9] [10] - -Actors communicate by exchanging tokens, whose flow is typically -controlled using handshake signals (strobe/ack). - -Each actor has a "scheduling model". It can be: - - N-sequential: the actor fires when tokens are available at all its - inputs, and it produces one output token after N cycles. It cannot - accept new input tokens until it has produced its output. A - multicycle integer divider would use this model. - - N-pipelined: similar to the sequential model, but the actor can - always accept new input tokens. It produces an output token N cycles - of latency after accepting input tokens. A pipelined multiplier would - use this model. - - Dynamic: the general case, when no simple hypothesis can be made on - the token flow behaviour of the actor. An actor accessing system - memory on a shared bus would use this model. - -Migen Flow automatically generates handshake logic for the first two -scheduling models. In the third case, the FHDL descriptions for the logic -driving the handshake signals must be provided by the actor. - -If sequential or pipelined actors are connected together, Migen Flow will -attempt to find a static schedule, remove the handshake signals, optimize -away the control logic in each actor and replace it with a centralized -FSM implementing the static schedule. - -An actor can be a composition of other actors. - -Actor graphs are managed using the NetworkX [11] library. - - -References: -[ 1] http://milkymist.org -[ 2] http://www.myhdl.org -[ 3] http://milkymist.org/thesis/thesis.pdf -[ 4] http://www.xilinx.com/publications/archives/xcell/Xcell77.pdf p30-35 -[ 5] http://cdn.opencores.org/downloads/wbspec_b4.pdf -[ 6] http://www.ohwr.org/projects/wishbone-gen -[ 7] http://opendf.svn.sourceforge.net/viewvc/opendf/trunk/doc/ - GentleIntro/GentleIntro.pdf -[ 8] http://orcc.sourceforge.net/ -[ 9] http://orc-apps.sourceforge.net/ -[10] http://opendf.sourceforge.net/ -[11] http://networkx.lanl.gov/ -[12] http://www.ddr-phy.org/ -- 2.30.2