% !TeX program = xelatex
% !TeX encoding = utf8
% !TeX root = DigME.tex
% vim: set ts=2 sw=2 et spell:

\documentclass[margin=small]{tex/hsrzf}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Packages

\usepackage{tex/hsrstud}
\usepackage{tex/docmacros}

%% Language configuration
\usepackage{polyglossia}
\setdefaultlanguage{english}

%% License configuration
\usepackage[
    type={CC},
    modifier={by-nc-sa},
    version={4.0},
]{doclicense}

%% Pretty pictures
\usepackage{tikz-timing}
\usetikztiminglibrary[rising arrows]{clockarrows}

\tikzset{
  timing/font = {\ttfamily},
  timing/xunit = 8mm,
  timing/yunit = 4mm,
}

\usepackage[
  european, americanports
]{circuitikz}

\ctikzset{
  logic ports = ieee,
  logic ports/scale = .7,
  resistors/scale = .5,
}

%% Customize Lists
\usepackage{enumitem}
\setlength{\itemsep}{0pt}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Metadata

\course{Electrial Engineering}
\module{DigMe}
\semester{Fall Semester 2021}

\authoremail{naoki.pross@ost.ch}
\author{\textsl{Naoki Pross} -- \texttt{\theauthoremail}}

\title{\texttt{\themodule}: Digital Microelectronics}
\date{\thesemester}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Document

\begin{document}

\pagenumbering{roman}
\maketitle
\tableofcontents

\section{License}
\doclicenseThis

\twocolumn
\setcounter{page}{1}
\pagenumbering{arabic}

\section{Introduction to SoC}

A system on chip (SoC) is a ``complete'' system that includes
\begin{itemize}
  \item a microprocessor, memory, peripherals and
  \item application specifici blocks (IP blocks).
\end{itemize}
SoCs can be made in FPGAs, which has the following advanteges:
\begin{itemize}
  \item Shorter development cycles
  \item Lower development cost
  \item Lower total cost for low to medium volume
    \item More flexibility in operation (updates, etc.)
\end{itemize}

\subsection{Xilinx Zynq-7000 Family SoCs}

The Zynq-7000 AP SoC architecture consists of two major sections and some analog extensions. It has a Processing System (PS) with an ARM Cortex-A9 (up to 1 GHz), a Programmable Logic (PL), and an analog / mixed signal block with 2 12-bit ADCs at 1 MS/s.

The PL is built like and FPGA from the Xilinx Series 7 device. The PL is made of an array of blocks (CLB) and switch matrices. Each CLB has 2 slices, and each slice has 4 look up tables (LUT). Each LUT has 6 inputs / outputs, a carry logic, a multiplexer, and 8 flip-flops. Depending on the structure, up to 4 flip-flops can be used as latches.

\section{Design Flow}

\section{Design constraints and static timing analysis (STA)}

Synthesis and implementation tools can reduce VHDL code into a set of combinatoric and sequetial logic parts, but for the last step information about the hardware is required. Such information is given through the \emph{constraints} defined through XDC\footnote{Xilix Design Constraints, proprietary format.}  or SDC\footnote{Synopsys Design Contraints, industry standard.} files. Both file formats are mostly a set ot TCL commands.

Constraints should be generally organized in three sections (or separate files):
\begin{itemize}
  \item Physical constraints: described below, usually before timing.
  \item Timing assertions: primary clocks, virtual clocks, generated clocks, clock groups, input and output delay constraints.
  \item Timing exceptions: false paths, min / max delay, multicycle paths, case analysis, disable timing.
\end{itemize}

\subsection{Physical constraints}

Physical contraints include: I/O contraints, Netlist constraints, Placement constraints, Routing constraings. Physical constraints are usually given through the graphical user interface.

\subsection{Timing constraints}

% \begin{figure}[h]
%   \centering
%   \begin{tikztimingtable}[]
%     Clock & ccccccccccc\\
%   \end{tikztimingtable}
% \end{figure}

\[
  t_\text{slack} = T - t_\text{arrival}
\]

\section{System level VHDL}

\subsection{Aliases}
The goal is now to build re-usable intellectual property (IP) blocks with VHDL. For that we need to refresh some important features of the lanugage. The first of which are aliases.
\begin{lstlisting}[language=vhdl]
signal data_bus:
  std_logic_vector(31 downto 0);
alias first_nibble:
  std_logic_vector(0 downto 3)
    is data_bus(31 downto 28);
\end{lstlisting}

\subsection{Generics}
%% TODO: generics

\subsection{Generators}
Another useful feature are \vhdl{generate} statement, with the syntax that allows the instantiation of multiple components.
\begin{lstlisting}[language=vhdl]
`\optionalph{label}`: for `\reqph{identifier}` in `\reqph{range}` generate
  -- optional declaration part
  -- begin only required if there is a declaration
`\textrm{[}`begin`\textrm{]}`
  -- concurrent statements
end generate `\optionalph{label}`;
\end{lstlisting}
For example:
\begin{lstlisting}[language=vhdl]
for i in 0 to 7 generate
  x(i) <= a(i) xor b(7 - i);
end generate;
\end{lstlisting}
Or in a more realistic case, with components imported from elsewhere.
\begin{lstlisting}[
  language = vhdl,
  caption = {
    Example of generate with a component.
    \label{lst:generate-component}
  },
]
-- in architecture
bcd_to_sseg_inst_loop:
for i in 0 to nr_digits - 1 generate
  bcd_to_sseg_inst: component bcd_to_sseg
    port map(
      clk => clk,
      rst => rst,
      bcd => bcd_array(i),
      sseg => sseg_array(i)
    );
end generate;
\end{lstlisting}
where \vhdl{bcd_array} and \vhdl{sseg_array} are of course array types, and \vhdl{nr_digits} is a constant.

\subsection{Functions and procedures}
Furthermore VHDL has functions that can be useful to avoid rewriting the same code. Function have multiple inputs and a signel output, are allowed to be called recursively, but cannot declare or assign signals, nor use \vhdl{wait} statements.
\begin{lstlisting}[language=vhdl]
function `\reqph{name}` (`\optionalph{list of arguments with type}`)
  return `\reqph{return type}`
is
  `\optionalph{declaration of variables}`
begin
  -- sequential statement (but not wait)
end function `\reqph{name}`;
\end{lstlisting}
An example is a parity generator:
\begin{lstlisting}[
  language = vhdl,
  caption = {
    An odd parity generator function.
    \label{lst:pargen}
  }
]
function pargen(avect: std_ulogic_vector)
  return std_ulogic
is
  variable po_var : std_logic;
begin
  po_var := '1';
  for i in avect'range loop
    if avect(i) = '1' then
      po_var := not po_var;
    end if;
  end loop;
  return po_var;
end function pargen;
\end{lstlisting}

In testbenches it is common to see procedures. They differ for function as they can have multiple inputs and \emph{multiple output}. Because of this they in practice are usually not synthetizable. The syntax is similar to functions:
\begin{lstlisting}[language=vhdl]
procedure `\reqph{name}` (`\optionalph{list of arguments with direction}`) is
  `\optionalph{declaration of variables}`
begin
  -- sequential statement
end procedure `\reqph{name}`;
\end{lstlisting}
With \emph{list of arguments with direction} it is meant an expression like \vhdl{a, b : in real; w : out real}, similar to the arguments of \vhdl{port}.

\subsection{Arrays and records}

To efficiently use \vhdl{generate} statement, such as in listing \ref{lst:generate-component}, we ned array types. Arrays types (fields) of other types are defined with the following syntax.
\begin{lstlisting}[language=vhdl]
type `\reqph{name}` is array (`\reqph{upper limit}` downto `\reqph{lower limit}`) of `\reqph{base type}`;
\end{lstlisting}
For example to complete listing \ref{lst:generate-component}, we create 1 by 1 matrices.
\begin{lstlisting}[language = vhdl]
constant nr_digits : integer := 3;
type bcd_array_type is
  array (0 to nr_digits -1)
  of std_ulogic_vector(3 downto 0);
type bcd_array_type is
  array (0 to nr_digits -1)
  of std_ulogic_vector(6 downto 0);
\end{lstlisting}

While all arrays elements must have the same underlying type, \emph{records} allow for different types to be combined together.
%% TODO: syntax block
For example:
\begin{lstlisting}[language = vhdl]
type memory_access is record
  address : integer range 0 to address_max -1;
  mem_block : integer range 0 to 3;
  data : std_ulogic_vector(word_width -1 downto 0);
end record;
\end{lstlisting}

\subsection{Packages}

To declare your own packges, the syntax is rather easy:
\begin{lstlisting}[language = vhdl]
`\reqph{{\tt library} and / or {\tt use} statements}`
package `\reqph{name}` is
  `\optionalph{declarations}`
end package `\reqph{package name}`;
\end{lstlisting}
And possibly in another file the implementation is give with:
\begin{lstlisting}[language = vhdl]
package body `\reqph{name}` is
  `\reqph{list of definitions}`
end package body `\reqph{name}`;
\end{lstlisting}

In practice it is common to see for example a configuration package, that contains all constants for the project. For example if we were to put the function \vhdl{pargen} from listing \ref{lst:pargen} we could do:
\begin{lstlisting}[language = vhdl]
package parity_helpers is
  constant nibble : integer;
  constant word   : integer;
  function pargen(avect : std_ulogic_vector) return std_ulogic;
end package parity_helpers;

package body parity_helpers is
  -- functions
  function pargen(avect: std_ulogic_vector)
    return std_ulogic
  is `\ldots \textrm{same as listing \ref{lst:pargen}} \ldots`
  end function pargen;
  -- instantiation of variables
  constant nibble : integer := 4;
  constant word   : integer := 8;
end package body parity_helpers;
\end{lstlisting}
And later use it with \vhdl{use work.parity_helpers.all}.

\subsection{Fixed point arithmetic}

\subsubsection{Mathematics}

Recall that a binary number is represented using weights `bits' \(a_k \in \{ 0, 1 \}\) in front of powers of 2, so that an integer \(z \in \mathbb{N}_0\) is represented with \(n\) bits as
\[
  z = \sum_{k=0}^{n-1} a_k 2^k .
\]
Thus with \(n\) bits we can represent the integer range \(\{0,\ldots, 2^{k-1}\}\).
To expand this to negative integers we shift everything by \(2^k\) obtaining
\[
  z = -(2^{n-1}) a_{n-1} + \sum_{k=0}^{n-2} a_k 2^k,
\]
which allows for values in the asymmetric integer range \(\{-2^{n-1},\ldots, 2^{n-1} -1\}\). To further extend this to the rational numbers we add to the \(n\) integer bits, \(m\) fractional bits, such that
\[
  z = \sum_{k = -m}^{n - 1} a_k 2^k .
\]
This format is known as the \texttt{Qn.m} or \(Q(n,m)\) format. It is however not specified if the values are to be interpreted as signed or unsigned. For that there are: \texttt{uQn.m} for unsigned values which has range 0 to \(2^n - 2^{-m}\), and \texttt{sQn.m} for signed values with range \(-2^{n-1}\) to \(2^{n-1} - 2^{-m}\) (same as previous but shifted by \(2^n\)).

When doing calculations using \texttt{Qn.m} with different sizes, generally the following rules apply:
\begin{align*}
  Q(n_1, m_1) &+ Q(n_2, m_2) \\
    &= Q(\max(n_1, n_2) +1, \max(m_1, m_2)) \\
  Q(n_1, m_1) &\cdot Q(n_2, m_2) = Q(n_1 + n_2, m_1 + m_2)
\end{align*}
%% TODO: review with skript
% TODO: guard bit
There is an edge case for products between \texttt{sQn.m} numbers where we can save a bit using
\begin{align*}
  Q_\mathrm{s}(n_1, m_1) &\cdot Q_\mathrm{s}(n_2, m_2) \\
  &= Q_\mathrm{s}(n_1 + n_2 -1, m_1 + m_2 + 1)
\end{align*}

\subsubsection{Manual implementation}

To manually implement fixed point arithmetic in VHDL, we can use \vhdl{integer} types by left shifting the numbers by the right amount. For example:
\begin{lstlisting}[language = vhdl]
constant A : real = 2.5248;
-- to convert this into a uQ2.6 (8 bits)
-- we have to left shift by 2^6.
variable a_fix : unsigned(7 downto 0) :=
  to_unsigned(integer(2.0 ** 6 * A), 8);
-- Note that by keeping only 6 digits
-- the value is truncated down to 2.5156
\end{lstlisting}

\subsubsection{With VHDL 2008 \vhdl{fixed_pkg}}

In VHDL 2008 there is a fixed point arithmetic library, which is unfortunately not completely standardized yet. It it not always optimum in terms of resource usage and speed because it guarantees overflow prevention. To import it we simply add the following:
\begin{lstlisting}[language = vhdl]
-- since VHDL 2008
library ieee;
use ieee.fixed_generic_pkg.all;
use ieee.fixed_float_types.all;
\end{lstlisting}
\begin{lstlisting}[language = vhdl]
-- older versions
library ieee_proposed;
use ieee_proposed.fixed_pkg.all;
use ieee_proposed.fixed_float_types.all;
\end{lstlisting}
To represent \texttt{uQn.m} numbers the syntax is:
\begin{lstlisting}[language = vhdl]
signal f : ufixed(`\reqph{n}` downto -`\reqph{m}`);
\end{lstlisting}
The minus sign implies that the values are after the comma.  To write \texttt{sQn.m} numbers there is the type \vhdl{sfixed}.  Actually any range is valid, so it is possible to write:
\begin{lstlisting}[language = vhdl]
signal f : ufixed(-2 downto -3);
\end{lstlisting}

Conversion operators \vhdl{to_ufixed}, \vhdl{to_sfixed} are available. To get back \(n\) and \(m\) the attributes \vhdl{'high} resp. \vhdl{'low} are available. Furthermore the library allows to control the behaviour of conversions and range limits, through arguments of \vhdl{to_ufixed} (or \vhdl{to_sfixed}).
\begin{itemize}
  \item Overflow is controlled with \vhdl{overflow_style} set to \vhdl{fixed_saturated} (default, value cannot increase / decrease) or \vhdl{fixed_wrap} (over / underflow).
  \item Rounding can be controlled by setting \vhdl{roud_style} to \vhdl{fixed_round} (default) or \vhdl{fixed_truncate}.
\end{itemize}

\subsection{Block RAM}


\section{Intellectual Property (IP) Blocks}

\section{Serial communication}

\subsection{Classification}

Serial communication protocols can be categorized by various criteria. From a network topology standpoint nodes can be connected as point to point (USART), star, bus (PCI), ring, mesh (IoT), fully connected, line, or tree . From a timing perspective a communication link can be either synchronos or asynchronous. The hardware interface can be serial or parallel. The communication can be On-Chip or Off-Chip. And finally, physically the electrical signal representing bits can be single ended, differential, voltage mode, or current mode.

Of the well known Open System Interconnect (OSI) model, which is composed of seven layers (from top to bottom): application, presentation, session, transport, network (packet), data-link (frame), physical (bit stream), in this course we will only care about the bottom 2, namely data-link and physical.

\subsection{Logic to physical signal conversion}
\begin{figure}[h]
  \centering
  \begin{circuitikz}[]
    \draw (0,7) node[anchor = east, buffer port] (in) {}
      to[short] ++(5mm,0)
      to[TL, label=\(Z_0\)] ++(20mm,0) coordinate (X)
      to[short] ++(5mm,0) node[anchor = west, buffer port] (out) {}
      %
      (X) to[R, label=\(R_\mathrm{f}\), label distance = 5pt, *-]
      ++(0,3) node[tground, label=\(V_\mathrm{cco}\)] {}
    ;

    \draw (0,0) node[anchor = east, buffer port] (in) {}
      to[short] ++(5mm,0) coordinate (Y)
      to[TL, label=\(Z_0\)] ++(20mm,0) coordinate (X)
      to[short] ++(5mm,0) node[anchor = west, buffer port] (out) {}
      %
      (X) to[R, label=\(R_\mathrm{n}\), label distance = 5pt, *-]
      ++(0,3) node[tground, label=\(V_\mathrm{cco}/2\)] {}
      %
      (Y) to[R, label=\(R_\mathrm{f}\), *-]
      ++(0,3) node[tground, label=\(V_\mathrm{cco}/2\)] {}
    ;

    \ctikzset{amplifiers/plus = {}, amplifiers/minus = {}}
    \draw (-.7,-7) node[anchor = east, fd op amp, scale = .5] (in) {}
      (in.out +) to[short] ++(1mm,5mm) to[R, label = \(R_s\)] ++(10mm,0) coordinate (Yu)
      to[TL, label=\(Z_0\)] ++(20mm,0) coordinate (Xu)
      %
      (in.out -) to[short] ++(1mm,-5mm) to[R, label = \(R_s\)] ++(10mm,0) coordinate (Yd)
      to[TL] ++(20mm,0) coordinate (Xd)
      %
      (in.east) ++(40mm,0) node[anchor = west, fd op amp, scale = .5] (out) {}
      (Xd) to[short] ++(8mm,0) to[short] ++(1mm,5mm) (out.+)
      (Xu) to[short] ++(8mm,0) to[short] ++(1mm,-5mm) (out.-)
      %
      (Yu) to[R, *-*, label = \(R_\mathrm{nd}\)] (Yd)
      (Xu) to[R, *-*, label = \(R_\mathrm{fd}\)] (Xd)
    ;
  \end{circuitikz}
  \caption{
    \label{fig:termination}
  }
\end{figure}



\end{document}
