Wednesday, April 21, 2010

Systemverilog Interview Questions 3

1) What is the difference between mailbox and queue?

Answer:

A queue is a variable-size, ordered collection of homogeneous elements. A Queue is analogous to one dimensional unpacked array that grows and shrinks automatically. Queues can be used to model a last in, first out buffer or first in, first out buffer.

// Other data type as reference
// int q[]; dynamic array
// int q[5]; fixed array
// int q[string]; associate array
// include <
// List#(integer) List1;    //


int q[$] = { 2, 4, 8 };
int p[$];
int e, pos;
e = q[0]; // read the first (leftmost) item
e = q[$]; // read the last (rightmost) item
q[0] = e; // write the first item
p = q; // read and write entire queue (copy)


A mailbox is a communication mechanism that allows messages to be exchanged between processes. Data can be sent to a mailbox by one process and retrieved by another. 


2) What data structure you used to build scoreboard?


Answer:

    In SV, we use mailbox to get data from different modules and compare the result.

class Scoreboard;

mailbox drvr2sb;
mailbox rcvr2sb;

function new(mailbox drvr2sb,mailbox rcvr2sb);
  this.drvr2sb = drvr2sb;
  this.rcvr2sb = rcvr2sb;
endfunction:new


task start();
  packet pkt_rcv,pkt_exp;
  forever
  begin
    rcvr2sb.get(pkt_rcv);
    $display(" %0d : Scorebooard : Scoreboard received a packet from receiver ",$time);
    drvr2sb.get(pkt_exp);
    if(pkt_rcv.compare(pkt_exp))
    $display(" %0d : Scoreboardd :Packet Matched ",$time);
    else
      $root.error++;
  end
endtask : start

endclass



In VMM, we use channels to connect all the modules and compare the result.


class Scoreboard extends vmm_xactor;

   Packet_channel   drvr2sb_chan;
   Packet_channel   rcvr2sb_chan;


function new(string inst = "class",
             int unsigned stream_id = -1,
             Packet_channel   drvr2sb_chan = null,
             Packet_channel   rcvr2sb_chan = null);

      super.new("sb",inst,stream_id);
   
      if(drvr2sb_chan == null)
           `vmm_fatal(this.log,"drvr2sb_channel is not constructed");
      else
           this.drvr2sb_chan = drvr2sb_chan;
     
      if(rcvr2sb_chan == null)
           `vmm_fatal(this.log,"rcvr2sb_channel is not constructed");
      else
           this.rcvr2sb_chan = rcvr2sb_chan;
     
      `vmm_note(log,"Scoreboard created ");

endfunction:new


task main();
  Packet pkt_rcv,pkt_exp;
  string msg;
  super.main();
  forever
  begin
    rcvr2sb_chan.get(pkt_rcv);
    $display(" %0d : Scoreboard : Scoreboard received a packet from receiver ",$time);
    drvr2sb_chan.get(pkt_exp);
    if(pkt_rcv.compare(pkt_exp,msg))
    $display(" %0d : Scoreboard :Packet Matched ",$time);
    else
    `vmm_error(this.log,$psprintf(" Packet MissMatched \n %s ",msg));
  end
endtask : main

endclass



3) What are the advantages of linkedlist over the queue ?
   
 Answer:


 Queue has a certain order. It's hard to insert the data within the queue. But Linkedlist can easily insert the data in any location.


4) What is the use of $cast?


Using Casting one can assign values to variables that might not ordinarily be valid because of differing data type. SystemVerilog adds 2 types of casting. Static casting and dynamic casting.


e.g.  i = int '(10.0-0.1); // static cast convert real to integer


// Dynamic casting
function int $cast( singular dest_var, singular source_exp );
or
task $cast( singular dest_var, singular source_exp );



e.g. $cast( col, 2 + 3 );

ASIC Verification Interview Questions

1)  What if design engineer and verification engineer do the same mistake in Test bench BFM(Bus Functional Model) and RTL(DUT)? How can you able to detect errors? 

 Answer:  1.   Code reviews & protocol checkers
                2.   IP gets verified in multiple environments .. like block level test bench, out of box testbench (connecting DUT back to back) , full fledged testbench using proven BFM, SoC level testbench using processor and all that etc... this all environments SHOULD be executed by diferent persons and so you should be able to catch that bug in one of this testbench ...
                3. customer will catch the problem ( worst case )

2)  If you got a failure from the customer, how do you debug this? How do you prevent it to happen again?


Answer: 1. First, try to reproduce the problem in your own environment. Try to get customer's vector, so you can inject the same vector to create the problem in house.
              2. If you confirm the problem and fix them, you should put the new assertion or test to catch the problem again. Add this new test in the future test plan, so the problem will not happen again.








Wednesday, February 17, 2010

Previous Interview Questions

1) Try to model Stack in Verilog code?

module Stack (DataIO, Reset, Push, Pop, SP, Full, Empty, Err);
//Verilog code for stack

/* declare input, output and inout ports */
inout [3:0] DataIO;
input Push,Pop,Reset;
output Empty,Err;
Full,output [2:0] SP; // Stack pointer

// declare registers
regEmpty,Err;
Full,reg [2:0] SP;
reg [3:0] Stack[7:0];
reg [3:0] DataR;

/* continuous assignment of DataIO to DataR register, with delay 0 */
wire [3:0] #(0) DataIO = DataR;

// put DataR in high impedance, so the stack can get data

always @ (negedge Pop)
begin
DataR = 4'bzzzz;
end


always @ (posedge Push or posedge Pop or posedge Reset)
begin


   if (Reset==1)
   begin
     DataR = 4'bzzzz;
     SP = 3'b0;
     Full = 0;
     Empty = 0;
     Err = 0;
  end
 
    if (Push==1) begin
      //when the stack is empty
      if (Empty==1)
      begin
         Stack[SP] = DataIO;
         Empty = 0;
         if (Err==1)
         Err=0;
      end
     else // when the stack is full
     if(full==1)
     begin
        Stack[SP] = DataIO;
        Err = 1;
     end
     else
     begin
        SP = SP +1;
        Stack [SP] = DataIO;
        if (SP == 3'b111)
            Full = 1;
     end
end  // end of push


    if(Pop==1) begin
    /* if SP indicates the last location but the stack is not empty */
     if ((SP == 3'b000) && (Empty!=1)
     begin
        DataR = Stack[SP];
        Empty = 1;
     end
     else // if the stack is emtpy
       if(Empty==1)
       begin
        DataR = Stack[SP];
        Err = 1;
       end
     else
     begin
     DataR = Stack[SP];
     if (SP != 3'b000)
        SP = SP-1;
      // if the stack is full
     if (Err==1) Err = 0;
     if (Full==1) Full = 0;
    end
 end  // end of pop
end  // end of always loop

endmodule

2) what is difference between CAM and TCAM?

First, CAM stands for Content Addressable Memory. A CAM is a special type of memory; some would say the opposite of RAM. With normal computer memory (RAM) the operating system provides an address, and receives the data stored at the supplied address. With a CAM, the operating system supplies the data, and the CAM returns a list of addresses where the data is stored, if it finds any. Furthermore, a CAM searches the entire memory in one operation, so it is considerably faster than RAM.

The most commonly implemented CAMs are called binary CAMs. They search only for ones and zeros; a simple operation. MAC address tables in switches commonly get stored inside binary CAMs. With CAMs, the operating system can find what it needs in a single operation. In this case it's the switchport that data should be sent out, based on the given MAC address,

The TCAM is a Ternary CAM. This allows the operating system to match a third state, "X." The X state is a "mask," meaning its value can be anything. This lends itself well to networking, since netmasks (define) operate this way. To calculate a subnet address we mask the bits we don't care about, and then apply the logical AND operation to the rest. Routers can store their entire routing table in these TCAMs, allowing for very quick lookups.

3) One-hot state machine vs highly encoded state machine

Answer:

     One-hot state machine: better performance, easy encode
     highly encode state machine has less bit for state parameters
 
   e.g.

  Using Single Always For Sequential, Combo And Output Logic
//==================================================== 2 // This is FSM demo program using single always 3 // for both seq and combo logic 4 // Design Name : fsm_using_single_always 5 // File Name : fsm_using_single_always.v 6 //===================================================== 7 module fsm_using_single_always (
8 clock , // clock 9 reset , // Active high, syn reset 10 req_0 , // Request 0 11 req_1 , // Request 1 12 gnt_0 , // Grant 0 13 gnt_1
14 );
15 //=============Input Ports============================= 16 input clock,reset,req_0,req_1;
17 //=============Output Ports=========================== 18 output gnt_0,gnt_1;
19 //=============Input ports Data Type=================== 20 wire clock,reset,req_0,req_1;
21 //=============Output Ports Data Type================== 22 reg gnt_0,gnt_1;
23 //=============Internal Constants====================== 24 parameter SIZE = 3 ;
25 parameter IDLE = 3'b001,GNT0 = 3'b010,GNT1 = 3'b100 ;
26 //=============Internal Variables====================== 27 reg [SIZE-1:0] state ;// Seq part of the FSM 28 reg [SIZE-1:0] next_state ;// combo part of FSM 29 //==========Code startes Here========================== 30 always @ (posedge clock)
31 begin : FSM
32 if (reset == 1'b1) begin
33 state <= #1 IDLE;
34 gnt_0 <= 0;
35 gnt_1 <= 0;
36 end else
37 case(state)
38 IDLE : if (req_0 == 1'b1) begin
39 state <= #1 GNT0;
40 gnt_0 <= 1;
41 end else if (req_1 == 1'b1) begin
42 gnt_1 <= 1;
43 state <= #1 GNT1;
44 end else begin
45 state <= #1 IDLE;
46 end
47 GNT0 : if (req_0 == 1'b1) begin
48 state <= #1 GNT0;
49 end else begin
50 gnt_0 <= 0;
51 state <= #1 IDLE;
52 end
53 GNT1 : if (req_1 == 1'b1) begin
54 state <= #1 GNT1;
55 end else begin
56 gnt_1 <= 0;
57 state <= #1 IDLE;
58 end
59 default : state <= #1 IDLE;
60 endcase
61 end
62
63 endmodule // End of Module arbiter


4) Write a perl script to read a file and then count the "ERROR=number" ? Check the number did increase.

Answer:
    First, you can use grep -f patternfile source > target to generate a new log file with ERROR=# format or directly use perl to do it.


  Assume the log file has the format  "ERROR=number" format in some lines,

   #!/usr/bin/perl
   system(grep "ERROR" logfile > error_logfile);
 
   open(IN, "error_logfile") or die "Cannot open the error_logfile!";

    while($line=) {
   chop($line);
   @err_array = split(/\d/,$line);
   $w=1;
      while ($$w<= @err_array) {
         if($err_array[$w-1] < $err_array[$w])
           {           $err_incr_cnt +=1;
           }
        else
             {         $err_decr_cnt +=1;       
             }
        $w++; 
     }  
}
   print "Total number of error = $w";
   print "Error Increment counter = $err_incr_cnt";
   print "Error Decrement counter =$err_decr_cnt;

Perl Hash examples

Example:

    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    %name = ('Tom',26,'Peter',51,'Jones', 23, 'John', 43);
    print "Sorted by Keys \n
";
    foreach $key (sort keys %name)
    {
      print "$key: $name{$key}
";
    }
    print "Sorted by Values \n
";
    foreach $value (sort {$name{$a} cmp $name{$b} }keys %name)
    {
      print "$value: $name{$value}
";
    }

Result:

Sorted by Keys
     John: 43
     Jones: 23
     Peter: 51
     Tom: 26
Sorted by Values
     Jones: 23
     Tom: 26
     John: 43
     Peter: 51


Regular expressions are that makes Perl an ideal language for "Practical extraction and reporting" as the name implies.To construct the regular expression, which is essentially a sequence of characters describing the pattern you would like to match.

Metacharacter      Default Behaviour
\     Quote next character
^     Match beginning-of-string
.     Match any character except newline
$     Match end-of-string
|     Alternation
()     Grouping and save subpattern
[ ]     Character class


The split() function is used to split up a string using a regular expression delimiter or a character or a string.
Syntax:

     split (string);

In the above syntax, split() function takes a "string" as the argument.
Example to split string using regular expression delimiter:

    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    $str1 = "how,are,you";
    $str2 = "how!!are!!you";
    $str3 = "how1are2you";
    @val1 = split(",", $str1);
    @val2 = split('!!', $str2);
    @val3 = split(/\d+/, $str3);
    print "Removed the character Comma","\n";
    print "
";
    foreach $val1 (@val1)
     {
       print "$val1\n";
     }
    print "
";
    print "Removed the string '!!'";
    print "
";
    foreach $val2 (@val2)
     {
       print "$val2\n";
     }
    print "
";
    print "Removed the decimals 1,2";
    print "
";
    foreach $val3 (@val3)
     {
       print "$val3\n";
     }

Result:

    Removed the character Comma
    how are you
    Removed the string '!!'
    how are you
    Removed the decimals 1,2
    how are you

In the above example the string "howareyou" is seperated first with a comma, then by a string "!!", at last seperated by decimals "1,2", which is removed using a regular expression "/\d+/". All these strings are split and stored in an array, then using a loop its returned one by one.

Tuesday, February 16, 2010

C++ Class example

Basic Class C++ example code

// example one
#include
#include

class Book
{
// by default, all data and function are private

int PageCount;
int CurrentPage;
public:
Book( int Numpages) ; // Constructor
~Book(){} ; // Destructor
void SetPage( int PageNumber) ;
int GetCurrentPage( void ) ;
};

Book::Book( int NumPages) {
PageCount = NumPages;
}



void Book::SetPage( int PageNumber) {
CurrentPage=PageNumber;
}

int Book::GetCurrentPage( void ) {
return CurrentPage;
}

int main() {
Book ABook(128) ;   // Call constructor() and set PageNum=128
ABook.SetPage( 56 ) ;  // Set the current page number
std::cout << "Current Page " << ABook.GetCurrentPage() << std::endl;    // print out the current page
return 0;    // call destructor
}



This example will demonstrate inheritance. This is a two class  application  with one class derived from another.

    #include
    #include

    class Point
    {
   // default private
    int x,y;
    public:
    Point(int atx,int aty ) ; // Constructor
    inline virtual ~Point() ; // Destructor
    virtual void Draw() ;
    };




    class Circle : public Point {
    int radius;
    public:
    Circle(int atx,int aty,int theRadius) ;
    inline virtual ~Circle() ;
    virtual void Draw() ;
    };


    Point ::Point(int atx,int aty) {
    x = atx;
    y = aty;
    }

    inline Point::~Point ( void ) {
    std::cout << "Point Destructor called\n";
    }

    void Point::Draw( void ) {
    std::cout << "Point::Draw point at " << x << " " << y << std::endl;
    }


    Circle::Circle(int atx,int aty,int theRadius) : Point(atx,aty) {
    radius = theRadius;
    }

    inline Circle::~Circle() {
    std::cout << "Circle Destructor called" << std::endl;
    }

    void Circle::Draw( void ) {
    Point::Draw() ;
    std::cout << "circle::Draw point " << " Radius "<< radius << std::endl;
    }

    int main() {
    Circle ACircle(10,10,5) ;
    ACircle.Draw() ;
    return 0;
    }

What is Polymorphism?

Polymorphism is a generic term that means 'many shapes'. In C++ the simplest form of Polymorphism is overloading of functions, for instance several functions called SortArray( arraytype ) where sortarray might be an array  of ints, or doubles. 

/* A base class of Shape gives rise to
two derived classes - Circle and Square.

An application called Polygon sets up an
array of Circles and Squares, and uses a
getarea method to find the area of each.

This getarea method is defined as a virtual
method in the base class, so that an array
of shapes CAN be defined on which two
different getarea methods can be run
depending on which type of shape is the
current one at the time. */

::::::::::::::
shape.h
::::::::::::::

#ifndef SHAPE
#define SHAPE 1

class Shape {
        public:
                void setsize(int owbig);
                virtual float getarea() {};
        protected:
                int givensize;
        };

#endif
::::::::::::::
shape.cpp
::::::::::::::
#include "shape.h"

void Shape::setsize(int sv) {
        givensize = sv;
        }

::::::::::::::
square.h
::::::::::::::
#include "shape.h"

class Square: public Shape {
        public:
                float getarea();
        };
::::::::::::::
square.cpp
::::::::::::::
#include "square.h"

float Square::getarea() {
        float result = givensize * givensize;
        return (result);
        }
::::::::::::::
circle.h
::::::::::::::
#include "shape.h"

class Circle: public Shape {
        public:
                float getarea();
        };
::::::::::::::
circle.cpp
::::::::::::::
#include "circle.h"

float Circle::getarea() {
        float result = 3.14159265f * givensize;
        return result;
        }
::::::::::::::
polygon.cpp
::::::::::::::
#include
#include "circle.h"
#include "square.h"

main () {

        int np = 10;
        Shape *jigsaw[np];

        for (int k=0; k
                jigsaw[k] = new Square();
                jigsaw[k+1] = new Circle();
        }
        for (int k=0; k
                jigsaw[k]->setsize(10+k);
                }
        for (int k=0; k
                float syze = jigsaw[k]->getarea();
                cout << "this is sq " << syze << endl;
                }

        return (0);
        }

Perl interview questions Part #7

1) What happens when you return a reference to a private variable?

Answer:
Perl Keeps track of your variables, whether dynamic or otherwise, and dones't free things before you're done using them.

2) How do I sort a hash by the hash value?

Answer:

#!/usr/bin/perl -w
# help sort a hash by the hash 'value', not the 'key'

sub sorthashValueDescendingNum {$grades{$b} <=> ${grades{$a}};

%grades =( student1=>90,
student2=>75,
student3=>76);

print "\n\tGRADES IN ASCENDING NUMERIC ORDER\n";
foreach $key (sort(keys(%grades))){
print "\t\t$grades{$key} \t\t$key\n";
}

print "\n\tGRADES IN DESCENDING NUMERIC ORDER\n";
foreach $key (sorthashValueDescendingNum(keys(%grades))){
print "\t\t$grades{$key} \t\t$key\n";
}

3) How to read file into hash array?

Answer:

The following little snippet of code should do exactly what you want:

open(IN, "filename")

          or die "Couldn't open file for processing: $!";
while (
) {
chomp;
$hash_table{$_} = 0;
}
close IN;

Once you've read in your values, the following single line of code
will print them all out for you:

print "$_ = $hash_table{$_}\n" foreach keys %hash_table;


4) Does Perl have reference type?

Answer:

$str="here we go"  ;  # a scalar variable
$strref = \$str;          # a reference to a scalar

@array=(1..10);       # an array
$arrayref =\@array;  # a reference to an array.

%hash=(key1=>vaule1,
             key2=>value2
);
$rhash-ref =\%hash;


4) How to initialize a hash?

Answer:
my %hash = ();    # initialize a hash
my $hash_ref = {};  # reference to empty hash

5) How to add data into hash?

Answer:
$hash{ 'key' } = 'value';    # hash

    $hash{ $key } = $value;      # hash, using variables

    $href->{ 'key' } = 'value';  # hash ref

    $href->{ $key } = $value;    # hash ref, using variables

    %hash = ( 'key1', 'value1', 'key2', 'value2', 'key3', 'value3' ); # add multiple items

    %hash = (
        key1 => 'value1',
        key2 => 'value2',
        key3 => 'value3',
    );

6) How to copy hash?

Answer:
   my %hash_copy = %hash;  # copy a hash

    my $href_copy = $href;  # copy a hash ref


7)  How to use while or for loop with Hash?


Use each within a while loop. Note that each iterates over entries in an apparently random order, but that order is guaranteed to be the same for the functions keys and values.

    while ( my ($key, $value) = each(%hash) ) {
        print "$key => $value\n";
    }


A hash reference would be only slightly different:

    while ( my ($key, $value) = each(%$hash_ref) ) {
        print "$key =>$value\n";
    }

Use keys with a for loop.

    for my $key ( keys %hash ) {
        my $value = $hash{$key};
        print "$key =>$value\n";
    }

8) What's the size of the hash?

Answer:
print "size of hash:  " . keys( %hash ) . ".\n";
 
 
Extra Hash information

Perl interview questions Part #6

1) Explain the difference between the following in Perl:
$array[3] vs $array->[3]

Answer:

$array[3] is the 4th element of the array "array"
$array->[3] is the hard reference to a (possible anonymous) array. It's the 4th element of the referenced array.


2) How to remove duplicates from an array?

Answer:

@array=(2,4,3,3,6,2);
my %seen=();
my @unique = grep { !seen{$_}++} @array;
print "@unique";

3) What is Perl on-liner?

Answer:
There are two ways a perl scripts can be run:
1. From a command line, called one-liner. It may contains many statements in one line.
e.g. perl -e "print \"Hello\";"

2. Script file, Perl program
e.g. perl program.pl

Search This Blog