\input texinfo    @c -*-texinfo-*-
%
% fmcadc100m14b4cha_firmware_manual.in - main file for the documentation
%
%%%%

%------------------------------------------------------------------------------
%
%                         NOTE FOR THE UNAWARE USER
%                         =========================
%
%    This file is a texinfo source. It isn't the binary file of some strange
%    editor of mine. If you want ASCII, you should "make fmcadc100m14b4cha_firmware_manual.txt".
%
%------------------------------------------------------------------------------

%
% This is not a conventional info file...
% I use three extra features:
%   - The '%' as a comment marker, if at beginning of line ("\%" -> "%")
%   - leading blanks are allowed (this is something I can't live without)
%   - braces are automatically escaped when they appear in example blocks
%

@comment %**start of header
@documentlanguage en
@documentencoding UTF-8
@setfilename fmcadc100m14b4cha_firmware_manual.info
@settitle fmcadc100m14b4cha_firmware_manual
@iftex
@afourpaper
@end iftex
@c @paragraphindent 0
@comment %**end of header

@setchapternewpage off

@set update-month April 2014

@finalout

@titlepage
@title FmcAdc100m14b4cha Gateware Guide
@subtitle @value{update-month} - Release 4.0
@subtitle For PCIe (SPEC) and VME64x (SVEC) FMC Carriers
@sp 10
@center @image{../fig/cern_logo,3cm,,,pdf} @hfill @image{../fig/ohr_logo,3cm,,,pdf}
@author Matthieu Cattin (CERN)
@end titlepage
@headings single

@iftex
@contents
@end iftex

@c ##########################################################################
@node Top
@top Introduction

This document describes the gateware developed to support the FmcAdc100m14b4cha (later refered to as fmc-adc) mezzanine card on the SPEC@footnote{@uref{http://www.ohwr.org/projects/spec}} and SVEC@footnote{@uref{http://www.ohwr.org/projects/svec}} carrier cards.
The gateware is the HDL code used to generate the bitstream that configures the FPGA on the carrier (sometimes also called firmware).
The gateware architecture is described in detail.
The configuration and operation of the fmc-adc is also explained.
On the other hand, this manual is not intended to provide information about the software used to control the fmc-adc board, nor details about it's hardware design.

@c ##########################################################################
@node Repositories and Releases
@chapter Repositories and Releases

This project is hosted on the Open Hardware Repository at the following link:
@uref{http://www.ohwr.org/projects/fmc-adc-100m14b4cha}

Here a list of resources that you can find on the project page.
@table @code

@c @item Document@footnote{@uref{http://www.ohwr.org/projects/fmc-adc-100m14b4cha/documents}}
@c contains the @t{.pdf} documentation for every official release.

@item File@footnote{@uref{http://www.ohwr.org/projects/fmc-adc-100m14b4cha/files}}
contains the @t{.bin} FPGA binary file and the @t{.pdf} documentation for every official release.

@item Repository@footnote{@uref{http://www.ohwr.org/projects/fmc-adc-100m14b4cha/repository}}
contains the git repository of the project.

@end table

On the repository the official releases have a tag named
@code{spec-fmc-adc-v#maj.#min} (or @code{svec-fmc-adc-v#maj.#min}) where @code{#maj} represent the major release
version of the gateware and @code{#min} the minor one (e.g @code{spec-fmc-adc-v1.2}).
The released FPGA binary files follow the same naming convention.

The git commit hash has to be written in the sdb meta-information, therefore the release consists in two commits.
The commit coming right after the tagged one contains the updated sdb meta-information file, the ise project and the synthesis, p&r, timing, reports.

@b{Note:} If you got this from the repository (as opposed to a named
@i{tar.gz} or @i{pdf} file) it may happen that you are looking at a later commit
than the release this manual claims to document.
It is a fact of life that developers forget to re-read and fix documentation
while updating the code. In that case, please run ``@code{git describe HEAD}''
to ensure where you are.

@c ==========================================================================
@section Software Support

For information on the fmc-adc Linux software support, please refer to the following project:@*
@uref{http://www.ohwr.org/projects/fmc-adc-100m14b4cha-sw}

As a general rule, a new minor version of the gateware, for a given major version, should be backward compatible.
If the interface with the driver changes, the major version should be incremented.
It means that driver versions 1.x should work with any gateware version 1.x.
But the driver version 2.0 might not work with the gateware version 1.1.


@c ##########################################################################
@page
@node About source code
@chapter About Source Code

@c ==========================================================================
@section Build from Sources

The fmc-adc hdl design make use of the @command{hdlmake}@footnote{@uref{http://www.ohwr.org/projects/hdl-make}} tool.
It automatically fetches the required hdl cores and libraries. It also generates Makefiles for synthesis/par and simulation.

Here is the procedure to build the FPGA binary image from the hdl source.

@enumerate
@item Install @command{hdlmake}.
@item Get fmc-adc hdl sources.@*
      @code{git clone git://ohwr.org/fmc-projects/fmc-adc-100m14b4cha.git <src_dir>}
@item Goto the synthesis directory.@*
      @code{cd <src_dir>/hdl/<carrier>/syn/}
@item Fetch the dependencies.@*
      @code{hdlmake -f}
@item Generate an ISE project file.@*
      @code{hdlmake --ise-proj}@*
      This will generate a basic ISE project file with default settings.
      If non-default setting is needed (e.g. binary bitstream output file .bin), the project file must be opened using ISE project navigator GUI and the setting changed manually.
@item Generate a synthesis Makefile.@*
      @code{hdlmake --make-ise}
@item Check that all dependencies are fetched.@*
      @code{hdlmake --list}
@item Synthesis, place and route.@*
      @code{make}
@end enumerate

@c TODO specify the hdlmake release (once they have stable version release).
@c TODO once git submodules setup, explain how to build without hdlmake.

@c ==========================================================================
@section Source Code Organisation

@table @file
@item hdl/adc/rtl/
      ADC specific hdl sources.
@item hdl/adc/wb_gen/
      ADC specific @command{wbgen2} sources, html documentation and C header file.
@item hdl/ip_cores/
      Location of fetched and generated hdl cores and libraries.
@item hdl/<carrier>/rtl/
      Carrier related hdl sources.
@item hdl/<carrier>/wb_gen/
      Carrier related @command{wbgen2} sources, html documentation and C header file.
@item hdl/<carrier>/syn/
      Synthesis directory for selected carrier. This is where the synthesis top manifest and the ISE project are stored.
      For each release, the synthesis, place&route and timing reports are also saved here.
@item hdl/<carrier>/sim/
      Carrier related simulation files and testbenches.
@item hdl/<carrier>/chipscope/
      Carrier related Chipscope projects used for debug purpose.
@end table

It could happen that a hdl source directory contains extra source files that are not used in the current gateware release.
In order to identify the source files used in a given release, refer to the @file{Manifest.py} files.

@c ==========================================================================
@section Dependencies

The fmc-adc gateware depends on the following hdl cores and libraries:
@table @b
@item general-cores
      @code{repo  : git://ohwr.org/hdl-core-lib/general-cores.git}@*
      @code{branch: proposed_master}
@item ddr3-sp6-core
      @code{repo  : git://ohwr.org/hdl-core-lib/ddr3-sp6-core}@*
      @code{branch: spec_bank3_64b_32b (for spec carrier)}@*
      @code{branch: svec_bank4_64b_32b_bank5_64b_32b (for svec carrier)}
@item gn4124-core (spec carrier only)
      @code{repo  : git://ohwr.org/hdl-core-lib/gn4124-core.git}@*
      @code{branch: master}
@item vme64x-core (svec carrier only)
      @code{repo  : git://ohwr.org/hdl-core-lib/vme64x-core.git}@*
      @code{branch: master}
@end table

@c ##########################################################################
@page
@node Architecture
@chapter Architecture

This chapter describes the internal blocks of the FPGA for both SPEC (PCIe) and SVEC (VME64x) carriers.
The gateware is designed around one or several Wishbone@footnote{@uref{http://opencores.org/opencores@comma{}wishbone}} buses.
@c FIXME  broken @comma{} to generate url link (prints 'comma{}' instead of ',')

@c ==========================================================================
@section SPEC (PCIe carrier)

In the PCIe version of the gateware, all blocks (except the memory controller) are connected to the PCIe bridge interface using the same Wishbone bus (@i{main} bus).
The ADC samples are written and read to/from the DDR memory using separated Wishbone buses.
Due to its size, the DDR memory is not mapped on the @i{main} Wishbone bus and can only be access through DMA.
The @ref{fig:spec_fw_arch} illustrates the fmc-adc gateware architecture on the SPEC carrier.
A crossbar from the general-cores@footnote{@uref{http://www.ohwr.org/projects/general-cores}} library is used to map the slaves in the Wishbone address space.

@float Figure,fig:spec_fw_arch
@center @image{../fig/spec_fw_arch, 15cm,,,pdf}
@caption{FMC-ADC gateware architecture on SPEC carrier.}
@end float

@sp 1

There are three different Wishbone bus in the design.
@table @b
@item Mapped WB bus (blue)
      This bus connects all the peripheral to the GN4142 core.@*
      Data: 32-bit, address: 32-bit (word aligned), clock: system clock (125MHz).
@item ADC core to memory controller (orange)
      This bus is used to write samples from the ADC core to the DDR memory.@*
      Data: 64-bit, address: 32-bit (word aligned), clock: system clock (125MHz).
@item Memory controller to GN4124 core (red)
      This bus is used to read samples from the DDR memory.@*
      Data: 32-bit, address: 32-bit (word aligned), clock: system clock (125MHz).
@end table


The @ref{tab:spec_memory_map} shows the Wishbone slaves mapping and hierarchy.
The first column represents the byte address offset from the start of the Wishbone address space (BAR 0).

@float Table,tab:spec_memory_map
@include spec_wb_tree.txt
@caption{Wishbone bus memory mapping (BAR 0).}
@end float

@ignore

@float Table,tab:memory_map
@multitable {Byte offset}{xwb_onewire_master}{fmc-adc-100m14b4cha}{Mezzanine system I2C master}
@headitem Byte offset @tab Core @tab Library @tab Description
@item @code{0x0000} @tab sdb_rom            @tab general-cores       @tab SDB records
@item @code{0x1000} @tab gn4124_core        @tab gn4124-core         @tab DMA controller
@item @code{0x1100} @tab xwb_onewire_master @tab general-cores       @tab Carrier 1-wire master
@item @code{0x1200} @tab carrier_csr        @tab fmc-adc-100m14b4cha @tab Carrier control and status
@item @code{0x1300} @tab irq_controller     @tab fmc-adc-100m14b4cha @tab Interrupt controller
@item @code{0x2000} @tab utc_core           @tab fmc-adc-100m14b4cha @tab Time-tagging core
@item @code{0x4000} @tab sdb_rom            @tab general-cores       @tab fmc-adc bridge SDB records
@item @code{0x5000} @tab xwb_i2c_master     @tab general-cores       @tab Mezzanine system I2C master
@item @code{0x5100} @tab xwb_spi            @tab general-cores       @tab Mezzanine SPI master
@item @code{0x5200} @tab xwb_i2c_master     @tab general-cores       @tab Mezzanine I2C master
@item @code{0x5300} @tab fmc_adc_100Ms_core @tab fmc-adc-100m14b4cha @tab ADC core
@item @code{0x5400} @tab xwb_onewire_master @tab general-cores       @tab Mezzanine 1-wire master
@end multitable
@caption{Wishbone bus memory mapping (BAR 0).}
@end float

@end ignore

@sp 1

The Wishbone crossbar also implements SDB@footnote{@uref{http://www.ohwr.org/projects/fpga-config-space}} records. Those records describe the Wishbone slaves and their mapping on the bus.
The SDB records ROM must be located at offset @code{0x0}.
In order to identify the gateware, SDB meta-information records are used.
The 'Integration', 'Top module repository url' and 'Synthesis tool information'  meta-information records are used in the design.
Below is a description of the fields and their content in the fmc-adc design on SPEC carrier.

@table @b
@item Integration
      vendor_id = 0x0000CE42 (CERN vendor ID)@*
      device_id = 0x47C786A2 (echo "spec_fmc-adc-100m14b4cha"|md5sum|cut -c1-8) @*
      version   = [31:16]=major, [15:0]=minor, bcd encoded@*
      date      = release date, format yyyymmdd@*
      name      = "spec_fmcadc100m14b"
@item Top module repository url
      repo_url = "git://ohwr.org/fmc-projects/fmc-adc-100m14b4cha.git"
@item Synthesis tool information
      syn_module_name  = "spec_top_fmc_adc"@*
      syn_commit_id    = git log -1 --format="%H" | cut -c1-32 @*
      syn_tool_name    = "ISE"@*
      syn_tool_version = bcd encoded synthesis tool version@*
      syn_date         = synthesis date, format yyyymmdd@*
      syn_username     = "mcattin" (synthesised by)
@end table


Note that some of the cores from the general-cores library are based on cores from
OpenCores@footnote{@uref{http://opencores.org/}}. Therefore, the documentation for those cores is hosted on the OpenCores website.

@c --------------------------------------------------------------------------
@subsection Clock Domains

The SPEC version of the fmc-adc design has four different clock domains. They are listed in the following table.

@float
@multitable {@code{sys_clk_125}}{ADC data de-serialiser clock}{125.00 MHz}{400MHz LTC2174 (mezzanine)}
@headitem Name @tab Description @tab Frequency @tab Source
@item @code{sys_clk_125} @tab Main system clock @tab 125.00 MHz @tab 20MHz TCXO (carrier)
@item @code{ddr_clk} @tab DDR interface clock @tab 333.33 MHz @tab 20MHz TCXO (carrier)
@item @code{fs_clk} @tab Sampling clock @tab 100.00 MHz @tab 400MHz LTC2174 (mezzanine)
@item @code{serdes_clk} @tab ADC data de-serialiser clock @tab 800.00 MHz @tab 400MHz LTC2174 (mezzanine)
@item @code{p2l_clk} @tab Local bus clock @tab 200.00 MHz @tab 200MHz GN4124 (carrier)
@end multitable
@end float

@sp 1

@c --------------------------------------------------------------------------
@subsection GN4124 Core

This block is the interface between the GN4124@footnote{PCI Express bridge from Semtech (formerly Gennum)} local bus and the other blocks in the FPGA.
The GN4124 is a four lane PCI Express Generation 1.1 bridge. In addition to th PHY, it also contains the data link and transaction layers.
The GN4124 bridge is used to access the FPGA registers, but also to generate MSI interrupts and re-program the FPGA.
The BAR 4 (Base Address Register) allows access to the GN4124 internal registers.
The BAR 0 is connected to the local bus and therefore allows access to the FPGA.

The GN4124 core is made of a local bus interface with the GN4124 chip, a Wishbone bus master mapped to BAR0 and a DMA controller. The DMA controller has two Wishbone ports, a Wishbone slave to configure the DMA controller and a Wishbone master.
In the fmc-adc gateware, the master port is connected to the DDR memory controller.
The GN4124 Wishbone interfaces (masters and slave) are 32-bit data width and 32-bit word aligned addresses.

@b{Note:} It would not be beneficial to insert an address converter (for non-interleaved data read) between the GN4124 core and the memory controller.
Because the DDR memory access is not efficient when reading non-consecutive addresses.

@c --------------------------------------------------------------------------
@subsection DMA Embedded Interrupt Controller (EIC)
The DMA EIC gathers the interrupts from the GN4124 DMA controller.
There are two inputs to the DMA EIC:
@itemize @textdegree
@item @b{DMA done}: This interrupt signals the end of a DMA transfer.
@item @b{DMA error}: This interrupt signals an error in a DMA transfer.
@end itemize
The two inputs are multiplexed and the result is forwarded to the VIC (@ref{Vectored Interrupt Controller (VIC)}).
Interrupt sources can be masked using the enable and disable registers.
An interrupt is cleared by writing a one to the corresponding bit of the status register.

The registers description can be found in annexe @ref{DMA Embedded Interrupt Controller Registers}).

@c --------------------------------------------------------------------------
@subsection SPEC Carrier Control and Status Registers

This block contains control and status registers related to the SPEC carrier board.
A first register allows to readout the carrier PCB revision and carrier type.
Another register signals the presence of a mezzanine in the FMC slot, gives the status of the local bus and system PLLs and indicates the DDR memory controller calibration state.
The last register of this block allows to control the two carrier's LEDs on the front panel.

@b{Note:} The ``Carrier Type'' field is used only for test purpose. The carrier board identification is done through the PCI Express vendor and device ID.

The registers description can be found in annexe @ref{SPEC Carrier Registers}.


@c ==========================================================================
@page
@section SVEC (VME64x carrier)

In the VME64x version of the gateware, all blocks are connected to the VME64x core using a single Wishbone bus. Here the DDR memory is not accessed through DMA, but using a indirect addressing scheme explained later in @ref{DDR Memory Controller}.
A crossbar from the general-cores@footnote{@uref{http://www.ohwr.org/projects/general-cores}} library is used to map the slaves in the Wishbone address space.

@float Figure,fig:svec_fw_arch
@center @image{../fig/svec_fw_arch, 15cm,,,pdf}
@caption{FMC-ADC gateware architecture on SVEC carrier.}
@end float

@sp 1

There are three different Wishbone bus in the design.
@table @b
@item Mapped WB bus (blue)
      This bus connects all the peripheral to the VME64x core.@*
      Data: 32-bit, address: 32-bit (word aligned),@*
      Clock: system clock (125MHz) and system clock / 2 (62.5MHz), see note below.
@item ADC cores to memory controllers (2x, orange)
      Those buses are used to write samples from the ADC cores to the DDR memories.@*
      Data: 64-bit, address: 32-bit (word aligned), clock: system clock (125MHz).
@end table

@b{Note:} The VME64x core cannot work with a clock frequency as high as 125MHz, therefore it is clocked with half the system clock frequency.
As the fmc-adc core needs 125MHz to work properly, a Wishbone clock crossing component is inserted between the VME64x core and the first Wishbone crossbar component.
With this topology, only the VME64x core runs at a lower frequency.


The @ref{tab:svec_memory_map} shows the Wishbone slaves mapping and hierarchy.
The first column represents the byte address offset from the start of the Wishbone address space.

@float Table,tab:svec_memory_map
@include svec_wb_tree.txt
@caption{Wishbone bus memory mapping.}
@end float

@sp 1

As for the SPEC version, SDB meta-information records are used to identify the gateware.
Below is a description of the fields and their content in the fmc-adc design on SVEC carrier.

@table @b
@item Integration
      vendor_id = 0x0000CE42 (CERN vendor ID)@*
      device_id = 0x47C786A2 (echo "svec_fmc-adc-100m14b4cha"|md5sum|cut -c1-8) @*
      version   = [31:16]=major, [15:0]=minor, bcd encoded@*
      date      = release date, format yyyymmdd@*
      name      = "svec_fmcadc100m14b"
@item Top module repository url
      repo_url = "git://ohwr.org/fmc-projects/fmc-adc-100m14b4cha.git"
@item Synthesis tool information
      syn_module_name  = "svec_top_fmc_adc"@*
      syn_commit_id    = git log -1 --format="%H" | cut -c1-32 @*
      syn_tool_name    = "ISE"@*
      syn_tool_version = bcd encoded synthesis tool version@*
      syn_date         = synthesis date, format yyyymmdd@*
      syn_username     = "mcattin" (synthesised by)
@end table

@c --------------------------------------------------------------------------
@page
@subsection Clock Domains
The SPEC version of the fmc-adc design has four different clock domains. They are listed in the following table.

@float
@multitable {@code{sys_clk_62_5}}{ADC data de-serialiser clock}{125.00 MHz}{400MHz LTC2174 (mezzanine)}
@headitem Name @tab Description @tab Frequency @tab Source
@item @code{sys_clk_125} @tab Main system clock @tab 125.00 MHz @tab 20MHz TCXO (carrier)
@item @code{sys_clk_62_5} @tab System clock / 2@tab 62.50 MHz @tab 20MHz TCXO (carrier)
@item @code{ddr_clk} @tab DDR interface clock @tab 333.33 MHz @tab 20MHz TCXO (carrier)
@item @code{fs_clk} @tab Sampling clock @tab 100.00 MHz @tab 400MHz LTC2174 (mezzanine)
@item @code{serdes_clk} @tab ADC data de-serialiser clock @tab 800.00 MHz @tab 400MHz LTC2174 (mezzanine)
@end multitable
@end float

@sp 1

@c --------------------------------------------------------------------------
@subsection VME64x Core
The VME64x core implements a VME slave on one side and a Wishbone pipelined master on the other side.
For more information about the VME64x core, visit the OHWR page@footnote{@uref{http://www.ohwr.org/projects/vme64x-core}}.

@c --------------------------------------------------------------------------
@subsection SVEC Carrier Control and Status
This block contains control and status registers related to the SVEC carrier board.
The registers description can be found in annexe (@ref{SVEC Carrier Registers}).

@c --------------------------------------------------------------------------
@subsection SVEC Carrier I2C Master

The I2C master accesses the 24AA64 64Kb EEPROM memory chip located on the SVEC board.
This memory is useful to store board specific data (e.g. MAC address, White Rabbit calibration data).
This block is based on an OpenCores design.

@float
@multitable @columnfractions .20 .50
@headitem I2C slave address @tab Peripheral
@item @code{0x51} @tab 24AA64 64Kb EEPROM memory
@end multitable
@sp 1
@end float

This block is clocked by the system clock (125 MHz).
Therefore for a SCL clock of 100 kHz, the prescaler configuration is @code{PRESCALER=249}.

@example
@group
PRESCALER = f_sys / (5 * f_scl) - 1
@end group
@end example

@uref{http://opencores.org/project@comma{}i2c}
@c FIXME broken @comma{} to generate url link (prints 'comma{}' instead of ',')

@uref{http://ww1.microchip.com/downloads/en/devicedoc/21189f.pdf}


@c ==========================================================================
@page
@section Common Cores

@c --------------------------------------------------------------------------
@subsection Carrier 1-wire Master

This 1-wire master controls the DS18B20 thermometer chip located on the carrier board.
This chip also contains a unique 64-bit identifier.
This block is based on an OpenCores design.

This block is clocked by the system clock (125 MHz).
Therefore the dividers configuration are @code{CDR_N=624} and @code{CDR_O=124}.

@example
@group
CDR_N = f_sys * 5E-6 - 1
CDR_O = f_sys * 1E-6 - 1
@end group
@end example

@uref{http://opencores.org/project@comma{}sockit_owm}
@c FIXME broken @comma{} to generate url link (prints 'comma{}' instead of ',')

@c --------------------------------------------------------------------------
@node DDR Memory Controller
@subsection DDR Memory Controller

The memory controller block is the interface between the 256MB DDR3 memory located on the carrier boards and the other blocks in the FPGA.
It is basically a MCB core (Memory Controller Block) generated with Xilinx CoreGen and an additional wrapper implementing two Wishbone slave interfaces.
One of the Wishbone slave interface is connected to the ADC core.
In the SPEC gateware, the other Wishbone slave interface is connected to the DMA Wishbone master of the GN4124 core.
While in the SVEC gateware, the other slave Wishbone interface is connected to an indirect addressing block.
This block consists in an address pointer register and a data FIFO.
To access the DDR memory, the VME host sets the address pointer and then read/write data using the FIFO.
On each access to the FIFO, the address pointer is automatically incremented.

@float
@multitable {WB Slave}{Description}{Data width}{Access type}
@headitem WB Slave @tab Description @tab Data width @tab Access type
@item @code{0} @tab ADC core @tab 64-bit @tab Write only
@item @code{1} @tab host side @tab 32-bit @tab Read/write
@sp 1
@end multitable

@end float

The memory controller side connected to the chip is 16-bit DDR data bus, clocked at 333.33 MHz.
This gives a maximum bandwidth of 1333.33 MB/s.
Each of the four channel is 200 MB/s, for a total of 800 MB/s.
In the current design, the two Wishbone port have the same priority.
The arbitration is done with a simple round-robin.
Therefore, the samples stored in the DDR memory cannot be read during an acquisition.

@uref{http://www.ohwr.org/projects/ddr3-sp6-core}

@uref{http://www.xilinx.com/support/documentation/user_guides/ug388.pdf}

@c --------------------------------------------------------------------------
@node Vectored Interrupt Controller (VIC)
@subsection Vectored Interrupt Controller (VIC)

In order to to redirect interrupts from different cores to corresponding driver in the Linux kernel in a generic way, a two layers scheme is used.
The first layer is the Embedded Interrupt Controllers (EIC) in each core multiplexing interrupt sources to a single line.
The second layer is the Vectored Interrupt Controller (VIC) multiplexing the interrupt lines from the EICs into a single line to the host.
The VIC keeps a table, initialized with the base addresses of the EICs connected to each of the input.

Note that the VIC configuration is different between the SPEC and SVEC carriers.
The SPEC uses an edge sensitive scheme while the SVEC uses a level sensitive scheme.

@table @b
@item SPEC, VIC control register:
      enable = 1@*
      polarity = 1@*
      emulate edge sensitive = 1@*
      edge emulation pulse = 750
@item SVEC, VIC control register:
      enable = 1@*
      polarity = 1@*
@end table

@b{Note:} On the SPEC carrier, the VIC interrupt request output is connected to the GPIO 8 of the GN4124 chip.
Therefore, the GN4124 must be configured to generate a MSI when a rising edge is detected on GPIO 8.

The registers description can be found in annexe @ref{Vectored Interrupt Controller}).

@c ==========================================================================
@page
@section FMC-ADC Core
The ADC core is the main block of the design.
On the mezzanine interface side, it takes a data flow from the LTC2174 ADC chip, an external trigger and controls the analogue switches to select the input range or calibration mode.
On the internal interface side, it has a Wishbone master to write data to the DDR memory controller.
It also has a Wishbone slave to access the internal components.

The internal detailed functioning of this block is described further in the document(@xref{Configuration}, @ref{Acquisition} and @ref{Calibration}).

@c --------------------------------------------------------------------------
@subsection Sampling clock

The sampling frequency is determined by a Si570 programmable oscillator located on the fmc-adc mezzanine.
By default, the sampling clock is 100MHz (oscillator factor default value).
But it can be changed to any frequency from 10MHz to 105MHz.
The lower bound is defined by the Si570 oscillator.
While the upper bound is limited by the LTC2174 ADC.

The Si570 clock output is connected to the LTC2174 ADC.
Then the data clock (DCO) output of the LTC2174 is connected to the FPGA.
The data clock is four times the sampling clock.
The sampling clock (@code{fs_clk}) and the ADC data de-serialiser clock (@code{serdes_clk}) are derived from the data clock using a PLL (internal to the FPGA).

@b{Note:} The internal PLL expects a 400MHz input frequency (define in the hdl code), therefore the sampling frequency has to be 100MHz and can't be change dynamically.

@c TODO : possibility to control the Si570 via I2C

The ADC core implements a sampling clock frequency meter.
The measured frequency (in Hz) can be read via a register (@pxref{ADC Core Registers}).

@c --------------------------------------------------------------------------
@subsection Time-tagging Core

This block allows time-tagging of important events in the ADC core.
It is based on two free-running counters;
a seconds counter and a 125MHz system clock ticks counter.
The system clock ticks counter is also called coarse counter.
Those two counters are accessible in read/write via a Wishbone interface.

For example, the host computer can use the OS time to set the seconds counter and simply reset the coarse counter.
It is planned, in a later release, to set the time-tagging core counters using the White Rabbit core, for more details @pxref{Missing Features and Improvements}.

A time-tag is made of four 32-bit words; meta-data, seconds, coarse, fine.
The fine field is always set to zero.
And the meta-data register does not contain useful information, only random data for debugging purposes.

The following events are time-tagged:
@itemize @textdegree
@item Trigger
@item Acquisition start
@item Acquisition stop
@item Acquisition end
@end itemize

@b{Note:} The trigger time tag corresponds to the moment when the acquisition state machine leaves the @code{WAIT_TRIG} state.

@b{Note:} The trigger time-tag is also stored in the data memory, after the post-trigger samples.
This allows to always have trigger time-tag, even in multi-shot mode (retrieving the time-tag using the trigger interrupt was not fast enough in certain cases).

@b{Note:} If during an acquisition no stop command is issued (normal case), the acquisition time-tag is not updated.

The register description can be found in annexe @ref{Time-tagging Core Registers}.

@c --------------------------------------------------------------------------
@page
@subsection FMC-ADC Control and Status Registers
This block contains control and status registers related to the fmc-adc core.
The registers description can be found in annexe (@ref{ADC Core Registers}).

@c --------------------------------------------------------------------------
@subsection Mezzanine SPI Master

This SPI master controls the LTC2174 ADC and the four MAX5442 offset DACs.
The following table shows how the peripherals are wired to the core.
This block is based on an OpenCores design.

@float
@multitable @columnfractions .20 .35
@headitem SPI slave select @tab Peripheral
@item @code{0} @tab LTC2174 ADC
@item @code{1} @tab MAX5442 DAC for channel 1
@item @code{2} @tab MAX5442 DAC for channel 2
@item @code{3} @tab MAX5442 DAC for channel 3
@item @code{4} @tab MAX5442 DAC for channel 4
@end multitable
@sp 1
@end float

This block is clocked by the system clock (125 MHz).
Therefore for a SCLK of ~620 kHz, the divider configuration is @code{DIVIDER=100}.

@example
@group
f_sclk = f_sys / ((DIVIDER+1) * 2)
@end group
@end example

@uref{http://opencores.org/project@comma{}spi}
@c FIXME broken @comma{} to generate url link (prints 'comma{}' instead of ',')

@uref{http://cds.linear.com/docs/en/datasheet/21754314fa.pdf}

@uref{http://datasheets.maximintegrated.com/en/ds/MAX5441-MAX5444.pdf}

@c --------------------------------------------------------------------------
@subsection Mezzanine 1-wire Master

This 1-wire master controls the DS18B20 thermometer chip located on the mezzanine board.
This chip also contains a unique 64-bit identifier.
This block is based on an OpenCores design.

This block is clocked by the system clock (125 MHz).
Therefore the dividers configuration are @code{CDR_N=624} and @code{CDR_O=124}.

@uref{http://opencores.org/project@comma{}sockit_owm}
@c FIXME broken @comma{} to generate url link (prints 'comma{}' instead of ',')

@uref{http://datasheets.maximintegrated.com/en/ds/DS18B20.pdf}

@c --------------------------------------------------------------------------
@subsection Mezzanine I2C Master

This I2C master controls the Si570 programmable oscillator chip located on the mezzanine board.
This chip is used to produce the ADC sampling clock.
This block is based on an OpenCores design.

@float
@multitable @columnfractions .20 .50
@headitem I2C slave address @tab Peripheral
@item @code{0x55} @tab Si570 programmable oscillator
@end multitable
@sp 1
@end float

This block is clocked by the system clock (125 MHz).
Therefore for a SCL clock of 100 kHz, the prescaler configuration is @code{PRESCALER=249}.

@example
@group
PRESCALER = f_sys / (5 * f_scl) - 1
@end group
@end example

@uref{http://opencores.org/project@comma{}i2c}
@c FIXME broken @comma{} to generate url link (prints 'comma{}' instead of ',')

@uref{https://www.silabs.com/Support%20Documents/TechnicalDocs/si570.pdf}

@c --------------------------------------------------------------------------
@subsection Mezzanine System Management I2C Master

This I2C master access the 24AA64 64Kb EEPROM memory chip located on the mezzanine board.
This memory is mandatory as specified in the FMC standard (VITA 57.1). It is connected to the system management I2C bus, also specified in the FMC standard.
This block is based on an OpenCores design.

@float
@multitable @columnfractions .20 .50
@headitem I2C slave address @tab Peripheral
@item @code{0x50} @tab 24AA64 64Kb EEPROM memory
@end multitable
@sp 1
@end float

This block is clocked by the system clock (125 MHz).
Therefore for a SCL clock of 100 kHz, the prescaler configuration is @code{PRESCALER=249}.

@example
@group
PRESCALER = f_sys / (5 * f_scl) - 1
@end group
@end example

@uref{http://opencores.org/project@comma{}i2c}
@c FIXME broken @comma{} to generate url link (prints 'comma{}' instead of ',')

@uref{http://ww1.microchip.com/downloads/en/devicedoc/21189f.pdf}

@c --------------------------------------------------------------------------
@subsection FMC-ADC Embedded Interrupt Controller (EIC)
The fmc-adc EIC gathers the interrupts from the ADC core.
There are two inputs to the fmc-adc EIC:
@itemize @textdegree
@item @b{Trigger}: This interrupt signals that a valid trigger arrived while the acquisition state machine was in the @code{WAIT_TRIG} state.
@item @b{Acquisition end}: This interrupt signals the end of an acquisition. In case of multi-shot acquisition, it occurs at the end of the last shot.
@end itemize
The two inputs are multiplexed and the result is forwarded to the VIC (@ref{Vectored Interrupt Controller (VIC)}).
Interrupt sources can be masked using the enable and disable registers.
An interrupt is cleared by writing a one to the corresponding bit of the status register.

The registers description can be found in annexe @ref{FMC-ADC Embedded Interrupt Controller Registers}).


@c ##########################################################################
@page
@node Configuration
@chapter Configuration

The @ref{fig:adc_core_fs_clk} is a block diagram of the ADC core part in the sampling clock domain. It contains a ADC data stream de-serialiser, an offset and gain correction block (for ADC data), an under-sampling block and a trigger unit.
The four channels data and the trigger signal are synchronised to the system clock domain using a FIFO.
The configuration signals coming from registers in the system clock domain are synchronised to the sampling clock within the Wishbone slave (@command{wbgen2} feature).

@float Figure,fig:adc_core_fs_clk
@center @image{../fig/adc_core_fs_clk, 14cm,,,pdf}
@caption{ADC core diagram (sampling clock domain).}
@end float

The LTC2174 is by default configured as @i{2-Lane Output Mode, 16-Bit Serialization}.
In the fmc-adc application, the default configuration is kept.
The figure @ref{fig:ltc2174_mode} is an extract from the LTC2174 datasheet illustrating the @i{2-Lane Output Mode, 16-Bit Serialization} waveforms.

@float Figure,fig:ltc2174_mode
@center @image{../fig/ltc2174_mode, 12cm,,,pdf}
@caption{LTC2174 data output mode waveforms.}
@end float

There is two 800Mb/s lanes per ADC channel.
The eight data lanes and the frame rate (FR) lane are fed to a de-serialiser in the FPGA.
The frame rate signal is used to align the de-serialiser to data words.
The four channel data (16-bit) are concatenated together to form a 64-bit vector.
As show in @ref{fig:ltc2174_mode}, the two LSB bits of a data word are set to zero.

@c ==========================================================================
@section Control and Status Registers

Writing one to to the @code{FMC_CLK_OE} field of the ADC core control register enables the sampling clock (Si570 chip).
Also, in order to use the input offset DACs, the @code{OFFSET_DAC_CLR_N} field must be set to one.

The field @code{MAN_BITSLIP} allows to 'manually' control the ADC data alignment in the de-serialiser.
When @code{TEST_DATA_EN} is set, the ADC core writes the address pointer to the memory instead of the ADC samples.
The fields @code{TRIG_LED} and @code{ACQ_LED} allows to control the FMC front panel LEDs.
Those four fields are for test purpose only and must stay zero in normal operation.

When the sampling clock is enabled, the @code{SERDES_PLL} and @code{SERDES_SYNCED} field from the ADC core status register must be set to one.

@c ==========================================================================
@section Input Ranges

The @ref{fig:analogue_input} shows a simplified schematics of the analogue input used for each channel.
Each input can be independently configured with one of the three available ranges; 100mV, 1V, 10V.
Each range is defined as the maximum peak-to-peak input voltage.
Independently to the selected range, a 50ohms termination can be added to each input.

In addition to the three ranges for normal operation, there are three more configurations used for offset calibration of each range.

Opto-isolated analogue switches allow the different configurations. They are represented by normal switched in the simplified schematics.

@float Figure,fig:analogue_input
@center @image{../fig/analogue_input, 10cm,,,pdf}
@caption{Simplified schematics of the analogue input.}
@end float

Only the following input switch configurations are valid.
For all others switch configurations, the behavior is not defined and therefore shouldn't be used.

@float Table,tab:switch_config
@multitable {SW[7..1]}{SW7}{SW6}{SW5}{SW4}{SW3}{SW2}{SW1}{100mV range offset calibration}
@headitem SW[7..1] @tab SW7 @tab SW6 @tab SW5 @tab SW4 @tab SW3 @tab SW2 @tab SW1 @tab Description
@item @code{0x23} @tab @code{OFF} @tab @code{ON}  @tab @code{OFF} @tab @code{X}   @tab @code{OFF} @tab @code{ON}  @tab @code{ON}  @tab 100mV range
@item @code{0x11} @tab @code{OFF} @tab @code{OFF} @tab @code{ON}  @tab @code{X}   @tab @code{OFF} @tab @code{OFF} @tab @code{ON}  @tab 1V range
@item @code{0x45} @tab @code{ON}  @tab @code{OFF} @tab @code{OFF} @tab @code{X}   @tab @code{ON}  @tab @code{OFF} @tab @code{ON}  @tab 10V range
@item @code{0x42} @tab @code{ON}  @tab @code{OFF} @tab @code{OFF} @tab @code{X}   @tab @code{OFF} @tab @code{ON}  @tab @code{OFF} @tab 100mV range offset calibration
@item @code{0x40} @tab @code{ON}  @tab @code{OFF} @tab @code{OFF} @tab @code{X}   @tab @code{OFF} @tab @code{OFF}  @tab @code{OFF}  @tab 1V range offset calibration
@item @code{0x44} @tab @code{ON}  @tab @code{OFF} @tab @code{OFF} @tab @code{X}   @tab @code{ON}  @tab @code{OFF} @tab @code{OFF} @tab 10V range offset calibration
@item @code{0x00} @tab @code{X}   @tab @code{OFF} @tab @code{OFF} @tab @code{OFF} @tab @code{X}   @tab @code{X}   @tab @code{OFF} @tab Input disconnected
@item @code{0x08} @tab @code{X}   @tab @code{X}   @tab @code{X}   @tab @code{ON}  @tab @code{X}   @tab @code{X}   @tab @code{X}   @tab 50ohm termination
@end multitable
@caption{Analogue input switches configurations.}
@end float

@c ==========================================================================
@section Input Offset

Each channel has a 16-bit DAC allowing to apply a dc offset to the input signal.
The voltage range of the DAC is 10V (-5V to +5V) and is independent from the selected input range.
The following equation shows how to convert a digital value written to a DAC to an offset voltage.

@example
@group
v_dac = (v_ref * d_dac/0x8000) - v_ref
Where:
v_ref = DAC's voltage reference = 5V
d_dac = Digital value written to the DAC
v_dac = DAC voltage

Example:
0xFFFF =>  4.999V
0x8000 =>  0.000V
0x0000 => -5.000V
@end group
@end example

The following equation shows the relation between the input voltage and the offset (applied by the DAC).
Note that the offset from the DAC is subtracted from the input voltage.

@example
@group
v_out = v_in - v_dac
Where:
v_in  = Input voltage
v_dac = DAC voltage
v_out = Output voltage (to filter and ADC)
@end group
@end example

@c ==========================================================================
@section Trigger

The trigger unit is made of two hardware and one software sources.
The hardware and software path can be enabled independently.
The two paths are then or'ed together to drive a delay generator.
The delay generator allows to insert an defined number of sampling clock period before the trigger goes to the acquisition state machine.
The @ref{fig:trig_unit} shows a simplified digram of trigger unit.

@float Figure,fig:trig_unit
@center @image{../fig/trigger_unit, 12cm,,,pdf}
@caption{Trigger unit diagram.}
@end float

The hardware trigger source can be either internal (based on an adc input channel) or external (dedicated trigger input).
For both internal and external hardware triggers, the polarity can be selected between positive and negative slope (resp. rising and falling edge).
By default the polarity is set to positive slope.

The external trigger input is synchronised to the sampling clock.
The external trigger pulse must be at least one sampling clock cycle wide.

To use the internal trigger source, the adc input channel and the threshold should be configured.
By default, the channel 1 is selected and the threshold is set to 0.
Note that the threshold is 16-bit signed (two's complement).
The @ref{fig:trig_hw_int} sketches the internal hardware trigger threshold behavior.
In addition, a glitch filter can be applied to the threshold detection.
The glitch filter is useful to trigger on noisy signal.
In order to help setting the glitch filter, an internal trigger test mode can be activated.
When the test mode is enabled, the data from channels 2 to 4 are replaced as follow:

@float
@multitable @columnfractions .12 .50
@item Channel 2 @tab Input signal over threshold
@item Channel 3 @tab Input signal over threshold filtered
@item Channel 4 @tab Trigger
@end multitable
@sp 1
@end float


The software trigger source consists in a pulse generated when a write cycle is detected on the @i{Software trigger} register.

For further information on the trigger configuration registers @pxref{ADC Core Registers}.

@float Figure,fig:trig_hw_int
@center @image{../fig/trig_hw_int, 8cm,,,pdf}
@caption{Internal hardware trigger threshold.}
@end float

@c ==========================================================================
@section Undersampling

The undersampling block is simply validating one in N samples and forwarding it to the acquisition logic.
The number (N) is configured in the @i{Sample rate} register.
If N > 1, then the trigger pulse is aligned to the next valid sample.
If N = 1 all the samples are valid and therefore the trigger is always aligned.
A value of N = 0 is treated as N = 1 in the gateware.

@b{Note:} Undersampling might be inaccurately called decimation in the documentation or source code.


@c ##########################################################################
@page
@node Calibration
@chapter Calibration

The calibration is done once during the production tests.
It can be repeated afterwards with the production test suite (PTS) and the corresponding testbench.
The calibration process gives the following four values per channel and per input range:
@itemize @textdegree
@item ADC gain correction
@item ADC offset correction
@item DAC gain correction
@item DAC offset correction
@end itemize

Note that the temperature during the calibration process is also measured.
This could be used for later temperature compensated calibration value computing.

@c ==========================================================================
@section Calibration data storage
All the calibration values are stored in the FmcAdc100m14b4cha EEPROM.
The EEPROM holds a sdbfs@footnote{@uref{http://www.ohwr.org/attachments/download/1594/sdbfs-2012-09-19.pdf}} file system.
In addition to the calibration values, the EEPROM also contains mandatory IPMI@footnote{Platform Management FRU Information Storage Definition v1.0} records specified in the FMC Standard VITA 57.1 (see table @ref{tab:eeprom_sdbfs} for mapping).

@float Table,tab:eeprom_sdbfs
@multitable @columnfractions .12 .18 .15 .30
@headitem Byte offset @tab File name @tab File Type @tab Description
@item @code{0x0}    @tab IPMI-FRU        @tab binary @tab IPMI records
@item @code{0x100}  @tab calib           @tab binary @tab Calibration values
@item @code{auto}   @tab name            @tab ascii  @tab Contains "adc_100m"
@item @code{0x800}  @tab data            @tab binary @tab Empty directory
@item @code{0x200}  @tab .               @tab binary @tab Root directory
@item               @tab                 @tab        @tab vendor = 0xCE42
@item               @tab                 @tab        @tab device = 0xC5BE045E
@end multitable
@caption{EEPROM sdb file system.}
@end float

Note that the vendor value 0xCE42 corresponds to CERN. While the device value 0xC5BE045E corresponds to the first 32-bit of the md5 sum of "fmc-adc-100m14b4cha".

@c ==========================================================================
@section Calibration Data Usage

@subsection ADC Calibration
Two registers per channel are implemented in the FPGA for ADC gain and offset correction.
When an input range is selected, the corresponding gain/offset correction values must be loaded from the EEPROM to those registers.

@float Figure,fig:off_gain_corr
@center @image{../fig/offset_gain_corr, 12cm,,,pdf}
@caption{ADC offset and gain correction block.}
@end float

The offset register takes a 16-bit signed value.
The gain register takes a 16-bit fixed point value.
The fixed point format is as follow:

@float Figure,fig:adc_gain_format
@center @image{../fig/adc_gain_format, 13cm,,,pdf}
@caption{ADC gain register format.}
@end float

After the offset and gain corrections are applied, the signal is saturated to a user programmable value.
One register per channel allows to set the saturation value.
The saturation register takes a 15-bit unsigned value.
From this value, two 'symmetrical' 16-bit signed numbers are derived and taken as the saturation boundaries.

@b{Note:} Because the default value (on FPGA start-up) is not configurable in wbgen2, the gain, offset and saturation registers are set to 0x0 at start-up.
Therefore, the driver has to initialise those registers.

@b{Note:} After gain and offset correction, the two LSB of the data words can be different from zero.

@b{Note:} It is usually the driver's task to read the calibration data from the FMC EEPROM and load them to the corresponding registers. This has to be done once at start-up and then every time the input range is changed.


@subsection DAC Calibration
The DAC value is only set once before an acquisition.
Therefore, there is no need to implement the gain and offset correction in the FPGA.
The software controlling the fmc-adc must apply the DAC gain and offset correction prior to write a value to the DAC.
As for the ADC correction values, there is one pair (offset, gain) of DAC correction values per input range.

Below is the formula to calculate the corrected DAC value (applying gain and offset correction):
@example
@group
c_val = ((val + offset) * gain/0x8000) - 0x8000
where:
c_val  = corrected value to write to DAC (16-bit unsigned)
val    = value from user (16-bit signed)
offset = DAC offset calibration value from EEPROM (16-bit signed)
gain   = DAC gain calibration value from EEPROM (16-bit fixed point)
@end group
@end example


@c ##########################################################################
@page
@node Acquisition
@chapter Acquisition

This chapter describes the two modes of acquisition, single-shot and multi-shot.
It also explains how the software is expected to control the fmc-adc acquisitions.

The @ref{fig:adc_core_sys_clk} shows the ADC core acquisition logic.
The heart of the acquisition logic is a state machine driven by user commands (start, stop), the trigger signal and counters events (e.g. pre-trig done, etc...).
The ADC samples are routed along a datapath (bold arrows), which depends on the acquisition mode.
It is explained in detail in the @ref{Single-shot Mode} and @ref{Multi-shot Mode}.
The four channels data and the trigger are concatenated together and fed to a FIFO to be synchronised between the sampling clock domain and the system clock domain.
Even if the LTC2174 ADC is 14-bit, the data of each channel is stored in a 16-bit word.
Along the datapath, we call @i{sample} a 64-bit vector containing a sample for each channel.
At the output of the ADC core, a flow control FIFO allows to cope with the memory controller temporary unavailabilities (due to DDR refresh cycles).

@float Figure,fig:adc_core_sys_clk
@center @image{../fig/adc_core_sys_clk, 15cm,,,pdf}
@caption{Acquisition logic diagram (system clock domain).}
@end float

Samples are stored interleaved in the DDR memory.
The @ref{fig:mem_samples} illustrates the way samples are written, stored and read in the DDR memory.
The DDR memory size is 2Gb or 256MB.
@w{It means that the maximum number of samples that can be stored is 128M samples (@math{2^{27}*16}).}

@float Figure,fig:mem_samples
@center @image{../fig/memory_samples, 15cm,,,pdf}
@caption{Illustration of samples storage in DDR memory.}
@end float

The acquisition process is driven by a state machine.
The @ref{fig:acq_fsm} represents its states and transitions.
At start-up, the state machine is @code{IDLE}, waiting for an acquisition start command (@code{ACQ_START}).
Commands are sent to the state machine by writing in the @code{FSM_CMD} field of the control register (@pxref{ADC Core Registers}).
When a start command is received, the state machine goes to @code{PRE_TRIG} and stays in this state until the programmed number of pre-trigger samples are recorded.
After that, it goes in @code{WAIT_TRIG} state and continue recording sample to memory.
When a valid trigger is detected, the state machine moves to @code{POST_TRIG}.
It will stays in this state until the programmed number of post-trigger samples is reached.
The next state is @code{TRIG_TAG} were the trigger time-tag (4x 32-bit word) is pushed after the last post-trigger sample (to be stored in DDR memory).
Then, depending on the mode, the state machine either goes back to @code{IDLE} (single-shot mode) or to @code{DECR_SHOT} (multi-shot mode).
From @code{DECR_SHOT} it either goes back to @code{IDLE} if the number of shots is reached or goes to @code{PRE_TRIG} for the next shot.
When the acquisition is finished (state machine back to @code{IDLE}) and all samples have been written to the DDR memory, only then the software can retrieve the samples using DMA transfer.
An interrupt is generated when the acquisition ends.

@b{Note:} Start commands are taken into account only in @code{IDLE} state.

@b{Note:} Trigger are taken into account only in @code{WAIT_TRIG} state.

@b{Note:} A stop command will bring the state machine back to @code{IDLE} from any state.

@b{Note:} After a stop command, no end of acquisition interrupt is generated.

@float Figure,fig:acq_fsm
@center @image{../fig/acq_fsm, 10cm,,,pdf}
@caption{Acquisition state machine.}
@end float

There are two LED on the fmc-adc front panel.
The LED labeled @code{ACQ} is turned ON when the acquisition state machine is @b{not} in the @code{IDLE} state.
The LED labeled @code{TRIG} flashes when a valid trigger is detected @b{and} the acquisition state machine is in the @code{WAIT_TRIG} state.

@b{Note:} The number of pre-trigger sample can be zero, but there @b{must} be at least one post-trigger sample.

@b{Note:} In addition to the requested pre/post-trigger samples, an additional sample, corresponding to the trigger, will be recoded.

@b{Note:} The start of an acquisition is prohibited if either the number of shot or the number of post-trigger samples is equal to zero.


@c ==========================================================================
@node Single-shot Mode
@section Single-shot Mode

The procedure below lists the different step of a single-shot acquisition process.

@enumerate
@item Configure acquisition (trigger, number of samples, interrupts, etc...).
@item Issue a start acquisition command (the acquisition state machine must be @code{IDLE}).
@item When a valid trigger is detected, an interrupt is generated (if enabled).
@item At the end of the acquisition, another interrupt is generated.
@item Read trigger position register.
@item Configure the DMA to retrieve data.
@item Start the DMA transfer (the acquisition state machine must be @code{IDLE}).
@item When the DMA transfer is done, an interrupt is generated.
@item The board is ready for a new acquisition start command.
@end enumerate

In single-shot mode, the DDR memory is used as a circular buffer.
When the acquisition starts, samples are directly written to the DDR memory (via FIFOs).
The acquisition logic stops writing to the memory when the configured number of pre/post-trigger samples is reached.
It could happen that the write pointer reaches the top of the memory before the end of the acquisition.
In this case, the write pointer is reset to address zero and overwrite previous samples.
In order to allow the software to retrieve the requested samples (around the trigger), the @i{Trigger address} register stores the write pointer address at the trigger moment.

@b{Note:} The value stored in the @i{Trigger address} register is a byte address.

@b{Note:} Every new acquisition starts writing at address @code{0x0}.

The @ref{fig:mem_single_shot} and @ref{fig:mem_single_shot_overlap} illustrate the use of the DDR memory as a circular buffer.
The acquisition state machine is also represented.

@float Figure,fig:mem_single_shot
@center @image{../fig/memory_single-shot, 15cm,,,pdf}
@caption{Single-shot mode acquisition example.}
@end float

@float Figure,fig:mem_single_shot_overlap
@center @image{../fig/memory_single-shot_overlap, 15cm,,,pdf}
@caption{Single-shot mode acquisition example (overlapping DDR memory).}
@end float

@b{Note:} @i{Orange}: Samples written to memory and read back via DMA.
@i{Grey}: Samples written to memory, but not read.
@i{White}: Empty memory (or previous acquisition samples).


@c ==========================================================================
@node Multi-shot Mode
@section Multi-shot Mode

The multi-shot acquisition process is almost identical to the single-shot one, except that once the acquisition is started it will go around the state machine as many time as the number of configured shots.
It means that if the board is configured for N shots, it will generate N trigger interrupts (if enabled) and then another interrupt at the end of the acquisition.
A counter, accessible via a register, shows the remaining number of shots (@pxref{ADC Core Registers}).

Unlike the single-mode acquisition, in multi-shot, the DDR memory is not used as a circular buffer.
Instead, two dual port RAM (dpram) are implemented inside the FPGA.
Those dprams are alternatively used as circular buffer for each shot.
Even shots uses dpram0 and odd shots dpram1.

@b{Note:} The dprams are 2048 samples deep (sample = 4x16 = 64 bits).
The trigger time-tag requires two 64-bit word to be stored at the end of the samples.
It means that the total number of samples (pre-trigger + trigger + post-trigger) for a shot cannot exceed 2048-2=2046.

When a shot is finished, the corresponding dpram samples are written to the DDR memory.
Only the pre-trigger samples, the post-trigger samples and the trigger time-tag are written.
The first shot is written starting at address @code{0x0}.
Then the second shot is written right after the trigger time-tag of the first shot.
The @ref{fig:mem_multi_shot} shows the shots organisation in the DDR memory.

@float Figure,fig:mem_multi_shot
@center @image{../fig/memory_multi-shot, 15cm,,,pdf}
@caption{DDR memory usage in multi-shot mode acquisition.}
@end float

@b{Note:} The number of samples per shot stored in memory is equal to: number of pre-trigger samples + number of post-trigger samples + 1 (trigger sample) + 2 (time-tag).

@b{Note:} In multi-shot mode, the start of an acquisition is prohibited if the number of sample per shot is bigger or equal to the dpram size.

@c ##########################################################################
@page
@node Missing Features and Improvements
@chapter Missing Features and Improvements

@itemize @textdegree
@c DONE Take data for threshold trigger after offset/gain correction.
@c DONE Solve the internal trigger threshold issue (triggering even if signal < threshold!).
@c      -> Taking the threshold trigger data after offset/gain correction solved the problem.
@c DONE Update interface of wbgen2 generated cores (name change).
@c DONE License header in every file -> check
@c DONE Rename UTC core in time-tagging core or something like that (strictly speaking, it is not UTC).
@c DONE check Atos comments.

@c DONE Remove carrier SPI master from mapping -> shift other slaves base addresses.
@c DONE Make the project ucfgen friendly.
@c        - Put all mezzanine related cores in a wrapper (fmc adc mezzanine).
@c        - Add a crossbar inside the fmc adc block -> check impact on sdb.
@c DONE @item Add a software reset feature?
@item Remove huge files from git repo. @b{!!! This will change all commits sha !!!}
@item Add WR core; 1)for time-tags, 2)for sampling clock control@*
      - Define behavior when WR is disconnected.@*
      - Assign signals to SPEC front panel LEDs.
@item Add Etherbone support.
@c DONE @item Remove multi-irq register from interrupt controller.@*
@c      Perhaps add a counter per interrupt source instead.@*
@c      Or use wbgen2 eic (with level interrupt output).
@c DONE @item Remove unused 250MHz clock signals and buffer.
@item Unify address interfaces: put all in bytes (wishbone addr, trig pointer, ...)@*
      - Change GN4142-core WB bus(es) to byte address.@*
      - Change DDR-core WB bus(es) to byte address?
      - Change SVEC DDR access fifo (DDR address register) to byte address.
@item Add error flags to status reg (+interrupt?):@*
      - Instead of overwriting memory for a given acquisition.@*
      - If read during acquisition (or even block read during acq?).
@item Rename decimation (and "sample rate" register) in under-sampling.
@c DONE @item Increase decimation register from 16 to 32 bits.
@item Use 200MHz clock for WB bus from ddr-ctrl to gn4124-core.
@item Clean-up adc core WB interface to DDR -> use only one clock (=> sys_clk).
@item Replace all Xilinx FIFO by generic ones from general-cores lib (! last time I tried, it broke the DMA.).@*
      - Seems to work with proposed master (05.08.2013).@*
      - Still need to replace FIFO in adc core.
@item Test sampling clocks from 10MHz to 105MHz.
@c DONE @item Add sampling clock presence flag. Or better a sampling clock frequency register.
@item Add over-heat and input over-load interrupts? (from original specification)
@c DONE @item Time-tag for every trigger in multi-shot. -> trigger time-tag array
@item Review reset logic.
@c @item Generate an end of acquisition interrupt after an acquisition stop command? => NOT USEFUL!
@c NO @item Remove meta-info field in time-tags?
@c DONE @item Move sdb device descriptions from top to the wishbone_pkg.vhd (general-cores lib).
@item Include the git tree in a .tar.gz along with the .bin file (in the files section) for each release. -> modify the Release chapter accordingly.
@item Use git submodules for dependencies (allows to work without hdlmake).
@c DONE @item Add a shot counter register.
@c DONE @item Add a check of the sample number in multishot and prevent starting acq with more than 2048 samples (-> acq config ok flag).
@c DONE @item Add hysteresis on internal trigger slope detection (-> non-monotonic signals, noisy).
@c DONE @item Add debug mode: ch1=analog input, ch2=int_trig_over_thres, ch3=int_trig, ch4=trig
@c DONE @item Make data saturation programmable.
@item Trigger hold-off in multi-shot mode?
@end itemize


@c ##########################################################################
@page
@node Appendix
@appendix

@c ==========================================================================
@section Calibration Data Storage in EEPROM
Tables @ref{tab:adc_calibr_data_eeprom} and @ref{tab:dac_calibr_data_eeprom} shows the calibration data types and the arrangement in the binary file.
The first column "Byte offset" represents the offset within the binary file.

@float Table,tab:adc_calibr_data_eeprom
@multitable @columnfractions .10 .10 .35 .40
@headitem Byte offset @tab Input range @tab Description @tab Type
@item @code{0x0} @tab 10V @tab Offset correction channel 1 @tab 16-bit signed
@item @code{0x2} @tab @tab Offset correction channel 2 @tab 16-bit signed
@item @code{0x4} @tab @tab Offset correction channel 3 @tab 16-bit signed
@item @code{0x6} @tab @tab Offset correction channel 4 @tab 16-bit signed
@item @code{0x8} @tab @tab Gain correction channel 1 @tab 16-bit unsigned
@item @code{0xA} @tab @tab Gain correction channel 2 @tab 16-bit unsigned
@item @code{0xC} @tab @tab Gain correction channel 3 @tab 16-bit unsigned
@item @code{0xE} @tab @tab Gain correction channel 4 @tab 16-bit unsigned
@item @code{0x10} @tab @tab Temperature @tab 16-bit unsigned * 0.01@textdegree{}
@item @code{0x12} @tab 1V @tab Offset correction channel 1 @tab 16-bit signed
@item @code{0x14} @tab @tab Offset correction channel 2 @tab 16-bit signed
@item @code{0x16} @tab @tab Offset correction channel 3 @tab 16-bit signed
@item @code{0x18} @tab @tab Offset correction channel 4 @tab 16-bit signed
@item @code{0x1A} @tab @tab Gain correction channel 1 @tab 16-bit unsigned
@item @code{0x1C} @tab @tab Gain correction channel 2 @tab 16-bit unsigned
@item @code{0x1E} @tab @tab Gain correction channel 3 @tab 16-bit unsigned
@item @code{0x20} @tab @tab Gain correction channel 4 @tab 16-bit unsigned
@item @code{0x22} @tab @tab Temperature @tab 16-bit unsigned * 0.01@textdegree{}
@item @code{0x24} @tab 100mV @tab Offset correction channel 1 @tab 16-bit signed
@item @code{0x26} @tab @tab Offset correction channel 2 @tab 16-bit signed
@item @code{0x28} @tab @tab Offset correction channel 3 @tab 16-bit signed
@item @code{0x2A} @tab @tab Offset correction channel 4 @tab 16-bit signed
@item @code{0x2C} @tab @tab Gain correction channel 1 @tab 16-bit unsigned
@item @code{0x2E} @tab @tab Gain correction channel 2 @tab 16-bit unsigned
@item @code{0x30} @tab @tab Gain correction channel 3 @tab 16-bit unsigned
@item @code{0x32} @tab @tab Gain correction channel 4 @tab 16-bit unsigned
@item @code{0x34} @tab @tab Temperature @tab 16-bit unsigned * 0.01@textdegree{}
@end multitable
@caption{ADC calibration data stored in EEPROM (calib file).}
@end float

@float Table,tab:dac_calibr_data_eeprom
@multitable @columnfractions .10 .10 .35 .40
@headitem Byte offset @tab Input range @tab Description @tab Type
@item @code{0x36} @tab 10V @tab Offset correction channel 1 @tab 16-bit signed
@item @code{0x38} @tab @tab Offset correction channel 2 @tab 16-bit signed
@item @code{0x3A} @tab @tab Offset correction channel 3 @tab 16-bit signed
@item @code{0x3C} @tab @tab Offset correction channel 4 @tab 16-bit signed
@item @code{0x3E} @tab @tab Gain correction channel 1 @tab 16-bit unsigned
@item @code{0x40} @tab @tab Gain correction channel 2 @tab 16-bit unsigned
@item @code{0x42} @tab @tab Gain correction channel 3 @tab 16-bit unsigned
@item @code{0x44} @tab @tab Gain correction channel 4 @tab 16-bit unsigned
@item @code{0x46} @tab @tab Temperature @tab 16-bit unsigned * 0.01@textdegree{}
@item @code{0x48} @tab 1V @tab Offset correction channel 1 @tab 16-bit signed
@item @code{0x4A} @tab @tab Offset correction channel 2 @tab 16-bit signed
@item @code{0x4C} @tab @tab Offset correction channel 3 @tab 16-bit signed
@item @code{0x4E} @tab @tab Offset correction channel 4 @tab 16-bit signed
@item @code{0x50} @tab @tab Gain correction channel 1 @tab 16-bit unsigned
@item @code{0x52} @tab @tab Gain correction channel 2 @tab 16-bit unsigned
@item @code{0x54} @tab @tab Gain correction channel 3 @tab 16-bit unsigned
@item @code{0x56} @tab @tab Gain correction channel 4 @tab 16-bit unsigned
@item @code{0x58} @tab @tab Temperature @tab 16-bit unsigned * 0.01@textdegree{}
@item @code{0x5A} @tab 100mV @tab Offset correction channel 1 @tab 16-bit signed
@item @code{0x5C} @tab @tab Offset correction channel 2 @tab 16-bit signed
@item @code{0x5E} @tab @tab Offset correction channel 3 @tab 16-bit signed
@item @code{0x60} @tab @tab Offset correction channel 4 @tab 16-bit signed
@item @code{0x62} @tab @tab Gain correction channel 1 @tab 16-bit unsigned
@item @code{0x64} @tab @tab Gain correction channel 2 @tab 16-bit unsigned
@item @code{0x66} @tab @tab Gain correction channel 3 @tab 16-bit unsigned
@item @code{0x68} @tab @tab Gain correction channel 4 @tab 16-bit unsigned
@item @code{0x6A} @tab @tab Temperature @tab 16-bit unsigned * 0.01@textdegree{}
@end multitable
@caption{DAC calibration data stored in EEPROM (calib file).}
@end float

@c --------------------------------------------------------------------------
@c macro to allow includes from wbgen2 generated tex register documentation
@macro regsection{name}
@section \name\
@end macro

@c --------------------------------------------------------------------------
@page
@appendix ADC Core Registers
The registers documentation have been generated using @command{wbgen2}@footnote{@uref{http://www.ohwr.org/projects/wishbone-gen}}.
@anchor{ADC Core Registers}
   @include fmc_adc_100Ms_csr.tex

@c --------------------------------------------------------------------------
@page
@appendix FMC-ADC Embedded Interrupt Controller Registers
The registers documentation have been generated using @command{wbgen2}@footnote{@uref{http://www.ohwr.org/projects/wishbone-gen}}.
@anchor{FMC-ADC Embedded Interrupt Controller Registers}
   @include fmc_adc_eic.tex

@c --------------------------------------------------------------------------
@page
@appendix DMA Embedded Interrupt Controller Registers
The registers documentation have been generated using @command{wbgen2}@footnote{@uref{http://www.ohwr.org/projects/wishbone-gen}}.
@anchor{DMA Embedded Interrupt Controller Registers}
   @include spec/dma_eic.tex

@c --------------------------------------------------------------------------
@page
@appendix Vectored Interrupt Controller
The registers documentation have been generated using @command{wbgen2}@footnote{@uref{http://www.ohwr.org/projects/wishbone-gen}}.
@anchor{Vectored Interrupt Controller}
   @include wb_vic.tex

@c --------------------------------------------------------------------------
@page
@appendix Time-tagging Core Registers
The registers documentation have been generated using @command{wbgen2}@footnote{@uref{http://www.ohwr.org/projects/wishbone-gen}}.
@anchor{Time-tagging Core Registers}
   @include timetag_core_regs.tex

@c --------------------------------------------------------------------------
@page
@appendix SPEC Carrier Registers
The registers documentation have been generated using @command{wbgen2}@footnote{@uref{http://www.ohwr.org/projects/wishbone-gen}}.
@anchor{SPEC Carrier Registers}
   @include spec/carrier_csr.tex

@c --------------------------------------------------------------------------
@page
@appendix SVEC Carrier Registers
The registers documentation have been generated using @command{wbgen2}@footnote{@uref{http://www.ohwr.org/projects/wishbone-gen}}.
@anchor{SVEC Carrier Registers}
   @include svec/carrier_csr.tex

@c --------------------------------------------------------------------------
@page
@appendix Glossary
@section Glossary

@table @b
@item Local bus
      The @b{local bus} is the interface between the GN4124 and the FPGA.
@item Pulse
      In this document, a @b{pulse} refers to a one clock tick wide pulse.
@item Tick
      A clock @b{tick} corresponds to a period of the clock.
@item SDB
      Self-Describing Bus
@item VIC
      Vectored Interrupt Controller
@item EIC
      Embedded Interrupt Controller
@end table



@bye
