1. What is callback ? Callback is one of the major confusing point for a System Verilog learner. Many people have asked the same question in many forums, but the answer doesn't seems to satisfy fully the quest of the person who has raised the querry. I too had the same issue, but I learned it slowly in a hard way. I am presenting here a way in which if I had an answer, I would have learned faster. We can pass data member to any function. Now consider a case where you are passing a function (say func1) as a data member to another function (say func2) and you get what is called callback. The reason why it is called callback is that the function func2 now can call anywhere in its code function func1. From wikipedia In computer programming, a callback is executable code that is passed as an argument to other code. It allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer. Note that SV doesn't give a straight-forward way of passing a function as argument for another function. But we can get the same result (almost we can say!) by using OOP. The idea is to describe all the functions (both func1 type and func2 type) in a base class (don't implement the funct2 kind of function and make them virtual for polymorphism), and then extend the class to a derived class where you implement the func2 type of function. Example:- class abc_transactor; virtual task pre_send(); endtask virtual task post_send(); endtask task xyz(); // Some code here this.pre_send(); // Some more code here this.post_send(); // And some more code here endtask : xyz endclass : abc_transactor class my_abc_transactor extend abc_transactor; virtual task pre_send(); ... // This function is implemented here
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1. What is callback ?
Callback is one of the major
confusing point for a System Verilog learner. Many people have asked the same question in many forums,
but the answer doesn't seems to satisfy fully the quest of the person who has raised the querry. I too had
the same issue, but I learned it slowly in a hard way. I am presenting here a way in which if I had an
answer, I would have learned faster.
We can pass data member to any function. Now consider a case where you are passing a function (say
func1) as a data member to another function (say func2) and you get what is called callback. The reason
why it is called callback is that the function func2 now can call anywhere in its code function func1.
From wikipedia
In computer programming, a callback is executable code that is passed as an argument to
other code. It allows a lower-level software layer to call a subroutine (or function) defined
in a higher-level layer.
Note that SV doesn't give a straight-forward way of passing a function as argument for another function.
But we can get the same result (almost we can say!) by using OOP. The idea is to describe all the
functions (both func1 type and func2 type) in a base class (don't implement the funct2 kind of function
and make them virtual for polymorphism), and then extend the class to a derived class where you
Now we are done with the bothering about the objects to be created. The next problem that we need to solve is to write the toy factory class itself. For simplicity, let's consider the case where we will want to pass 1 to get an instance of tank class and 2 for getting an instance of bus class from the factory. Now the factory class will look like this.
class TOY_factory;
Toy my_toy
// Common methods
function toy get_toy(int type);
if(type == 1) this.my_toy = new TOY_Tank();
if(type == 2) this.my_toy = new TOY_Bus();
return this.my_toy;
endfunction : get_toy
endclass : TOY_factory
Note that we are using virtual function for bringing polymorphism in action and save us from having an
individual instance of the toy type in the factory class.
3. Explain the difference between data types logic and reg and wire
Wire:-
1. Wires are used for connecting different elements
2. They can be treated as a physical wire
3. They can be read or assigned
4. No values get stored in them
5. They need to be driven by either continuous assign statement or from a port of a module Reg:-
1. Contrary to their name, regs doesn't necessarily corresponds to physical registers
2. They represents data storage elements in Verilog/SystemVerilog
3. They retain their value till next value is assigned to them (not through assign statement)
4. They can be synthesized to FF, latch or combinational circuit (They might not be synthesizable
!!!) Wires and Regs are present from Verilog timeframe. SystemVerilog added a new data type called logic to them. So the next question is what is this logic data type and how it is different from our good old wire/reg. Logic:-
1. As we have seen, reg data type is bit mis-leading in Verilog. SystemVerilog's logic data type
addition is to remove the above confusion. The idea behind having a new data type called logic
which at least doesn't give an impression that it is hardware synthesizable
2. Logic data type doesn't permit multiple driver. It has a last assignment wins behavior in case of
multiple assignment (which implies it has no hardware equivalence). Reg/Wire data type give X if
multiple driver try to drive them with different value. Logic data type simply assign the last
assignment value.
3. The next difference between reg/wire and logic is that logic can be both driven by assign block,
output of a port and inside a procedural block like this
logic a;
assign a = b ^ c; // wire style
always (c or d) a = c + d; // reg style
MyModule module(.out(a), .in(xyz)); // wire style
4. What is the need of clocking blocks ?
In Verilog, the communication between blocks is specified using module ports. SystemVerilog adds the interface, a key construct that encapsulates the communication between blocks, thereby enabling users to easily change the level of abstraction at which the intermodule communication is to be modeled. An interface can specify the signals or nets through which a testbench communicates with a device under test (DUT). However, an interface does not explicitly specify any timing disciplines, synchronization requirements, or clocking paradigms. SystemVerilog adds the clocking block that identifies clock signals and captures the timing and synchronization requirements of the blocks being modeled. A clocking block assembles signals that are synchronous to a particular clock and makes their timing explicit. The clocking block is a key element in a cycle-based methodology, which enables users to write testbenches at a higher level of abstraction. Rather than focusing on signals and transitions in time, the test can be defined in terms of cycles and transactions. Depending on the environment, a testbench can contain one or more clocking blocks, each containing its own clock plus an arbitrary number of signals. The clocking block separates the timing and synchronization details from the structural, functional, and procedural elements of a testbench. Thus, the timing for sampling and driving clocking block signals is implicit and relative to the clocking block’s clock. This enables a set of key operations to be written very succinctly, without explicitly using clocks or specifying timing. These operations are as follows: — Synchronous events — Input sampling — Synchronous drives Clocking block in SystemVerilog are used for specifying the clock signal, timing, and synchronization
requirements of various blocks. It separates the timing related information from structural, functional and
procedural element of the TB. There are quite a few links on clocking block in the internet. These are
- Specify synchronization characteristics of the design
- Offer a clean way to drive and sample signals
- Provides race-free operation if input skew > 0
- Helps in testbench driving the signals at the right time
- Features
- Clock specification
- Input skew,output skew
- Cycle delay (##)
- Can be declared inside interface,module or program
Example :
01.Module M1(ck, enin, din, enout, dout);
02.input ck,enin;
03.input [31:0] din ;
04.output enout ;
05.output [31:0] dout ;
06.
07.clocking sd @(posedge ck);
08.input #2ns ein,din ;
09.output #3ns enout, dout;
10.endclocking:sd
11.
12.reg [7:0] sab ;
13.initial begin
14.sab = sd.din[7:0];
15.end
16.endmodule:M1
5. What are the ways to avoid race condition between testbench and RTL
using SystemVerilog?
There are two major sources of nondeterminism in Verilog. The first one is that active events are processed in an arbitrary order. The second one is that statements without time control constructs in behavioral blocks do not execute as one event. However, from the testbench perspective, these effects are all unimportant details. The primary task of a testbench is to generate valid input stimulus for the design under test and to verify that the device operates correctly. Furthermore, testbenches that use cycle abstractions are only concerned with the stable or steady state of the system for both checking the current outputs and for computing stimuli for the next cycle. Formal tools also work in this fashion.
Statements within a program block that are sensitive to changes (e.g., update events) in design signals (declared in modules, not program blocks) are scheduled in the Reactive region. Consider a program block that contains the statement @(clk) S1; where clk is a design signal in some module. Every transition of signal clk will cause the statement S1
to be scheduled into the Reactive region. Likewise, initial blocks within program blocks are scheduled in the Reactive region; in contrast, initial blocks in modules are scheduled in the Active region. In addition, design signals driven from within the program must be assigned using nonblocking assignments and are updated in the NBA region. Thus, even signals driven with no delay are propagated into the design as one event. With this behavior, correct cycle semantics can be modeled without races, thereby making program-based testbenches compatible with clocked assertions and formal tools. Because the program schedules events in the Reactive region, the clocking block construct is very useful to automatically sample the steady-state values of previous time steps or clock cycles. Programs that read design values exclusively through clocking
blocks with #0 input skews are insensitive to read-write races. It is important to understand that simply sampling input signals (or setting nonzero skews on clocking
block inputs) does not eliminate the potential for races. Proper input sampling only addresses a single clocking block. With multiple clocks, the arbitrary order in which overlapping or simultaneous clocks are processed is still a potential source for races. The program construct addresses this issue by scheduling its execution in the Reactive region, after all design events have been processed, including clocks driven by nonblocking assignments.
6. Explain Event regions in SV.
The first division is by time. Every event has one and only one simulation execution time,
which at any given point during simulation can be the current time or some future time.
All scheduled events at a specific time define a time slot. Simulation proceeds by
executing and removing all events in the current simulation time slot before moving on to
the next nonempty time slot, in time order. This procedure guarantees that the simulator
never goes backwards in time.
A time slot is divided into a set of ordered regions:
a) Preponed
b) Pre-active
c) Active
d) Inactive
e) Pre-NBA
f) NBA
g) Post-NBA
h) Observed
i) Post-observed
j) Reactive
k) Re-inactive
l) Pre-postponed
m) Postponed
The purpose of dividing a time slot into these ordered regions is to provide predictable
interactions between the design and testbench code.
Except for the Observed, Reactive, and Re-inactive regions and the Post-observed PLI
region, these regions essentially encompass IEEE 1364 reference model for simulation,
with exactly the same level of determinism. In other words, legacy Verilog code shall
continue to run correctly without modification within the new mechanism. The Postponed
region is where the monitoring of signals, and other similar events, takes place. No new
value changes are allowed to happen in the time slot once the Postponed region is
reached. The Observed, Reactive, and Re-inactive regions are new in this standard, and
events are only scheduled
into these new regions from new language constructs. The Observed region is for the
evaluation of the property expressions when they are triggered. A criterion
for this determinism is that the property evaluations must only occur once in any clock
triggering time slot.
During the property evaluation, pass/fail code shall be scheduled in the Reactive region
of the current time slot. PLI callbacks are not allowed in the Observed region. The new
#1step sampling delay provides the ability to sample data immediately before entering
the current time slot and is a preferred construct over other equivalent constructs
because it allows the 1step time delay
to be parameterized. This #1step construct is a conceptual mechanism that provides a
method for defining when sampling takes place and does not require that an event be
created in this previous time slot. Conceptually, this #1step sampling is identical to
taking the data samples in the Preponed region of the current time slot. The code
specified in the program block and the pass/fail code from property expressions are
scheduled in the Reactive region. A #0 control delay specified in a program block
schedules the process for resumption in
the Re-inactive region. The Re-inactive region is the program block dual of the Inactive
region (see below).
The Pre-active, Pre-NBA, and Post-NBA regions are new in this standard but support
existing PLI callbacks.
The Post-observed region is new in this standard and has been added for PLI support.
The Pre-active region provides for a PLI callback control point that allows PLI application
routines to read and write values and create events before events in the Active region
are evaluated (see 9.4).
The Pre-NBA region provides for a PLI callback control point that allows PLI application
routines to read and write values and create events before the events in the NBA region
are evaluated (see 9.4).
The Post-NBA region provides for a PLI callback control point that allows PLI application
routines to read and write values and create events after the events in the NBA region
are evaluated (see 9.4).
The Post-observed region provides for a PLI callback control point that allows PLI
application routines to read values after properties are evaluated (in Observed or earlier
region).
NOTE—The PLI currently does not schedule callbacks in the Post-observed region.
The Pre-postponed region provides a PLI callback control point that allows PLI
application routines to read and write values and create events after processing all other
regions except the Postponed region.
The flow of execution of the event regions is specified in Figure 9-1.
The Active, Inactive, Pre-NBA, NBA, Post-NBA, Observed, Post-observed, Reactive,
Re-inactive, and Prepostponed regions are known as the iterative regions.
The Preponed region provides for a PLI callback control point that allows PLI application
routines to access data at the current time slot before any net or variable has changed
state. Within this region, it is illegal to write values to any net or variable or to schedule
an event in any other region within the current time slot.
NOTE—The PLI currently does not schedule callbacks in the Preponed region.
The Active region holds current events being evaluated and can be processed in any
order.
The Inactive region holds the events to be evaluated after all the active events are
processed.
An explicit #0 delay control requires that the process be suspended and an event
scheduled into the Inactive region (or Re-inactive for program blocks) of the current time
slot so that the process can be resumed in the next inactive to active iteration.
A nonblocking assignment creates an event in the NBA region, scheduled for the current
or a later simulation time.
The Postponed region provides for a PLI callback control point that allows PLI
application routines to be suspended until after all the Active, Inactive, NBA, Observed,
Reactive, and Re-inactive regions have completed.
Within this region, it is illegal to write values to any net or variable or to schedule an
event in any previous region within the current time slot.
9.3.1 The SystemVerilog simulation reference algorithm
execute_simulation {
T = 0;
initialize the values of all nets and variables;
schedule all initialization events into time 0 slot;
while (some time slot is nonempty) {
move to the next future nonempty time slot and set T;
preponed
pre-active
active
inactive
pre-NBA
NBA
post-NBA
observed
post-observed
reactive
postponed
time slot
from previous
time slot
to next
time slot
region
PLI region
Legend:
re-inactive
pre-postponed
7. What are the types of coverages available in SV ?
Using Cover Groups: Variables, expressions and their cross
Using Cover Properties
8. What is OOPS? Brief Introduction To Oop
Unlike procedural programming, here in the OOP programming model programs are
organized around objects and data rather than actions and logic. Objects represent some
concepts or things and like any other objects in the real Objects in programming language
have certain behavior, properties, type, and identity. In OOP based language the principal
aim is to find out the objects to manipulate and their relation between each other. OOP
offers greater flexibility and compatibility then procedural language like verilog.
Objects are key to understanding object-oriented technology. Look around right now and
you'll find many examples of real-world objects: your system, your desk, your chair.
Real-world objects share two characteristics: They all have state and behavior. System
have state (name, color) and behavior (playing music,switch off). Identifying the state and
behavior for real-world objects is a great way to begin thinking in terms of object-oriented
programming.
SystemVerilog is a object oriented programming and to understand the functionality of
OOP in SystemVerilog, we first need to understand several fundamentals related to
objects. These include class, method, inheritance, encapsulation, abstraction,
polymorphism etc.
Class
It is the central point of OOP and that contains data and codes with behavior. In
SystemVerilog OOPS , everything happens within class and it describes a set of objects
with common behavior. The class definition describes all the properties, behavior, and
30. Without using randomize method or rand,generate an array of unique
values?
...
2.int UniqVal[10];
3.foreach(UniqVal[i]) UniqVal[i] = i;
4.UniqVal.shuffle();
5....
31. Explain about pass by ref and pass by value? Pass by value is the default method through which arguments are passed into functions and
tasks. Each subroutine retains a local copy of the argument. If the arguments are changed
within the subroutine declaration, the changes do not affect the caller.
In pass by reference functions and tasks directly access the specified variables passed as
arguments.Its like passing pointer of the variable.
example:
task pass(int i) // task pass(var int i) pass by reference
{
delay(10);
i = 1;
printf(" i is changed to %d at %d\n",i,get_time(LO) );
delay(10);
i = 2;
printf(" i is changed to %d at %d\n",i,get_time(LO) );
}
32. What is the difference between bit[7:0] sig_1; and byte sig_2; byte is signed whereas bit [7:0] is unsigned.
33. What is the difference between program block and module ?
Program block is newly added in SystemVerilog. It serves these purposes
1. It separates testbench from DUT
2. It helps in ensuring that testbench doesn't have any race condition with DUT
3. It provides an entry point for execution of testbench
4. It provides syntactic context (via program ... endprogram) that specifies scheduling in the
Reactive Region. Having said this the major difference between module and program blocks are
1. Program blocks can't have always block inside them, modules can have.
2. Program blocks can't contain UDP, modules, or other instance of program block inside them.
Modules don't have any such restrictions.
3. Inside a program block, program variable can only be assigned using blocking assignment and
non-program variables can only be assigned using non-blocking assignments. No such restrictions
on module
4. Program blocks get executed in the re-active region of scheduling queue, module blocks get
executed in the active region
5. A program can call a task or function in modules or other programs. But a module can not call a
task or function in a program.
34. What is final block ?
35. How to implement always block logic in program block ? Use of forever begin end. If it is a complex always block statement like always (@ posedge clk or negedge reset_)
always @(posedge clk or negedge reset_) begin
if(!reset_) begin
data <= '0;
end else begin
data <= data_next;
end
end
// Using forever : slightly complex but doable
forever begin
fork
begin : reset_logic
@ (negedge reset_);
data <= '0;
end : reset_logic
begin : clk_logic
@ (posedge clk);
if(!reset_) data <= '0;
else data <= data_next;
end : clk_logic
join_any
disable fork
end
36. What is the difference between fork/joins, fork/join_none fork/join_any ?
I have added histstat hit counter for my blog to have an idea about traffic/visitor/search engine
trends. One interesting I am observing is that quite a few hit to my site is coming for fork/join
interview questions in Google. Hence I thought, why not have a real useful post on fork/join{x} of
SystemVerilog and its associated disable/wait command.
Fork-join statement has come from Verilog. It is used for forking out parallel processes in test
bench. SV substantially improved fork/join construct to have much more controllability in
process creation, destruction, and waiting for end of the process.
The basic syntax of fork join block looks like this:
01.fork
02.begin : First_thread
03.// Code for 1st thread
04.end
05.begin : Second_thread
06.// Code for 2nd thread
07.end
08.begin : Third thread
09.// Code for 3rd branch
10.end
11....
12.join // Can be join_any, join_none in SV
There are 3 different kind of join keyword in SV, each specifying a different way of waiting for completion of the threads/process created by the fork.
o join : waits for completion of all of the threads
o join_any : waits for the completion of the 1st thread, then comes out of fork loop, but lets the
other process/thread execute as usual
o join_none : doesn't wait for completion of any thread, just starts then and immediately exits
fork loop. Now, suppose you have exited the fork loop by join_none or join_any and after some
steps, you want to wait till completion of all the threads spanned by the previous fork
loop. SV has "wait fork" for the same.
Now, suppose you have exited the fork loop by join_none or join_any and after some
steps, you want to killall the threads spanned by the previous fork loop. SV has "disable
fork" for the same.
Next interesting scenario: you have exited fork loop by join_none or join_any and after
some steps, you want to kill just one thread (out of many). The solution, have named
begin end block and call "disable ". (For example, in the last example if you want to kill
only the 2nd thread after exiting the loop via join_any/join_none, then add "disable
Second_thread;" at the point where you want to disable the second thread.
I have created a image to pictorially depict fork/join in SV. Hope that will help
understand this in a much better way.
37. What is the use of modports ?
Modports are part of Interface. Modports are used for specifing the direction of the signals with respect to various modules the interface connects to.
1....
2.interface my_intf;
3.wire x, y, z;
4.modport master (input x, y, output z);
5.modport slave (output x, y, input z);
6.endinterface
Please refer section 19.4 of SV LRM for more details
38. Write a clock generator without using always block.
39. What is forward referencing and how to avoid this problem?
40. What is circular dependency and how to avoid this problem ?
41. What is cross coverage ?
42. Describe the difference between Code Coverage and Functional Coverage
Which is more important and Why we need them Code Coverage indicates the how much of RTL has been exercised. The Functional Coverage
indicates which features or functions has been executed. Both of them are very
important. With only Code Coverage, it may not present the real features coverage. On the
other hand, the functional coverage may miss some unused RTL coverage.
43. How to kill a process in fork/join?
44. Difference between Associative array and Dynamic array ? 1) Difference between Associative array and Dynamic array ?
Answer:
Dynamic arrays are useful for dealing with contiguous collections of variables whose number
changes dynamically.
e.g. int array[];
When the size of the collection is unknown or the data space is sparse, an associative array
is a better option. In associative array, it uses the transaction names as the keys in associative
array.
e.g. int array[string];
45. Difference b/w Procedural and Concurrent Assertions?
46. What are the advantages of SystemVerilog DPI? SystemVerilog introduces a new foreign language interface called the Direct Programming
Interface (DPI). The DPI provides a very simple, straightforward, and efficient way to connect
SystemVerilog and foreign language code unlike PLI or VPI.
47. How to randomize dynamic arrays of objects?
class ABC;
// Dynamic array
rand bit [7:0] data [];
// Constraints
constraint cc {
// Constraining size
data.size inside {[1:10]};
// Constraining individual entry
data[0] > 5;
// All elements
foreach(data[i])
if(i > 0)
data[i] > data[i-1];
}
endclass : ABC
48. What is randsequence and what is its use?
49. What is bin? A coverage-point bin associates a name and a count with a set of values or a sequence of value
transitions. If the bin designates a set of values, the count is incremented every time the
coverage point matches one of the values in the set. If the bin designates a sequence of value
transitions, the count is incremented every time the coverage point matches the entire
sequence of value transitions.
e.g.
program main;
bit [0:2] y;
bit [0:2] values[$]= '{3,5,6};
covergroup cg;
cover_point_y : coverpoint y
{ option.auto_bin_max = 4 ; }
endgroup
cg cg_inst = new();
initial
foreach(values[i])
begin
y = values[i];
cg_inst.sample();
end
endprogram
50. Why always block is not allowed in program block?
51. Which is best to use to model transaction? Struct or class ?
52. How SV is more random stable then Verilog?
53. Difference between assert and expect statements?
54. How to add a new processs with out disturbing the random number
generator state ?
55. What is the need of alias in SV?
56. What is the need to implement explicitly a copy() method inside a
transaction , when we can simple assign one object to other ?
57. How different is the implementation of a struct and union in SV.
58. What is "this"?
59. What is tagged union ?
60. What is "scope resolution operator"?
61. What is the difference between Verilog Parameterized Macros and
SystemVerilog Parameterized Macros?
62. What is the difference between view source print?
1.logic data_1;
2.var logic data_2;
3.wire logic data_3j;
4.bit data_4;
5.var bit data_5;
63. What is the difference between bits and logic?
64. Write a Statemechine in SV styles.
65. What is the difference between $rose and posedge?
66. What is advantage of program block over clockcblock w.r.t race condition?
67. How to avoid the race condition between programblock ?
68. What is the difference between assumes and assert?
69. What is coverage driven verification?
70. What is layered architecture ?
71. What are the simulation phases in your verification environment?
72. How to pick a element which is in queue from random index?
73. What data structure is used to store data in your environment and why ?
74. What is casting? Explain about the various types of casting available in SV.
75. How to import all the items declared inside a package ?
76. Explain how the timescale unit and precision are taken when a module
does not have any timescalerdeclaration in RTL?
77. What is streaming operator and what is its use?
78. What are void functions ?
79. How to make sure that a function argument passed has ref is not changed
by the function?
80. What is the use of "extern"?
81. What is the difference between initial block and final block?
There are many difference between initial and final block. I am listing the few differences that is coming to mind now.
1. The most obvious one : Initial blocks get executed at the beginning of the simulation, final block
at the end of simulation
2. Final block has to be executed in zero time, which implies it can't have any delay, wait, or non-
blocking assignments. Initial block doesn't have any such restrictions of execution in zero time
(and can have delay, wait and non-blocking statements) Final block can be used to display statistical/genaral information regarding the status of the execution like this:-
1.final begin
2.$display("Simulation Passed");
3.$display("Final value of xyz = %h",xyz);
4.$display("Bye :: So long, and Thanks for all the fishes");
5.end
82. How to check weather a handles is holding object or not ?
83. How to disable multiple threads which are spawned by fork...join