---
# System prepended metadata

title: Class 1 (03/29/2022)

---

# Class 1 (03/29/2022)

* Assums exxperts in 172 material, such as multiplexers and encoders/decoders
* HDL= Hardware Description Language
* Will create weekly assignments module, and will scan slides not included in text and upload to canvas
* The intel lab has a board that we will use for class
* Can use own board/simulator to demonstrate to TA
* ways FPGA's are used
    * FPGA  is target device
    * applicaion specific integrated circuit
    * suppose you hvae a design that requires a microprocessor that has some amount of volatile/nonvolatile memory. FPGA is a general device, but the chip is basically blind unitil you get and program the chip. For asic, you only use whats on the silicon and nothing else.
    * Problems: costly, tedious, time consuming process.
    * You would not go ASIC unless you **REALLY** have to watch the size of the chip
    * takes a lot to get ASIC up and running
    * software ENGs do not have any way to debug their code until the ASIC chip is finished being developed.
    * hardware and software in this case are sequential processes, not concurrent.
    * One solution: use the FPGA to 'prototype' the ASIC chip - Take all the functionality and all the **TIMING** that you expect from the ASIC chip, and implement it into the FPGA.

* Two ways to implement design - HDL and Schematic Capture. People use Hardware Description Language to build their design
* When you write RTL code, your Veralog code is written at Dataflow or behavior Level flow
* No gate level flow for Register Transfer level design. **(Registers feeding combinational logic feeding registers.)**
* REVIEW LOGIC COUNTERS AND FINITE STATE MACHINES

We will learn Verilog (System Verilog and Verilog merged, but we will be focusing on Standard Verilog)
* Verilog has an Alphabet, Semantics, and additonal features
* Definitions
    * Alphabet: Characters that can be used
    * Syntax: rules for using the alphabet to construct program
    * semantics: meaning or interpretation of a syntactically correct program statement
* Double quotes around var: truns variable into string.
    * strings dont hold much value in Verilog
* C and Verilog have similar syntax
* There are 3 types of operators
     * Urinary: **A = ~ B** (A is equal to the compliment of B)
     * Binary: **Y = C + D**
     * Tertiary:**a = b? c:d**(if then else statement)



# Class 2 (03/31/2022)
**Identifiers:**
* Variable names
* rules
    * must start with "" or a letter
    * cant use $
**keywords**
* reserved names
* eg
    * assign
    * begin 
    * end
* **must be lower case** remember that verilog is case sensitive

```
value set = { 0, 1, x, z}
```
we can therefore define (net) as an interconnection between circuit elements
* keywords:
    * wire, word, WOR

**declare a net variable**
```
wire a,y;
```
**The following is on Pg 46**
```
wire a; //Declare net a for the above circuit
wire b,c; //Declare two wires b,c for the above circuit
wire d = 1'b0; //Net d is fixed to logic value 0 at declaration
```
* last one does not make sense because it does not have a specific declared value

**Register variables**
* they store values
* Keyword: reg
* Notes:
    * can be single or multiple bits
    * not a register (like a D Flip-Flop)
    * it is just a variable that can hold a value

**Example 3-1 Example fof register**
```
reg reset; //declare a variable reset that can hold its value
initial     //this constuct will be discussed later
begin
    reset = 1'b1;
    #100 reset = 1'b0;
end
```
* default time is 1 ns

**Example 3-2 Signed register declaration**
```
reg signed [63:0]m; //64 bit signed val *****KNOW THIS NOTATION
integer i; //32 bit signed value
```

**board example**
```
reg y;         // y is a 1 bit reg variable
reg[7:0]a;    // 'a' is a 8 bit reg var
reg[3:0]b;       //'b' is a 4 bit reg var

//therefore youre allowed to do

a= 8'b10011101;
b= a[4:1];    // b = 4'b1110
y= a[6];      //y = 1'b0

```

**Board example: Declare memory**
```
reg[7:0]M[4095:0];
    
```
[7:0] means bits/location
[4095:0] means # of locations

**Parameter declaration**
* defines constants at compile time
* eg.
    * parameter byte = 8;
    * parameter is the keyword
    * `reg[byte-1:0]M[4095:0]`

**Strings**
* they are defined in double quotes
* strings can be stored in reg
```
reg[8*18:1] string_value;
initial
    string_value = "Hello World";
```

**Displaying information**
```
$display
```
* equivalent to printf in C
* only time you will use this is for test benches
* `$display$time` would give you the simulation time (Ch3 Ex 5 i think)

**Compiler Directives**
```
define
```
* used to define text macros in Verilog

**Instantiation**
* process of creating an objectfroma module template

**Instance**
* object created during instantiation

**C vs verilog ex**

C:
```
float foo(float x){
====== //subroutine
}
main(void){
====
y=foo(22);
=====
}
```

Verilog
```
**module foo(...); **       //this is a module template
**====**
**endmodule**

module____
=====
foo();                   //instance can say foo is instantiated in module____     
endmodule

```

**make sure to study ex 2-1**

**Modules are the basic building blocks of your code** 

Header:
* Module Name
* port list , port declaration(fi ports present)
* Parameters(optional)

Body:
* Declarations of wires, regs and other variables
* Data flow statements (assign)
* instantiation of lower level modules

Footer:
* endmodule statement

Ports are the interface between a module and the external world

**Port Declaration**
* Keyword: Input
    * Type of port: input port
* output
    * output port
* inout
    * bidirectional port

 **Ex 4-3 Port declarations**
```
module fulladd4(sum, c_out, a, b, c_in);

//Begin port declarations sections
output[3:0]sum;
output c_out

```
**KEEP FIGURE 4-4 HANDY**

* It has port connection rules

**Example 4-6**
```
module Top;
//Declare connection variables
reg[3:0]A,B;
reg C_IN;
reg[3:0] SUM;
wire C_OUT;

    //Instantiate fulladd4, call it fa0
    fulladd4 fa0 (SUM, C_OUT, A,B,C_IN);
    ...
    <stimulus>
    ...
endmodule

```

**Abstraction**
* providing information while hiding irrelevant or superfalous or (possibly) confusing information.

**More abstraction**
* less detail


In verilog, there are **3** levels of abstraction
1. gate level
2. dataflow: you are writing boolean eq
3. behavioral: if-then else, repeat-until, case statements, etc.


* schematic
* boolean eqns
    * gives you boolean eq and basic idea, but not telling you what exactly to do (hardware independent)
* truth table
    * no information at all
    * provides less info than the behavioral level

# Class 3 (4/5/2022)
**Gate-level**
* Lowest level
* has the greatest of chance of a successful synthesis
* since you specify the gates, the compiler has very little to figure out
**Def(Primitive gate): a basic logic gate that is predefined**
* goes over img 5-1

Format: 

`gate_type gate identifier (out, in1, in2...)`

* gate_type can be and/or

There is no such thing as 3 input XOR or XNOR gate

**Goes over Ex 5-1**
* Recommend to use U for gates as the gate identifier (ie U1, U2, U3, etc)

```
and U1(out1, in1, in2);
and U2(out2, in3, in4);

//Is the same as

and U1(out1, IN1, IN2), U2(OUT2,IN3,IN4);
```

**Goes over tbl 5-1**

**Goes over image 5-2**
* you can specify multi-output gates
* Why would you want that?
    * where you can come into fan out programs
    * help split the outputs to get enough current drive

**Goes over image 5-3**
**Goes over image 5-4**
**Goes over image 5-5**

In C we are used to code going line by line

In verilog, order is irrelavent

code changes meaning, or result, whenever the input changes.
* kinda, updates once the input is changed for a specific output.

**Goes over img 5-7**

**Goes over img 5-8**
* it is used to introduce a propagation delay
* `and #5 U6(e,a,b);
    * **WE DONT WANT THIS**
    * Once we put a time component, you make the code technology dependent
    * In verilog, we want our code to be technology INDEPENDENT

**Gate level modeling**
* advantages
    * intuitive
    * high probability of successful sythesis
* Disadvantage
    * unwieldy for large design

**dataflow or behavioral**
* RTL

* reg variables can hold values
* wire(net) variables cannot

**How do we give wire variables values?**
* there are 2 ways
    * drive it with a module output
    * continuous assignment statement
        * Keyword: Assign

Ex:
```
wire y1, y2;

xor U6(y1, a, b);    //Example of first method 
assign y2 = a+b;    //Example of second method
```
* In general: assign (lefthand) = (righthand)

LHS can be:
* scalar variable
* vector variable
* bit select of a vector
* part select of a vector
* concantenation ofany of the above

Ex:
```
assign s[7:0] = ...    //Example of vector variable

wire[5:0]A;
assign A[2] = ...     //Example of bit select

assign[4:1]= ...     //Example of part select

```

**Defn(Expression): combination of operators and operans**
**Defn(Operand): any data element(net, reg, constants)**
**Defn(Operator): ANything that acts on operans**

1) On Arithmetic operator
    * size matters
    * e.g:
```
reg[3:0]A,B,C;
reg[5:0]D;

A= B+C;    // result is 4-bits
D=B+c;    //result is 6-bits
```

2) if any operand is 'x' (dont care) then the result is 'x' (dont care)

Logical operators
* the entire variable is treated as logic 0 or logic 1
    * logic 1: always the case if variable != 0;

e.g.
A= 3, B = 1, C = 0
A&&B = Logic 1
B&&C = Logic 0

Exception:
if any bit is 'x' or 'z' (high impedence) result is 'x'

D= 2'bix
B||D = 'x'

**Goes over img 6.2**

In verilog **{}** are concantenation operatiors

**Concantenation**
* joins things together
* e.g.
```
wire[7:0]D;
wire[7:0]E;
assign D[7:4] = {E[0], E[1], E[2], E[3]};
```
# Class 4

**Shift operator**
* syntax: LHS = RHS << # (decimal)
* A= 4'b1001, B= 4'b1100
* A=B>>2

For loops in C:
for{
...
}

for loops in Verilog:
for
begin
...
end


**Pg 104**
Replication

**Conditional Operators**
* Syntax: Condition? <-- Predicate(meaning its either true or false)
    * expr1 : expr2

**Pg105**
```
```
**7.6.2**

Relational operators result in a 1 or 0 
Ex:
```
assign #EQ_DELAY a_eq_b = a == b; //a_eq_b will be either a 0 or 1
assign #GT_DELAY a_gt_b = a>b;
assign #LT_DELAY a_lt_b = a<b;
```

**Example 6-2**
add: module mux4_to_1(out,i0,i1,i2,i3,s1,s0);

**Example 6-3**

**Example 6-4**

**Example 6-6**

**Example 6-7**

# Behavioral Level

**Defn(Testbench)**
* a program to rest and verify functionally a desgin
* notes:
    * written in verilog
    * restbenches have 2 functions
        * generate test patterns
        * collect the design responses
    * testbench uses only the behavioral level of abstraction syntax
    * not everything in the behavioral level of abstraction is synthesizable

behavioral models have 2 procedures
* initial 
* always
* Notes:
    * initial/always execute concurrently
    * no limit on the number of initial and always procedures
    * initial/alwaus procedues begin executuin at simulation time t=0
    * no nesting

Keyword: Initial
* begins execution  @ t=0
* executes once
* syntax: initial[delay] statement(s)
    * This statement could be any of the following:
        * an assignment(blcoking or non-blocking)
        * continuous assignment statement <-- only case you would have a data flow type of instruction
        * conditional statement
        * case statement
        * a loop
        * an event trigger
        * parrallel block //if its a parrallel block, there must be a sequential one
        * wait
        * disable

**Defn(Sequential block)**
a set of instructions that execute in the order they appear

**Always**
```
//Literally a forever loop
always
begin
...
end
```

## imt

reg A;
.
.
.
A=2; //Can only be done inside an initial or always statement

**Example 7.5: Way to create a clock module**

**Blocking vs non-Blocking assignments**
```
A=B;    //Blocking


A<=B;   //Non-Blocking
//This is analogous to...
```
A<-B

**What is the difference between blocking and non-Blocking?**
* Blocking assignment:
    * LHS = RHS
        * this occurs before you go on to the next statement

* non-blocking assignment:
    * RHS's are recorded
        * LHS updates all occur when you hit "end" statement

```
initial
    begin
        A=3;
        B=2;
        
    end
initial
    begin
    #10 A=B;
    B=A;
    end
    
//A=B=2
```

```
initial
    begin
        A=3;
        B=2;
    end
    
initial
    begin 
    #10 A<=B;
    B<=A;
    end
    
//A=2, B=3
```
Notes:
* do nto use non blocking assingment in continuous assignments
* do not mix within a initial/always statement

# Class 5

```
always
    begin
        #on_delay;
        A= 1'b1;
        #off_delay;
        A=1'b0;
    end
```
 we can also use expressions
 `#on_delay/5)A = 1'b0;`
 
 **Timing controls**
 
 ```
 parameter on_delay=3, off_delay = 5;
 
 reg A;
 
 initial
     A=0;
    
Always
    Begin
        #on_delay A= 1;
        #off_delay A=0;        //These two delays are relative to eachother and are additive
    end
```

**(No need to memorite these next two)**

**Intra-assignment delay**    

```
a = #2b;

//which is equivalent to...

begin
    hold = b
    #2;
    a=hold;
end
```

**"regular" delay**
```
#2a=b;

//which is equivalent to...

begin
    #2;
    a=b;
end
```

**Testbench Syntax**

```
module module_name; //no port list
    local variable delcarations;
    instantiated modules;
    generate test signals using initial/always statements
end module
```

**Example**
```
initial
    begin
        reset = 0;
        #100 reset =1;
        #80 reset =0;
        #30 reset =1;
        end 
        
// Now lets move the reset values to the right hand side

initial
    begin
        reset=0;
        reset = #100 1;
        reset = #80 0;
        reset = #30 1;
    end

//Waveform is going to look the same between the two.
//Why?
//Cause they are both blocking statments
//meaning one line cant occur until the one before it finishes.
//Unless we rearrange the order, the waveform will be the same.

//nonblocking assign
initial
    begin
        reset <=0;
        reset <= #100 1;
        reset <= #80 0;
        reset <= #30 1;
    end
//This wave form is difference because the data is ONLY updated until it reaches the end statement.
//What do we need to do to have the same waveform?

begin
    reset <= #0;
    reset <= #100;
    reset <= #180;
    reset <= #210;
    
end
```

**Event based timing control**
* uses : @
* Purpose: is to synchronize events in a module
* Two types: edge triggered, and level sensitive

**Edge Triggered**
* Keywords: posedge(0->1 transition)
            negedge(0->1 transition)

**Example 7-13**

**Example 7-15**
* when combining both always and events, it will always loop, and will always look for an event in order to begin the loop

**Example 7-17**
* having @* translates to "in the case that any variable in the right hand side changes, it will cause a trigger"

**Example Pg 137**

**Example 7-18**


In C:
switch{}
.
.
.

in verilog:
Case statements

syntax:
```
case(expr)
    value1:
    value2:
    value3:
    .
    .
    .
    valueN:
endcase
```

**Ex 7-18**

**Ex 7-19**

suppose "expr" is 4-bits with each bit all{0,1,x,z}

cause- everything must match
casez - all z bits are ignored
casex - all z and x bits are ignored

Note: by "ignore" meanse those bit positions are not compared

Let A = 2'b11

case(A)
    2'bx1: b = 0;
    default: B=1;
endcode 

B will. = 1 in this case

casex(A)
    2'bx1: b= 0
    default: B=1
endcode

B will = 0 in this case

**Example 7-21**

4 types of loops:
* while
* for
* repeat
* forever

**Example 7-23**
**Example 7-24**
**Example 7-25**

**Defn(Parallel block)**
* all instructions execute concurrently (subject to even trigggers and/or #delays)

Notes:
* statements execute concurrently eve if blocking assignments are used
* delays are relative to when the blocks were entered
* Keywords: fork, join

**Example 7-26**

# Class 6

**Example 7-35**
* out is declared as a reg variable so it could be used in a always statement
* theres an 'or' in your always statment, but it could be a comma aswell

**Example 7-36**
* if you have reg variables that you have delcared, intial value is "x" (dont care)

In C we have Subroutines,
In verilog, we hve tasks and functions.

**Task and Functions**
* They are declared inside the module where it is used
* **table 8-1 for comparing Functions and tasks

**tasks**
* Properties:
    * must be clled from an initial or always satement
    * may have 0 arguments
    * can have timing/even controls
* Syntax:
     `task[automatic]task_name;task
     (keyworkds)    port declarations:
                    procedural statements
      endtask`
* Notes:
    * all ports are regs
    * ports in tasks(which is used to pass values to/from) != ports in modules(interconnection signals)
    * parameters are pass by value only
    * can manipulate any variables within the module where delcared
    * "automate" makes the task re-enterant
    
**Example 8-4**


* there are no delay, timing, or even control constructs in the procedure
* there are no nonblocking assignments
* Syntax:
```
fucntion[range] func_name;
input declarations;
other declarations;
procedural statments;
endfunction
```
* keywords: 

```
module func_example;
    parameter Max=8;
    //function template
    function[MAX-1:0]reverse_bits;
    input[MAX-1:0]DIN;
        for(k=0; k<MAX; k= K +1)
    endfunction    reverse_bits[MAX-K-1] = DIN[K]
    .
    .
    .
    endmodule
```
**Example 8-9**

normally
LHS = RHS;
* sometimes you may want to overrite the normal assignment two ways
    * assign/deassign
    * force/release 

# Class 7 

**Module instance**
* parameter values
    * eg:
```
module ALU;
    parameter delay1=2;
    parameter delay2=3;
    parameter delay3=7;
    ...
    <module internals>
    ...
endmodule

//parameter assingment by position
ALU #(4,5,6)b1(); //delay1-4,delay2=5,delay3=6

//parameter assingment by name(no worrying about order)

ALU#(.delay2(5), .delay3(6))b2();
```

```
module bus_master
    parameter width =8;
    parameter speed =10;
    ...
    <internals>
    ...
endmodule

busmaster #.width(32))bus_master();
```
* it is good to use parameters in the case where variables change


**Time scales**
* syntax: 'timescale time_unit/time_precision
* notes:
    * values must be 1, 10, 100
    * units are s, ms, us, ns, ps, fs
    * time_unit sets delay scale. time_precision the round off units during simulation
    * eg.
```
'timescale 1ns/loops
assign #5 Y=A; //delay is 5 ns

'timescale 100ns/1us
assign #5 Y=A; //delay is 0.5 us
```

**File I/O**
OPENING syntax:
```
$fopen = ("file_name");
returns an integer pointer to the file "file_name"


integer file_ptr;
file_ptr = $fopen("my_file");
```

CLOSING syntax:
```
$fclose(file_ptr);

```

to write to a file
```
fdisplay(file_ptr, p1,p2,...);
```

There are two system commands one can use in order to read from a file

```
$readmemb    //assumes that these are bytes
$readmemh    //assumes that these are hex char
```


**example 9-14**
* will come back to it, there are some errors

**Value change dump (VCD) file**
* defn: an ASCII file that timestamped signal changes.
* its used by post-processing tools
* it tells you what signal change, what did it change to, 

**Figure 9-1**

**Defn (Synthesis)**
* the process of converting a high level design description into an optimized gate level netlist
* notes:
    * high level description if mostly RTL code
    * also need
        * design library
        * design constraints

**Table 14-1**

simulation results does not equal synthesis results

Note:
* 'x' and 'z' have no meaning to a synthesizer

**Example 14-14**
**Fig 14-6**

**Example 14-4**

# Class 8

**Assume "test.vec" contains:** 
010 010 0 100 0
010 011 1 110 0

**Managing Complexity**
* guiding principle:
    * clearly separate the control path and data path
* datapath def:
    * collection of ALU, register, MUXES, wtf needed t manipulate or operate on data
* controlpath def: 
    * sequencing logic that affects what happens on the datapath

1) structure your data path
    * from the specification determine the functional units needed 
        * by functional units we mean: ALUS, decoders,...
    * do design tradeoffs in this step

2) define the control points (ie, the status/control signals needed)

3) define a control strategy
    * fsm
    * counter

4) determine a "reset" strategy
    * dont forget some initialization is asynchronous while others are synchronous
    * when does it reset? How long does it last?

5) Greenwood's 1st law
    * always design before coding

**Defn: Design partitioning**
* the process of splitting into modules thereby creating a design hierarchy
    * you can do vertical and horizontal partitioning

Only modules are the bottom of the hierarchy should be gate level abstractions

**Defn: critical path**
* the longest delay path in the circuit
* try to put entire critical path in one module

Whereever possible regitser all output modules 

use resource sharing

keep modules as small as possible


Let say we want a program that takes the squareroot(93.8)

**2-1 week 4 module**
![](https://i.imgur.com/023w7Xd.png)

**2-2 week 4 module--NonBlocking**
![](https://i.imgur.com/B9kkbRg.png)

**2-3 antoher nonblocking design**


Rules 1combinaton logic use non blocking
sequential logic uses blocking

rules 2: dont mix within a module

Latch inference ia bad thing...

**Defn:latch inference**
* the unintended addtion of latches into a design

# Class 9
**Example in documents posted for week4**
**Example 2.3.2 Priotry decoder**
**Example 2.4.1**
**2-44 in doc**

**Using non-blocking statements**
```
always@(posedge clk)
    begin
        B<=A;
        C<=B;
        D<=C;


```
We want something synthesized like :

|A| ->D Q |B| ->D Q |C|-> D Q |D|->

:. WRONG
IT GIVES US A PARALLEL REGISTER

```
B=A;
C=B;
D=C;
```

CORRECT


registering output can help in speeding up your circuit

X3,x2,x1 -> FF -> logic 1 ->logic 2 -> logic3 -> FF ->

t_su=t_n =0;
Processing time: 3MT

Amdahls law (gues speed up)
* M =40
  Speedup = 120/42 = 2.9 
  3MT/3+(M-1)T = 3M/3+(M-1) <-w/o pipelining

**Inferring bidirectional I/O**

configurable logic block(CLB)

FPGA fabric

Input/output blocks(IOB)

* when you program a FPGA, we call this configuration

there 3 things that you will program (configure)
* CLB functionality
* IOB functionality
* routing

how do you implement boolean expressions in a configurable logic box? LUT!

# 5/10
* Any combinational circuit can be implemented in a memory chip
**Imtellectual Property(IP)** : Previously design and synthesize modules.
* There are two types:
    * Soft IP: HDL coded module
    * Hard IP: Hardware implementation externel to the FPGA Fabric
        * FPGA Fabric: matrix of configurable logic blocks


There are 3 types of IP:
* 1st party: IP you write
* 2nd party: IP provided by the FPGA vendor
    * Vendor: companies that actually sell IP (usually free)
* 3rd party: IP provided by a company that is NOT an FPGA vendor

**Difference between instantiation and inference:**
* Instantiation: you have a module and you instantiate it in antoher module
    * Advantage: control over the design
    * Disadvantage: not portable
        * your design between FPGAs may not be compatible

* Inference: Im writing my code, the way I write it says what module im looking for. Synthesizer believes you wanted something paticular.
    * Advantage: flexibility
    * Disadvantage: less controll

**Tbl 14.1**
IP core == IP module

```
//Ex of Inference
assign B_func = dnf_DECODE (func_A)
```

**Vortex 5 family overview:**
* The LUT has 6 inputs
* Sometimess there is a trade off, more inputs, less luts, vice versa

**Distrubuted RAM**:Uses luts from the FPGA fabric to distribute memory throughout
**Block RAM**: hard IP eternal to the FPGA fabric

**DSP Slices**: *disgital system processing*

FPGAs are static RAM base

Everytime you turn on power, we will ned to reconfigure it

All vendors will have application engineers:
* They are like a help line
* help with a variety of different  issues for design
* They are advisors
* You can call up, and ask "what am i doing wrong"
* They have designs that are willing to share with you

# 5/12

When we implement a design, you want to use hard rather than soft IP as much as possible
* Why?
    * You want to preserve LUX
    * youre gonna get more timing info

**VIRTEX 5 FPGA CODING**

