Monday, July 20, 2020

System Verilog Assertion to check if no more than 3 ACK are generated in a 10 cycle window

The above problem statement gives us 2 conditions.
  1. Window of check should be 10 cycles
  2. Number of ACK should be no more than 3.
Since the both end at the same time we will use INTERSECT operator.

Assertion :
  property check_ack;
    @(posedge clk) ack[->3] intersect 1[*10];
  endproperty

ack[->3] or ack[=3] satisfies point 2.
Since we need to check it in 10 cycles (i.e., 10 posedge clk's) we used 1[*10] --> 10 consecutive clock edges.


Code :

// Generate whatever pattern you want in the test class
class test;
   rand bit ack_b;
endclass: test

module top;
  test t;
 
  bit clk;
  bit ack;
 
  initial begin
    $timeformat(-9,0,"ns",8);
    clk <= 0;
    forever #5 clk = !clk;
   
  end
 
  initial begin
    t = new;
    repeat(20) begin //{
      @(posedge clk);
      void'(t.randomize());
      ack = t.ack_b;  
    end //}
    $finish;
  end
 
  property check_ack;
    @(posedge clk) ack[->3] intersect 1[*10];
  endproperty

 

  abc: assert property (check_ack) $display("@%0t ACK is through",$time); else
      $error("Check failed at %0t",$time);


 
  initial
    begin //{
    forever begin //{
      @(posedge clk);
      $display("Time:%0t ACK:%0d",$time,ack);
    end //}
    end //}
endmodule: top


Result :
# //
# Loading sv_std.std
# Loading work.testbench_sv_unit(fast)
# Loading work.top(fast)
#
# vsim -voptargs=+acc=npr
# run -all
# Time:5ns ACK:0
# Time:15ns ACK:1
# Time:25ns ACK:1
# Time:35ns ACK:0
# Time:45ns ACK:1
# Time:55ns ACK:0
# ** Error: Check failed at 55ns
# Time: 55 ns Started: 25 ns Scope: top.abc File: testbench.sv Line: 54
# ** Error: Check failed at 55ns
# Time: 55 ns Started: 15 ns Scope: top.abc File: testbench.sv Line: 54
# ** Error: Check failed at 55ns
# Time: 55 ns Started: 5 ns Scope: top.abc File: testbench.sv Line: 54
# Time:65ns ACK:1
# Time:75ns ACK:1
# ** Error: Check failed at 75ns
# Time: 75 ns Started: 35 ns Scope: top.abc File: testbench.sv Line: 54
# Time:85ns ACK:0
# ** Error: Check failed at 85ns
# Time: 85 ns Started: 55 ns Scope: top.abc File: testbench.sv Line: 54
# ** Error: Check failed at 85ns
# Time: 85 ns Started: 45 ns Scope: top.abc File: testbench.sv Line: 54
# Time:95ns ACK:0
# Time:105ns ACK:1
# Time:115ns ACK:0
# ** Error: Check failed at 115ns
# Time: 115 ns Started: 75 ns Scope: top.abc File: testbench.sv Line: 54
# ** Error: Check failed at 115ns
# Time: 115 ns Started: 65 ns Scope: top.abc File: testbench.sv Line: 54
# Time:125ns ACK:1
# Time:135ns ACK:0
# ** Error: Check failed at 135ns
# Time: 135 ns Started: 85 ns Scope: top.abc File: testbench.sv Line: 54
# Time:145ns ACK:0
# Time:155ns ACK:0
# Time:165ns ACK:0
# Time:175ns ACK:0
# Time:185ns ACK:0
# ** Error: Check failed at 185ns
# Time: 185 ns Started: 95 ns Scope: top.abc File: testbench.sv Line: 54
# ** Note: $finish : testbench.sv(45)
# Time: 195 ns Iteration: 1 Instance: /top
# End time: 11:23:36 on Jul 20,2020, Elapsed time: 0:00:00
# Errors: 20, Warnings: 1

Saturday, July 18, 2020

Generating RANDC without using the keyword

In many interviews people ask this question,
how can we reproduce functionality of RANDC without using the keyword in the variable declaration.


About the code:

Here we used a variable 'v' which ranges from 3:0 covering 0-15 values.
Let us say we need to limit the range to 10.
We used a queue to place the value generated by 'v' in post_randomize().
Since the constraint unique { v,v_q } ensures unique values in v and v_q, v will not generate the same value again, therefore matching the behavior of randc.
Once queue reaches size of 10, we clear it.

Here is the piece of code which does the work.

CODE:

class test;
  rand bit [3:0] v;
  bit [3:0] v_q[$];

  constraint c_v { unique {v,v_q};
                            v inside {[1:10]};
                 }

  function void post_randomize();
    v_q.push_back(v);
    if(v_q.size() == 10) v_q.delete();
  endfunction: post_randomize

  function void display();
    $display("V:%0d",v);
  endfunction: display

endclass

module top;
  test t;

  initial begin
    t = new;
    repeat(20) begin
      void'(t.randomize());
      t.display();
    end
  end
endmodule: top


Results :
CPU time: .234 seconds to compile + .310 seconds to elab + .310 seconds to link
Chronologic VCS simulator copyright 1991-2019
Contains Synopsys proprietary information.
Compiler version P-2019.06-1; Runtime version P-2019.06-1; Jul 18 23:48 2020
V:3
V:5
V:8
V:9
V:7
V:10
V:4
V:6
V:1
V:2
V:10
V:7
V:6
V:5
V:4
V:8
V:1
V:2
V:9
V:3
V C S S i m u l a t i o n R e p o r t

X propagation in ASIC/FPGA simulations

Ternary operator is used as a program statement.
If-else is a programming block.
Both can achieve similar results when a non 'X' or 'Z' value is used in conditional expression.
But when X is present inside conditional expression, the scenario changes.

Let us look at 3 scenarios.

When conditional expressions has 'bxx, 'bx0, 'bx1 values.

=========================================================================
module top;
  logic [1:0] a;
  logic [1:0] b;
  logic [1:0] c;
  logic [1:0] d;
  logic [1:0] e;
  
  initial begin
    b = 'bxx;
    c = 'b10;
    d = 'b11;
    
    a = b ? c : d;
    if(b) e = c;
    else  e = d;
    $display("Outputs - A:%0b E:%0b  || Condition:%0b || Inputs - C:%0b D:%0b",a,e,b,c,d);

    b = 'bx0;
    a = b ? c : d;
    if(b) e = c;
    else  e = d;
    $display("Outputs - A:%0b E:%0b  || Condition:%0b || Inputs - C:%0b D:%0b",a,e,b,c,d);

    b = 'bx1;
    a = b ? c : d;
    if(b) e = c;
    else  e = d;
    $display("Outputs - A:%0b E:%0b  || Condition:%0b || Inputs - C:%0b D:%0b",a,e,b,c,d);
  end
endmodule: top

===========================================================
Compiler version P-2019.06-1; Runtime version P-2019.06-1; Jul 18 06:15 2020

Outputs - A:1x E:11 || Condition:xx || Inputs - C:10 D:11
Outputs - A:1x E:11 || Condition:x0 || Inputs - C:10 D:11
Outputs - A:10 E:10 || Condition:x1 || Inputs - C:10 D:11

If you replace 'X' with 'Z' the result is the same.

Outputs - A:1x E:11 || Condition:zz || Inputs - C:10 D:11
Outputs - A:1x E:11 || Condition:z0 || Inputs - C:10 D:11
Outputs - A:10 E:10 || Condition:z1 || Inputs - C:10 D:11

Thursday, July 16, 2020

Solving queen puzzle using system verilog constraints

 Problem statement :
  • 8 queens should be placed on a chess board such that no queen can kill each other.
Notes :
  • To solve this we need to know how queen moves on the chess board.
  • Queen can move through entire ROW, COLUMN and across the DIAGONAL.
  • Therefore, we should have only 1 queen across each row, column and diagonal.
  • Queen in the 2-d matrix used is represented by 1 and the rest are 0's in the matrix(2-D).
  • We have 2 set of constraints for the problem.
    • diag_c : for controlling the diagonals ( same direction and anti diagonals )
    • Transpose_c : for using a transpose matrix for application of sum on the columns.
Constraints :
  • diag_c :
    • For this, use 2 matrices, one for normal directional diagonals and one for the other direction.
    • Map the elements of the diagonal to the main matrix board.
    • Number of row equal number of diagonals present. ( 2*N -1 ).
    • The number of colums for each row depends on the length of the diagonal.
    • For example, if we take a 3x3 matrix, we have 3 diagonals on each side.
    • [00].[0,1] [1,0] , [0,2] [1,1] [2,0]. [1,2] [2,1], [3,3]
    • Mapping of these will be
      • diag - board
      • [0,0] - [0,0]
      • [1,0] - [0,1] , [1,1] - [1,0]
      • [2,0] - [0,2] , [2,1] - [1,1], [2,2] - [2,0]
      • [3,0] - [1,2] , [3,1] - [2,1]
      • [4,0] - [3,3]
  • transpose_c :
    • 3 constraints
      • board_t transpose map to board
      • sum on each row for board
      • sum on each row for board_t, in effect it would be a sum on each row of board.
  • And we are done. :)
//======================================================================//
class queen#(parameter N=3);
  rand bit board[N][N];
  rand bit board_t[N][N];
  rand bit diag[2*N-1][];
  rand bit anti_diag[2*N-1][];

  constraint diag_c {
    foreach(diag[i,j]) {
      if(i < N) diag[i][j] == board[j][i-j];
      else      diag[i][j] == board
[(N-1)-j][i+j-N+1];
    }
    foreach(anti_diag[i,j]) {
      if(i < N) anti_diag[i][j] == board[j][N-1-i+j];
      else      anti_diag[i][j] == board[i-(N-1)+j][j];
    }
    foreach (diag[i]     ) {
      diag[i].sum() with (int'(item)) inside {0,1};
    }
    foreach (anti_diag[i]) {
      anti_diag[i].sum() with (int'(item)) inside {0,1};
    }
  }
 
 
  constraint transpose_c {
    foreach(board[i,j])  { board[i][j] == board_t[j][i];  }
    foreach (board[i])   { board[i].sum(item)   with (int'(item))== 1;  }
    foreach (board_t[i]) { board_t[i].sum(item) with (int'(item))== 1;  }
  }
 

  function void pre_randomize();
    int unsigned n;
    foreach(diag[i]) begin //{
      n = (i < N) ? i+1 : 2*N -(i+1);
      diag[i]      = new[n];
      anti_diag[i] = new[n];
    end //}
  endfunction: pre_randomize


  function void display();
    foreach(board[i,j]) begin //{
      $write("%0b ",board[i][j]);
      if(j== N-1) $write("\n");
    end //}
/*
    foreach(diag[i,j]) begin
      if(i < N)  $display(" DIAG %0d %0d BOARD %0d %0d",i,j,j,i-j);
      else       $display(" DIAG %0d %0d BOARD %0d %0d",i,j,((N-1)-j),(i+j-N+1));
    end
    foreach(anti_diag[i,j]) begin
      if(i < N) $display(" DIAG %0d %0d BOARD %0d %0d",i,j,j,(N-1-i+j));
      else      $display(" DIAG %0d %0d BOARD %0d %0d",i,j,(i-(N-1)+j),j);
    end
    */
  endfunction: display
   
endclass: queen

module top;
  queen#(8) q;

  initial begin //{
    q = new;
    void'(q.randomize());
    q.display();
  end //}
endmodule: top

Generating Sudoko using System verilog constraints


Constraints:
  • c_values : Constraint on minimum and maximum values any element in the matrix can hold
  • c_row_unique :
    • We need to have unique value (from 1 to 9) in each row, for this we run 2 loops
    • Loop - 1 [i,j] iterates through all elements in 2d-matrix
    • Loop - 2 [ ,l] iterates only through each column element
    • If condition is used for not picking up the same element for comparison
  • Constraint c_row_unique and c_col_unique employs similar strategy to generate unique elements in each row and column
  • c_subs_unique :
    • since each sub matrix 3x3 too should have unique values, we can simply divide the i,j and k,l with 3 to pick each 3x3 matrix and apply unique condition for them as well.
    •   !(i==l && j==k) is used to skip same element for comparision.
    • matrix[i][j] != matrix[k][l] , compares one element against all the other elements to avoid replication. 

//------------------------------------------------------------------------------------------------------------------------//

class sudoku;
  rand bit [3:0] matrix[9][9];

  constraint c_values     { foreach (matrix[i,j]) { matrix[i][j] inside {[1:9]}; } }
  constraint c_row_unique { foreach (matrix[i,j]) { foreach (matrix[,l]) { if(j!=l) matrix[i][j] != matrix[i][l]; } } }                    
  constraint c_col_unique { foreach (matrix[i,j]) { foreach (matrix[k,]) { if(i!=k) matrix[i][j] != matrix[k][j]; } } }  

constraint c_sub_unique { foreach (matrix[i,j]) { foreach (matrix[k,l]){ if(i/3 == k/3 && j/3 == l/3 && !(i==k && j==l)) matrix[i][j] != matrix[k][l]; } } } 


  function void display();
    foreach(matrix[i,j]) begin //{
      $write("%0d ",matrix[i][j]);
      if(j == 8) $write("\n");
    end //}
  endfunction: display

endclass: sudoku

module top;
  sudoku s;

  initial begin
    s = new;
    void'(s.randomize());
    s.display();
  end
endmodule:top

Wednesday, July 14, 2010

VHDL examples

============
single port ram
============

library ieee;
use ieee.std_logic_1164.all;

entity single_port_ram is
port
(
data : in std_logic_vector(7 downto 0);
addr : in natural range 0 to 63;
we : in std_logic := '1';
clk : in std_logic;
q : out std_logic_vector(7 downto 0)
);

end entity;

architecture rtl of single_port_ram is

-- Build a 2-D array type for the RAM
subtype word_t is std_logic_vector(7 downto 0);
type memory_t is array(63 downto 0) of word_t;

-- Declare the RAM signal.
signal ram : memory_t;

-- Register to hold the address
signal addr_reg : natural range 0 to 63;

begin

process(clk)
begin
if(rising_edge(clk)) then
if(we = '1') then
ram(addr) <= data;
end if;

-- Register the address for reading
addr_reg <= addr;
end if;

end process;

q <= ram(addr_reg);

end rtl;

=====================
FSM : moore -> BCD counter
=====================

library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.std_logic_arith.all;

entity bcd is
port (
clk : in std_logic;
rst : in std_logic;
count: out std_logic_vector);
end bcd;

architecture beh_bcd of bcd is

-- enumeration of states
type state is (zero,one,two,three,four,five,six,seven,eight,nine);
signal pr_state,nxt_state: state;

--coding starts here
begin

-- sequential part
process(clk,rst)
begin
if(rst = '1') then
pr_state <= zero;
elsif rising_edge(clk) then
pr_state <= nxt_state;
end if;
end process;

-- combinational part
process(pr_state)
begin
case pr_state is
when zero =>
count <= "0000";
nxt_state <= one;
when one =>
count <= "0001";
nxt_state <= two;
when two =>
count <= "0010";
nxt_state <= three;
when three =>
count <= "0011";
nxt_state <= four;
when four =>
count <= "0100";
nxt_state <= five;
when five =>
count <= "0101";
nxt_state <= six;
when six =>
count <= "0110";
nxt_state <= seven;
when seven =>
count <= "0111";
nxt_state <= eight;
when eight =>
count <= "1000";
nxt_state <= nine;
when nine =>
count <= "1001";
nxt_state <= zero;
end case;

end process;

end beh_bcd;

============
2-bit grey code:
============

library IEEE;
use IEEE.Std_logic_1164.all;



entity grey is
port(
x: in std_logic_vector(1 downto 0);
y: out std_logic_vector(1 downto 0)
);
end entity;

architecture beh of grey is
begin
y(1) <= x(1);
y(0) <= x(0) xor x(1);
end beh;

Wednesday, December 2, 2009

Links on IIT videos and some Electronic software downloads

Here we go.......

IIT lecture vidoe links:
-----------------------
1. ECE lectures
http://nptel.iitm.ac.in/courses.php?branch=Ece
2.Digital Image Processing
http://nptel.iitm.ac.in/video.php?courseId=1079

For Free Download of Books:
-----------------------------
1. www.chmpdf.com
2. www.freebookspot.in
3. gigapedia.ws

For Electronics Software:
--------------------------

1. gigle.ws
2. electronic-student.blogspot.com

---Thats all for this post.....
pavan

Thursday, July 9, 2009

Verilog Interview Questions and Problems

Introduction :

A fresh graduate faces some tough questions in his first job interview. The questions themselves are simple but require practical and innovative approach to solve them.

What matters is your approach to solution and understanding of basic hardware design principles.


Some other pages on interview questions:

1. Electrical Engineering Technical Interview Questions/Review : This page has answers too.

2. http://enpub.fulton.asu.edu/cse517/interview.html


Recently added questions

Q. Design a memory system as shown in diagram below.

Note: Only 2000 data entries will be used at a given time. Entries should be programmable by external CPU.

Q. Create "AND" gate using a 2:1 multiplexer. (Create all other gates too.)

Q. Design XOR gate using just NAND gates.

Q. Design a "Stackable First One" finder.

Design a small unit which processes just 1 bit. Design in such a way that it can be stacked to accept make input of any length.


Q Micro architect DMA controller block for given specifications

Note:
- Overall performance should be almost same as performance of Encryption Engine which is 1Gbps.


Q. Design Gray counter to count 6.


Q. Design a block to generate output according to the following timing diagram.

Q. Design a module as shown in following block diagram.


Note: channel_id is 11 bits wide to accomodate 2K entries in 2K deep SRAM. operation is 1 bit wide.
operation = 00 means write to current location.
operation = 01 means add 1 to existing data
operation = 10 means subtract 1 from existing data in SRAM.
Do not optimize based on operation as in future operations bits can change.
Design such that you can support 1 operation every clock.

Q. Design a hardware to implement following equations without using multipliers or dividers.
out = 7x + 8y;
out = .78x + .17y;


Old Questions

Q. Create 4 bit multiplier using a ROM and what will be the size of the ROM. How can you realize it when the outputs are specified.

Q. How can you swap 2 integers a and b, without using a 3rd variable

Q. Which one is preferred? 1's complement or 2's complement and why?

Q. Which one is preferred in FSM design? Mealy or Moore? Why?

Q. Which one is preferred in design entry? RTL coding or Schematic? Why?

Q. Design a 2 input OR gate using a 2:1 mux.

Q. Design a 2 input AND gate using a 2 input XOR gate.

Q. Design a logic which mimics a infinite width register. It takes input serially 1 bit at a time. Output is asserted high when this register holds a value which is divisible by 5.

For example:

Input Sequence Value Output
1 1 1 0
0 10 2 0
1 101 5 1
0 1010 10 1
1 10101 21 0


(Hint: Use a FSM to create this)


Q. Design a block which has 3 inputs as followed.
1. system clock of pretty high freq
2. asynch clock input P
3. asynch clock input Q

P and Q clocks have 50% duty cycle each. Their frequencies are close enough and they have phase difference. Design the block to generate these outputs.

1. PeqQ : goes high if periods of P and Q are same
2. PleQ : goes high if P's period is less than that of Q.
3. PgrQ : goes high if P's period is greater than that of Q.


Q. What's the difference between a latch and a flip-flop? Write Verilog RTL code for each. (This is one of the most common questions but still some EE's don't know how to explain it correctly!)


Q. Design a black box whose input clock and output relationship as shown in diagram.

__ __ __ __ __ __ __ __ __
clk __| |__| |__| |__| |__| |__| |__| |__| |__| |__

__ __ __ __ __
Output __| |________| |________| |________| |________| |__


Q. Design a digital circuit to delay the negative edge of the input
signal by 2 clock cycles.
______________________
input
________| |_____________
_ _ _ _ _ _ _ _ _ _ _ _ _
clock _| |_| |_| |_| |_| |_| |_| |_| |_| |_| |_| |_| |_| |_
___________________________
output _________| |___________


Q. Design a Pattern matching block

- Output is asserted if pattern "101" is detected in last 4 inputs.
- How will you modify this design if it is required to detect same "101" pattern anywhere in last
8 samples?


Questions:

Q.

The digital circuit is shown with logic delay (dly3) and two clock buffer delays (dly1, dly2).

- How will you fix setup timing violations occurring at pin B?
- How will you fix hold violations occurring at pin B?

(Hint: Change the values of three delays to get desired effect)


Q.

Sender sends data at the rate of 80 words / 100 clocks
Receiver can consume at the rate of 8 words / 10 clocks

Calculate the depth of FIFO so that no data is dropped.
Assumptions: There is no feedback or handshake mechanism. Occurrence of data in that time period is guaranteed but exact place in those clock cycles is indeterminate.


Q

Optical sensors A and B are positioned at 90 degrees to each other as shown in Figure. Half od the disc is white and remaining is black. When black portion is under sensor it generates logic 0 and logic 1 when white portion is under sensor.

Design Direction finder block using digital components (flip flops and gates) to indicate speed. Logic 0 for clockwise and Logic 1 for counter clockwise.


Q

Will this design work satisfactorily?
Assumptions: thold = tsetup = tclock_out = tclock_skew = 1ns.
After reset A = 0, B = 1


Q. Design a 4:1 mux in Verilog.
      4:1 MUX
  • Multiple styles of coding. e.g.

  • Using if-else statements

    if(sel_1 == 0 && sel_0 == 0) output = I0;
    else if(sel_1 == 0 && sel_0 == 1) output = I1;
    else if(sel_1 == 1 && sel_0 == 0) output = I2;
    else if(sel_1 == 1 && sel_0 == 1) output = I3;

    Using case statement

    case ({sel_1, sel_0})
    00 : output = I0;
    01 : output = I1;
    10 : output = I2;
    11 : output = I3;
    default : output = I0;
    endcase

  • What are the advantages / disadvantages of each coding style shown above?
  • How Synthesis tool will give result for above codes?
  • What happens if default statement is removed in case statement?
  • What happens if combination 11 and default statement is removed? (Hint Latch inference)

  • (Comments : Though this questions looks simple and out of text books, the answers to supporting questions can come only after some experience / experimentation.)

Q. Design a FSM (Finite State Machine) to detect a sequence 10110.

  • Have a good approach to solve the design problem.
  • Know the difference between Mealy, Moore, 1-Hot type of state encoding.
  • Each state should have output transitions for all combinations of inputs.
  • All states make transition to appropriate states and not to default if sequence is broken. e.g. S3 makes transition to S2 in example shown.
  • Take help of FSM block diagram to write Verilog code.

Q. One more sequence detector:

Design a FSM (Finite State Machine) to detect more than one "1"s in last 3 samples.
For example: If the input sampled at clock edges is 0 1 0 1 0 1 1 0 0 1
then output should be 0 0 0 1 0 1 1 1 0 0 as shown in timing diagram.

And yes, you have to design this FSM using not more than 4 states!!

Sequence Detector Timing Diagram


Q. Design a state machine to divide the clock by 3/2.

frequency divider

(Hint: 2 FSMs working on posedge and negedge)


Q. Draw timing diagrams for following circuit.

Diagram of cascaded flip-flops

Timing Diagram

  • What is the maximum frequency at which this circuit can operate?
  • What is the minimum width of input pulse and position?
  • Problem can be given interesting twist by specifying all delays in min and max types.

Q. Design a Digital Peak Detector in Verilog.

Peak Detector Diagrams


Q. Design a RZ (return to zero )circuit. Design a clock to pulse circuit in Verilog / hardware gates.

Return to Zero Circuit


Q. Miscellaneous Basic Verilog Questions:

  • What is the difference between Behavior modeling and RTL modeling?
  • What is the benefit of using Behavior modeling style over RTL modeling?
  • What is the difference between blocking assignments and non-blocking assignments ?
  • How do you implement the bi-directional ports in Verilog HDL
  • How to model inertial and transport delay using Verilog?
  • How to synchronize control signals and data between two different clock domains?

Constraint to have N elements distributed in M bins

Code to distribute N elements into M bins, you add unique keyword to have each bin will have unique number of elements. class test; param...